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