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
(in-package :hh-parse)

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

(defvar *new-rules* nil "New rules under construction")

(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 compoundtermp (term)
  (and (listp term) (member (car 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 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 (gensym "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 '^)
		  (let* ((alternate-body (transform-term (cdr term))) 
			 (alternate-rule-name (gensym "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 (gensym "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
			     ;; (format *standard-output* "New nilable term: ~s~%" term)
			     (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)
							  ;; (format *standard-output* "Expanded ~s:~s to ~s~%" rule-name rhs expanded-rhs)
							  (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-extended-grammar-to-fundamental (start-rule-name grammar ) 
  (transform-for-nil 'start-rule
		     (let ((*new-rules* nil)
			   (augmented-grammar (cons `(start-rule () (,start-rule-name)) grammar)))
		       (append (for-each-rhs augmented-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

(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 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

(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
		    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 symbols-in-grammar (specification)
  (let ((symbols ()))
    (loop for production in (productions-in-grammar specification)
	 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 (specification)
  (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 (specification start-rule-name)
  (make-instance 'lr1-state
		 :items (closure-of-lr1-items specification 
					      (let ((rule (assoc start-rule-name specification)))
						(loop for production in (rule-productions rule)
						   collect (initial-lr1-item-for-production production :eof))))))

(defun rule-productions-in-grammar (specification rule-name)
  (loop for rule in specification
     if (eql (rule-spec-rule-name rule) rule-name)
     return (rule-productions rule)))

(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 (specification 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 ((productions (rule-productions-in-grammar specification symbol)))
    (if productions
	;; non-terminal
	(let ((firsts ())) 
	  (loop for production in 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 specification new-first)
			 do (pushnew first firsts))))))
	  firsts)
	;; terminal -- no productions
	(list symbol))))

(defun closure-of-lr1-items (specification 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 productions = (rule-productions-in-grammar specification next-term)
	     when productions
	     do (loop for production in productions
		   do (loop for first in (first-of-symbol specification 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 (specification items symbol)
  (closure-of-lr1-items specification 
		    (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 (specification start-rule-name)
  (let ((states (make-array 0
			    :element-type 'lr1-state 
			    :adjustable t
			    :fill-pointer t))
	(symbols (symbols-in-grammar specification)))
    (vector-push-extend (initial-lr1-state-for-grammar specification 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 specification (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)
  (let* ((states (lr1-states-for-grammar specification 'start-rule))
	 (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 'start-rule (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 :specification specification :states states :actions action-table :gotos goto-table)))

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

(defun ignore-terms (&rest args)
  (declare (ignorable args))
  nil)

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

(defmacro defgrammar (name start-rule-name &rest rules)
  "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)
"
  `(let* ((specification (transform-extended-grammar-to-fundamental ',start-rule-name ',rules))
	  (grammar (make-grammar specification)))
     (defun ,name ()
       grammar)))