1 ! Copyright (C) 2007, 2008 Chris Double.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences strings fry namespaces make math assocs
4 io vectors arrays math.parser math.order combinators
5 classes sets unicode.categories compiler.units parser words
6 quotations memoize accessors locals splitting
7 combinators.short-circuit generalizations ;
10 TUPLE: parse-result remaining ast ;
11 TUPLE: parse-error position messages ;
12 TUPLE: parser peg compiled id ;
14 M: parser equal? { [ [ class ] bi@ = ] [ [ id>> ] bi@ = ] } 2&& ;
15 M: parser hashcode* id>> hashcode* ;
17 C: <parse-result> parse-result
18 C: <parse-error> parse-error
22 : (merge-errors) ( a b -- c )
24 { [ over position>> not ] [ nip ] }
25 { [ dup position>> not ] [ drop ] }
26 [ 2dup [ position>> ] bi@ <=> {
29 { +eq+ [ messages>> over messages>> union [ position>> ] dip <parse-error> ] }
35 error-stack get dup length 1 > [
36 dup pop over pop swap (merge-errors) swap push
41 : add-error ( remaining message -- )
42 <parse-error> error-stack get push ;
46 : packrat ( id -- cache )
47 #! The packrat cache is a mapping of parser-id->cache.
48 #! For each parser it maps to a cache holding a mapping
49 #! of position->result. The packrat cache therefore keeps
50 #! track of all parses that have occurred at each position
51 #! of the input string and the results obtained from that
53 \ packrat get [ drop H{ } clone ] cache ;
61 #! A mapping from position->peg-head. It maps a
62 #! position in the input string being parsed to
63 #! the head of the left recursion which is currently
64 #! being grown. It is 'f' at any position where
65 #! left recursion growth is not underway.
68 : failed? ( obj -- ? )
71 : peg-cache ( -- cache )
72 #! Holds a hashtable mapping a peg tuple to
73 #! the parser tuple for that peg. The parser tuple
74 #! holds a unique id and the compiled form of that peg.
75 \ peg-cache get-global [
76 H{ } clone dup \ peg-cache set-global
80 H{ } clone \ peg-cache set-global ;
84 #! An entry in the table of memoized parse results
85 #! ast = an AST produced from the parse
86 #! or the symbol 'fail'
87 #! or a left-recursion object
88 #! pos = the position in the input string of this entry
89 TUPLE: memo-entry ans pos ;
91 TUPLE: left-recursion seed rule-id head next ;
92 TUPLE: peg-head rule-id involved-set eval-set ;
94 : rule-id ( word -- id )
95 #! A rule is the parser compiled down to a word. It has
96 #! a "peg-id" property containing the id of the original parser.
99 : input-slice ( -- slice )
100 #! Return a slice of the input from the current parse position
101 input get pos get tail-slice ;
103 : input-from ( input -- n )
104 #! Return the index from the original string that the
105 #! input slice is based on.
106 dup slice? [ from>> ] [ drop 0 ] if ;
108 : process-rule-result ( p result -- result )
110 nip [ ast>> ] [ remaining>> ] bi input-from pos set
115 : eval-rule ( rule -- ast )
116 #! Evaluate a rule, return an ast resulting from it.
117 #! Return fail if the rule failed. The rule has
118 #! stack effect ( -- parse-result )
119 pos get swap execute( -- parse-result ) process-rule-result ; inline
121 : memo ( pos id -- memo-entry )
122 #! Return the result from the memo cache.
124 ! " memo result " write dup .
127 : set-memo ( memo-entry pos id -- )
128 #! Store an entry in the cache
131 : update-m ( ast m -- )
132 swap >>ans pos get >>pos drop ;
134 : stop-growth? ( ast m -- ? )
135 [ failed? pos get ] dip
138 : setup-growth ( h p -- )
139 pos set dup involved-set>> clone >>eval-set drop ;
141 : (grow-lr) ( h p r: ( -- result ) m -- )
142 [ [ setup-growth ] 2keep ] 2dip
143 [ dup eval-rule ] dip swap
144 dup pick stop-growth? [
149 ] if ; inline recursive
151 : grow-lr ( h p r m -- ast )
152 [ [ heads set-at ] 2keep ] 2dip
153 pick over [ (grow-lr) ] 2dip
155 dup pos>> pos set ans>>
158 :: (setup-lr) ( l s -- )
160 s left-recursion? [ s throw ] unless
161 s head>> l head>> eq? [
163 l head>> [ s rule-id>> suffix ] change-involved-set drop
164 l s next>> (setup-lr)
168 :: setup-lr ( r l -- )
170 r rule-id V{ } clone V{ } clone peg-head boa l (>>head)
172 l lrstack get (setup-lr) ;
174 :: lr-answer ( r p m -- ast )
178 h rule-id>> r rule-id eq? [
179 m ans>> seed>> m (>>ans)
190 :: recall ( r p -- memo-entry )
192 m [ p r rule-id memo ]
196 m r rule-id h involved-set>> h rule-id>> suffix member? not and [
197 fail p memo-entry boa
199 r rule-id h eval-set>> member? [
200 h [ r rule-id swap remove ] change-eval-set drop
213 :: apply-non-memo-rule ( r p -- ast )
215 lr [ fail r rule-id f lrstack get left-recursion boa ]
216 m [ lr lrstack set lr p memo-entry boa dup p r rule-id set-memo ]
219 lrstack get next>> lrstack set
222 m ans>> left-recursion? [
232 : apply-memo-rule ( r m -- ast )
233 [ ans>> ] [ pos>> ] bi pos set
234 dup left-recursion? [
235 [ setup-lr ] keep seed>>
240 : apply-rule ( r p -- ast )
241 ! 2dup [ rule-id ] dip 2array "apply-rule: " write .
246 ! " not memoed" print
250 : with-packrat ( input quot -- result )
251 #! Run the quotation with a packrat cache active.
256 V{ } clone error-stack set
257 H{ } clone \ heads set
258 H{ } clone \ packrat set
260 ] with-scope ; inline
263 GENERIC: (compile) ( peg -- quot )
265 : process-parser-result ( result -- result )
269 input-slice swap <parse-result>
272 : execute-parser ( word -- result )
273 pos get apply-rule process-parser-result ;
275 : preset-parser-word ( parser -- parser word )
276 gensym [ >>compiled ] keep ;
278 : define-parser-word ( parser word -- )
279 #! Return the body of the word that is the compiled version
281 2dup swap peg>> (compile) (( -- result )) define-declared
282 swap id>> "peg-id" set-word-prop ;
284 : compile-parser ( parser -- word )
285 #! Look to see if the given parser has been compiled.
286 #! If not, compile it to a temporary word, cache it,
287 #! and return it. Otherwise return the existing one.
288 #! Circular parsers are supported by getting the word
289 #! name and storing it in the cache, before compiling,
290 #! so it is picked up when re-entered.
294 preset-parser-word [ define-parser-word ] keep
297 : compile-parser-quot ( parser -- quot )
298 compile-parser [ execute-parser ] curry ;
302 : fixup-delayed ( -- )
303 #! Work through all delayed parsers and recompile their
304 #! words to have the correct bodies.
306 call( -- parser ) compile-parser-quot (( -- result )) define-declared
309 : compile ( parser -- word )
312 compile-parser-quot (( -- result )) define-temp fixup-delayed
314 ] with-compilation-unit ;
316 : compiled-parse ( state word -- result )
317 swap [ execute( -- result ) [ error-stack get first throw ] unless* ] with-packrat ;
319 : (parse) ( input parser -- result )
320 dup word? [ compile ] unless compiled-parse ;
322 : parse ( input parser -- ast )
330 #! Return the next unique id for a parser
332 dup 1 + id set-global
337 : wrap-peg ( peg -- parser )
338 #! Wrap a parser tuple around the peg object.
339 #! Look for an existing parser tuple for that
345 TUPLE: token-parser symbol ;
347 : parse-token ( input string -- result )
348 #! Parse the string, returning a parse result
349 [ ?head-slice ] keep swap [
350 <parse-result> f f add-error
352 [ drop pos get "token '" ] dip append "'" append 1vector add-error f
355 M: token-parser (compile) ( peg -- quot )
356 symbol>> '[ input-slice _ parse-token ] ;
358 TUPLE: satisfy-parser quot ;
360 : parse-satisfy ( input quot -- result )
364 unclip-slice rot dupd call [
372 M: satisfy-parser (compile) ( peg -- quot )
373 quot>> '[ input-slice _ parse-satisfy ] ;
375 TUPLE: range-parser min max ;
377 : parse-range ( input min max -- result )
381 [ dup first ] 2dip between? [
382 unclip-slice <parse-result>
388 M: range-parser (compile) ( peg -- quot )
389 [ min>> ] [ max>> ] bi '[ input-slice _ _ parse-range ] ;
391 TUPLE: seq-parser parsers ;
393 : ignore? ( ast -- bool )
396 : calc-seq-result ( prev-result current-result -- next-result )
398 [ remaining>> swap (>>remaining) ] 2keep
402 swap [ ast>> push ] keep
408 : parse-seq-element ( result quot -- result )
415 M: seq-parser (compile) ( peg -- quot )
417 [ input-slice V{ } clone <parse-result> ] %
419 parsers>> unclip compile-parser-quot [ parse-seq-element ] curry ,
420 [ compile-parser-quot [ merge-errors ] compose [ parse-seq-element ] curry , ] each
424 TUPLE: choice-parser parsers ;
426 M: choice-parser (compile) ( peg -- quot )
429 parsers>> [ compile-parser-quot ] map
430 unclip , [ [ merge-errors ] compose , ] each
434 TUPLE: repeat0-parser p1 ;
436 : (repeat) ( quot: ( -- result ) result -- result )
438 [ remaining>> swap (>>remaining) ] 2keep
439 ast>> swap [ ast>> push ] keep
443 ] if* ; inline recursive
445 M: repeat0-parser (compile) ( peg -- quot )
446 p1>> compile-parser-quot '[
447 input-slice V{ } clone <parse-result> _ swap (repeat)
450 TUPLE: repeat1-parser p1 ;
452 : repeat1-empty-check ( result -- result )
454 dup ast>> empty? [ drop f ] when
459 M: repeat1-parser (compile) ( peg -- quot )
460 p1>> compile-parser-quot '[
461 input-slice V{ } clone <parse-result> _ swap (repeat) repeat1-empty-check
464 TUPLE: optional-parser p1 ;
466 : check-optional ( result -- result )
467 [ input-slice f <parse-result> ] unless* ;
469 M: optional-parser (compile) ( peg -- quot )
470 p1>> compile-parser-quot '[ @ check-optional ] ;
472 TUPLE: semantic-parser p1 quot ;
474 : check-semantic ( result quot -- result )
476 over ast>> swap call [ drop f ] unless
481 M: semantic-parser (compile) ( peg -- quot )
482 [ p1>> compile-parser-quot ] [ quot>> ] bi
483 '[ @ _ check-semantic ] ;
485 TUPLE: ensure-parser p1 ;
487 : check-ensure ( old-input result -- result )
488 [ ignore <parse-result> ] [ drop f ] if ;
490 M: ensure-parser (compile) ( peg -- quot )
491 p1>> compile-parser-quot '[ input-slice @ check-ensure ] ;
493 TUPLE: ensure-not-parser p1 ;
495 : check-ensure-not ( old-input result -- result )
496 [ drop f ] [ ignore <parse-result> ] if ;
498 M: ensure-not-parser (compile) ( peg -- quot )
499 p1>> compile-parser-quot '[ input-slice @ check-ensure-not ] ;
501 TUPLE: action-parser p1 quot ;
503 : check-action ( result quot -- result )
505 over ast>> swap call >>ast
510 M: action-parser (compile) ( peg -- quot )
511 [ p1>> compile-parser-quot ] [ quot>> ] bi '[ @ _ check-action ] ;
513 TUPLE: sp-parser p1 ;
515 M: sp-parser (compile) ( peg -- quot )
516 p1>> compile-parser-quot '[
517 input-slice [ blank? ] trim-head-slice input-from pos set @
520 TUPLE: delay-parser quot ;
522 M: delay-parser (compile) ( peg -- quot )
523 #! For efficiency we memoize the quotation.
524 #! This way it is run only once and the
525 #! parser constructed once at run time.
526 quot>> gensym [ delayed get set-at ] keep 1quotation ;
528 TUPLE: box-parser quot ;
530 M: box-parser (compile) ( peg -- quot )
531 #! Calls the quotation at compile time
532 #! to produce the parser to be compiled.
533 #! This differs from 'delay' which calls
535 quot>> call( -- parser ) compile-parser-quot ;
539 : token ( string -- parser )
540 token-parser boa wrap-peg ;
542 : satisfy ( quot -- parser )
543 satisfy-parser boa wrap-peg ;
545 : range ( min max -- parser )
546 range-parser boa wrap-peg ;
548 : seq ( seq -- parser )
549 seq-parser boa wrap-peg ;
551 : 2seq ( parser1 parser2 -- parser )
554 : 3seq ( parser1 parser2 parser3 -- parser )
557 : 4seq ( parser1 parser2 parser3 parser4 -- parser )
560 : seq* ( quot -- paser )
561 { } make seq ; inline
563 : choice ( seq -- parser )
564 choice-parser boa wrap-peg ;
566 : 2choice ( parser1 parser2 -- parser )
569 : 3choice ( parser1 parser2 parser3 -- parser )
572 : 4choice ( parser1 parser2 parser3 parser4 -- parser )
575 : choice* ( quot -- paser )
576 { } make choice ; inline
578 : repeat0 ( parser -- parser )
579 repeat0-parser boa wrap-peg ;
581 : repeat1 ( parser -- parser )
582 repeat1-parser boa wrap-peg ;
584 : optional ( parser -- parser )
585 optional-parser boa wrap-peg ;
587 : semantic ( parser quot -- parser )
588 semantic-parser boa wrap-peg ;
590 : ensure ( parser -- parser )
591 ensure-parser boa wrap-peg ;
593 : ensure-not ( parser -- parser )
594 ensure-not-parser boa wrap-peg ;
596 : action ( parser quot -- parser )
597 action-parser boa wrap-peg ;
599 : sp ( parser -- parser )
600 sp-parser boa wrap-peg ;
602 : hide ( parser -- parser )
603 [ drop ignore ] action ;
605 : delay ( quot -- parser )
606 delay-parser boa wrap-peg ;
608 : box ( quot -- parser )
609 #! because a box has its quotation run at compile time
610 #! it must always have a new parser wrapper created,
611 #! not a cached one. This is because the same box,
612 #! compiled twice can have a different compiled word
613 #! due to running at compile time.
614 #! Why the [ ] action at the end? Box parsers don't get
615 #! memoized during parsing due to all box parsers being
616 #! unique. This breaks left recursion detection during the
617 #! parse. The action adds an indirection with a parser type
618 #! that gets memoized and fixes this. Need to rethink how
619 #! to fix boxes so this isn't needed...
620 box-parser boa f next-id parser boa [ ] action ;
622 ERROR: parse-failed input word ;
626 [let | effect [ ] def [ ] word [ ] |
629 [let | compiled-def [ def call compile ] |
631 dup compiled-def compiled-parse
632 [ ast>> ] [ word parse-failed ] ?if
634 word swap effect define-declared
636 ] with-compilation-unit
640 USING: vocabs vocabs.loader ;
643 "peg.debugger" require