Source

HH-Parse / grammar.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
;; Copyright (c) 2010 Phil Hargett

;; 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 above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.

;; 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.

(in-package :hh-parse)

;; ---------------------------------------------------------------------------------------------------------------------
;; Grammar specifications

(defvar *new-rules* nil "New rules under construction")
(defvar *next-rule-number* 0 "Used for creating unique rule names")

(defun genrulesym (name &optional (*package* *package*))
  (intern (format nil "~a~a" name (incf *next-rule-number*)) *package*))

(defun rule-spec-rule-name (rule)
  (destructuring-bind (rule-name options &rest rhss) rule
    (declare (ignorable options rhss))
    rule-name))

(defun rule-spec-rule-options (rule)
  (destructuring-bind (rule-name options &rest rhss) rule
    (declare (ignorable rule-name rhss))
    options))

(defun rule-spec-rule-rhss (rule)
  (destructuring-bind (rule-name options &rest rhss) rule
    (declare (ignorable rule-name options))
    rhss))

(defun rule-spec-rule-slots (rule)
  "From a rule specification find all of the slots for which there are captures (eg., = or +=)"
  (let ((slots ()))
    (labels ((collect-captures (term)
	       (cond ((and (listp term) (or (eql '= (car term)) (eql '+= (car term))))
		      (push (cadr term) slots))
		     ((listp term)
		      (loop for child-term in term
			 do (collect-captures child-term)))
		     (t t))))
      (loop for rhs in (rule-spec-rule-rhss rule)
	 do (collect-captures rhs))
      (reverse slots))))

