-
Notifications
You must be signed in to change notification settings - Fork 25
/
esrap.lisp
1534 lines (1364 loc) · 59.8 KB
/
esrap.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;;; ESRAP -- a packrat parser for Common Lisp
;;;; by Nikodemus Siivola, 2007-2012
;;;;
;;;; Homepage and documentation:
;;;;
;;;; http://nikodemus.github.com/esrap/
;;;;
;;;; References:
;;;;
;;;; * Bryan Ford, 2002, "Packrat Parsing: a Practical Linear Time
;;;; Algorithm with Backtracking".
;;;; http://pdos.csail.mit.edu/~baford/packrat/thesis/
;;;;
;;;; Licence:
;;;;
;;;; Permission is hereby granted, free of charge, to any person
;;;; obtaining a copy of this software and associated documentation files
;;;; (the "Software"), to deal in the Software without restriction,
;;;; including without limitation the rights to use, copy, modify, merge,
;;;; publish, distribute, sublicense, and/or sell copies of the Software,
;;;; and to permit persons to whom the Software is furnished to do so,
;;;; subject to the following conditions:
;;;;
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
;;;; IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
;;;; CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
;;;; TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
;;;; SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(defpackage :esrap
(:use :cl :alexandria)
#+sbcl
(:lock t)
(:export
#:&bounds
#:! #:? #:+ #:* #:& #:~
#:character-ranges
#:add-rule
#:call-transform
#:change-rule
#:concat
#:defrule
#:describe-grammar
#:esrap-error
#:esrap-error-position
#:esrap-error-text
#:find-rule
#:invalid-expression-error
#:invalid-expression-error-expression
#:left-recursion
#:left-recursion-nonterminal
#:left-recursion-path
#:parse
#:remove-rule
#:rule
#:rule-dependencies
#:rule-expression
#:rule-symbol
#:text
#:trace-rule
#:untrace-rule
))
(in-package :esrap)
;;; Conditions
(define-condition invalid-expression-error (condition)
((expression :initarg :expression :reader invalid-expression-error-expression))
(:default-initargs
:expression (required-argument :expression))
(:documentation
"Signaled when an invalid expression is encountered."))
(defmethod print-object ((condition invalid-expression-error) stream)
(format stream "Invalid expression: ~S"
(invalid-expression-error-expression condition)))
(defun invalid-expression-error (expression)
(error 'invalid-expression-error :expression expression))
(define-condition esrap-error (parse-error)
((text :initarg :text :initform nil :reader esrap-error-text)
(position :initarg :position :initform nil :reader esrap-error-position))
(:documentation
"Signaled when an Esrap parse fails. Use ESRAP-ERROR-TEXT to obtain the
string that was being parsed, and ESRAP-ERROR-POSITION the position at which
the error occurred."))
(defmethod print-object ((condition esrap-error) stream)
(if *print-escape*
(call-next-method)
;; FIXME: this looks like it won't do the right thing when used as part of a
;; logical block.
(when (or (not *print-lines*) (> *print-lines* 1))
(if-let ((text (esrap-error-text condition))
(position (esrap-error-position condition)))
(let* ((line (count #\Newline text :end position))
(column (- position (or (position #\Newline text
:end position
:from-end t)
0)
1))
;; FIXME: magic numbers
(start (or (position #\Newline text
:start (max 0 (- position 32))
:end (max 0 (- position 24))
:from-end t)
(max 0 (- position 24))))
(end (min (length text) (+ position 24)))
(newline (or (position #\Newline text
:start start
:end position
:from-end t)
start))
(*print-circle* nil))
(format stream "~2& Encountered at:~% ~
~A~% ~
~V@T^ (Line ~D, Column ~D, Position ~D)~%"
(if (emptyp text)
""
(subseq text start end))
(- position newline)
(1+ line) (1+ column)
position))
(format stream "~2& <text and position not available>")))))
(define-condition simple-esrap-error (esrap-error simple-condition) ())
(defmethod print-object :before ((condition simple-esrap-error) stream)
(apply #'format stream
(simple-condition-format-control condition)
(simple-condition-format-arguments condition)))
(declaim (ftype (function (t t t &rest t) (values nil &optional))
simple-esrap-error))
(defun simple-esrap-error (text position format-control &rest format-arguments)
(error 'simple-esrap-error
:text text
:position position
:format-control format-control
:format-arguments format-arguments))
(define-condition left-recursion (esrap-error)
((nonterminal :initarg :nonterminal :initform nil :reader left-recursion-nonterminal)
(path :initarg :path :initform nil :reader left-recursion-path))
(:documentation
"Signaled when left recursion is detected during Esrap parsing.
LEFT-RECURSION-NONTERMINAL names the symbol for which left recursion was
detected, and LEFT-RECURSION-PATH lists nonterminals of which the left
recursion cycle consists."))
(defmethod print-object :before ((condition left-recursion) stream)
(format stream "Left recursion in nonterminal ~S. ~_Path: ~
~{~S~^ -> ~}"
(left-recursion-nonterminal condition)
(left-recursion-path condition)))
;;; Miscellany
(defun text (&rest arguments)
"Arguments must be strings, or lists whose leaves are strings.
Catenates all the strings in arguments into a single string."
(with-output-to-string (s)
(labels ((cat-list (list)
(dolist (elt list)
(etypecase elt
(string (write-string elt s))
(character (write-char elt s))
(list (cat-list elt))))))
(cat-list arguments))))
(setf (symbol-function 'concat) (symbol-function 'text))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun note-deprecated (old new)
(warn 'simple-style-warning
:format-control "~S is deprecated, use ~S instead."
:format-arguments (list old new))))
(define-compiler-macro concat (&whole form &rest arguments)
(declare (ignore arguments))
(note-deprecated 'concat 'text)
form)
(defun text/bounds (strings start end)
(declare (ignore start end))
(text strings))
(defun lambda/bounds (function)
(lambda (result start end)
(declare (ignore start end))
(funcall function result)))
(defun identity/bounds (identity start end)
(declare (ignore start end))
identity)
(defun parse-lambda-list-maybe-containing-&bounds (lambda-list)
"Parse &BOUNDS section in LAMBDA-LIST and return three values:
1. The standard lambda list sublist of LAMBDA-LIST
2. A symbol that should be bound to the start of a matching substring
3. A symbol that should be bound to the end of a matching substring
4. A list containing symbols that were GENSYM'ed.
The second and/or third values are GENSYMS if LAMBDA-LIST contains a
partial or no &BOUNDS section, in which case fourth value contains them
for use with IGNORE."
(let ((length (length lambda-list)))
(multiple-value-bind (lambda-list start end gensyms)
(cond
;; Look for &BOUNDS START END.
((and (>= length 3)
(eq (nth (- length 3) lambda-list) '&bounds))
(values (subseq lambda-list 0 (- length 3))
(nth (- length 2) lambda-list)
(nth (- length 1) lambda-list)
nil))
;; Look for &BOUNDS START.
((and (>= length 2)
(eq (nth (- length 2) lambda-list) '&bounds))
(let ((end (gensym "END")))
(values (subseq lambda-list 0 (- length 2))
(nth (- length 1) lambda-list)
end
(list end))))
;; No &BOUNDS section.
(t
(let ((start (gensym "START"))
(end (gensym "END")))
(values lambda-list
start
end
(list start end)))))
(check-type start symbol)
(check-type end symbol)
(values lambda-list start end gensyms))))
(deftype nonterminal ()
"Any symbol except CHARACTER and NIL can be used as a nonterminal symbol."
'(and symbol (not (member character nil))))
(deftype terminal ()
"Literal strings and characters are used as case-sensitive terminal symbols,
and expressions of the form \(~ <literal>) denote case-insensitive terminals."
`(or string character
(cons (eql ~) (cons (or string character) null))))
(deftype character-range ()
"A character range is either a single character or a list of two
characters."
`(or character
(cons character (cons character null))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *expression-kinds*
`((character . (eql character))
(character-ranges . (cons (eql character-ranges)))
(string . (cons (eql string) (cons array-length null)))
(and . (cons (eql and)))
(or . (cons (eql or)))
,@(mapcar (lambda (symbol)
`(,symbol . (cons (eql ,symbol) (cons t null))))
'(not * + ? & !))
(terminal . terminal)
(nonterminal . nonterminal)
(predicate . (cons symbol (cons (not null) null)))
(t . t))
"Names and corresponding types of acceptable expression
constructors."))
;;; RULE REPRESENTATION AND STORAGE
;;;
;;; For each rule, there is a RULE-CELL in *RULES*, whose %INFO slot has the
;;; function that implements the rule in car, and the rule object in CDR. A
;;; RULE object can be attached to only one non-terminal at a time, which is
;;; accessible via RULE-SYMBOL.
(defvar *rules* (make-hash-table))
(defun clear-rules ()
(clrhash *rules*)
nil)
(defstruct (rule-cell (:constructor
make-rule-cell
(symbol &aux (%info (cons (undefined-rule-function symbol) nil))))
(:conc-name cell-))
(%info (required-argument) :type (cons function t))
(trace-info nil)
(referents nil :type list))
(declaim (inline cell-function))
(defun cell-function (cell)
(car (cell-%info cell)))
(defun cell-rule (cell)
(cdr (cell-%info cell)))
(defun set-cell-info (cell function rule)
;; Atomic update
(setf (cell-%info cell) (cons function rule))
(let ())
cell)
(defun undefined-rule-function (symbol)
(lambda (&rest args)
(declare (ignore args))
(error "Undefined rule: ~S" symbol)))
(defun ensure-rule-cell (symbol)
(check-type symbol nonterminal)
;; FIXME: Need to lock *RULES*.
(or (gethash symbol *rules*)
(setf (gethash symbol *rules*)
(make-rule-cell symbol))))
(defun delete-rule-cell (symbol)
(remhash symbol *rules*))
(defun reference-rule-cell (symbol referent)
(let ((cell (ensure-rule-cell symbol)))
(when referent
(pushnew referent (cell-referents cell)))
cell))
(defun dereference-rule-cell (symbol referent)
(let ((cell (ensure-rule-cell symbol)))
(setf (cell-referents cell) (delete referent (cell-referents cell)))
cell))
(defun find-rule-cell (symbol)
(check-type symbol nonterminal)
(gethash symbol *rules*))
(defclass rule ()
((%symbol
:initform nil)
(%expression
:initarg :expression
:initform (required-argument :expression))
(%guard-expression
:initarg :guard-expression
:initform t
:reader rule-guard-expression)
;; Either T for rules that are always active (the common case),
;; NIL for rules that are never active, or a function to call
;; to find out if the rule is active or not.
(%condition
:initarg :condition
:initform t
:reader rule-condition)
(%transform
:initarg :transform
:initform nil
:reader rule-transform)
(%around
:initarg :around
:initform nil
:reader rule-around)))
(defun rule-symbol (rule)
"Returns the nonterminal associated with the RULE, or NIL of the rule
is not attached to any nonterminal."
(slot-value rule '%symbol))
(defun detach-rule (rule)
(dolist (dep (%rule-direct-dependencies rule))
(dereference-rule-cell dep (rule-symbol rule)))
(setf (slot-value rule '%symbol) nil))
(defmethod shared-initialize :after ((rule rule) slots &key)
(check-expression (rule-expression rule)))
(defmethod print-object ((rule rule) stream)
(print-unreadable-object (rule stream :type t :identity nil)
(let ((symbol (rule-symbol rule)))
(if symbol
(format stream "~S <- " symbol)
(format stream "(detached) ")))
(write (rule-expression rule) :stream stream)))
(defun sort-dependencies (symbol dependencies)
(let ((symbols (delete symbol dependencies))
(defined nil)
(undefined nil))
(dolist (sym symbols)
(if (find-rule sym)
(push sym defined)
(push sym undefined)))
(values defined undefined)))
(defun rule-dependencies (rule)
"Returns the dependencies of the RULE: primary value is a list of defined
nonterminal symbols, and secondary value is a list of undefined nonterminal
symbols."
(sort-dependencies
(rule-symbol rule) (%expression-dependencies (rule-expression rule) nil)))
(defun rule-direct-dependencies (rule)
(sort-dependencies
(rule-symbol rule) (%expression-direct-dependencies (rule-expression rule) nil)))
(defun %rule-direct-dependencies (rule)
(delete (rule-symbol rule) (%expression-direct-dependencies (rule-expression rule) nil)))
;;; Expression destructuring and validation
(defmacro with-expression ((expr lambda-list) &body body)
(let* ((type (car lambda-list))
(car-var (gensym "CAR"))
(fixed-list (cons car-var (cdr lambda-list))))
(once-only (expr)
`(destructuring-bind ,fixed-list ,expr
,(if (eq t type)
`(declare (ignore ,car-var))
`(unless (eq ',type ,car-var)
(error "~S-expression expected, got: ~S" ',type ,expr)))
(locally ,@body)))))
;;; MEMOIZATION CACHE
;;;
;;; Because each [rule, position] tuple has an unambiguous
;;; result per source text, we can cache this result -- this is what
;;; makes packrat parsing O(N).
;;;
;;; For now we just use EQUAL hash-tables, but a specialized
;;; representation would probably pay off.
(defvar *cache*)
(defun make-cache ()
(make-hash-table :test #'equal))
(defun get-cached (symbol position cache)
(gethash (cons symbol position) cache))
(defun (setf get-cached) (result symbol position cache)
(setf (gethash (cons symbol position) cache) result))
(defvar *nonterminal-stack* nil)
;;; SYMBOL, POSITION, and CACHE must all be lexical variables!
(defmacro with-cached-result ((symbol position &optional (text nil)) &body forms)
(with-gensyms (cache result)
`(let* ((,cache *cache*)
(,result (get-cached ,symbol ,position ,cache))
(*nonterminal-stack* (cons ,symbol *nonterminal-stack*)))
(cond ((eq t ,result)
(error 'left-recursion
:text ,text
:position ,position
:nonterminal ,symbol
:path (reverse *nonterminal-stack*)))
(,result
,result)
(t
;; First mark this pair with T to detect left-recursion,
;; then compute the result and cache that.
(setf (get-cached ,symbol ,position ,cache) t
(get-cached ,symbol ,position ,cache) (locally ,@forms)))))))
;;; RESULT REPRESENTATION
;;;
;;; We always return a result -- ERROR-RESULT for failed parses, and
;;; RESULT for successes.
;;;
;;; We implement a simple lazy evaluation for the productions. This is
;;; used to perform semantic actions only when necessary -- either
;;; when we call a semantic predicate or once parse has finished.
(defstruct error-result)
(defstruct (inactive-rule (:include error-result))
name)
(defstruct (failed-parse (:include error-result))
;; Expression that failed to match.
expression
;; Position at which match was attempted.
(position (required-argument) :type array-index)
;; A nested error, closer to actual failure site.
detail)
(defstruct (result (:constructor %make-result))
;; Either a list of results, whose first element is the production, or a
;; function to call that will return the production.
%production
;; Position after the match.
(position (required-argument) :type array-index))
(defmacro make-result (&rest arguments &key production &allow-other-keys)
(if production
(let ((args (copy-list arguments)))
(remf args :production)
`(%make-result ,@args
:%production ,(if (symbolp production)
`(list ,production)
`(lambda () ,production))))
`(%make-result ,@arguments)))
(defun result-production (result)
(let ((thunk (result-%production result)))
(if (functionp thunk)
(let ((value (funcall thunk)))
(setf (result-%production result) (list value))
value)
(car thunk))))
;;; MAIN INTERFACE
(defun parse (expression text &key (start 0) end junk-allowed)
"Parses TEXT using EXPRESSION from START to END. Incomplete parses
are allowed only if JUNK-ALLOWED is true."
;; There is no backtracking in the toplevel expression -- so there's
;; no point in compiling it as it will be executed only once -- unless
;; it's a constant, for which we have a compiler-macro.
(let ((end (or end (length text))))
(process-parse-result
(let ((*cache* (make-cache)))
(eval-expression expression text start end))
text
end
junk-allowed)))
(define-compiler-macro parse (&whole form expression &rest arguments
&environment env)
(if (constantp expression env)
(with-gensyms (expr-fun)
`(let ((,expr-fun (load-time-value (compile-expression ,expression))))
;; This inline-lambda here provides keyword defaults and
;; parsing, so the compiler-macro doesn't have to worry
;; about evaluation order.
((lambda (text &key (start 0) end junk-allowed)
(let ((*cache* (make-cache))
(end (or end (length text))))
(process-parse-result
(funcall ,expr-fun text start end)
text
end
junk-allowed)))
,@arguments)))
form))
(defun process-parse-result (result text end junk-allowed)
(if (error-result-p result)
(if junk-allowed
(values nil 0)
(if (failed-parse-p result)
(labels ((expressions (e)
(when e
(cons (failed-parse-expression e)
(expressions (failed-parse-detail e))))))
(let ((expressions (expressions result)))
(simple-esrap-error text (failed-parse-position result)
"Could not parse subexpression ~S when ~
parsing~2&~< Expression ~S~@{~& ~
Subexpression ~S~}~:>"
(lastcar expressions)
expressions)))
(simple-esrap-error text nil "rule ~S not active"
(inactive-rule-name result))))
(let ((position (result-position result)))
(values (result-production result)
(when (< position end)
(if junk-allowed
position
(simple-esrap-error text position "Incomplete parse.")))))))
(defmacro defrule (&whole form symbol expression &body options)
"Define SYMBOL as a nonterminal, using EXPRESSION as associated the parsing expression.
Following OPTIONS can be specified:
* (:WHEN TEST)
The rule is active only when TEST evaluates to true. This can be used
to specify optional extensions to a grammar.
* (:CONSTANT CONSTANT)
No matter what input is consumed or what EXPRESSION produces, the production
of the rule is always CONSTANT.
* (:FUNCTION FUNCTION)
If provided the production of the expression is transformed using
FUNCTION. FUNCTION can be a function name or a lambda-expression.
* (:IDENTITY BOOLEAN)
If true, the production of expression is used as-is, as if (:FUNCTION IDENTITY)
has been specified. If no production option is specified, this is the default.
* (:TEXT BOOLEAN)
If true, the production of expression is flattened and concatenated into a string
as if by (:FUNCTION TEXT) has been specified.
* (:LAMBDA LAMBDA-LIST &BODY BODY)
If provided, same as using the corresponding lambda-expression with :FUNCTION.
As an extension of the standard lambda list syntax, LAMBDA-LIST accepts
the optional pseudo lambda-list keyword ESRAP:&BOUNDS, which (1) must appear
after all standard lambda list keywords. (2) can be followed by one or two
variables to which bounding indexes of the matching substring are bound.
Therefore:
LAMBDA-LIST ::= (STANDARD-LAMBDA-LIST-ELEMENTS [&BOUNDS START [END]])
* (:DESTRUCTURE DESTRUCTURING-LAMBDA-LIST &BODY BODY)
If provided, same as using a lambda-expression that destructures its argument
using DESTRUCTURING-BIND and the provided lambda-list with :FUNCTION.
DESTRUCTURING-LAMBDA-LIST can use ESRAP:&BOUNDS in the same way
as described for :LAMBDA.
* (:AROUND ([&BOUNDS START [END]]) &BODY BODY)
If provided, execute BODY around the construction of the production of the
rule. BODY has to call ESRAP:CALL-TRANSFORM to trigger the computation of
the production. Any transformation provided via :LAMBDA, :FUNCTION
or :DESTRUCTURE is executed inside the call to ESRAP:CALL-TRANSFORM. As a
result, modification to the dynamic state are visible within the
transform.
ESRAP:&BOUNDS can be used in the same way as described for :LAMBDA
and :DESTRUCTURE.
This option can be used to safely track nesting depth, manage symbol
tables or for other stack-like operations.
"
(let ((transform nil)
(around nil)
(guard t)
(condition t)
(guard-seen nil))
(when options
(dolist (option options)
(flet ((set-transform (trans)
(if transform
(error "Multiple transforms in DEFRULE:~% ~S" form)
(setf transform trans)))
(set-guard (expr test)
(if guard-seen
(error "Multiple guards in DEFRULE:~% ~S" form)
(setf guard-seen t
guard expr
condition test))))
(destructuring-ecase option
((:when expr)
(when (cddr option)
(error "Multiple expressions in a :WHEN:~% ~S" form))
(if (constantp expr)
(if (eval expr)
(set-guard expr t)
(set-guard expr nil))
(set-guard expr `(lambda () ,expr))))
((:constant value)
(setf transform `(constantly ,value)))
((:concat value)
(note-deprecated :concat :text)
(when value
(setf transform '#'text/bounds)))
((:text value)
(when value
(setf transform '#'text/bounds)))
((:identity value)
(when value
(setf transform '#'identity/bounds)))
((:lambda lambda-list &body forms)
(multiple-value-bind (lambda-list start end ignore)
(parse-lambda-list-maybe-containing-&bounds lambda-list)
(setf transform
`(lambda (,@lambda-list ,start ,end)
(declare (ignore ,@ignore))
,@forms))))
((:function designator)
(setf transform `(lambda/bounds (function ,designator))))
((:destructure lambda-list &body forms)
(multiple-value-bind (lambda-list start end ignore)
(parse-lambda-list-maybe-containing-&bounds lambda-list)
(setf transform
(with-gensyms (production)
`(lambda (,production ,start ,end)
(declare (ignore ,@ignore))
(destructuring-bind ,lambda-list ,production
,@forms))))))
((:around lambda-list &body forms)
(multiple-value-bind (lambda-list start end ignore)
(parse-lambda-list-maybe-containing-&bounds lambda-list)
(assert (null lambda-list))
(setf around `(lambda (,start ,end transform)
(declare (ignore ,@ignore)
(function transform))
(flet ((call-transform ()
(funcall transform)))
,@forms)))))))))
`(eval-when (:load-toplevel :execute)
(add-rule ',symbol (make-instance 'rule
:expression ',expression
:guard-expression ',guard
:transform ,(or transform '#'identity/bounds)
:around ,around
:condition ,condition)))))
(defun add-rule (symbol rule)
"Associates RULE with the nonterminal SYMBOL. Signals an error if the
rule is already associated with a nonterminal. If the symbol is already
associated with a rule, the old rule is removed first."
;; FIXME: This needs locking and WITHOUT-INTERRUPTS.
(check-type symbol nonterminal)
(when (rule-symbol rule)
(error "~S is already associated with the nonterminal ~S -- remove it first."
rule (rule-symbol rule)))
(let* ((cell (ensure-rule-cell symbol))
(function (compile-rule symbol
(rule-expression rule)
(rule-condition rule)
(rule-transform rule)
(rule-around rule)))
(trace-info (cell-trace-info cell)))
(set-cell-info cell function rule)
(setf (cell-trace-info cell) nil)
(setf (slot-value rule '%symbol) symbol)
(when trace-info
(trace-rule symbol :break (second trace-info)))
symbol))
(defun find-rule (symbol)
"Returns rule designated by SYMBOL, if any. Symbol must be a nonterminal
symbol."
(check-type symbol nonterminal)
(let ((cell (find-rule-cell symbol)))
(when cell
(cell-rule cell))))
(defun remove-rule (symbol &key force)
"Makes the nonterminal SYMBOL undefined. If the nonterminal is defined an
already referred to by other rules, an error is signalled unless :FORCE is
true."
(check-type symbol nonterminal)
;; FIXME: Lock and WITHOUT-INTERRUPTS.
(let* ((cell (find-rule-cell symbol))
(rule (cell-rule cell))
(trace-info (cell-trace-info cell)))
(when cell
(flet ((frob ()
(set-cell-info cell (undefined-rule-function symbol) nil)
(when trace-info
(setf (cell-trace-info cell) (list (cell-%info cell) (second trace-info))))
(when rule
(detach-rule rule))))
(cond ((and rule (cell-referents cell))
(unless force
(error "Nonterminal ~S is used by other nonterminal~P:~% ~{~S~^, ~}"
symbol (length (cell-referents cell)) (cell-referents cell)))
(frob))
((not (cell-referents cell))
(frob)
;; There are no references to the rule at all, so
;; we can remove the cell.
(unless trace-info
(delete-rule-cell symbol)))))
rule)))
(defvar *trace-level* 0)
(defvar *trace-stack* nil)
(defun trace-rule (symbol &key recursive break)
"Turn on tracing of nonterminal SYMBOL. If RECURSIVE is true, turn
on tracing for the whole grammar rooted at SYMBOL. If BREAK is true,
break is entered when the rule is invoked."
(unless (member symbol *trace-stack* :test #'eq)
(let ((cell (find-rule-cell symbol)))
(unless cell
(error "Undefined rule: ~S" symbol))
(when (cell-trace-info cell)
(let ((*trace-stack* nil))
(untrace-rule symbol)))
(let ((fun (cell-function cell))
(rule (cell-rule cell))
(info (cell-%info cell)))
(set-cell-info cell
(lambda (text position end)
(when break
(break "rule ~S" symbol))
(let ((space (make-string *trace-level* :initial-element #\space))
(*trace-level* (+ 1 *trace-level*)))
(format *trace-output* "~&~A~D: ~S ~S? ~%"
space *trace-level* symbol position)
(finish-output *trace-output*)
(let ((result (funcall fun text position end)))
(if (error-result-p result)
(format *trace-output* "~&~A~D: ~S -|~%"
space *trace-level* symbol)
(format *trace-output* "~&~A~D: ~S ~S-~S -> ~S~%"
space *trace-level* symbol
position
(result-position result)
(result-production result)))
(finish-output *trace-output*)
result)))
rule)
(setf (cell-trace-info cell) (list info break)))
(when recursive
(let ((*trace-stack* (cons symbol *trace-stack*)))
(dolist (dep (%rule-direct-dependencies (cell-rule cell)))
(trace-rule dep :recursive t :break break))))
t)))
(defun untrace-rule (symbol &key recursive break)
"Turn off tracing of nonterminal SYMBOL. If RECURSIVE is true, untraces the
whole grammar rooted at SYMBOL. BREAK is ignored, and is provided only for
symmetry with TRACE-RULE."
(declare (ignore break))
(unless (member symbol *trace-stack* :test #'eq)
(let ((cell (find-rule-cell symbol)))
(unless cell
(error "Undefined rule: ~S" symbol))
(let ((trace-info (cell-trace-info cell)))
(when trace-info
(setf (cell-%info cell) (car trace-info)
(cell-trace-info cell) nil))
(when recursive
(let ((*trace-stack* (cons symbol *trace-stack*)))
(dolist (dep (%rule-direct-dependencies (cell-rule cell)))
(untrace-rule dep :recursive t))))))
nil))
(defun rule-expression (rule)
"Return the parsing expression associated with the RULE."
(slot-value rule '%expression))
(defun (setf rule-expression) (expression rule)
"Modify RULE to use EXPRESSION as the parsing expression. The rule must be
detached beforehand."
(let ((name (rule-symbol rule)))
(when name
(error "~@<Cannot change the expression of an active rule, ~
remove ~S first, or use CHANGE-RULE.~:@>"
name))
(setf (slot-value rule '%expression) expression)))
(defun change-rule (symbol expression)
"Modifies the nonterminal SYMBOL to use EXPRESSION instead. Temporarily
removes the rule while it is being modified."
(let ((rule (remove-rule symbol :force t)))
(unless rule
(error "~S is not a defined rule." symbol))
(setf (rule-expression rule) expression)
(add-rule symbol rule)))
(defun symbol-length (x)
(length (symbol-name x)))
(defun describe-grammar (symbol &optional (stream *standard-output*))
"Prints the grammar tree rooted at nonterminal SYMBOL to STREAM for human
inspection."
(check-type symbol nonterminal)
(let ((rule (find-rule symbol)))
(cond ((not rule)
(format stream "Symbol ~S is not a defined nonterminal." symbol))
(t
(format stream "~&Grammar ~S:~%" symbol)
(multiple-value-bind (defined undefined) (rule-dependencies rule)
(let ((length
(+ 4 (max (reduce #'max (mapcar #'symbol-length defined)
:initial-value 0)
(reduce #'max (mapcar #'symbol-length undefined)
:initial-value 0)))))
(format stream "~3T~S~VT<- ~S~@[ : ~S~]~%"
symbol length (rule-expression rule)
(when (rule-condition rule)
(rule-guard-expression rule)))
(when defined
(dolist (s defined)
(let ((dep (find-rule s)))
(format stream "~3T~S~VT<- ~S~@[ : ~S~]~%"
s length (rule-expression dep)
(when (rule-condition rule)
(rule-guard-expression rule))))))
(when undefined
(format stream "~%Undefined nonterminal~P:~%~{~3T~S~%~}"
(length undefined) undefined))))))))
;;; COMPILING RULES
(defvar *current-rule* nil)
(defun compile-rule (symbol expression condition transform around)
(declare (type (or boolean function) condition transform around))
(let* ((*current-rule* symbol)
;; Must bind *CURRENT-RULE* before compiling the expression!
(function (compile-expression expression))
(rule-not-active (when condition (make-inactive-rule :name symbol))))
(cond ((not condition)
(named-lambda inactive-rule (text position end)
(declare (ignore text position end))
rule-not-active))
(transform
(flet ((exec-rule/transform (text position end)
(let ((result (funcall function text position end)))
(if (error-result-p result)
(make-failed-parse
:expression symbol
:position (if (failed-parse-p result)
(failed-parse-position result)
position)
:detail result)
(if around
(make-result
:position (result-position result)
:production (flet ((call-rule ()
(funcall transform
(result-production result)
position
(result-position result))))
(funcall around position (result-position result) #'call-rule)))
(make-result
:position (result-position result)
:production (funcall transform
(result-production result)
position
(result-position result))))))))
(if (eq t condition)
(named-lambda rule/transform (text position end)
(with-cached-result (symbol position text)
(exec-rule/transform text position end)))
(named-lambda condition-rule/transform (text position end)
(with-cached-result (symbol position text)
(if (funcall condition)
(exec-rule/transform text position end)
rule-not-active))))))
(t
(if (eq t condition)
(named-lambda rule (text position end)
(with-cached-result (symbol position text)
(funcall function text position end)))
(named-lambda conditional-rule (text position end)
(with-cached-result (symbol position text)
(if (funcall condition)
(funcall function text position end)
rule-not-active))))))))
;;; EXPRESSION COMPILER & EVALUATOR
(eval-when (:compile-toplevel)
(defmacro expression-case (expression &body clauses)
"Similar to
(cl:typecase EXPRESSION CLAUSES)
but clause heads designate kinds of expressions instead of types. See
*EXPRESSION-KINDS*."
(let ((available (copy-list *expression-kinds*)))
(labels ((type-for-expression-kind (kind)
(if-let ((cell (assoc kind available)))
(progn
(removef available cell)
(cdr cell))
(error "Invalid or duplicate clause: ~S" kind)))
(process-clause (clause)
(destructuring-bind (kind &body body) clause
(etypecase kind
(cons
`((or ,@(mapcar #'type-for-expression-kind kind))
,@body))
(symbol
`(,(type-for-expression-kind kind)
,@body))))))
(let ((clauses (mapcar #'process-clause clauses)))
;; We did not provide clauses for all expression constructors
;; and did not specify a catch-all-clauses => error.
(when (and (assoc t available) (> (length available) 1))
(error "Unhandled expressions kinds: ~{~S~^, ~}"
(remove t (mapcar #'car available))))
;; If we did not specify a catch-all-clauses, insert one which
;; signals INVALID-EXPRESSION-ERROR.
(once-only (expression)
`(typecase ,expression
,@clauses
,@(when (assoc t available)
`((t (invalid-expression-error ,expression)))))))))))
(defun check-expression (expression)
(labels
((rec (expression)
(expression-case expression
((character string terminal nonterminal))
(character-ranges