]> gitweb.factorcode.org Git - factor.git/blob - basis/peg/peg.factor
Fix comments to be ! not #!.
[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 set
116     ] [
117         pos 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 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 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 set lr p memo-entry boa dup p r rule-id set-memo :> m
213     r eval-rule :> ans
214     lrstack get next>> lrstack 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 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 [ execute( -- result ) [ error-stack get first throw ] unless* ] with-packrat ;
307
308 : (parse) ( input parser -- result )
309     dup word? [ compile ] unless compiled-parse ;
310
311 : parse ( input parser -- ast )
312     (parse) ast>> ;
313
314 <PRIVATE
315
316 : next-id ( -- n )
317     ! Return the next unique id for a parser
318     \ next-id counter ;
319
320 : wrap-peg ( peg -- parser )
321     ! Wrap a parser tuple around the peg object.
322     ! Look for an existing parser tuple for that
323     ! peg object.
324     peg-cache [
325         f next-id parser boa
326     ] cache ;
327
328 TUPLE: token-parser symbol ;
329
330 : parse-token ( input string -- result )
331     ! Parse the string, returning a parse result
332     [ ?head-slice ] keep swap [
333         <parse-result> f f f add-error
334     ] [
335         [ seq>> pos get swap ] dip "'" "'" surround 1vector add-error f
336     ] if ;
337
338 M: token-parser (compile) ( peg -- quot )
339     symbol>> '[ input-slice _ parse-token ] ;
340
341 TUPLE: satisfy-parser quot ;
342
343 : parse-satisfy ( input quot -- result )
344     swap dup empty? [
345         2drop f
346     ] [
347         unclip-slice rot dupd call [
348             <parse-result>
349         ] [
350             2drop f
351         ] if
352     ] if ; inline
353
354 M: satisfy-parser (compile)
355     quot>> '[ input-slice _ parse-satisfy ] ;
356
357 TUPLE: range-parser min max ;
358
359 : parse-range ( input min max -- result )
360     pick empty? [
361         3drop f
362     ] [
363         [ dup first ] 2dip between? [
364             unclip-slice <parse-result>
365         ] [
366             drop f
367         ] if
368     ] if ;
369
370 M: range-parser (compile)
371     [ min>> ] [ max>> ] bi '[ input-slice _ _ parse-range ] ;
372
373 TUPLE: seq-parser parsers ;
374
375 : ignore? ( ast -- bool )
376     ignore = ;
377
378 : calc-seq-result ( prev-result current-result -- next-result )
379     [
380         [ remaining>> swap remaining<< ] 2keep
381         ast>> dup ignore? [
382             drop
383         ] [
384             swap [ ast>> push ] keep
385         ] if
386     ] [
387         drop f
388     ] if* ;
389
390 : parse-seq-element ( result quot -- result )
391     over [
392         call calc-seq-result
393     ] [
394         2drop f
395     ] if ; inline
396
397 M: seq-parser (compile)
398     [
399         [ input-slice V{ } clone <parse-result> ] %
400         [
401             parsers>> unclip compile-parser-quot [ parse-seq-element ] curry ,
402             [ compile-parser-quot [ merge-errors ] compose [ parse-seq-element ] curry , ] each
403         ] { } make , \ 1&& ,
404     ] [ ] make ;
405
406 TUPLE: choice-parser parsers ;
407
408 M: choice-parser (compile)
409     [
410         [
411             parsers>> [ compile-parser-quot ] map
412             unclip , [ [ merge-errors ] compose , ] each
413         ] { } make , \ 0|| ,
414     ] [ ] make ;
415
416 TUPLE: repeat0-parser parser ;
417
418 : (repeat) ( quot: ( -- result ) result -- result )
419     over call [
420         [ remaining>> swap remaining<< ] 2keep
421         ast>> swap [ ast>> push ] keep
422         (repeat)
423     ] [
424         nip
425     ] if* ; inline recursive
426
427 M: repeat0-parser (compile)
428     parser>> compile-parser-quot '[
429         input-slice V{ } clone <parse-result> _ swap (repeat)
430     ] ;
431
432 TUPLE: repeat1-parser parser ;
433
434 : repeat1-empty-check ( result -- result )
435     [
436         dup ast>> empty? [ drop f ] when
437     ] [
438         f
439     ] if* ;
440
441 M: repeat1-parser (compile)
442     parser>> compile-parser-quot '[
443         input-slice V{ } clone <parse-result> _ swap (repeat)
444         repeat1-empty-check
445     ] ;
446
447 TUPLE: optional-parser parser ;
448
449 : check-optional ( result -- result )
450       [ input-slice f <parse-result> ] unless* ;
451
452 M: optional-parser (compile)
453       parser>> compile-parser-quot '[ @ check-optional ] ;
454
455 TUPLE: semantic-parser parser quot ;
456
457 : check-semantic ( result quot -- result )
458     over [
459         over ast>> swap call [ drop f ] unless
460     ] [
461         drop
462     ] if ; inline
463
464 M: semantic-parser (compile)
465     [ parser>> compile-parser-quot ] [ quot>> ] bi
466     '[ @ _ check-semantic ] ;
467
468 TUPLE: ensure-parser parser ;
469
470 : check-ensure ( old-input result -- result )
471     [ ignore <parse-result> ] [ drop f ] if ;
472
473 M: ensure-parser (compile)
474     parser>> compile-parser-quot '[ input-slice @ check-ensure ] ;
475
476 TUPLE: ensure-not-parser parser ;
477
478 : check-ensure-not ( old-input result -- result )
479     [ drop f ] [ ignore <parse-result> ] if ;
480
481 M: ensure-not-parser (compile)
482     parser>> compile-parser-quot '[ input-slice @ check-ensure-not ] ;
483
484 TUPLE: action-parser parser quot ;
485
486 : check-action ( result quot -- result )
487     over [
488         over ast>> swap call( ast -- ast ) >>ast
489     ] [
490         drop
491     ] if ;
492
493 M: action-parser (compile)
494     [ parser>> compile-parser-quot ] [ quot>> ] bi '[ @ _ check-action ] ;
495
496 TUPLE: sp-parser parser ;
497
498 M: sp-parser (compile)
499     parser>> compile-parser-quot '[
500         input-slice [ blank? ] trim-head-slice input-from pos set @
501     ] ;
502
503 TUPLE: delay-parser quot ;
504
505 M: delay-parser (compile)
506     ! For efficiency we memoize the quotation.
507     ! This way it is run only once and the
508     ! parser constructed once at run time.
509     quot>> gensym [ delayed get set-at ] keep 1quotation ;
510
511 TUPLE: box-parser quot ;
512
513 M: box-parser (compile)
514     ! Calls the quotation at compile time
515     ! to produce the parser to be compiled.
516     ! This differs from 'delay' which calls
517     ! it at run time.
518     quot>> call( -- parser ) compile-parser-quot ;
519
520 PRIVATE>
521
522 : token ( string -- parser )
523     token-parser boa wrap-peg ;
524
525 : satisfy ( quot -- parser )
526     satisfy-parser boa wrap-peg ;
527
528 : range ( min max -- parser )
529     range-parser boa wrap-peg ;
530
531 : seq ( seq -- parser )
532     seq-parser boa wrap-peg ;
533
534 : 2seq ( parser1 parser2 -- parser )
535     2array seq ;
536
537 : 3seq ( parser1 parser2 parser3 -- parser )
538     3array seq ;
539
540 : 4seq ( parser1 parser2 parser3 parser4 -- parser )
541     4array seq ;
542
543 : seq* ( quot -- paser )
544     { } make seq ; inline
545
546 : choice ( seq -- parser )
547     choice-parser boa wrap-peg ;
548
549 : 2choice ( parser1 parser2 -- parser )
550     2array choice ;
551
552 : 3choice ( parser1 parser2 parser3 -- parser )
553     3array choice ;
554
555 : 4choice ( parser1 parser2 parser3 parser4 -- parser )
556     4array choice ;
557
558 : choice* ( quot -- paser )
559     { } make choice ; inline
560
561 : repeat0 ( parser -- parser )
562     repeat0-parser boa wrap-peg ;
563
564 : repeat1 ( parser -- parser )
565     repeat1-parser boa wrap-peg ;
566
567 : optional ( parser -- parser )
568     optional-parser boa wrap-peg ;
569
570 : semantic ( parser quot -- parser )
571     semantic-parser boa wrap-peg ;
572
573 : ensure ( parser -- parser )
574     ensure-parser boa wrap-peg ;
575
576 : ensure-not ( parser -- parser )
577     ensure-not-parser boa wrap-peg ;
578
579 : action ( parser quot -- parser )
580     action-parser boa wrap-peg ;
581
582 : sp ( parser -- parser )
583     sp-parser boa wrap-peg ;
584
585 : hide ( parser -- parser )
586     [ drop ignore ] action ;
587
588 : delay ( quot -- parser )
589     delay-parser boa wrap-peg ;
590
591 : box ( quot -- parser )
592     ! because a box has its quotation run at compile time
593     ! it must always have a new parser wrapper created,
594     ! not a cached one. This is because the same box,
595     ! compiled twice can have a different compiled word
596     ! due to running at compile time.
597     ! Why the [ ] action at the end? Box parsers don't get
598     ! memoized during parsing due to all box parsers being
599     ! unique. This breaks left recursion detection during the
600     ! parse. The action adds an indirection with a parser type
601     ! that gets memoized and fixes this. Need to rethink how
602     ! to fix boxes so this isn't needed...
603     box-parser boa f next-id parser boa [ ] action ;
604
605 ERROR: parse-failed input word ;
606
607 SYNTAX: PEG:
608     [let
609         (:) :> ( word def effect )
610         [
611             [
612                 def call compile :> compiled-def
613                 [
614                     dup compiled-def compiled-parse
615                     [ ast>> ] [ word parse-failed ] ?if
616                 ]
617                 word swap effect define-declared
618             ] with-compilation-unit
619         ] append!
620     ] ;
621
622 USE: vocabs.loader
623
624 { "debugger" "peg" } "peg.debugger" require-when