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