1 ! Copyright (C) 2007, 2008 Chris Double.
2 ! See https://factorcode.org/license.txt for BSD license.
4 USING: accessors arrays assocs classes combinators
5 combinators.short-circuit compiler.units effects.parser fry
6 kernel make math math.order namespaces quotations sequences
7 sets splitting unicode vectors vocabs.loader words ;
11 TUPLE: parse-result remaining ast ;
12 TUPLE: parse-error position got messages ;
13 TUPLE: parser peg compiled id ;
15 M: parser equal? { [ [ class-of ] same? ] [ [ id>> ] same? ] } 2&& ;
16 M: parser hashcode* id>> hashcode* ;
18 C: <parse-result> parse-result
19 C: <parse-error> parse-error
23 : merge-overlapping-errors ( a b -- c )
24 dupd [ messages>> ] bi@ union [ [ position>> ] [ got>> ] bi ] dip
27 : (merge-errors) ( a b -- c )
29 { [ over position>> not ] [ nip ] }
30 { [ dup position>> not ] [ drop ] }
32 2dup [ position>> ] compare {
35 { +eq+ [ merge-overlapping-errors ] }
41 error-stack get dup length 1 > [
42 [ pop ] [ pop swap (merge-errors) ] [ ] tri push
47 : add-error ( position got message -- )
48 <parse-error> error-stack get push ;
52 : ignore? ( obj -- ? )
55 : packrat ( id -- cache )
56 ! The packrat cache is a mapping of parser-id->cache.
57 ! For each parser it maps to a cache holding a mapping
58 ! of position->result. The packrat cache therefore keeps
59 ! track of all parses that have occurred at each position
60 ! of the input string and the results obtained from that
62 \ packrat get [ drop H{ } clone ] cache ;
70 ! A mapping from position->peg-head. It maps a
71 ! position in the input string being parsed to
72 ! the head of the left recursion which is currently
73 ! being grown. It is 'f' at any position where
74 ! left recursion growth is not underway.
77 : failed? ( obj -- ? )
80 : peg-cache ( -- cache )
81 ! Holds a hashtable mapping a peg tuple to
82 ! the parser tuple for that peg. The parser tuple
83 ! holds a unique id and the compiled form of that peg.
84 \ peg-cache get-global [
85 H{ } clone dup \ peg-cache set-global
89 H{ } clone \ peg-cache set-global ;
93 ! An entry in the table of memoized parse results
94 ! ast = an AST produced from the parse
95 ! or the symbol 'fail'
96 ! or a left-recursion object
97 ! pos = the position in the input string of this entry
98 TUPLE: memo-entry ans pos ;
100 TUPLE: left-recursion seed rule-id head next ;
101 TUPLE: peg-head rule-id involved-set eval-set ;
103 : rule-id ( word -- id )
104 ! A rule is the parser compiled down to a word. It has
105 ! a "peg-id" property containing the id of the original parser.
108 : input-slice ( -- slice )
109 ! Return a slice of the input from the current parse position
110 input get pos get tail-slice ;
112 : input-from ( input -- n )
113 ! Return the index from the original string that the
114 ! input slice is based on.
115 dup slice? [ from>> ] [ drop 0 ] if ;
117 : process-rule-result ( p result -- result )
119 nip [ ast>> ] [ remaining>> ] bi input-from pos namespaces:set
121 pos namespaces:set fail
124 : eval-rule ( rule -- ast )
125 ! Evaluate a rule, return an ast resulting from it.
126 ! Return fail if the rule failed. The rule has
127 ! stack effect ( -- parse-result )
128 pos get swap execute( -- parse-result ) process-rule-result ; inline
130 : memo ( pos id -- memo-entry )
131 ! Return the result from the memo cache.
134 : set-memo ( memo-entry pos id -- )
135 ! Store an entry in the cache
138 : update-m ( ast m -- )
139 swap >>ans pos get >>pos drop ;
141 : stop-growth? ( ast m -- ? )
142 [ failed? pos get ] dip pos>> <= or ;
144 : setup-growth ( h p -- )
145 pos namespaces:set dup involved-set>> clone >>eval-set drop ;
147 : (grow-lr) ( h p r: ( -- result ) m -- )
148 [ [ setup-growth ] 2keep ] 2dip
149 [ dup eval-rule ] dip swap
150 dup pick stop-growth? [
155 ] if ; inline recursive
157 : grow-lr ( h p r m -- ast )
158 [ [ heads set-at ] 2keep ] 2dip
159 pick over [ (grow-lr) ] 2dip
161 dup pos>> pos namespaces:set ans>>
164 :: (setup-lr) ( l s -- )
166 s left-recursion? [ s throw ] unless
167 s head>> l head>> eq? [
169 l head>> [ s rule-id>> suffix ] change-involved-set drop
170 l s next>> (setup-lr)
174 :: setup-lr ( r l -- )
176 r rule-id V{ } clone V{ } clone peg-head boa l head<<
178 l lrstack get (setup-lr) ;
180 :: lr-answer ( r p m -- ast )
182 h rule-id>> r rule-id eq? [
183 m ans>> seed>> m ans<<
193 :: recall ( r p -- memo-entry )
194 p r rule-id memo :> m
197 m r rule-id h involved-set>> h rule-id>> suffix member? not and [
198 fail p memo-entry boa
200 r rule-id h eval-set>> member? [
201 h [ r rule-id swap remove ] change-eval-set drop
213 :: apply-non-memo-rule ( r p -- ast )
214 fail r rule-id f lrstack get left-recursion boa :> lr
215 lr lrstack namespaces:set lr p memo-entry boa dup p r rule-id set-memo :> m
217 lrstack get next>> lrstack namespaces:set
220 m ans>> left-recursion? [
229 : apply-memo-rule ( r m -- ast )
230 [ ans>> ] [ pos>> ] bi pos namespaces:set
231 dup left-recursion? [
232 [ setup-lr ] keep seed>>
237 : apply-rule ( r p -- ast )
244 : with-packrat ( input quot -- result )
245 ! Run the quotation with a packrat cache active.
250 V{ } clone error-stack ,,
251 H{ } clone \ heads ,,
252 H{ } clone \ packrat ,,
253 ] H{ } make swap with-variables ; inline
255 GENERIC: (compile) ( peg -- quot )
257 : process-parser-result ( result -- result )
261 input-slice swap <parse-result>
264 : execute-parser ( word -- result )
265 pos get apply-rule process-parser-result ;
267 : preset-parser-word ( parser -- word parser )
268 gensym tuck >>compiled ;
270 : define-parser-word ( word parser -- )
271 ! Return the body of the word that is the compiled version
273 [ peg>> (compile) ( -- result ) define-declared ]
274 [ id>> "peg-id" set-word-prop ] 2bi ;
276 : compile-parser ( parser -- word )
277 ! Look to see if the given parser has been compiled.
278 ! If not, compile it to a temporary word, cache it,
279 ! and return it. Otherwise return the existing one.
280 ! Circular parsers are supported by getting the word
281 ! name and storing it in the cache, before compiling,
282 ! so it is picked up when re-entered.
286 preset-parser-word dupd define-parser-word
289 : compile-parser-quot ( parser -- quot )
290 compile-parser '[ _ execute-parser ] ;
292 : compile-parsers-quots ( parsers -- quots )
293 [ compile-parser-quot ] map dup rest-slice
294 [ '[ @ merge-errors ] ] map! drop ;
298 : fixup-delayed ( -- )
299 ! Work through all delayed parsers and recompile their
300 ! words to have the correct bodies.
302 call( -- parser ) compile-parser-quot ( -- result ) define-declared
305 : compile ( parser -- word )
308 compile-parser fixup-delayed
310 ] with-compilation-unit ;
312 : compiled-parse ( state word -- result )
315 [ error-stack get ?first [ throw ]
316 [ pos get input get f <parse-error> throw ] if* ] unless*
319 : (parse) ( input parser -- result )
320 compile compiled-parse ;
322 : parse ( input parser -- ast )
328 ! Return the next unique id for a parser
331 : wrap-peg ( peg -- parser )
332 ! Wrap a parser tuple around the peg object.
333 ! Look for an existing parser tuple for that
335 peg-cache [ f next-id parser boa ] cache ;
337 TUPLE: token-parser symbol ;
339 : parse-token ( input string -- result )
340 ! Parse the string, returning a parse result
341 [ ?head-slice ] keep swap [
344 [ seq>> pos get swap ] dip "'" "'" surround 1vector add-error f
347 M: token-parser (compile)
348 symbol>> '[ input-slice _ parse-token ] ;
350 TUPLE: satisfy-parser quot ;
352 :: parse-satisfy ( input quot -- result/f )
354 unclip-slice dup quot call [
361 M: satisfy-parser (compile)
362 quot>> '[ input-slice _ parse-satisfy ] ;
364 TUPLE: range-parser min max ;
366 :: parse-range ( input min max -- result/f )
368 dup first min max between? [
369 unclip-slice <parse-result>
375 M: range-parser (compile)
376 [ min>> ] [ max>> ] bi '[ input-slice _ _ parse-range ] ;
378 TUPLE: seq-parser parsers ;
380 : calc-seq-result ( prev-result current-result -- next-result )
382 [ remaining>> >>remaining ] [ ast>> ] bi
383 dup ignore? [ drop ] [ over ast>> push ] if
388 : parse-seq-element ( result quot -- result )
389 '[ @ calc-seq-result ] [ f ] if* ; inline
391 M: seq-parser (compile)
392 parsers>> compile-parsers-quots
393 [ '[ _ parse-seq-element ] ] map
394 '[ input-slice V{ } clone <parse-result> _ 1&& ] ;
396 TUPLE: choice-parser parsers ;
398 M: choice-parser (compile)
399 parsers>> compile-parsers-quots '[ _ 0|| ] ;
401 TUPLE: repeat0-parser parser ;
403 : (repeat) ( quot: ( -- result/f ) result -- result )
405 [ remaining>> >>remaining ] [ ast>> ] bi
406 over ast>> push (repeat)
409 ] if* ; inline recursive
411 M: repeat0-parser (compile)
412 parser>> compile-parser-quot '[
413 input-slice V{ } clone <parse-result> _ swap (repeat)
416 TUPLE: repeat1-parser parser ;
418 : repeat1-empty-check ( result -- result )
419 [ dup ast>> empty? [ drop f ] when ] [ f ] if* ;
421 M: repeat1-parser (compile)
422 parser>> compile-parser-quot '[
423 input-slice V{ } clone <parse-result> _ swap (repeat)
427 TUPLE: optional-parser parser ;
429 : check-optional ( result -- result )
430 [ input-slice f <parse-result> ] unless* ;
432 M: optional-parser (compile)
433 parser>> compile-parser-quot '[ @ check-optional ] ;
435 TUPLE: semantic-parser parser quot ;
437 : check-semantic ( result quot -- result )
438 dupd '[ dup ast>> @ [ drop f ] unless ] when ; inline
440 M: semantic-parser (compile)
441 [ parser>> compile-parser-quot ] [ quot>> ] bi
442 '[ @ _ check-semantic ] ;
444 TUPLE: ensure-parser parser ;
446 : check-ensure ( old-input result -- result )
447 [ ignore <parse-result> ] [ drop f ] if ;
449 M: ensure-parser (compile)
450 parser>> compile-parser-quot '[ input-slice @ check-ensure ] ;
452 TUPLE: ensure-not-parser parser ;
454 : check-ensure-not ( old-input result -- result )
455 [ drop f ] [ ignore <parse-result> ] if ;
457 M: ensure-not-parser (compile)
458 parser>> compile-parser-quot '[ input-slice @ check-ensure-not ] ;
460 TUPLE: action-parser parser quot ;
462 : check-action ( result quot -- result )
463 dupd '[ [ _ call( ast -- ast ) ] change-ast ] when ;
465 M: action-parser (compile)
466 [ parser>> compile-parser-quot ] [ quot>> ] bi
467 '[ @ _ check-action ] ;
469 TUPLE: sp-parser parser ;
471 M: sp-parser (compile)
472 parser>> compile-parser-quot '[
473 input-slice [ blank? ] trim-head-slice input-from pos namespaces:set @
476 TUPLE: delay-parser quot ;
478 M: delay-parser (compile)
479 ! For efficiency we memoize the quotation.
480 ! This way it is run only once and the
481 ! parser constructed once at run time.
482 quot>> gensym [ delayed get set-at ] keep 1quotation ;
484 TUPLE: box-parser quot ;
486 M: box-parser (compile)
487 ! Calls the quotation at compile time
488 ! to produce the parser to be compiled.
489 ! This differs from 'delay' which calls
491 quot>> call( -- parser ) compile-parser-quot ;
495 : token ( string -- parser )
496 token-parser boa wrap-peg ;
498 : satisfy ( quot -- parser )
499 satisfy-parser boa wrap-peg ;
501 : range ( min max -- parser )
502 range-parser boa wrap-peg ;
504 : seq ( seq -- parser )
505 seq-parser boa wrap-peg ;
507 : 2seq ( parser1 parser2 -- parser )
510 : 3seq ( parser1 parser2 parser3 -- parser )
513 : 4seq ( parser1 parser2 parser3 parser4 -- parser )
516 : seq* ( quot -- parser )
517 { } make seq ; inline
519 : choice ( seq -- parser )
520 choice-parser boa wrap-peg ;
522 : 2choice ( parser1 parser2 -- parser )
525 : 3choice ( parser1 parser2 parser3 -- parser )
528 : 4choice ( parser1 parser2 parser3 parser4 -- parser )
531 : choice* ( quot -- parser )
532 { } make choice ; inline
534 : repeat0 ( parser -- parser )
535 repeat0-parser boa wrap-peg ;
537 : repeat1 ( parser -- parser )
538 repeat1-parser boa wrap-peg ;
540 : optional ( parser -- parser )
541 optional-parser boa wrap-peg ;
543 : semantic ( parser quot -- parser )
544 semantic-parser boa wrap-peg ;
546 : ensure ( parser -- parser )
547 ensure-parser boa wrap-peg ;
549 : ensure-not ( parser -- parser )
550 ensure-not-parser boa wrap-peg ;
552 : action ( parser quot -- parser )
553 action-parser boa wrap-peg ;
555 : sp ( parser -- parser )
556 sp-parser boa wrap-peg ;
558 : hide ( parser -- parser )
559 [ drop ignore ] action ;
561 : delay ( quot -- parser )
562 delay-parser boa wrap-peg ;
564 : box ( quot -- parser )
565 ! because a box has its quotation run at compile time
566 ! it must always have a new parser wrapper created,
567 ! not a cached one. This is because the same box,
568 ! compiled twice can have a different compiled word
569 ! due to running at compile time.
570 ! Why the [ ] action at the end? Box parsers don't get
571 ! memoized during parsing due to all box parsers being
572 ! unique. This breaks left recursion detection during the
573 ! parse. The action adds an indirection with a parser type
574 ! that gets memoized and fixes this. Need to rethink how
575 ! to fix boxes so this isn't needed...
576 box-parser boa f next-id parser boa [ ] action ;
578 ERROR: parse-failed input word ;
582 (:) :> ( word def effect )
585 def call compile :> compiled-def
587 dup compiled-def compiled-parse
588 [ ast>> ] [ word parse-failed ] ?if
589 ] effect define-declared
590 ] with-compilation-unit
594 { "debugger" "peg" } "peg.debugger" require-when