(defun capture-compoundtermp (term)
  (and (listp term) (member (car term) '(= +=))))

(defun noncapture-compoundtermp (term)
  (and (listp term) (member (car term) '(+ ? * ^))))

(defun compoundtermp (term)
  (or (capture-compoundtermp term) (noncapture-compoundtermp term)))

(defun make-new-named-rule (rule-name options rhss) 	       
  (let ((rule (cons rule-name (cons options rhss))))
    (setf *new-rules*
	  (append *new-rules* (list rule)))
    rule-name))

(defun for-each-rule (grammar rule-func)
  (loop for rule in grammar
     collect (or (funcall rule-func rule) rule)))

(defun for-each-rhs (grammar rhs-func)
  (for-each-rule grammar
		 #'(lambda (rule)
		     (destructuring-bind (rule-name options &rest rhss) rule
		       (cons rule-name (cons options 
					     (loop for rhs in rhss
						collect (or (funcall rhs-func rhs) rhs))))))))

(defun set-captured-value (parser slot value)
  (setf (captures parser) 
	(cons (list slot value) 
	      (loop for capture in (captures parser)
		 for (captured-slot captured-value) = capture
		 unless (equal captured-slot slot)
		 collect (list captured-slot captured-value)))))

(defun append-captured-value (parser slot value)
  (setf (captures parser) 
	(loop for capture in (captures parser)
	   for (captured-slot captured-value) = capture
	   if (equal captured-slot slot)
	   collect (list captured-slot (if (listp captured-value)
					   (cons value captured-value)
					   (list value captured-value)))
	   else 
	   collect (list captured-slot (list captured-value)))))

(defun augment-grammar (start-rule-name grammar)
  (let ((augmented-start-rule-name (genrulesym "START-")))
    (values augmented-start-rule-name (cons `(,augmented-start-rule-name () (,start-rule-name)) grammar))))

(defun transform-term (term)
  (cond ((null term) term)
	((not (listp term)) term)
	(t ;; some kind of list
	 ;; checking compound terms first
	 (let ((term-type (car term)))
	   (cond ((eq term-type '+)
		  (let* ((repeat-body (transform-term (cdr term)))
			 (repeat-rule-name (genrulesym "REPEAT-")))
		    (make-new-named-rule repeat-rule-name () `( (,repeat-rule-name ,@repeat-body)
							     (,@repeat-body)) )))
		 ((eq term-type '*)
		  ;; cheating here--reusing the ? and + transformations
		  (transform-term `(? (+ ,@(transform-term (cdr term))))) )
		 ((eq term-type '=)
		  ;; TODO here's where we need to figure out the name of the value (e.g., the slot name)
		  ;; to capture, and set things up so we do--perhaps in reduce?
		  (let* ((capture-slot (cadr term)) ;; slot name is 1st after the =
			 (capture-body (transform-term (cddr term))) 
			 (capture-rule-name (genrulesym "CAPTURE-")))
		    (make-new-named-rule capture-rule-name 
					 `(reduction (lambda (parser rule-name arg) 
						       ;; note that with the above signature we expect only 1 arg
						       ;; that means terms like (= a b c) are not valid, only (= a b)
						       (let ((reduced-term (make-instance rule-name)))
							 (set-captured-value parser ',capture-slot (value-of arg))
							 reduced-term)))
					 `(,capture-body))))
		 ((eq term-type '+=)
		  (let* ((capture-slot (cadr term)) ;; slot name is 1st after the =
			 (capture-body (transform-term (cddr term))) 
			 (capture-rule-name (genrulesym "CAPTURE-")))
		    (make-new-named-rule capture-rule-name 
					 `(reduction (lambda (parser rule-name arg) 
						       ;; note that with the above signature we expect only 1 arg
						       ;; that means terms like (+= a b c) are not valid, only (+= a b)
						       (let ((reduced-term (make-instance rule-name)))
							 (append-captured-value parser ',capture-slot (value-of arg))
							 reduced-term)))
					 `(,capture-body))))
		 ((eq term-type '^)
		  (let* ((alternate-body (transform-term (cdr term))) 
			 (alternate-rule-name (genrulesym "ALTERNATE-")))
		    (make-new-named-rule alternate-rule-name ()
					 (loop for alternate in alternate-body
					    collect (if (listp alternate) alternate (list alternate))))))
		 ((eq term-type '?)
		  (let* ((optional-body (transform-term (cdr term)))
			 (optional-rule-name (genrulesym "OPTIONAL-")))
		    (make-new-named-rule optional-rule-name () `( ( ,@optional-body)
							       ( :nil)) )))
		 (t ;; ordinary list, term list, or group--take your pick of language
		  (loop for item in term
		     collect (transform-term item))))))))

(defun transform-rhs (rhs)
  (let ((new-rhs (cond ((null rhs) rhs)
		       ((compoundtermp rhs)
			(transform-term rhs))
		       (t (loop for term in rhs
			     ;; this is important--we don't treat
			     ;; an rhs as a term, because then we couldn't recognize
			     ;; groups as a simple termlist--couldn't know difference
			     collect (transform-term term))))))
    (if (listp new-rhs) new-rhs (list new-rhs)))) ;; make sure it's always a list

(defun transform-for-nil (start-rule-name grammar)
  "Transform the grammar as needed to remove all occurrences of nil"
  (let ((nilable ())
	(transforming nil)
	(new-grammar grammar))
    (labels ((term-expansions (term)
	       "Return a list of term expansions (including :nil)"
	       (let ((rule (assoc term grammar)))
		 (rule-spec-rule-rhss rule)))
	     (expand-term (term-list position expansion)
	       (loop for index from 0 below (length term-list)
		  if (= position index) 
		  collect expansion 
		  else 
		  collect (elt term-list index)))
	     (flatten (term-list)
	       (loop for term in term-list
		    if (listp term)
		    append term
		    else append (list term)))
	     (nilable-p (term grammar)
	       "A term is nilable if we have already identified it as such, or if 
                one of it's RHS is (:nil); we remember that a rule is nilable,
                to simplify future checks"
	       (if (member term nilable)
		   t  ;; already known to be nilable
		   (let ((rule (assoc term grammar)))
		     (when rule ;; terminals are not nilable
		       (let ((rhss (rule-spec-rule-rhss rule)))
			 (when (member `(:nil) rhss :test #'equal)
			   (progn
			     (push term nilable)
			     ;; setting this, too, in case this changes
			     ;; how we handle RHSs we have already seen--so
			     ;; will have to go 'round again
			     (setf transforming t)
			     t)))))))
	     (compute-nilable-terms (grammar)
	       (loop for rule in grammar
		  do (nilable-p (rule-spec-rule-name rule) grammar)))
	     (substitute-and-split-rhss (grammar)
	       (for-each-rule grammar
			      #'(lambda (rule)
				  (destructuring-bind (rule-name options &rest rhss) rule
				    (let ((new-rhss ()))
				      (loop for rhs in rhss
					 with expanded = nil
					 do (loop for position from 0 below (length rhs)
					       for term = (elt rhs position)
					       if (nilable-p term grammar)
					       do (loop for expansion in (term-expansions term)
						     for expanded-rhs = (flatten (expand-term rhs position expansion))
						     do (progn 
							  (setf expanded t)
							  (setf transforming t)
							  (push expanded-rhs new-rhss))))
					 unless expanded do (push rhs new-rhss))
				      (cons rule-name 
					    (cons options
						  ;; ensure uniques
						  (loop for rhs in (reverse new-rhss)
						     unless (member rhs unique-rhs :test #'equal)
						     collect rhs into unique-rhs
						     finally (return unique-rhs)))))))))
	     (collapse-nils (grammar)
	       (for-each-rhs grammar
			     #'(lambda (rhs)
				 (or (loop for term in rhs
					  unless (equal :nil term)
					  collect term)
				     `(:nil)))))

	     (remove-unused-rules (start-rule-name grammar)
	       "After all of the :nil substitutions have been made, it is reasonable that some rules
                may no longer be used anywhere; let's just drop them, to simplify table development"
	       ;; TODO gotta pass in the start rule, otherwise it gets removed also!
	       (loop for rule in grammar
		  for rule-name = (rule-spec-rule-name rule)
		  if (or (equal rule-name start-rule-name)
			 (loop for any-rule in grammar
			    with used = nil
			    do (loop for any-rhs in (rule-spec-rule-rhss any-rule)
				  if (member rule-name any-rhs :test #'equal)
				  do (setf used t))
			    until used
			    finally (return used)))
		  collect rule)))
      (loop ;; for i from 1 to 10
      	 do (setf transforming nil)
      	 do (progn
	      (setf new-grammar (substitute-and-split-rhss new-grammar))
	      (setf new-grammar (collapse-nils new-grammar))
	      (compute-nilable-terms new-grammar))
      	 while transforming)

      (setf new-grammar (remove-unused-rules start-rule-name new-grammar))
      new-grammar)))

(defun transform-for-captures (grammar)
  (for-each-rule grammar
		 #'(lambda (rule)
		     (let ((slots (rule-spec-rule-slots rule))
			   (options (rule-spec-rule-options rule))
			   (rule-name (rule-spec-rule-name rule))
			   (rhss (rule-spec-rule-rhss rule)))
		       (cons rule-name (cons (append `(slots ,slots) options) rhss))))))

(defun transform-extended-grammar-to-fundamental (start-rule-name grammar ) 
  ;; TODO this could be done in a pipeline model where different stages evolve the grammar
  ;; independently, but use (and depend upon) the input of the prior stage
  (transform-for-nil start-rule-name
		     (let ((*new-rules* nil))
		       (append (for-each-rhs (transform-for-captures grammar)
					      #'(lambda (rhs)		      
						  (transform-rhs (if (listp rhs) rhs (list rhs)))))
			       *new-rules*))))

;; ---------------------------------------------------------------------------------------------------------------------
;; LALR(1) grammar construction

;; helper
(defmacro equal-slots ( (&rest slots) left right &key ((:test test) ''equal)) 
  `(and ,@(loop for slot in slots
	     collect `(funcall ,test (slot-value ,left ',slot) (slot-value ,right ',slot)))))

;; Classes + types

;; printing

(defgeneric print-rule-slots (rule stream)
  (:documentation "Print a rule's slots to a stream"))

(defmethod print-object ((obj production) stream)
  (print-unreadable-object (obj stream :type t :identity t)
    (with-slots (rule-name options rhs) obj
      (format stream "Rule=~s Options=~s RHS=~s" rule-name options rhs))))

(defmethod print-object ((obj rule-node) stream)
  (print-unreadable-object (obj stream :type t :identity t)
    (with-slots (value children) obj
      (format stream "~@[Value=~s~] ~@[Children=~s~]" value children)
      (print-rule-slots obj stream))))

(defmethod print-object ((obj lr-parse-table) stream)
  (print-unreadable-object (obj stream :type t :identity t)
    (format stream "Max states=~a~%" (number-of-states obj))
    (format stream "Entries:~{~a:~a~%~}%"
	    (loop for k being the hash-keys of (entries obj)
		 append (list k (gethash k (entries obj)))))))

(defmethod print-object ((obj lr1-item) stream)
  (print-unreadable-object (obj stream :type t :identity t)
    (with-slots (position lookahead production) obj
      (format stream "Position=~a Lookahead=~s Production=~s" position lookahead production))))

;; equality

(defgeneric equal-items (left right)
  (:method ((left production) (right production))
    (with-slots ((left-rule-name rule-name) (left-rhs rhs)) left
      (with-slots ((right-rule-name rule-name) (right-rhs rhs)) right
	(and (equal left-rule-name right-rule-name)
	     (equal left-rhs right-rhs)))))
  (:method ((left lr1-item) (right lr1-item))
    (with-slots ((left-position position) (left-lookahead lookahead) (left-production production)) left
      (with-slots ((right-position position) (right-lookahead lookahead) (right-production production)) right
	(and (= left-position right-position)
	     (equal left-lookahead right-lookahead)
	     (equal-items left-production right-production)))))
  (:method ((left list) (right list))
    (and (= (length left) (length right)) 
	 (loop for left-item in left
	    for right-item in right
	    with same = t
	    do (setf same (and same (equal-items left-item right-item)))
	    while same
	    finally (return same))))
  (:method ((left t) (right t))
    (equal left right)))

;; specifications

;; TODO this routine gets called multiple times during grammar creation, but
;; the results are not preserved between invocations--so a *lot* of work happens
;; each time, only to be thrown away
(defun rule-productions (rule)
  (destructuring-bind (rule-name options &rest rhss) rule
    (loop for rhs in rhss
       collect (let ((production (make-instance 'production :rule rule-name :rhs rhs)))
		 (loop for (slot value) on options by #'cddr
		    ;; TODO consider eval'ing the value first; depends on use cases for doing so
		    when (slot-exists-p production slot) 
		    do (setf (slot-value production slot) (eval value)))
		 production))))

(defun productions-in-grammar (specification)
  "Given a specification, return as rule-name -> rhs pairs (actually, just short lists);
  because of the way its constructed rule names and rhss are reused, but space for 
  the each production itself is extra"
  (loop for rule in specification
       append (rule-productions rule)))

(defun rule-productions-in-grammar (productions rule-name)
  (loop for production in productions
     if (eql (rule-name production) rule-name)
     collect production))

(defun symbols-in-grammar (productions)
  (let ((symbols ()))
    (loop for production in productions
	 do (with-slots (rule-name rhs) production
	      (pushnew rule-name symbols)
	      (loop for term in rhs
		 do (unless (equal term :nil) 
		      (pushnew term symbols)))))
    symbols))

(defun non-terminals-in-grammar (specification)
  "Given a specification, find all of the non-terminals (that is, symbols with a rule) in the specification"
  (loop for rule in specification
       collect (rule-spec-rule-name rule)))

;; (defun terminals-in-grammar (productions)
;;   (let ((non-terminals (non-terminals-in-grammar specification)))
;;     (loop for symbol in (symbols-in-grammar specification)
;;        unless (member symbol non-terminals)
;;        collect symbol)))

(defun initial-lr1-item-for-production (production lookahead)
  (make-instance 'lr1-item :position 0 :production production :lookahead lookahead))

(defun initial-lr1-state-for-grammar (productions start-rule-name)
  (make-instance 'lr1-state
		 :items (closure-of-lr1-items productions 
					      (loop for production in (rule-productions-in-grammar productions start-rule-name)
						 collect (initial-lr1-item-for-production production :eof)))))

(defun item-finished-p (item)
  (with-slots (position production) item
    (with-slots (rule-name rhs) production
      (>= position (length rhs)))))

(defun next-term-for-item (item)
  (unless (item-finished-p item) 
    (with-slots (position production) item
      (with-slots ( rule-name rhs) production
	(elt rhs position)))))

(defun next-term-and-lookahead-for-item (item default-lookahead)
  (unless (item-finished-p item) 
    (with-slots (position production) item
      (with-slots ( rule-name rhs) production
	(values (elt rhs position)
		(let ((lookahead-position (1+ position)))
		  (if (< lookahead-position (length rhs))
		      (elt rhs lookahead-position)
		      default-lookahead)))))))

(defun increment-lr1-item-position (item)
  (with-slots (position lookahead production) item
    (make-instance 'lr1-item :position (1+ position) :lookahead lookahead :production production)))

(defun item< (left right)
  (labels ((symbol< (left right)
	     (string< (symbol-name left) (symbol-name right)))
	   (production< (left right)
	     (with-slots ((left-rule-name rule-name) ( left-rhs rhs)) left
	       (with-slots (( right-rule-name rule-name) ( right-rhs rhs)) right
		 (cond ((symbol< left-rule-name right-rule-name) t)
		       ((equal left-rule-name right-rule-name)
			(and (<= (length left-rhs) (length right-rhs))
			     (loop for left-term in left-rhs
				for right-term in right-rhs
				with result = t
				do (setf result (and result (symbol< left-term right-term)))
				finally (return result))))
		       (t nil))))))
    (with-slots (( left-position position) ( left-production production)) left
      (with-slots (( right-position position) ( right-production production)) right
	(cond ((< left-position right-position) t)
	      ((> left-position right-position) nil)
	      (t (production< left-production right-production)))))))

(defun first-of-symbol (productions symbol)
  "Given a symbol of a specification, return it's FIRST(); if the symbol is a terminal,
  then the FIRST is just a list containing the symbol itself.  If it's a 
  non-terminal, then it's the union of the FIRSTs for the first symbol on
  the rhs of each of the non-terminals productions"
  ;; TODO consider whether we need to include non-terminals in our list of firsts,
  ;; as that may help later when we consider supporting incremental parsing
  (let ((rule-productions (rule-productions-in-grammar productions symbol)))
    (if rule-productions
	;; non-terminal
	(let ((firsts ())) 
	  (loop for production in rule-productions
	     do (with-slots (rule-name rhs) production
		  (declare (ignore rule-name))
		  (let ((new-first (car rhs)))
		    (unless (or (equal symbol new-first) (member new-first firsts))
		      (loop for first in (first-of-symbol productions new-first)
			 do (pushnew first firsts))))))
	  firsts)
	;; terminal -- no productions
	(list symbol))))

(defun closure-of-lr1-items (productions items)
  (let ((closure items))
    (loop for done = t
       do (loop for item in closure
	     for (next-term lookahead) = (multiple-value-list (next-term-and-lookahead-for-item item (slot-value item 'lookahead)))
	     for rule-productions = (rule-productions-in-grammar productions next-term)
	     when rule-productions
	     do (loop for production in rule-productions
		   do (loop for first in (first-of-symbol productions lookahead) 
			 do (let ((initial-item (initial-lr1-item-for-production production first)))
			      (unless (member initial-item closure :test #'equal-items)
				(setf done nil)
				(push initial-item closure))))))
       until done
       ;; note: we sort here, to ensure that we can use #'equal-items as a canonical
       ;; test of uniqueness (and set membership, too)
       finally (return (sort closure #'item<)))))

(defgeneric equal-cores (left right)
  (:method ((left lr1-item) (right lr1-item))
    (and (equal-slots (position) left right)
	 (equal-slots (production) left right :test 'equal-cores)))
  (:method ((left production) (right production))
    (equal-slots (rule-name rhs) left right))
  (:method ((left list) (right list))
    (and (= (length left) (length right)) 
	 (loop for left-item in left
	    for right-item in right
	    with same = t
	    do (setf same (and same (equal-cores left-item right-item)))
	    while same
	    finally (return same))))
  (:method ((left t) (right t))
    (equal left right)))

(defun lr1-goto-for-symbol (productions items symbol)
  (closure-of-lr1-items productions 
		    (loop for item in items
		       if (equal symbol (next-term-and-lookahead-for-item item (slot-value item 'lookahead)))
		       unless (item-finished-p item)
		       collect (increment-lr1-item-position item))))

(defun lr1-states-for-grammar (productions start-rule-name)
  (let ((states (make-array 0
			    :element-type 'lr1-state 
			    :adjustable t
			    :fill-pointer t))
	(symbols (symbols-in-grammar productions)))
    (vector-push-extend (initial-lr1-state-for-grammar productions start-rule-name) states)
    (loop for done = t
       do (loop for state across states
	     do (loop for symbol in symbols
		   do (let ((goto (lr1-goto-for-symbol productions (items state) symbol)))
			(when goto
			  (let ((goto-index (position goto states :test #'(lambda (goto state) 
									   (equal-items goto (items state))))))
			    (if goto-index
				;; existing state
				(setf (gethash symbol (exits state)) goto-index)
				;; new state
				(progn (setf done nil)
				       ;; index will be the index of the new last one--so length
				       ;; is a shortcut way of finding it
				       (setf (gethash symbol (exits state)) (length states))
				       (vector-push-extend (make-instance 'lr1-state :items goto) states))))))))
       until done
       finally (return  states))))

(defun make-grammar (specification &key ((:augmented-start augmented-start-rule-name) nil) ((:start start-rule-name) nil))
  (let* ((effective-start-rule-name (or augmented-start-rule-name 'start-rule)) 
	 (productions (productions-in-grammar specification))
	 (states (lr1-states-for-grammar productions effective-start-rule-name))
	 (non-terminals (non-terminals-in-grammar specification))
	 (action-table (make-instance 'lr-parse-table :states (length states)))
	 (goto-table (make-instance 'lr-parse-table :states (length states))))

    (labels ((shifting-p (item)
	       (let* ((rhs (slot-value (slot-value item 'production) 'rhs))
		     (length (length rhs)))
		 (< (slot-value item 'position) length)))

	     (record-shift (statei next-symbol)
	       (setf (gethash (list statei next-symbol) (entries action-table))
		     (let ((state (elt states statei)))
		       (list :shift (gethash next-symbol (exits state))))))

	     (record-reduce (statei next-symbol production)
	       (setf (gethash (list statei next-symbol) (entries action-table))
		     ;; we need the production to 1) know what symbol to reduce to, and 2) to know
		     ;; how many items on the stack to pop
		     (list :reduce production )))

	     (record-accept (statei next-symbol production)
	       ;; note we're assuming next-symbol will be :eof
	       (setf (gethash (list statei next-symbol) (entries action-table)) (list :accept production)))

	     (record-goto (statei non-terminal)
	       (let* ((state (elt states statei)) 
		     (goto (gethash non-terminal (exits state))))
		 (when goto
		   (setf (gethash (list statei non-terminal) (entries goto-table)) goto)))))

      (loop for i from 0 below (length states)
      	 for state = (elt states i)
      	 do (loop for item in (items state)
      	       ;; action table
      	       do (let ((next-symbol (next-term-for-item item)))
      		    ;; we record nothing for errors, so a nil
      		    ;; entry in table means an error
      		    (if (shifting-p item)
      			;; shifting
      			(record-shift i next-symbol)
      			;; reducing or accepting -- use lookahead to decide
			(with-slots (lookahead production) item
			  (if (and (equal :eof lookahead)
				   (equal effective-start-rule-name (slot-value production 'rule-name)))
			      ;; accepting
			      (record-accept i lookahead production)
			      ;; reducing
			      (record-reduce i lookahead production)))))
      		 ;; goto table
      		 do (loop for non-terminal in non-terminals
      			 do (record-goto i non-terminal)))))
    (make-instance 'lalr1-grammar 
		   :augmented-start augmented-start-rule-name
		   :start start-rule-name
		   :specification specification 
		   :states states 
		   :actions action-table 
		   :gotos goto-table)))

;; ---------------------------------------------------------------------------------------------------------------------
;; Reductions

(defun list-terms (parser rule-name &rest args)
  (declare (ignorable parser))
  (make-instance rule-name :children args))

(defun ignore-terms (parser rule-name &rest args)
  (declare (ignorable parser))
  (declare (ignorable args))
  (make-instance rule-name))

;; ---------------------------------------------------------------------------------------------------------------------
;;

(defmacro defgrammar (name start-rule-name &rest specification)
  "Defines a grammar, later accessible by calling a function named for the grammar, where the specification for
  the grammar consists of one or more rules of the form:

  ;; (rule-name alt1 alt2 ...)

  where each term alt1/alt2 etc.s is a list of either symbols, literals, or lists with any of 
  the following as heads:

  + repeat terms 1 or more times
  * repeat terms 0 or more times
  ? optional terms: appear 0 or 1 times
  ^ alternative terms : choose 1 term to appear

  also: 

  any () around terms represents a logical grouping (that is, if the head
  is none of the above symbols)

  All of these reduce to a more fundamental grammar (similar to CL-YACC) of:

  ;; (rule-name alt1 alt2 ...)

  where 

  rule = symbol identifying name of rule
  alt1/alt2 = each is a sequence (list) of other rule names or tokens

  Transforming the extended grammar into the fundamental grammar involves the following:

  * Treat the head of each rule as its name; set that aside
  * For each item in the tail of rule, treat each item as a discrete alternate right-hand side that is possible
  * For any RHS that is not a list, make it a list
  * Convert () : For each RHS, walk the RHS and convert any list that does not have a recognized head (eg., see above)
    into a reference to a new rule that has that list as a sequence in its single RHS
  * Convert * : For each occurence in a RHS of a list with * as the head, replace with (? (+ ...)) instead
  * Convert ? : For each occurrence of ? as the head of a list, convert the containing RHS into 2 separate RHS 
    one with the rest of the list in place of the term containing ? and another without the ? terms at as
    if it's not there
  * Convert + : For each occurrence of + , convert to a reference to a new rule that has 2 alternatives, one with
    repetition, one without

  Terminology:

  * A grammar comprises one or more rules
  * A rule is a list whose car is a symbol for the rule name, and the cdr is a list of right-hand side alternatives
  * A right-hand side (or rhs) is a list, each element of which is either the symbolic name of a rule, a list
    with one of the extended symbols above as it's head, or a literal (terminal)
  * A production is a logical idea only: it's the pairing of a rule name with 1 rhs (so a rule is just a
    short-hand for a set of productions all with the same rule name)
"
  (multiple-value-bind (augmented-start-rule-name augmented-specification) (augment-grammar start-rule-name specification)
    (let* ((fundamental-specification (transform-extended-grammar-to-fundamental augmented-start-rule-name augmented-specification))
	   (ast-classes (loop for rule-name in (non-terminals-in-grammar fundamental-specification)
			   for rule = (assoc rule-name fundamental-specification)
			   for rule-options = (rule-spec-rule-options rule)
			   for rule-slots = (getf rule-options 'slots )
			   collect `(progn 
				      (defclass ,rule-name (rule-node) (,@rule-slots))
				      (defmethod print-rule-slots ((rule ,rule-name) stream)
					,@(loop for slot in rule-slots
					     collect `(when (slot-boundp rule ',slot) 
							(format stream " ~s=~s" ',slot (slot-value rule ',slot)))))))))
      `(progn
	 ,@ast-classes
	 (let ((grammar (make-grammar ',fundamental-specification
				      :augmented-start ',augmented-start-rule-name
				      :start ',start-rule-name)))
	   (defun ,name ()
	     grammar))))))