]> gitweb.factorcode.org Git - factor.git/blob - basis/peg/peg.factor
1ac261494b372218c3b743b9121dae5ce78417e2
[factor.git] / basis / peg / peg.factor
1 ! Copyright (C) 2007, 2008 Chris Double.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays assocs classes combinators
4 combinators.short-circuit compiler.units effects.parser fry
5 generalizations kernel locals make math math.order namespaces
6 quotations sequences sets splitting unicode.categories vectors
7 words ;
8 IN: peg
9
10 TUPLE: parse-result remaining ast ;
11 TUPLE: parse-error position got messages ;
12 TUPLE: parser peg compiled id ;
13
14 M: parser equal? { [ [ class-of ] same? ] [ [ id>> ] same? ] } 2&& ;
15 M: parser hashcode* id>> hashcode* ;
16
17 C: <parse-result> parse-result
18 C: <parse-error>  parse-error
19
20 SYMBOL: error-stack
21
22 : merge-overlapping-errors ( a b -- c )
23     dupd [ messages>> ] bi@ union [ [ position>> ] [ got>> ] bi ] dip
24     <parse-error> ;
25
26 : (merge-errors) ( a b -- c )
27     {
28         { [ over position>> not ] [ nip ] }
29         { [ dup  position>> not ] [ drop ] }
30         [
31             2dup [ position>> ] compare {
32                 { +lt+ [ nip ] }
33                 { +gt+ [ drop ] }
34                 { +eq+ [ merge-overlapping-errors ] }
35             } case
36         ]
37     } cond ;
38
39 : merge-errors ( -- )
40     error-stack get dup length 1 >  [
41         dup pop over pop swap (merge-errors) swap push
42     ] [
43         drop
44     ] if ;
45
46 : add-error ( position got message -- )
47     <parse-error> error-stack get push ;
48
49 SYMBOL: ignore
50
51 : packrat ( id -- cache )
52     ! The packrat cache is a mapping of parser-id->cache.
53     ! For each parser it maps to a cache holding a mapping
54     ! of position->result. The packrat cache therefore keeps
55     ! track of all parses that have occurred at each position
56     ! of the input string and the results obtained from that
57     ! parser.
58     \ packrat get [ drop H{ } clone ] cache ;
59
60 SYMBOL: pos
61 SYMBOL: input
62 SYMBOL: fail
63 SYMBOL: lrstack
64
65 : heads ( -- cache )
66     ! A mapping from position->peg-head. It maps a
67     ! position in the input string being parsed to
68     ! the head of the left recursion which is currently
69     ! being grown. It is 'f' at any position where
70     ! left recursion growth is not underway.
71     \ heads get ;
72
73 : failed? ( obj -- ? )
74     fail = ;
75
76 : peg-cache ( -- cache )
77     ! Holds a hashtable mapping a peg tuple to
78     ! the parser tuple for that peg. The parser tuple
79     ! holds a unique id and the compiled form of that peg.
80     \ peg-cache get-global [
81         H{ } clone dup \ peg-cache set-global
82     ] unless* ;
83
84 : reset-pegs ( -- )
85     H{ } clone \ peg-cache set-global ;
86
87 reset-pegs
88
89 ! An entry in the table of memoized parse results
90 ! ast = an AST produced from the parse
91 !       or the symbol 'fail'
92 !       or a left-recursion object
93 ! pos = the position in the input string of this entry
94 TUPLE: memo-entry ans pos ;
95
96 TUPLE: left-recursion seed rule-id head next ;
97 TUPLE: peg-head rule-id involved-set eval-set ;
98
99 : rule-id ( word -- id )
100     ! A rule is the parser compiled down to a word. It has
101     ! a "peg-id" property containing the id of the original parser.
102     "peg-id" word-prop ;
103
104 : input-slice ( -- slice )
105     ! Return a slice of the input from the current parse position
106     input get pos get tail-slice ;
107
108 : input-from ( input -- n )
109     ! Return the index from the original string that the
110     ! input slice is based on.
111     dup slice? [ from>> ] [ drop 0 ] if ;
112
113 : process-rule-result ( p result -- result )
114     [
115         nip [ ast>> ] [ remaining>> ] bi input-from pos namespaces:set
116     ] [
117         pos namespaces:set fail
118     ] if* ;
119
120 : eval-rule ( rule -- ast )
121     ! Evaluate a rule, return an ast resulting from it.
122     ! Return fail if the rule failed. The rule has
123     ! stack effect ( -- parse-result )
124     pos get swap execute( -- parse-result ) process-rule-result ; inline
125
126 : memo ( pos id -- memo-entry )
127     ! Return the result from the memo cache.
128     packrat at ;
129
130 : set-memo ( memo-entry pos id -- )
131     ! Store an entry in the cache
132     packrat set-at ;
133
134 : update-m ( ast m -- )
135     swap >>ans pos get >>pos drop ;
136
137 : stop-growth? ( ast m -- ? )
138     [ failed? pos get ] dip
139     pos>> <= or ;
140
141 : setup-growth ( h p -- )
142     pos namespaces:set dup involved-set>> clone >>eval-set drop ;
143
144 : (grow-lr) ( h p r: ( -- result ) m -- )
145     [ [ setup-growth ] 2keep ] 2dip
146     [ dup eval-rule ] dip swap
147         dup pick stop-growth? [
148         5 ndrop
149     ] [
150         over update-m
151         (grow-lr)
152     ] if ; inline recursive
153
154 : grow-lr ( h p r m -- ast )
155     [ [ heads set-at ] 2keep ] 2dip
156     pick over [ (grow-lr) ] 2dip
157     swap heads delete-at
158     dup pos>> pos namespaces:set ans>>
159     ; inline
160
161 :: (setup-lr) ( l s -- )
162     s [
163         s left-recursion? [ s throw ] unless
164         s head>> l head>> eq? [
165             l head>> s head<<
166             l head>> [ s rule-id>> suffix ] change-involved-set drop
167             l s next>> (setup-lr)
168         ] unless
169     ] when ;
170
171 :: setup-lr ( r l -- )
172     l head>> [
173         r rule-id V{ } clone V{ } clone peg-head boa l head<<
174     ] unless
175     l lrstack get (setup-lr) ;
176
177 :: lr-answer ( r p m -- ast )
178     m ans>> head>> :> h
179     h rule-id>> r rule-id eq? [
180         m ans>> seed>> m ans<<
181         m ans>> failed? [
182             fail
183         ] [
184             h p r m grow-lr
185         ] if
186     ] [
187         m ans>> seed>>
188     ] if ; inline
189
190 :: recall ( r p -- memo-entry )
191     p r rule-id memo :> m
192     p heads at :> h
193     h [
194         m r rule-id h involved-set>> h rule-id>> suffix member? not and [
195             fail p memo-entry boa
196         ] [
197             r rule-id h eval-set>> member? [
198                 h [ r rule-id swap remove ] change-eval-set drop
199                 r eval-rule
200                 m update-m
201                 m
202             ] [
203                 m
204             ] if
205         ] if
206     ] [
207         m
208     ] if ; inline
209
210 :: apply-non-memo-rule ( r p -- ast )
211     fail r rule-id f lrstack get left-recursion boa :> lr
212     lr lrstack namespaces:set lr p memo-entry boa dup p r rule-id set-memo :> m
213     r eval-rule :> ans
214     lrstack get next>> lrstack namespaces:set
215     pos get m pos<<
216     lr head>> [
217         m ans>> left-recursion? [
218             ans lr seed<<
219             r p m lr-answer
220         ] [ ans ] if
221     ] [
222         ans m ans<<
223         ans
224     ] if ; inline
225
226 : apply-memo-rule ( r m -- ast )
227     [ ans>> ] [ pos>> ] bi pos namespaces:set
228     dup left-recursion? [
229         [ setup-lr ] keep seed>>
230     ] [
231         nip
232     ] if ;
233
234 : apply-rule ( r p -- ast )
235     2dup recall [
236         nip apply-memo-rule
237     ] [
238         apply-non-memo-rule
239     ] if* ; inline
240
241 : with-packrat ( input quot -- result )
242     ! Run the quotation with a packrat cache active.
243     [
244         swap input ,,
245         0 pos ,,
246         f lrstack ,,
247         V{ } clone error-stack ,,
248         H{ } clone \ heads ,,
249         H{ } clone \ packrat ,,
250     ] H{ } make swap with-variables ; inline
251
252 GENERIC: (compile) ( peg -- quot )
253
254 : process-parser-result ( result -- result )
255     dup failed? [
256         drop f
257     ] [
258         input-slice swap <parse-result>
259     ] if ;
260
261 : execute-parser ( word -- result )
262     pos get apply-rule process-parser-result ;
263
264 : preset-parser-word ( parser -- parser word )
265     gensym [ >>compiled ] keep ;
266
267 : define-parser-word ( parser word -- )
268     ! Return the body of the word that is the compiled version
269     ! of the parser.
270     2dup swap peg>> (compile) ( -- result ) define-declared
271     swap id>> "peg-id" set-word-prop ;
272
273 : compile-parser ( parser -- word )
274     ! Look to see if the given parser has been compiled.
275     ! If not, compile it to a temporary word, cache it,
276     ! and return it. Otherwise return the existing one.
277     ! Circular parsers are supported by getting the word
278     ! name and storing it in the cache, before compiling,
279     ! so it is picked up when re-entered.
280     dup compiled>> [
281         nip
282     ] [
283         preset-parser-word [ define-parser-word ] keep
284     ] if* ;
285
286 : compile-parser-quot ( parser -- quot )
287     compile-parser [ execute-parser ] curry ;
288
289 SYMBOL: delayed
290
291 : fixup-delayed ( -- )
292     ! Work through all delayed parsers and recompile their
293     ! words to have the correct bodies.
294     delayed get [
295         call( -- parser ) compile-parser-quot ( -- result ) define-declared
296     ] assoc-each ;
297
298 : compile ( parser -- word )
299     [
300         H{ } clone delayed [
301             compile-parser-quot ( -- result ) define-temp fixup-delayed
302         ] with-variable
303     ] with-compilation-unit ;
304
305 : compiled-parse ( state word -- result )
306     swap [
307         execute( -- result )
308         [ error-stack get ?first [ throw ]
309         [ pos get input get f <parse-error> throw ] if* ] unless*
310     ] with-packrat ;
311
312 : (parse) ( input parser -- result )
313     dup word? [ compile ] unless compiled-parse ;
314
315 : parse ( input parser -- ast )
316     (parse) ast>> ;
317
318 <PRIVATE
319
320 : next-id ( -- n )
321     ! Return the next unique id for a parser
322     \ next-id counter ;
323
324 : wrap-peg ( peg -- parser )
325     ! Wrap a parser tuple around the peg object.
326     ! Look for an existing parser tuple for that
327     ! peg object.
328     peg-cache [
329         f next-id parser boa
330     ] cache ;
331
332 TUPLE: token-parser symbol ;
333
334 : parse-token ( input string -- result )
335     ! Parse the string, returning a parse result
336     [ ?head-slice ] keep swap [
337         <parse-result>
338     ] [
339         [ seq>> pos get swap ] dip "'" "'" surround 1vector add-error f
340     ] if ;
341
342 M: token-parser (compile) ( peg -- quot )
343     symbol>> '[ input-slice _ parse-token ] ;
344
345 TUPLE: satisfy-parser quot ;
346
347 : parse-satisfy ( input quot -- result )
348     swap [
349         drop f
350     ] [
351         unclip-slice rot dupd call [
352             <parse-result>
353         ] [
354             2drop f
355         ] if
356     ] if-empty ; inline
357
358 M: satisfy-parser (compile)
359     quot>> '[ input-slice _ parse-satisfy ] ;
360
361 TUPLE: range-parser min max ;
362
363 : parse-range ( input min max -- result )
364     pick empty? [
365         3drop f
366     ] [
367         [ dup first ] 2dip between? [
368             unclip-slice <parse-result>
369         ] [
370             drop f
371         ] if
372     ] if ;
373
374 M: range-parser (compile)
375     [ min>> ] [ max>> ] bi '[ input-slice _ _ parse-range ] ;
376
377 TUPLE: seq-parser parsers ;
378
379 : ignore? ( ast -- bool )
380     ignore = ;
381
382 : calc-seq-result ( prev-result current-result -- next-result )
383     [
384         [ remaining>> swap remaining<< ] 2keep
385         ast>> dup ignore? [
386             drop
387         ] [
388             swap [ ast>> push ] keep
389         ] if
390     ] [
391         drop f
392     ] if* ;
393
394 : parse-seq-element ( result quot -- result )
395     over [
396         call calc-seq-result
397     ] [
398         2drop f
399     ] if ; inline
400
401 M: seq-parser (compile)
402     [
403         [ input-slice V{ } clone <parse-result> ] %
404         [
405             parsers>> unclip compile-parser-quot [ parse-seq-element ] curry ,
406             [ compile-parser-quot [ merge-errors ] compose [ parse-seq-element ] curry , ] each
407         ] { } make , \ 1&& ,
408     ] [ ] make ;
409
410 TUPLE: choice-parser parsers ;
411
412 M: choice-parser (compile)
413     [
414         [
415             parsers>> [ compile-parser-quot ] map
416             unclip , [ [ merge-errors ] compose , ] each
417         ] { } make , \ 0|| ,
418     ] [ ] make ;
419
420 TUPLE: repeat0-parser parser ;
421
422 : (repeat) ( quot: ( -- result ) result -- result )
423     over call [
424         [ remaining>> swap remaining<< ] 2keep
425         ast>> swap [ ast>> push ] keep
426         (repeat)
427     ] [
428         nip
429     ] if* ; inline recursive
430
431 M: repeat0-parser (compile)
432     parser>> compile-parser-quot '[
433         input-slice V{ } clone <parse-result> _ swap (repeat)
434     ] ;
435
436 TUPLE: repeat1-parser parser ;
437
438 : repeat1-empty-check ( result -- result )
439     [
440         dup ast>> empty? [ drop f ] when
441     ] [
442         f
443     ] if* ;
444
445 M: repeat1-parser (compile)
446     parser>> compile-parser-quot '[
447         input-slice V{ } clone <parse-result> _ swap (repeat)
448         repeat1-empty-check
449     ] ;
450
451 TUPLE: optional-parser parser ;
452
453 : check-optional ( result -- result )
454       [ input-slice f <parse-result> ] unless* ;
455
456 M: optional-parser (compile)
457       parser>> compile-parser-quot '[ @ check-optional ] ;
458
459 TUPLE: semantic-parser parser quot ;
460
461 : check-semantic ( result quot -- result )
462     over [
463         over ast>> swap call [ drop f ] unless
464     ] [
465         drop
466     ] if ; inline
467
468 M: semantic-parser (compile)
469     [ parser>> compile-parser-quot ] [ quot>> ] bi
470     '[ @ _ check-semantic ] ;
471
472 TUPLE: ensure-parser parser ;
473
474 : check-ensure ( old-input result -- result )
475     [ ignore <parse-result> ] [ drop f ] if ;
476
477 M: ensure-parser (compile)
478     parser>> compile-parser-quot '[ input-slice @ check-ensure ] ;
479
480 TUPLE: ensure-not-parser parser ;
481
482 : check-ensure-not ( old-input result -- result )
483     [ drop f ] [ ignore <parse-result> ] if ;
484
485 M: ensure-not-parser (compile)
486     parser>> compile-parser-quot '[ input-slice @ check-ensure-not ] ;
487
488 TUPLE: action-parser parser quot ;
489
490 : check-action ( result quot -- result )
491     over [
492         over ast>> swap call( ast -- ast ) >>ast
493     ] [
494         drop
495     ] if ;
496
497 M: action-parser (compile)
498     [ parser>> compile-parser-quot ] [ quot>> ] bi '[ @ _ check-action ] ;
499
500 TUPLE: sp-parser parser ;
501
502 M: sp-parser (compile)
503     parser>> compile-parser-quot '[
504         input-slice [ blank? ] trim-head-slice input-from pos namespaces:set @
505     ] ;
506
507 TUPLE: delay-parser quot ;
508
509 M: delay-parser (compile)
510     ! For efficiency we memoize the quotation.
511     ! This way it is run only once and the
512     ! parser constructed once at run time.
513     quot>> gensym [ delayed get set-at ] keep 1quotation ;
514
515 TUPLE: box-parser quot ;
516
517 M: box-parser (compile)
518     ! Calls the quotation at compile time
519     ! to produce the parser to be compiled.
520     ! This differs from 'delay' which calls
521     ! it at run time.
522     quot>> call( -- parser ) compile-parser-quot ;
523
524 PRIVATE>
525
526 : token ( string -- parser )
527     token-parser boa wrap-peg ;
528
529 : satisfy ( quot -- parser )
530     satisfy-parser boa wrap-peg ;
531
532 : range ( min max -- parser )
533     range-parser boa wrap-peg ;
534
535 : seq ( seq -- parser )
536     seq-parser boa wrap-peg ;
537
538 : 2seq ( parser1 parser2 -- parser )
539     2array seq ;
540
541 : 3seq ( parser1 parser2 parser3 -- parser )
542     3array seq ;
543
544 : 4seq ( parser1 parser2 parser3 parser4 -- parser )
545     4array seq ;
546
547 : seq* ( quot -- paser )
548     { } make seq ; inline
549
550 : choice ( seq -- parser )
551     choice-parser boa wrap-peg ;
552
553 : 2choice ( parser1 parser2 -- parser )
554     2array choice ;
555
556 : 3choice ( parser1 parser2 parser3 -- parser )
557     3array choice ;
558
559 : 4choice ( parser1 parser2 parser3 parser4 -- parser )
560     4array choice ;
561
562 : choice* ( quot -- paser )
563     { } make choice ; inline
564
565 : repeat0 ( parser -- parser )
566     repeat0-parser boa wrap-peg ;
567
568 : repeat1 ( parser -- parser )
569     repeat1-parser boa wrap-peg ;
570
571 : optional ( parser -- parser )
572     optional-parser boa wrap-peg ;
573
574 : semantic ( parser quot -- parser )
575     semantic-parser boa wrap-peg ;
576
577 : ensure ( parser -- parser )
578     ensure-parser boa wrap-peg ;
579
580 : ensure-not ( parser -- parser )
581     ensure-not-parser boa wrap-peg ;
582
583 : action ( parser quot -- parser )
584     action-parser boa wrap-peg ;
585
586 : sp ( parser -- parser )
587     sp-parser boa wrap-peg ;
588
589 : hide ( parser -- parser )
590     [ drop ignore ] action ;
591
592 : delay ( quot -- parser )
593     delay-parser boa wrap-peg ;
594
595 : box ( quot -- parser )
596     ! because a box has its quotation run at compile time
597     ! it must always have a new parser wrapper created,
598     ! not a cached one. This is because the same box,
599     ! compiled twice can have a different compiled word
600     ! due to running at compile time.
601     ! Why the [ ] action at the end? Box parsers don't get
602     ! memoized during parsing due to all box parsers being
603     ! unique. This breaks left recursion detection during the
604     ! parse. The action adds an indirection with a parser type
605     ! that gets memoized and fixes this. Need to rethink how
606     ! to fix boxes so this isn't needed...
607     box-parser boa f next-id parser boa [ ] action ;
608
609 ERROR: parse-failed input word ;
610
611 SYNTAX: PEG:
612     [let
613         (:) :> ( word def effect )
614         [
615             [
616                 def call compile :> compiled-def
617                 [
618                     dup compiled-def compiled-parse
619                     [ ast>> ] [ word parse-failed ] ?if
620                 ]
621                 word swap effect define-declared
622             ] with-compilation-unit
623         ] append!
624     ] ;
625
626 USE: vocabs.loader
627
628 { "debugger" "peg" } "peg.debugger" require-when