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 vectors combinators
5 classes sets unicode.categories compiler.units parser words
6 quotations effects memoize accessors locals effects 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 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) ( r l s -- )
159 s head>> l head>> eq? [
161 l head>> [ s rule-id>> suffix ] change-involved-set drop
162 r l s next>> (setup-lr)
165 :: setup-lr ( r l -- )
167 r rule-id V{ } clone V{ } clone peg-head boa l (>>head)
169 r l lrstack get (setup-lr) ;
171 :: lr-answer ( r p m -- ast )
175 h rule-id>> r rule-id eq? [
176 m ans>> seed>> m (>>ans)
187 :: recall ( r p -- memo-entry )
189 m [ p r rule-id memo ]
193 m r rule-id h involved-set>> h rule-id>> suffix member? not and [
194 fail p memo-entry boa
196 r rule-id h eval-set>> member? [
197 h [ r rule-id swap remove ] change-eval-set drop
210 :: apply-non-memo-rule ( r p -- ast )
212 lr [ fail r rule-id f lrstack get left-recursion boa ]
213 m [ lr lrstack set lr p memo-entry boa dup p r rule-id set-memo ]
216 lrstack get next>> lrstack set
227 : apply-memo-rule ( r m -- ast )
228 [ ans>> ] [ pos>> ] bi pos set
229 dup left-recursion? [
230 [ setup-lr ] keep seed>>
235 : apply-rule ( r p -- ast )
236 ! 2dup [ rule-id ] dip 2array "apply-rule: " write .
241 ! " not memoed" print
245 : with-packrat ( input quot -- result )
246 #! Run the quotation with a packrat cache active.
251 V{ } clone error-stack set
252 H{ } clone \ heads set
253 H{ } clone \ packrat set
254 ] H{ } make-assoc swap bind ; inline
257 GENERIC: (compile) ( peg -- quot )
259 : process-parser-result ( result -- result )
263 input-slice swap <parse-result>
266 : execute-parser ( word -- result )
267 pos get apply-rule process-parser-result ; inline
269 : parser-body ( parser -- quot )
270 #! Return the body of the word that is the compiled version
272 gensym 2dup swap peg>> (compile) (( -- result )) define-declared
273 swap dupd id>> "peg-id" set-word-prop
274 [ execute-parser ] curry ;
276 : preset-parser-word ( parser -- parser word )
277 gensym [ >>compiled ] keep ;
279 : define-parser-word ( parser word -- )
280 swap parser-body (( -- result )) define-declared ;
282 : compile-parser ( parser -- word )
283 #! Look to see if the given parser has been compiled.
284 #! If not, compile it to a temporary word, cache it,
285 #! and return it. Otherwise return the existing one.
286 #! Circular parsers are supported by getting the word
287 #! name and storing it in the cache, before compiling,
288 #! so it is picked up when re-entered.
292 preset-parser-word [ define-parser-word ] keep
297 : fixup-delayed ( -- )
298 #! Work through all delayed parsers and recompile their
299 #! words to have the correct bodies.
301 call compile-parser 1quotation (( -- result )) define-declared
304 : compile ( parser -- word )
307 compile-parser fixup-delayed
309 ] with-compilation-unit ;
311 : compiled-parse ( state word -- result )
312 swap [ execute [ error-stack get first throw ] unless* ] with-packrat ; inline
314 : (parse) ( input parser -- result )
315 dup word? [ compile ] unless compiled-parse ;
317 : parse ( input parser -- ast )
325 #! Return the next unique id for a parser
332 : wrap-peg ( peg -- parser )
333 #! Wrap a parser tuple around the peg object.
334 #! Look for an existing parser tuple for that
340 TUPLE: token-parser symbol ;
342 : parse-token ( input string -- result )
343 #! Parse the string, returning a parse result
344 [ ?head-slice ] keep swap [
345 <parse-result> f f add-error
347 [ drop pos get "token '" ] dip append "'" append 1vector add-error f
350 M: token-parser (compile) ( peg -- quot )
351 symbol>> '[ input-slice _ parse-token ] ;
353 TUPLE: satisfy-parser quot ;
355 : parse-satisfy ( input quot -- result )
359 unclip-slice rot dupd call [
367 M: satisfy-parser (compile) ( peg -- quot )
368 quot>> '[ input-slice _ parse-satisfy ] ;
370 TUPLE: range-parser min max ;
372 : parse-range ( input min max -- result )
376 [ dup first ] 2dip between? [
377 unclip-slice <parse-result>
383 M: range-parser (compile) ( peg -- quot )
384 [ min>> ] [ max>> ] bi '[ input-slice _ _ parse-range ] ;
386 TUPLE: seq-parser parsers ;
388 : ignore? ( ast -- bool )
391 : calc-seq-result ( prev-result current-result -- next-result )
393 [ remaining>> swap (>>remaining) ] 2keep
397 swap [ ast>> push ] keep
403 : parse-seq-element ( result quot -- result )
410 M: seq-parser (compile) ( peg -- quot )
412 [ input-slice V{ } clone <parse-result> ] %
414 parsers>> unclip compile-parser 1quotation [ parse-seq-element ] curry ,
415 [ compile-parser 1quotation [ merge-errors ] compose [ parse-seq-element ] curry , ] each
419 TUPLE: choice-parser parsers ;
421 M: choice-parser (compile) ( peg -- quot )
424 parsers>> [ compile-parser ] map
425 unclip 1quotation , [ 1quotation [ merge-errors ] compose , ] each
429 TUPLE: repeat0-parser p1 ;
431 : (repeat) ( quot: ( -- result ) result -- result )
433 [ remaining>> swap (>>remaining) ] 2keep
434 ast>> swap [ ast>> push ] keep
438 ] if* ; inline recursive
440 M: repeat0-parser (compile) ( peg -- quot )
441 p1>> compile-parser 1quotation '[
442 input-slice V{ } clone <parse-result> _ swap (repeat)
445 TUPLE: repeat1-parser p1 ;
447 : repeat1-empty-check ( result -- result )
449 dup ast>> empty? [ drop f ] when
454 M: repeat1-parser (compile) ( peg -- quot )
455 p1>> compile-parser 1quotation '[
456 input-slice V{ } clone <parse-result> _ swap (repeat) repeat1-empty-check
459 TUPLE: optional-parser p1 ;
461 : check-optional ( result -- result )
462 [ input-slice f <parse-result> ] unless* ;
464 M: optional-parser (compile) ( peg -- quot )
465 p1>> compile-parser 1quotation '[ @ check-optional ] ;
467 TUPLE: semantic-parser p1 quot ;
469 : check-semantic ( result quot -- result )
471 over ast>> swap call [ drop f ] unless
476 M: semantic-parser (compile) ( peg -- quot )
477 [ p1>> compile-parser 1quotation ] [ quot>> ] bi
478 '[ @ _ check-semantic ] ;
480 TUPLE: ensure-parser p1 ;
482 : check-ensure ( old-input result -- result )
483 [ ignore <parse-result> ] [ drop f ] if ;
485 M: ensure-parser (compile) ( peg -- quot )
486 p1>> compile-parser 1quotation '[ input-slice @ check-ensure ] ;
488 TUPLE: ensure-not-parser p1 ;
490 : check-ensure-not ( old-input result -- result )
491 [ drop f ] [ ignore <parse-result> ] if ;
493 M: ensure-not-parser (compile) ( peg -- quot )
494 p1>> compile-parser 1quotation '[ input-slice @ check-ensure-not ] ;
496 TUPLE: action-parser p1 quot ;
498 : check-action ( result quot -- result )
500 over ast>> swap call >>ast
505 M: action-parser (compile) ( peg -- quot )
506 [ p1>> compile-parser 1quotation ] [ quot>> ] bi '[ @ _ check-action ] ;
508 TUPLE: sp-parser p1 ;
510 M: sp-parser (compile) ( peg -- quot )
511 p1>> compile-parser 1quotation '[
512 input-slice [ blank? ] trim-head-slice input-from pos set @
515 TUPLE: delay-parser quot ;
517 M: delay-parser (compile) ( peg -- quot )
518 #! For efficiency we memoize the quotation.
519 #! This way it is run only once and the
520 #! parser constructed once at run time.
521 quot>> gensym [ delayed get set-at ] keep 1quotation ;
523 TUPLE: box-parser quot ;
525 M: box-parser (compile) ( peg -- quot )
526 #! Calls the quotation at compile time
527 #! to produce the parser to be compiled.
528 #! This differs from 'delay' which calls
530 quot>> call compile-parser 1quotation ;
534 : token ( string -- parser )
535 token-parser boa wrap-peg ;
537 : satisfy ( quot -- parser )
538 satisfy-parser boa wrap-peg ;
540 : range ( min max -- parser )
541 range-parser boa wrap-peg ;
543 : seq ( seq -- parser )
544 seq-parser boa wrap-peg ;
546 : 2seq ( parser1 parser2 -- parser )
549 : 3seq ( parser1 parser2 parser3 -- parser )
552 : 4seq ( parser1 parser2 parser3 parser4 -- parser )
555 : seq* ( quot -- paser )
556 { } make seq ; inline
558 : choice ( seq -- parser )
559 choice-parser boa wrap-peg ;
561 : 2choice ( parser1 parser2 -- parser )
564 : 3choice ( parser1 parser2 parser3 -- parser )
567 : 4choice ( parser1 parser2 parser3 parser4 -- parser )
570 : choice* ( quot -- paser )
571 { } make choice ; inline
573 : repeat0 ( parser -- parser )
574 repeat0-parser boa wrap-peg ;
576 : repeat1 ( parser -- parser )
577 repeat1-parser boa wrap-peg ;
579 : optional ( parser -- parser )
580 optional-parser boa wrap-peg ;
582 : semantic ( parser quot -- parser )
583 semantic-parser boa wrap-peg ;
585 : ensure ( parser -- parser )
586 ensure-parser boa wrap-peg ;
588 : ensure-not ( parser -- parser )
589 ensure-not-parser boa wrap-peg ;
591 : action ( parser quot -- parser )
592 action-parser boa wrap-peg ;
594 : sp ( parser -- parser )
595 sp-parser boa wrap-peg ;
597 : hide ( parser -- parser )
598 [ drop ignore ] action ;
600 : delay ( quot -- parser )
601 delay-parser boa wrap-peg ;
603 : box ( quot -- parser )
604 #! because a box has its quotation run at compile time
605 #! it must always have a new parser wrapper created,
606 #! not a cached one. This is because the same box,
607 #! compiled twice can have a different compiled word
608 #! due to running at compile time.
609 #! Why the [ ] action at the end? Box parsers don't get
610 #! memoized during parsing due to all box parsers being
611 #! unique. This breaks left recursion detection during the
612 #! parse. The action adds an indirection with a parser type
613 #! that gets memoized and fixes this. Need to rethink how
614 #! to fix boxes so this isn't needed...
615 box-parser boa f next-id parser boa [ ] action ;
617 ERROR: parse-failed input word ;
621 [let | def [ ] word [ ] |
624 [let | compiled-def [ def call compile ] |
626 dup compiled-def compiled-parse
627 [ ast>> ] [ word parse-failed ] ?if
631 ] with-compilation-unit
635 USING: vocabs vocabs.loader ;
638 "peg.debugger" require