1 ! Copyright (C) 2007, 2008 Chris Double.
2 ! See http://factorcode.org/license.txt for BSD license.
4 USING: accessors arrays assocs classes combinators
5 combinators.short-circuit compiler.units effects.parser fry
6 generalizations kernel locals make math math.order namespaces
7 quotations sequences sets splitting unicode vectors
12 TUPLE: parse-result remaining ast ;
13 TUPLE: parse-error position got messages ;
14 TUPLE: parser peg compiled id ;
16 M: parser equal? { [ [ class-of ] same? ] [ [ id>> ] same? ] } 2&& ;
17 M: parser hashcode* id>> hashcode* ;
19 C: <parse-result> parse-result
20 C: <parse-error> parse-error
24 : merge-overlapping-errors ( a b -- c )
25 dupd [ messages>> ] bi@ union [ [ position>> ] [ got>> ] bi ] dip
28 : (merge-errors) ( a b -- c )
30 { [ over position>> not ] [ nip ] }
31 { [ dup position>> not ] [ drop ] }
33 2dup [ position>> ] compare {
36 { +eq+ [ merge-overlapping-errors ] }
42 error-stack get dup length 1 > [
43 [ pop ] [ pop swap (merge-errors) ] [ ] tri push
48 : add-error ( position got message -- )
49 <parse-error> error-stack get push ;
53 : ignore? ( obj -- ? )
56 : packrat ( id -- cache )
57 ! The packrat cache is a mapping of parser-id->cache.
58 ! For each parser it maps to a cache holding a mapping
59 ! of position->result. The packrat cache therefore keeps
60 ! track of all parses that have occurred at each position
61 ! of the input string and the results obtained from that
63 \ packrat get [ drop H{ } clone ] cache ;
71 ! A mapping from position->peg-head. It maps a
72 ! position in the input string being parsed to
73 ! the head of the left recursion which is currently
74 ! being grown. It is 'f' at any position where
75 ! left recursion growth is not underway.
78 : failed? ( obj -- ? )
81 : peg-cache ( -- cache )
82 ! Holds a hashtable mapping a peg tuple to
83 ! the parser tuple for that peg. The parser tuple
84 ! holds a unique id and the compiled form of that peg.
85 \ peg-cache get-global [
86 H{ } clone dup \ peg-cache set-global
90 H{ } clone \ peg-cache set-global ;
94 ! An entry in the table of memoized parse results
95 ! ast = an AST produced from the parse
96 ! or the symbol 'fail'
97 ! or a left-recursion object
98 ! pos = the position in the input string of this entry
99 TUPLE: memo-entry ans pos ;
101 TUPLE: left-recursion seed rule-id head next ;
102 TUPLE: peg-head rule-id involved-set eval-set ;
104 : rule-id ( word -- id )
105 ! A rule is the parser compiled down to a word. It has
106 ! a "peg-id" property containing the id of the original parser.
109 : input-slice ( -- slice )
110 ! Return a slice of the input from the current parse position
111 input get pos get tail-slice ;
113 : input-from ( input -- n )
114 ! Return the index from the original string that the
115 ! input slice is based on.
116 dup slice? [ from>> ] [ drop 0 ] if ;
118 : process-rule-result ( p result -- result )
120 nip [ ast>> ] [ remaining>> ] bi input-from pos namespaces:set
122 pos namespaces:set fail
125 : eval-rule ( rule -- ast )
126 ! Evaluate a rule, return an ast resulting from it.
127 ! Return fail if the rule failed. The rule has
128 ! stack effect ( -- parse-result )
129 pos get swap execute( -- parse-result ) process-rule-result ; inline
131 : memo ( pos id -- memo-entry )
132 ! Return the result from the memo cache.
135 : set-memo ( memo-entry pos id -- )
136 ! Store an entry in the cache
139 : update-m ( ast m -- )
140 swap >>ans pos get >>pos drop ;
142 : stop-growth? ( ast m -- ? )
143 [ failed? pos get ] dip pos>> <= or ;
145 : setup-growth ( h p -- )
146 pos namespaces:set dup involved-set>> clone >>eval-set drop ;
148 : (grow-lr) ( h p r: ( -- result ) m -- )
149 [ [ setup-growth ] 2keep ] 2dip
150 [ dup eval-rule ] dip swap
151 dup pick stop-growth? [
156 ] if ; inline recursive
158 : grow-lr ( h p r m -- ast )
159 [ [ heads set-at ] 2keep ] 2dip
160 pick over [ (grow-lr) ] 2dip
162 dup pos>> pos namespaces:set ans>>
165 :: (setup-lr) ( l s -- )
167 s left-recursion? [ s throw ] unless
168 s head>> l head>> eq? [
170 l head>> [ s rule-id>> suffix ] change-involved-set drop
171 l s next>> (setup-lr)
175 :: setup-lr ( r l -- )
177 r rule-id V{ } clone V{ } clone peg-head boa l head<<
179 l lrstack get (setup-lr) ;
181 :: lr-answer ( r p m -- ast )
183 h rule-id>> r rule-id eq? [
184 m ans>> seed>> m ans<<
194 :: recall ( r p -- memo-entry )
195 p r rule-id memo :> m
198 m r rule-id h involved-set>> h rule-id>> suffix member? not and [
199 fail p memo-entry boa
201 r rule-id h eval-set>> member? [
202 h [ r rule-id swap remove ] change-eval-set drop
214 :: apply-non-memo-rule ( r p -- ast )
215 fail r rule-id f lrstack get left-recursion boa :> lr
216 lr lrstack namespaces:set lr p memo-entry boa dup p r rule-id set-memo :> m
218 lrstack get next>> lrstack namespaces:set
221 m ans>> left-recursion? [
230 : apply-memo-rule ( r m -- ast )
231 [ ans>> ] [ pos>> ] bi pos namespaces:set
232 dup left-recursion? [
233 [ setup-lr ] keep seed>>
238 : apply-rule ( r p -- ast )
245 : with-packrat ( input quot -- result )
246 ! Run the quotation with a packrat cache active.
251 V{ } clone error-stack ,,
252 H{ } clone \ heads ,,
253 H{ } clone \ packrat ,,
254 ] H{ } make swap with-variables ; inline
256 GENERIC: (compile) ( peg -- quot )
258 : process-parser-result ( result -- result )
262 input-slice swap <parse-result>
265 : execute-parser ( word -- result )
266 pos get apply-rule process-parser-result ;
268 : preset-parser-word ( parser -- word parser )
269 gensym tuck >>compiled ;
271 : define-parser-word ( word parser -- )
272 ! Return the body of the word that is the compiled version
274 [ peg>> (compile) ( -- result ) define-declared ]
275 [ id>> "peg-id" set-word-prop ] 2bi ;
277 : compile-parser ( parser -- word )
278 ! Look to see if the given parser has been compiled.
279 ! If not, compile it to a temporary word, cache it,
280 ! and return it. Otherwise return the existing one.
281 ! Circular parsers are supported by getting the word
282 ! name and storing it in the cache, before compiling,
283 ! so it is picked up when re-entered.
287 preset-parser-word dupd define-parser-word
290 : compile-parser-quot ( parser -- quot )
291 compile-parser '[ _ execute-parser ] ;
293 : compile-parsers-quots ( parsers -- quots )
294 [ compile-parser-quot ] map dup rest-slice
295 [ '[ @ merge-errors ] ] map! drop ;
299 : fixup-delayed ( -- )
300 ! Work through all delayed parsers and recompile their
301 ! words to have the correct bodies.
303 call( -- parser ) compile-parser-quot ( -- result ) define-declared
306 : compile ( parser -- word )
309 compile-parser fixup-delayed
311 ] with-compilation-unit ;
313 : compiled-parse ( state word -- result )
316 [ error-stack get ?first [ throw ]
317 [ pos get input get f <parse-error> throw ] if* ] unless*
320 : (parse) ( input parser -- result )
321 compile compiled-parse ;
323 : parse ( input parser -- ast )
329 ! 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
336 peg-cache [ f next-id parser boa ] cache ;
338 TUPLE: token-parser symbol ;
340 : parse-token ( input string -- result )
341 ! Parse the string, returning a parse result
342 [ ?head-slice ] keep swap [
345 [ seq>> pos get swap ] dip "'" "'" surround 1vector add-error f
348 M: token-parser (compile)
349 symbol>> '[ input-slice _ parse-token ] ;
351 TUPLE: satisfy-parser quot ;
353 :: parse-satisfy ( input quot -- result/f )
355 unclip-slice dup quot call [
362 M: satisfy-parser (compile)
363 quot>> '[ input-slice _ parse-satisfy ] ;
365 TUPLE: range-parser min max ;
367 :: parse-range ( input min max -- result/f )
369 dup first min max between? [
370 unclip-slice <parse-result>
376 M: range-parser (compile)
377 [ min>> ] [ max>> ] bi '[ input-slice _ _ parse-range ] ;
379 TUPLE: seq-parser parsers ;
381 : calc-seq-result ( prev-result current-result -- next-result )
383 [ remaining>> >>remaining ] [ ast>> ] bi
384 dup ignore? [ drop ] [ over ast>> push ] if
389 : parse-seq-element ( result quot -- result )
390 '[ @ calc-seq-result ] [ f ] if* ; inline
392 M: seq-parser (compile)
393 parsers>> compile-parsers-quots
394 [ '[ _ parse-seq-element ] ] map
395 '[ input-slice V{ } clone <parse-result> _ 1&& ] ;
397 TUPLE: choice-parser parsers ;
399 M: choice-parser (compile)
400 parsers>> compile-parsers-quots '[ _ 0|| ] ;
402 TUPLE: repeat0-parser parser ;
404 : (repeat) ( quot: ( -- result/f ) result -- result )
406 [ remaining>> >>remaining ] [ ast>> ] bi
407 over ast>> push (repeat)
410 ] if* ; inline recursive
412 M: repeat0-parser (compile)
413 parser>> compile-parser-quot '[
414 input-slice V{ } clone <parse-result> _ swap (repeat)
417 TUPLE: repeat1-parser parser ;
419 : repeat1-empty-check ( result -- result )
420 [ dup ast>> empty? [ drop f ] when ] [ f ] if* ;
422 M: repeat1-parser (compile)
423 parser>> compile-parser-quot '[
424 input-slice V{ } clone <parse-result> _ swap (repeat)
428 TUPLE: optional-parser parser ;
430 : check-optional ( result -- result )
431 [ input-slice f <parse-result> ] unless* ;
433 M: optional-parser (compile)
434 parser>> compile-parser-quot '[ @ check-optional ] ;
436 TUPLE: semantic-parser parser quot ;
438 : check-semantic ( result quot -- result )
439 dupd '[ dup ast>> @ [ drop f ] unless ] when ; inline
441 M: semantic-parser (compile)
442 [ parser>> compile-parser-quot ] [ quot>> ] bi
443 '[ @ _ check-semantic ] ;
445 TUPLE: ensure-parser parser ;
447 : check-ensure ( old-input result -- result )
448 [ ignore <parse-result> ] [ drop f ] if ;
450 M: ensure-parser (compile)
451 parser>> compile-parser-quot '[ input-slice @ check-ensure ] ;
453 TUPLE: ensure-not-parser parser ;
455 : check-ensure-not ( old-input result -- result )
456 [ drop f ] [ ignore <parse-result> ] if ;
458 M: ensure-not-parser (compile)
459 parser>> compile-parser-quot '[ input-slice @ check-ensure-not ] ;
461 TUPLE: action-parser parser quot ;
463 : check-action ( result quot -- result )
464 dupd '[ [ _ call( ast -- ast ) ] change-ast ] when ;
466 M: action-parser (compile)
467 [ parser>> compile-parser-quot ] [ quot>> ] bi
468 '[ @ _ check-action ] ;
470 TUPLE: sp-parser parser ;
472 M: sp-parser (compile)
473 parser>> compile-parser-quot '[
474 input-slice [ blank? ] trim-head-slice input-from pos namespaces:set @
477 TUPLE: delay-parser quot ;
479 M: delay-parser (compile)
480 ! For efficiency we memoize the quotation.
481 ! This way it is run only once and the
482 ! parser constructed once at run time.
483 quot>> gensym [ delayed get set-at ] keep 1quotation ;
485 TUPLE: box-parser quot ;
487 M: box-parser (compile)
488 ! Calls the quotation at compile time
489 ! to produce the parser to be compiled.
490 ! This differs from 'delay' which calls
492 quot>> call( -- parser ) compile-parser-quot ;
496 : token ( string -- parser )
497 token-parser boa wrap-peg ;
499 : satisfy ( quot -- parser )
500 satisfy-parser boa wrap-peg ;
502 : range ( min max -- parser )
503 range-parser boa wrap-peg ;
505 : seq ( seq -- parser )
506 seq-parser boa wrap-peg ;
508 : 2seq ( parser1 parser2 -- parser )
511 : 3seq ( parser1 parser2 parser3 -- parser )
514 : 4seq ( parser1 parser2 parser3 parser4 -- parser )
517 : seq* ( quot -- parser )
518 { } make seq ; inline
520 : choice ( seq -- parser )
521 choice-parser boa wrap-peg ;
523 : 2choice ( parser1 parser2 -- parser )
526 : 3choice ( parser1 parser2 parser3 -- parser )
529 : 4choice ( parser1 parser2 parser3 parser4 -- parser )
532 : choice* ( quot -- parser )
533 { } make choice ; inline
535 : repeat0 ( parser -- parser )
536 repeat0-parser boa wrap-peg ;
538 : repeat1 ( parser -- parser )
539 repeat1-parser boa wrap-peg ;
541 : optional ( parser -- parser )
542 optional-parser boa wrap-peg ;
544 : semantic ( parser quot -- parser )
545 semantic-parser boa wrap-peg ;
547 : ensure ( parser -- parser )
548 ensure-parser boa wrap-peg ;
550 : ensure-not ( parser -- parser )
551 ensure-not-parser boa wrap-peg ;
553 : action ( parser quot -- parser )
554 action-parser boa wrap-peg ;
556 : sp ( parser -- parser )
557 sp-parser boa wrap-peg ;
559 : hide ( parser -- parser )
560 [ drop ignore ] action ;
562 : delay ( quot -- parser )
563 delay-parser boa wrap-peg ;
565 : box ( quot -- parser )
566 ! because a box has its quotation run at compile time
567 ! it must always have a new parser wrapper created,
568 ! not a cached one. This is because the same box,
569 ! compiled twice can have a different compiled word
570 ! due to running at compile time.
571 ! Why the [ ] action at the end? Box parsers don't get
572 ! memoized during parsing due to all box parsers being
573 ! unique. This breaks left recursion detection during the
574 ! parse. The action adds an indirection with a parser type
575 ! that gets memoized and fixes this. Need to rethink how
576 ! to fix boxes so this isn't needed...
577 box-parser boa f next-id parser boa [ ] action ;
579 ERROR: parse-failed input word ;
583 (:) :> ( word def effect )
586 def call compile :> compiled-def
588 dup compiled-def compiled-parse
589 [ ast>> ] [ word parse-failed ] ?if
590 ] effect define-declared
591 ] with-compilation-unit
595 { "debugger" "peg" } "peg.debugger" require-when