1 ;;; semantic/wisent/comp.el --- GNU Bison for Emacs - Grammar compiler
3 ;; Copyright (C) 1984, 1986, 1989, 1992, 1995, 2000-2007, 2009-2013 Free
4 ;; Software Foundation, Inc.
6 ;; Author: David Ponce <david@dponce.com>
7 ;; Maintainer: David Ponce <david@dponce.com>
8 ;; Created: 30 January 2002
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; Grammar compiler that produces Wisent's LALR automatons.
30 ;; Wisent (the European Bison ;-) is an Elisp implementation of the
31 ;; GNU Compiler Compiler Bison. The Elisp code is a port of the C
32 ;; code of GNU Bison 1.28 & 1.31.
34 ;; For more details on the basic concepts for understanding Wisent,
35 ;; read the Bison manual ;)
37 ;; For more details on Wisent itself read the Wisent manual.
43 (require 'semantic/wisent)
45 ;;;; -------------------
46 ;;;; Misc. useful things
47 ;;;; -------------------
49 ;; As much as possible I would like to keep the name of global
50 ;; variables used in Bison without polluting too much the Elisp global
51 ;; name space. Elisp dynamic binding allows that ;-)
53 ;; Here are simple macros to easily define and use set of variables
54 ;; bound locally, without all these "reference to free variable"
57 (defmacro wisent-context-name (name)
58 "Return the context name from NAME."
59 `(if (and ,name (symbolp ,name))
60 (intern (format "wisent-context-%s" ,name))
61 (error "Invalid context name: %S" ,name)))
63 (defmacro wisent-context-bindings (name)
64 "Return the variables in context NAME."
65 `(symbol-value (wisent-context-name ,name)))
67 (defmacro wisent-defcontext (name &rest vars)
68 "Define a context NAME that will bind variables VARS."
69 (let* ((context (wisent-context-name name))
70 (bindings (mapcar #'(lambda (v) (list 'defvar v)) vars)))
73 (defvar ,context ',vars))))
74 (put 'wisent-defcontext 'lisp-indent-function 1)
76 (defmacro wisent-with-context (name &rest body)
77 "Bind variables in context NAME then eval BODY."
78 `(let* ,(wisent-context-bindings name)
80 (put 'wisent-with-context 'lisp-indent-function 1)
82 ;; A naive implementation of data structures! But it suffice here ;-)
84 (defmacro wisent-struct (name &rest fields)
85 "Define a simple data structure called NAME.
86 Which contains data stored in FIELDS. FIELDS is a list of symbols
87 which are field names or pairs (FIELD INITIAL-VALUE) where
88 INITIAL-VALUE is a constant used as the initial value of FIELD when
89 the data structure is created. INITIAL-VALUE defaults to nil.
91 This defines a `make-NAME' constructor, get-able `NAME-FIELD' and
92 set-able `set-NAME-FIELD' accessors."
93 (let ((size (length fields))
95 accors field sufx fun ivals)
97 (setq field (car fields)
100 (setq ivals (cons (cadr field) ivals)
102 (setq ivals (cons nil ivals)))
103 (setq sufx (format "%s-%s" name field)
104 fun (intern (format "%s" sufx))
105 accors (cons `(defmacro ,fun (s)
108 fun (intern (format "set-%s" sufx))
109 accors (cons `(defmacro ,fun (s v)
114 (defmacro ,(intern (format "make-%s" name)) ()
115 (cons 'vector ',(nreverse ivals)))
117 (put 'wisent-struct 'lisp-indent-function 1)
121 (defsubst wisent-pad-string (s n &optional left)
122 "Fill string S with spaces.
123 Return a new string of at least N characters. Insert spaces on right.
124 If optional LEFT is non-nil insert spaces on left."
125 (let ((i (length s)))
128 (concat (make-string (- n i) ?\ ) s)
129 (concat s (make-string (- n i) ?\ )))
132 ;;;; ------------------------
133 ;;;; Environment dependencies
134 ;;;; ------------------------
136 (defconst wisent-BITS-PER-WORD
138 (do-shift (if (boundp 'most-positive-fixnum)
139 (lambda (i) (lsh most-positive-fixnum (- i)))
140 (lambda (i) (lsh 1 i)))))
141 (while (not (zerop (funcall do-shift i)))
145 (defsubst wisent-WORDSIZE (n)
146 "(N + BITS-PER-WORD - 1) / BITS-PER-WORD."
147 (/ (1- (+ n wisent-BITS-PER-WORD)) wisent-BITS-PER-WORD))
149 (defsubst wisent-SETBIT (x i)
150 "X[I/BITS-PER-WORD] |= 1 << (I % BITS-PER-WORD)."
151 (let ((k (/ i wisent-BITS-PER-WORD)))
152 (aset x k (logior (aref x k)
153 (lsh 1 (% i wisent-BITS-PER-WORD))))))
155 (defsubst wisent-RESETBIT (x i)
156 "X[I/BITS-PER-WORD] &= ~(1 << (I % BITS-PER-WORD))."
157 (let ((k (/ i wisent-BITS-PER-WORD)))
158 (aset x k (logand (aref x k)
159 (lognot (lsh 1 (% i wisent-BITS-PER-WORD)))))))
161 (defsubst wisent-BITISSET (x i)
162 "(X[I/BITS-PER-WORD] & (1 << (I % BITS-PER-WORD))) != 0."
163 (not (zerop (logand (aref x (/ i wisent-BITS-PER-WORD))
164 (lsh 1 (% i wisent-BITS-PER-WORD))))))
166 (defsubst wisent-noninteractive ()
167 "Return non-nil if running without interactive terminal."
168 (if (featurep 'xemacs)
172 (defvar wisent-debug-flag nil
173 "Non-nil means enable some debug stuff.")
178 (defconst wisent-log-buffer-name "*wisent-log*"
179 "Name of the log buffer.")
181 (defvar wisent-new-log-flag nil
182 "Non-nil means to start a new report.")
184 (defvar wisent-verbose-flag nil
185 "*Non-nil means to report verbose information on generated parser.")
187 (defun wisent-toggle-verbose-flag ()
188 "Toggle whether to report verbose information on generated parser."
190 (setq wisent-verbose-flag (not wisent-verbose-flag))
191 (when (called-interactively-p 'interactive)
192 (message "Verbose report %sabled"
193 (if wisent-verbose-flag "en" "dis"))))
195 (defmacro wisent-log-buffer ()
196 "Return the log buffer.
197 Its name is defined in constant `wisent-log-buffer-name'."
198 `(get-buffer-create wisent-log-buffer-name))
200 (defmacro wisent-clear-log ()
201 "Delete the entire contents of the log buffer."
202 `(with-current-buffer (wisent-log-buffer)
205 (defvar byte-compile-current-file)
207 (defun wisent-source ()
208 "Return the current source file name or nil."
209 (let ((source (or (and (boundp 'byte-compile-current-file)
210 byte-compile-current-file)
211 load-file-name (buffer-file-name))))
213 (file-relative-name source))))
215 (defun wisent-new-log ()
216 "Start a new entry into the log buffer."
217 (setq wisent-new-log-flag nil)
218 (let ((text (format "\n\n*** Wisent %s - %s\n\n"
219 (or (wisent-source) (buffer-name))
220 (format-time-string "%Y-%m-%d %R"))))
221 (with-current-buffer (wisent-log-buffer)
222 (goto-char (point-max))
225 (defsubst wisent-log (&rest args)
226 "Insert text into the log buffer.
227 `format' is applied to ARGS and the result string is inserted into the
228 log buffer returned by the function `wisent-log-buffer'."
229 (and wisent-new-log-flag (wisent-new-log))
230 (with-current-buffer (wisent-log-buffer)
231 (insert (apply 'format args))))
233 (defconst wisent-log-file "wisent.output"
235 Used when running without interactive terminal.")
237 (defun wisent-append-to-log-file ()
238 "Append contents of logging buffer to `wisent-log-file'."
239 (if (get-buffer wisent-log-buffer-name)
241 (with-current-buffer (wisent-log-buffer)
243 (if (> (point-max) (point-min))
244 (write-region (point-min) (point-max)
247 (message "*** %s" (error-message-string err))))))
249 ;;;; -----------------------------------
250 ;;;; Representation of the grammar rules
251 ;;;; -----------------------------------
253 ;; ntokens is the number of tokens, and nvars is the number of
254 ;; variables (nonterminals). nsyms is the total number, ntokens +
257 ;; Each symbol (either token or variable) receives a symbol number.
258 ;; Numbers 0 to ntokens-1 are for tokens, and ntokens to nsyms-1 are
259 ;; for variables. Symbol number zero is the end-of-input token. This
260 ;; token is counted in ntokens.
262 ;; The rules receive rule numbers 1 to nrules in the order they are
263 ;; written. Actions and guards are accessed via the rule number.
265 ;; The rules themselves are described by three arrays: rrhs, rlhs and
266 ;; ritem. rlhs[R] is the symbol number of the left hand side of rule
267 ;; R. The right hand side is stored as symbol numbers in a portion of
268 ;; ritem. rrhs[R] contains the index in ritem of the beginning of the
269 ;; portion for rule R.
271 ;; The length of the portion is one greater than the number of symbols
272 ;; in the rule's right hand side. The last element in the portion
273 ;; contains minus R, which identifies it as the end of a portion and
274 ;; says which rule it is for.
276 ;; The portions of ritem come in order of increasing rule number and
277 ;; are followed by an element which is nil to mark the end. nitems is
278 ;; the total length of ritem, not counting the final nil. Each
279 ;; element of ritem is called an "item" and its index in ritem is an
282 ;; Item numbers are used in the finite state machine to represent
283 ;; places that parsing can get to.
285 ;; The vector rprec contains for each rule, the item number of the
286 ;; symbol giving its precedence level to this rule. The precedence
287 ;; level and associativity of each symbol is recorded in respectively
288 ;; the properties 'wisent--prec and 'wisent--assoc.
290 ;; Precedence levels are assigned in increasing order starting with 1
291 ;; so that numerically higher precedence values mean tighter binding
292 ;; as they ought to. nil as a symbol or rule's precedence means none
295 (defcustom wisent-state-table-size 1009
296 "The size of the state table."
300 ;; These variables only exist locally in the function
301 ;; `wisent-compile-grammar' and are shared by all other nested
303 (wisent-defcontext compile-grammar
304 F LA LAruleno accessing-symbol conflicts consistent default-prec
305 derives err-table fderives final-state first-reduction first-shift
306 first-state firsts from-state goto-map includes itemset nitemset
307 kernel-base kernel-end kernel-items last-reduction last-shift
308 last-state lookaheads lookaheadset lookback maxrhs ngotos nitems
309 nrules nshifts nstates nsyms ntokens nullable nvars rassoc redset
310 reduction-table ritem rlhs rprec rrc-count rrc-total rrhs ruseful
311 rcode ruleset rulesetsize shift-symbol shift-table shiftset
312 src-count src-total start-table state-table tags this-state to-state
313 tokensetsize ;; nb of words req. to hold a bit for each rule
314 varsetsize ;; nb of words req. to hold a bit for each variable
315 error-token-number start-symbol token-list var-list
316 N P V V1 nuseless-nonterminals nuseless-productions
317 ptable ;; symbols & characters properties
320 (defmacro wisent-ISTOKEN (s)
321 "Return non-nil if item number S defines a token (terminal).
322 That is if S < `ntokens'."
325 (defmacro wisent-ISVAR(s)
326 "Return non-nil if item number S defines a nonterminal.
327 That is if S >= `ntokens'."
330 (defsubst wisent-tag (s)
331 "Return printable form of item number S."
332 (wisent-item-to-string (aref tags s)))
334 ;; Symbol and character properties
336 (defsubst wisent-put (object propname value)
337 "Store OBJECT's PROPNAME property with value VALUE.
338 Use `eq' to locate OBJECT."
339 (let ((entry (assq object ptable)))
340 (or entry (setq entry (list object) ptable (cons entry ptable)))
341 (setcdr entry (plist-put (cdr entry) propname value))))
343 (defsubst wisent-get (object propname)
344 "Return the value of OBJECT's PROPNAME property.
345 Use `eq' to locate OBJECT."
346 (plist-get (cdr (assq object ptable)) propname))
348 (defsubst wisent-item-number (x)
349 "Return the item number of symbol X."
350 (wisent-get x 'wisent--item-no))
352 (defsubst wisent-set-item-number (x n)
353 "Set the item number of symbol X to N."
354 (wisent-put x 'wisent--item-no n))
356 (defsubst wisent-assoc (x)
357 "Return the associativity of symbol X."
358 (wisent-get x 'wisent--assoc))
360 (defsubst wisent-set-assoc (x a)
361 "Set the associativity of symbol X to A."
362 (wisent-put x 'wisent--assoc a))
364 (defsubst wisent-prec (x)
365 "Return the precedence level of symbol X."
366 (wisent-get x 'wisent--prec))
368 (defsubst wisent-set-prec (x p)
369 "Set the precedence level of symbol X to P."
370 (wisent-put x 'wisent--prec p))
372 ;;;; ----------------------------------------------------------
373 ;;;; Type definitions for nondeterministic finite state machine
374 ;;;; ----------------------------------------------------------
376 ;; These type definitions are used to represent a nondeterministic
377 ;; finite state machine that parses the specified grammar. This
378 ;; information is generated by the function `wisent-generate-states'.
380 ;; Each state of the machine is described by a set of items --
381 ;; particular positions in particular rules -- that are the possible
382 ;; places where parsing could continue when the machine is in this
383 ;; state. These symbols at these items are the allowable inputs that
386 ;; A core represents one state. States are numbered in the number
387 ;; field. When `wisent-generate-states' is finished, the starting
388 ;; state is state 0 and `nstates' is the number of states. (A
389 ;; transition to a state whose state number is `nstates' indicates
390 ;; termination.) All the cores are chained together and `first-state'
391 ;; points to the first one (state 0).
393 ;; For each state there is a particular symbol which must have been
394 ;; the last thing accepted to reach that state. It is the
395 ;; accessing-symbol of the core.
397 ;; Each core contains a vector of `nitems' items which are the indices
398 ;; in the `ritems' vector of the items that are selected in this
401 ;; The link field is used for chaining buckets that hash states by
402 ;; their itemsets. This is for recognizing equivalent states and
403 ;; combining them when the states are generated.
405 ;; The two types of transitions are shifts (push the lookahead token
406 ;; and read another) and reductions (combine the last n things on the
407 ;; stack via a rule, replace them with the symbol that the rule
408 ;; derives, and leave the lookahead token alone). When the states are
409 ;; generated, these transitions are represented in two other lists.
411 ;; Each shifts structure describes the possible shift transitions out
412 ;; of one state, the state whose number is in the number field. The
413 ;; shifts structures are linked through next and first-shift points to
414 ;; them. Each contains a vector of numbers of the states that shift
415 ;; transitions can go to. The accessing-symbol fields of those
416 ;; states' cores say what kind of input leads to them.
418 ;; A shift to state zero should be ignored. Conflict resolution
419 ;; deletes shifts by changing them to zero.
421 ;; Each reductions structure describes the possible reductions at the
422 ;; state whose number is in the number field. The data is a list of
423 ;; nreds rules, represented by their rule numbers. `first-reduction'
424 ;; points to the list of these structures.
426 ;; Conflict resolution can decide that certain tokens in certain
427 ;; states should explicitly be errors (for implementing %nonassoc).
428 ;; For each state, the tokens that are errors for this reason are
429 ;; recorded in an errs structure, which has the state number in its
430 ;; number field. The rest of the errs structure is full of token
433 ;; There is at least one shift transition present in state zero. It
434 ;; leads to a next-to-final state whose accessing-symbol is the
435 ;; grammar's start symbol. The next-to-final state has one shift to
436 ;; the final state, whose accessing-symbol is zero (end of input).
437 ;; The final state has one shift, which goes to the termination state
438 ;; (whose number is `nstates'-1).
439 ;; The reason for the extra state at the end is to placate the
440 ;; parser's strategy of making all decisions one token ahead of its
451 (wisent-struct shifts
457 (wisent-struct reductions
467 ;;;; --------------------------------------------------------
468 ;;;; Find unreachable terminals, nonterminals and productions
469 ;;;; --------------------------------------------------------
471 (defun wisent-bits-equal (L R n)
472 "Visit L and R and return non-nil if their first N elements are `='.
473 L and R must be vectors of integers."
476 (while (and iseq (natnump i))
477 (setq iseq (= (aref L i) (aref R i))
481 (defun wisent-nbits (i)
482 "Return number of bits set in integer I."
484 (while (not (zerop i))
485 ;; i ^= (i & ((unsigned) (-(int) i)))
486 (setq i (logxor i (logand i (- i)))
490 (defun wisent-bits-size (S n)
491 "In vector S count the total of bits set in first N elements.
492 S must be a vector of integers."
496 (setq count (+ count (wisent-nbits (aref S i)))
500 (defun wisent-useful-production (i N0)
501 "Return non-nil if production I is in useful set N0."
505 (while (and useful (> (setq n (aref ritem r)) 0))
507 (setq useful (wisent-BITISSET N0 (- n ntokens))))
511 (defun wisent-useless-nonterminals ()
512 "Find out which nonterminals are used."
513 (let (Np Ns i n break)
514 ;; N is set as built. Np is set being built this iteration. P is
515 ;; set of all productions which have a RHS all in N.
516 (setq n (wisent-WORDSIZE nvars)
517 Np (make-vector n 0))
519 ;; The set being computed is a set of nonterminals which can
520 ;; derive the empty string or strings consisting of all
521 ;; terminals. At each iteration a nonterminal is added to the set
522 ;; if there is a production with that nonterminal as its LHS for
523 ;; which all the nonterminals in its RHS are already in the set.
524 ;; Iterate until the set being computed remains unchanged. Any
525 ;; nonterminals not in the set at that point are useless in that
526 ;; they will never be used in deriving a sentence of the language.
528 ;; This iteration doesn't use any special traversal over the
529 ;; productions. A set is kept of all productions for which all
530 ;; the nonterminals in the RHS are in useful. Only productions
531 ;; not in this set are scanned on each iteration. At the end,
532 ;; this set is saved to be used when finding useful productions:
533 ;; only productions in this set will appear in the final grammar.
539 (aset Np i (aref N i))
544 (if (not (wisent-BITISSET P i))
545 (when (wisent-useful-production i N)
546 (wisent-SETBIT Np (- (aref rlhs i) ntokens))
547 (wisent-SETBIT P i)))
549 (if (wisent-bits-equal N Np n)
556 (defun wisent-inaccessible-symbols ()
557 "Find out which productions are reachable and which symbols are used."
558 ;; Starting with an empty set of productions and a set of symbols
559 ;; which only has the start symbol in it, iterate over all
560 ;; productions until the set of productions remains unchanged for an
561 ;; iteration. For each production which has a LHS in the set of
562 ;; reachable symbols, add the production to the set of reachable
563 ;; productions, and add all of the nonterminals in the RHS of the
564 ;; production to the set of reachable symbols.
566 ;; Consider only the (partially) reduced grammar which has only
567 ;; nonterminals in N and productions in P.
569 ;; The result is the set P of productions in the reduced grammar,
570 ;; and the set V of symbols in the reduced grammar.
572 ;; Although this algorithm also computes the set of terminals which
573 ;; are reachable, no terminal will be deleted from the grammar. Some
574 ;; terminals might not be in the grammar but might be generated by
575 ;; semantic routines, and so the user might want them available with
576 ;; specified numbers. (Is this true?) However, the non reachable
577 ;; terminals are printed (if running in verbose mode) so that the
579 (let (Vp Vs Pp i tt r n m break)
580 (setq n (wisent-WORDSIZE nsyms)
581 m (wisent-WORDSIZE (1+ nrules))
583 Pp (make-vector m 0))
585 ;; If the start symbol isn't useful, then nothing will be useful.
586 (when (wisent-BITISSET N (- start-symbol ntokens))
587 (wisent-SETBIT V start-symbol)
591 (aset Vp i (aref V i))
595 (when (and (not (wisent-BITISSET Pp i))
596 (wisent-BITISSET P i)
597 (wisent-BITISSET V (aref rlhs i)))
598 (setq r (aref rrhs i))
599 (while (natnump (setq tt (aref ritem r)))
600 (if (or (wisent-ISTOKEN tt)
601 (wisent-BITISSET N (- tt ntokens)))
602 (wisent-SETBIT Vp tt))
604 (wisent-SETBIT Pp i))
606 (if (wisent-bits-equal V Vp n)
613 ;; Tokens 0, 1 are internal to Wisent. Consider them useful.
614 (wisent-SETBIT V 0) ;; end-of-input token
615 (wisent-SETBIT V 1) ;; error token
618 (setq nuseless-productions (- nrules (wisent-bits-size P m))
619 nuseless-nonterminals nvars
622 (if (wisent-BITISSET V i)
623 (setq nuseless-nonterminals (1- nuseless-nonterminals)))
626 ;; A token that was used in %prec should not be warned about.
630 (wisent-SETBIT V1 (aref rprec i)))
634 (defun wisent-reduce-grammar-tables ()
635 "Disable useless productions."
636 (if (> nuseless-productions 0)
638 (while (<= pn nrules)
639 (aset ruseful pn (wisent-BITISSET P pn))
640 (setq pn (1+ pn))))))
642 (defun wisent-nonterminals-reduce ()
643 "Remove useless nonterminals."
644 (let (i n r item nontermmap tags-sorted)
645 ;; Map the nonterminals to their new index: useful first, useless
646 ;; afterwards. Kept for later report.
647 (setq nontermmap (make-vector nvars 0)
651 (when (wisent-BITISSET V i)
652 (aset nontermmap (- i ntokens) n)
657 (unless (wisent-BITISSET V i)
658 (aset nontermmap (- i ntokens) n)
661 ;; Shuffle elements of tables indexed by symbol number
662 (setq tags-sorted (make-vector nvars nil)
665 (setq n (aref nontermmap (- i ntokens)))
666 (aset tags-sorted (- n ntokens) (aref tags i))
670 (aset tags i (aref tags-sorted (- i ntokens)))
672 ;; Replace all symbol numbers in valid data structures.
675 (aset rlhs i (aref nontermmap (- (aref rlhs i) ntokens)))
678 (while (setq item (aref ritem r))
679 (if (wisent-ISVAR item)
680 (aset ritem r (aref nontermmap (- item ntokens))))
682 (setq start-symbol (aref nontermmap (- start-symbol ntokens))
683 nsyms (- nsyms nuseless-nonterminals)
684 nvars (- nvars nuseless-nonterminals))
687 (defun wisent-total-useless ()
688 "Report number of useless nonterminals and productions."
689 (let* ((src (wisent-source))
690 (src (if src (concat " in " src) ""))
691 (msg (format "Grammar%s contains" src)))
692 (if (> nuseless-nonterminals 0)
693 (setq msg (format "%s %d useless nonterminal%s"
694 msg nuseless-nonterminals
695 (if (> nuseless-nonterminals 0) "s" ""))))
696 (if (and (> nuseless-nonterminals 0) (> nuseless-productions 0))
697 (setq msg (format "%s and" msg)))
698 (if (> nuseless-productions 0)
699 (setq msg (format "%s %d useless rule%s"
700 msg nuseless-productions
701 (if (> nuseless-productions 0) "s" ""))))
704 (defun wisent-reduce-grammar ()
705 "Find unreachable terminals, nonterminals and productions."
706 ;; Allocate the global sets used to compute the reduced grammar
707 (setq N (make-vector (wisent-WORDSIZE nvars) 0)
708 P (make-vector (wisent-WORDSIZE (1+ nrules)) 0)
709 V (make-vector (wisent-WORDSIZE nsyms) 0)
710 V1 (make-vector (wisent-WORDSIZE nsyms) 0)
711 nuseless-nonterminals 0
712 nuseless-productions 0)
714 (wisent-useless-nonterminals)
715 (wisent-inaccessible-symbols)
717 (when (> (+ nuseless-nonterminals nuseless-productions) 0)
718 (wisent-total-useless)
719 (or (wisent-BITISSET N (- start-symbol ntokens))
720 (error "Start symbol `%s' does not derive any sentence"
721 (wisent-tag start-symbol)))
722 (wisent-reduce-grammar-tables)
723 (if (> nuseless-nonterminals 0)
724 (wisent-nonterminals-reduce))))
726 (defun wisent-print-useless ()
727 "Output the detailed results of the reductions."
729 (when (> nuseless-nonterminals 0)
730 ;; Useless nonterminals have been moved after useful ones.
731 (wisent-log "\n\nUseless nonterminals:\n\n")
733 (while (< i nuseless-nonterminals)
734 (wisent-log " %s\n" (wisent-tag (+ nsyms i)))
739 (unless (or (wisent-BITISSET V i) (wisent-BITISSET V1 i))
741 (wisent-log "\n\nTerminals which are not used:\n\n"))
743 (wisent-log " %s\n" (wisent-tag i)))
745 (when (> nuseless-productions 0)
746 (wisent-log "\n\nUseless rules:\n\n")
749 (unless (aref ruseful i)
750 (wisent-log "#%s " (wisent-pad-string (format "%d" i) 4))
751 (wisent-log "%s:" (wisent-tag (aref rlhs i)))
752 (setq r (aref rrhs i))
753 (while (natnump (aref ritem r))
754 (wisent-log " %s" (wisent-tag (aref ritem r)))
758 (if (or b (> nuseless-nonterminals 0) (> nuseless-productions 0))
762 ;;;; -----------------------------
763 ;;;; Match rules with nonterminals
764 ;;;; -----------------------------
766 (defun wisent-set-derives ()
767 "Find, for each variable (nonterminal), which rules can derive it.
768 It sets up the value of DERIVES so that DERIVES[i - NTOKENS] points to
769 a list of rule numbers, terminated with -1."
770 (let (i lhs p q dset delts)
771 (setq dset (make-vector nvars nil)
772 delts (make-vector (1+ nrules) 0))
773 (setq p 0 ;; p = delts
776 (when (aref ruseful i)
777 (setq lhs (aref rlhs i))
778 ;; p->next = dset[lhs];
780 (aset delts p (cons i (aref dset (- lhs ntokens)))) ;; (value . next)
781 (aset dset (- lhs ntokens) p) ;; dset[lhs] = p
782 (setq p (1+ p)) ;; p++
786 (setq derives (make-vector nvars nil)
791 p (aref dset (- i ntokens))) ;; p = dset[i]
794 (setq p (aref delts p)
795 q (cons (car p) q) ;;q++ = p->value
796 p (cdr p))) ;; p = p->next
797 (setq q (nreverse (cons -1 q))) ;; *q++ = -1
798 (aset derives (- i ntokens) q) ;; derives[i] = q
802 ;;;; --------------------------------------------------------
803 ;;;; Find which nonterminals can expand into the null string.
804 ;;;; --------------------------------------------------------
806 (defun wisent-print-nullable ()
809 (wisent-log "NULLABLE\n")
812 (wisent-log "\t%s: %s\n" (wisent-tag i)
813 (if (aref nullable (- i ntokens))
816 (wisent-log "\n\n")))
818 (defun wisent-set-nullable ()
820 A vector saying which nonterminals can expand into the null string.
821 NULLABLE[i - NTOKENS] is nil if symbol I can do so."
822 (let (ruleno s1 s2 p r squeue rcount rsets relts item any-tokens)
823 (setq squeue (make-vector nvars 0)
824 rcount (make-vector (1+ nrules) 0)
825 rsets (make-vector nvars nil) ;; - ntokens
826 relts (make-vector (+ nitems nvars 1) nil)
827 nullable (make-vector nvars nil)) ;; - ntokens
828 (setq s1 0 s2 0 ;; s1 = s2 = squeue
831 (while (<= ruleno nrules)
832 (when (aref ruseful ruleno)
833 (if (> (aref ritem (aref rrhs ruleno)) 0)
835 ;; This rule has a non empty RHS.
837 r (aref rrhs ruleno))
838 (while (> (aref ritem r) 0)
839 (if (wisent-ISTOKEN (aref ritem r))
843 ;; This rule has only nonterminals: schedule it for the
846 (setq r (aref rrhs ruleno))
847 (while (> (setq item (aref ritem r)) 0)
848 (aset rcount ruleno (1+ (aref rcount ruleno)))
849 ;; p->next = rsets[item];
850 ;; p->value = ruleno;
851 (aset relts p (cons ruleno (aref rsets (- item ntokens))))
853 (aset rsets (- item ntokens) p)
856 ;; This rule has an empty RHS.
857 ;; assert (ritem[rrhs[ruleno]] == -ruleno)
858 (when (and (aref ruseful ruleno)
859 (setq item (aref rlhs ruleno))
860 (not (aref nullable (- item ntokens))))
861 (aset nullable (- item ntokens) t)
862 (aset squeue s2 item)
866 (setq ruleno (1+ ruleno)))
870 (setq p (aref rsets (- (aref squeue s1) ntokens))
873 (setq p (aref relts p)
875 p (cdr p)) ;; p = p->next
876 ;; if (--rcount[ruleno] == 0)
877 (when (zerop (aset rcount ruleno (1- (aref rcount ruleno))))
878 (setq item (aref rlhs ruleno))
879 (aset nullable (- item ntokens) t)
880 (aset squeue s2 item)
883 (if wisent-debug-flag
884 (wisent-print-nullable))
891 (defun wisent-print-fderives ()
894 (wisent-log "\n\n\nFDERIVES\n")
897 (wisent-log "\n\n%s derives\n\n" (wisent-tag i))
898 (setq rp (aref fderives (- i ntokens))
901 (if (wisent-BITISSET rp j)
902 (wisent-log " %d\n" j))
906 (defun wisent-set-fderives ()
908 An NVARS by NRULES matrix of bits indicating which rules can help
909 derive the beginning of the data for each nonterminal. For example,
910 if symbol 5 can be derived as the sequence of symbols 8 3 20, and one
911 of the rules for deriving symbol 8 is rule 4, then the
912 \[5 - NTOKENS, 4] bit in FDERIVES is set."
914 (setq fderives (make-vector nvars nil))
917 (aset fderives i (make-vector rulesetsize 0))
926 ;; if (BITISSET (FIRSTS (i), j - ntokens))
927 (when (wisent-BITISSET (aref firsts (- i ntokens)) (- j ntokens))
928 (setq k (aref derives (- j ntokens)))
929 (while (> (car k) 0) ;; derives[j][k] > 0
930 ;; SETBIT (FDERIVES (i), derives[j][k]);
931 (wisent-SETBIT (aref fderives (- i ntokens)) (car k))
936 (if wisent-debug-flag
937 (wisent-print-fderives))
940 (defun wisent-print-firsts ()
943 (wisent-log "\n\n\nFIRSTS\n\n")
946 (wisent-log "\n\n%s firsts\n\n" (wisent-tag i))
947 (setq v (aref firsts (- i ntokens))
950 (if (wisent-BITISSET v j)
951 (wisent-log "\t\t%d (%s)\n"
952 (+ j ntokens) (wisent-tag (+ j ntokens))))
956 (defun wisent-TC (R n)
958 Given R an N by N matrix of bits, modify its contents to be the
959 transitive closure of what was given."
961 ;; R (J, I) && R (I, K) => R (J, K).
962 ;; I *must* be the outer loop.
967 (when (wisent-BITISSET (aref R j) i)
970 (if (wisent-BITISSET (aref R i) k)
971 (wisent-SETBIT (aref R j) k))
976 (defun wisent-RTC (R n)
977 "Reflexive Transitive Closure.
978 Same as `wisent-TC' and then set all the bits on the diagonal of R, an
979 N by N matrix of bits."
984 (wisent-SETBIT (aref R i) i)
987 (defun wisent-set-firsts ()
989 An NVARS by NVARS bit matrix indicating which items can represent the
990 beginning of the input corresponding to which other items. For
991 example, if some rule expands symbol 5 into the sequence of symbols 8
992 3 20, the symbol 8 can be the beginning of the data for symbol 5, so
993 the bit [8 - NTOKENS, 5 - NTOKENS] in FIRSTS is set."
994 (let (row symbol sp rowsize i)
995 (setq rowsize (wisent-WORDSIZE nvars)
997 firsts (make-vector nvars nil)
1000 (aset firsts i (make-vector rowsize 0))
1003 (setq row 0 ;; row = firsts
1006 (setq sp (aref derives (- i ntokens)))
1007 (while (>= (car sp) 0)
1008 (setq symbol (aref ritem (aref rrhs (car sp)))
1010 (when (wisent-ISVAR symbol)
1011 (setq symbol (- symbol ntokens))
1012 (wisent-SETBIT (aref firsts row) symbol)
1017 (wisent-RTC firsts nvars)
1019 (if wisent-debug-flag
1020 (wisent-print-firsts))
1023 (defun wisent-initialize-closure (n)
1024 "Allocate the ITEMSET and RULESET vectors.
1025 And precompute useful data so that `wisent-closure' can be called.
1026 N is the number of elements to allocate for ITEMSET."
1027 (setq itemset (make-vector n 0)
1028 rulesetsize (wisent-WORDSIZE (1+ nrules))
1029 ruleset (make-vector rulesetsize 0))
1031 (wisent-set-fderives))
1033 (defun wisent-print-closure ()
1036 (wisent-log "\n\nclosure n = %d\n\n" nitemset)
1037 (setq i 0) ;; isp = itemset
1038 (while (< i nitemset)
1039 (wisent-log " %d\n" (aref itemset i))
1042 (defun wisent-closure (core n)
1043 "Set up RULESET and ITEMSET for the transitions out of CORE state.
1044 Given a vector of item numbers items, of length N, set up RULESET and
1045 ITEMSET to indicate what rules could be run and which items could be
1046 accepted when those items are the active ones.
1048 RULESET contains a bit for each rule. `wisent-closure' sets the bits
1049 for all rules which could potentially describe the next input to be
1052 ITEMSET is a vector of item numbers; NITEMSET is the number of items
1053 in ITEMSET. `wisent-closure' places there the indices of all items
1054 which represent units of input that could arrive next."
1055 (let (c r v symbol ruleno itemno)
1059 v (aref fderives (- start-symbol ntokens)))
1060 (while (< r rulesetsize)
1061 ;; ruleset[r] = FDERIVES (start-symbol)[r];
1062 (aset ruleset r (aref v r))
1065 (fillarray ruleset 0)
1068 (setq symbol (aref ritem (aref core c)))
1069 (when (wisent-ISVAR symbol)
1071 v (aref fderives (- symbol ntokens)))
1072 (while (< r rulesetsize)
1073 ;; ruleset[r] |= FDERIVES (ritem[core[c]])[r];
1074 (aset ruleset r (logior (aref ruleset r) (aref v r)))
1081 r (* rulesetsize wisent-BITS-PER-WORD))
1083 (when (wisent-BITISSET ruleset ruleno)
1084 (setq itemno (aref rrhs ruleno))
1085 (while (and (< c n) (< (aref core c) itemno))
1086 (aset itemset nitemset (aref core c))
1087 (setq nitemset (1+ nitemset)
1089 (aset itemset nitemset itemno)
1090 (setq nitemset (1+ nitemset)))
1091 (setq ruleno (1+ ruleno)))
1094 (aset itemset nitemset (aref core c))
1095 (setq nitemset (1+ nitemset)
1098 (if wisent-debug-flag
1099 (wisent-print-closure))
1102 ;;;; --------------------------------------------------
1103 ;;;; Generate the nondeterministic finite state machine
1104 ;;;; --------------------------------------------------
1106 (defun wisent-allocate-itemsets ()
1107 "Allocate storage for itemsets."
1108 (let (symbol i count symbol-count)
1109 ;; Count the number of occurrences of all the symbols in RITEMS.
1110 ;; Note that useless productions (hence useless nonterminals) are
1111 ;; browsed too, hence we need to allocate room for _all_ the
1114 symbol-count (make-vector (+ nsyms nuseless-nonterminals) 0)
1116 (while (setq symbol (aref ritem i))
1118 (setq count (1+ count))
1119 (aset symbol-count symbol (1+ (aref symbol-count symbol))))
1121 ;; See comments before `wisent-new-itemsets'. All the vectors of
1122 ;; items live inside kernel-items. The number of active items
1123 ;; after some symbol cannot be more than the number of times that
1124 ;; symbol appears as an item, which is symbol-count[symbol]. We
1125 ;; allocate that much space for each symbol.
1126 (setq kernel-base (make-vector nsyms nil)
1127 kernel-items (make-vector count 0)
1131 (aset kernel-base i count)
1132 (setq count (+ count (aref symbol-count i))
1134 (setq shift-symbol symbol-count
1135 kernel-end (make-vector nsyms nil))
1138 (defun wisent-allocate-storage ()
1139 "Allocate storage for the state machine."
1140 (wisent-allocate-itemsets)
1141 (setq shiftset (make-vector nsyms 0)
1142 redset (make-vector (1+ nrules) 0)
1143 state-table (make-vector wisent-state-table-size nil)))
1145 (defun wisent-new-itemsets ()
1146 "Find which symbols can be shifted in the current state.
1147 And for each one record which items would be active after that shift.
1148 Uses the contents of ITEMSET. SHIFT-SYMBOL is set to a vector of the
1149 symbols that can be shifted. For each symbol in the grammar,
1150 KERNEL-BASE[symbol] points to a vector of item numbers activated if
1151 that symbol is shifted, and KERNEL-END[symbol] points after the end of
1153 (let (i shiftcount isp ksp symbol)
1154 (fillarray kernel-end nil)
1157 (while (< isp nitemset)
1158 (setq i (aref itemset isp)
1160 symbol (aref ritem i))
1162 (setq ksp (aref kernel-end symbol))
1164 ;; shift-symbol[shiftcount++] = symbol;
1165 (aset shift-symbol shiftcount symbol)
1166 (setq shiftcount (1+ shiftcount)
1167 ksp (aref kernel-base symbol)))
1169 (aset kernel-items ksp (1+ i))
1171 (aset kernel-end symbol ksp)))
1172 (setq nshifts shiftcount)))
1174 (defun wisent-new-state (symbol)
1175 "Create a new state for those items, if necessary.
1176 SYMBOL is the core accessing-symbol.
1177 Subroutine of `wisent-get-state'."
1178 (let (n p isp1 isp2 iend items)
1179 (setq isp1 (aref kernel-base symbol)
1180 iend (aref kernel-end symbol)
1183 items (make-vector n 0))
1184 (set-core-accessing-symbol p symbol)
1185 (set-core-number p nstates)
1186 (set-core-nitems p n)
1187 (set-core-items p items)
1188 (setq isp2 0) ;; isp2 = p->items
1189 (while (< isp1 iend)
1190 ;; *isp2++ = *isp1++;
1191 (aset items isp2 (aref kernel-items isp1))
1192 (setq isp1 (1+ isp1)
1194 (set-core-next last-state p)
1196 nstates (1+ nstates))
1199 (defun wisent-get-state (symbol)
1200 "Find the state we would get to by shifting SYMBOL.
1201 Return the state number for the state we would get to (from the
1202 current state) by shifting SYMBOL. Create a new state if no
1203 equivalent one exists already. Used by `wisent-append-states'."
1204 (let (key isp1 isp2 iend sp sp2 found n)
1205 (setq isp1 (aref kernel-base symbol)
1206 iend (aref kernel-end symbol)
1209 ;; Add up the target state's active item numbers to get a hash key
1210 (while (< isp1 iend)
1211 (setq key (+ key (aref kernel-items isp1))
1213 (setq key (% key wisent-state-table-size)
1214 sp (aref state-table key))
1219 (when (= (core-nitems sp) n)
1221 isp1 (aref kernel-base symbol)
1222 ;; isp2 = sp->items;
1226 (while (and found (< isp1 iend))
1227 ;; if (*isp1++ != *isp2++)
1228 (if (not (= (aref kernel-items isp1)
1231 (setq isp1 (1+ isp1)
1235 (setq sp (core-link sp))
1236 ;; sp = sp->link = new-state(symbol)
1237 (setq sp (set-core-link sp (wisent-new-state symbol))
1240 ;; state-table[key] = sp = new-state(symbol)
1241 (setq sp (wisent-new-state symbol))
1242 (aset state-table key sp))
1243 ;; return (sp->number);
1246 (defun wisent-append-states ()
1247 "Find or create the core structures for states.
1248 Use the information computed by `wisent-new-itemsets' to find the
1249 state numbers reached by each shift transition from the current state.
1250 SHIFTSET is set up as a vector of state numbers of those states."
1252 ;; First sort shift-symbol into increasing order
1254 (while (< i nshifts)
1255 (setq symbol (aref shift-symbol i)
1257 (while (and (> j 0) (> (aref shift-symbol (1- j)) symbol))
1258 (aset shift-symbol j (aref shift-symbol (1- j)))
1260 (aset shift-symbol j symbol)
1263 (while (< i nshifts)
1264 (setq symbol (aref shift-symbol i))
1265 (aset shiftset i (wisent-get-state symbol))
1269 (defun wisent-initialize-states ()
1270 "Initialize states."
1271 (let ((p (make-core)))
1277 (defun wisent-save-shifts ()
1278 "Save the NSHIFTS of SHIFTSET into the current linked list."
1280 (setq p (make-shifts)
1281 shifts (make-vector nshifts 0)
1283 (set-shifts-number p (core-number this-state))
1284 (set-shifts-nshifts p nshifts)
1285 (set-shifts-shifts p shifts)
1286 (while (< i nshifts)
1287 ;; (p->shifts)[i] = shiftset[i];
1288 (aset shifts i (aref shiftset i))
1292 (set-shifts-next last-shift p)
1293 (setq first-shift p))
1294 (setq last-shift p)))
1296 (defun wisent-insert-start-shift ()
1297 "Create the next-to-final state.
1298 That is the state to which a shift has already been made in the
1299 initial state. Subroutine of `wisent-augment-automaton'."
1301 (setq statep (make-core))
1302 (set-core-number statep nstates)
1303 (set-core-accessing-symbol statep start-symbol)
1304 (set-core-next last-state statep)
1305 (setq last-state statep)
1306 ;; Make a shift from this state to (what will be) the final state.
1307 (setq sp (make-shifts))
1308 (set-shifts-number sp nstates)
1309 (setq nstates (1+ nstates))
1310 (set-shifts-nshifts sp 1)
1311 (set-shifts-shifts sp (vector nstates))
1312 (set-shifts-next last-shift sp)
1313 (setq last-shift sp)))
1315 (defun wisent-augment-automaton ()
1316 "Set up initial and final states as parser wants them.
1317 Make sure that the initial state has a shift that accepts the
1318 grammar's start symbol and goes to the next-to-final state, which has
1319 a shift going to the final state, which has a shift to the termination
1320 state. Create such states and shifts if they don't happen to exist
1322 (let (i k statep sp sp2 sp1 shifts)
1323 (setq sp first-shift)
1326 (if (zerop (shifts-number sp))
1328 (setq k (shifts-nshifts sp)
1329 statep (core-next first-state))
1330 ;; The states reached by shifts from first-state are
1331 ;; numbered 1...K. Look for one reached by
1333 (while (and (< (core-accessing-symbol statep) start-symbol)
1334 (< (core-number statep) k))
1335 (setq statep (core-next statep)))
1336 (if (= (core-accessing-symbol statep) start-symbol)
1338 ;; We already have a next-to-final state. Make
1339 ;; sure it has a shift to what will be the final
1341 (setq k (core-number statep))
1342 (while (and sp (< (shifts-number sp) k))
1344 sp (shifts-next sp)))
1345 (if (and sp (= (shifts-number sp) k))
1347 (setq i (shifts-nshifts sp)
1349 shifts (make-vector (1+ i) 0))
1350 (set-shifts-number sp2 k)
1351 (set-shifts-nshifts sp2 (1+ i))
1352 (set-shifts-shifts sp2 shifts)
1353 (aset shifts 0 nstates)
1355 ;; sp2->shifts[i] = sp->shifts[i - 1];
1356 (aset shifts i (aref (shifts-shifts sp) (1- i)))
1358 ;; Patch sp2 into the chain of shifts in
1359 ;; place of sp, following sp1.
1360 (set-shifts-next sp2 (shifts-next sp))
1361 (set-shifts-next sp1 sp2)
1362 (if (eq sp last-shift)
1363 (setq last-shift sp2))
1365 (setq sp2 (make-shifts))
1366 (set-shifts-number sp2 k)
1367 (set-shifts-nshifts sp2 1)
1368 (set-shifts-shifts sp2 (vector nstates))
1369 ;; Patch sp2 into the chain of shifts between
1371 (set-shifts-next sp2 sp)
1372 (set-shifts-next sp1 sp2)
1374 (setq last-shift sp2))
1377 ;; There is no next-to-final state as yet.
1378 ;; Add one more shift in FIRST-SHIFT, going to the
1379 ;; next-to-final state (yet to be made).
1380 (setq sp first-shift
1382 i (shifts-nshifts sp)
1383 shifts (make-vector (1+ i) 0))
1384 (set-shifts-nshifts sp2 (1+ i))
1385 (set-shifts-shifts sp2 shifts)
1386 ;; Stick this shift into the vector at the proper place.
1387 (setq statep (core-next first-state)
1390 (while (< i (shifts-nshifts sp))
1391 (when (and (> (core-accessing-symbol statep) start-symbol)
1393 (aset shifts k nstates)
1395 (aset shifts k (aref (shifts-shifts sp) i))
1396 (setq statep (core-next statep))
1400 (aset shifts k nstates)
1402 ;; Patch sp2 into the chain of shifts in place of
1403 ;; sp, at the beginning.
1404 (set-shifts-next sp2 (shifts-next sp))
1405 (setq first-shift sp2)
1406 (if (eq last-shift sp)
1407 (setq last-shift sp2))
1408 ;; Create the next-to-final state, with shift to
1409 ;; what will be the final state.
1410 (wisent-insert-start-shift)))
1411 ;; The initial state didn't even have any shifts. Give it
1412 ;; one shift, to the next-to-final state.
1413 (setq sp (make-shifts))
1414 (set-shifts-nshifts sp 1)
1415 (set-shifts-shifts sp (vector nstates))
1416 ;; Patch sp into the chain of shifts at the beginning.
1417 (set-shifts-next sp first-shift)
1418 (setq first-shift sp)
1419 ;; Create the next-to-final state, with shift to what will
1420 ;; be the final state.
1421 (wisent-insert-start-shift)))
1422 ;; There are no shifts for any state. Make one shift, from the
1423 ;; initial state to the next-to-final state.
1424 (setq sp (make-shifts))
1425 (set-shifts-nshifts sp 1)
1426 (set-shifts-shifts sp (vector nstates))
1427 ;; Initialize the chain of shifts with sp.
1428 (setq first-shift sp
1430 ;; Create the next-to-final state, with shift to what will be
1432 (wisent-insert-start-shift))
1433 ;; Make the final state--the one that follows a shift from the
1434 ;; next-to-final state. The symbol for that shift is 0
1436 (setq statep (make-core))
1437 (set-core-number statep nstates)
1438 (set-core-next last-state statep)
1439 (setq last-state statep)
1440 ;; Make the shift from the final state to the termination state.
1441 (setq sp (make-shifts))
1442 (set-shifts-number sp nstates)
1443 (setq nstates (1+ nstates))
1444 (set-shifts-nshifts sp 1)
1445 (set-shifts-shifts sp (vector nstates))
1446 (set-shifts-next last-shift sp)
1447 (setq last-shift sp)
1448 ;; Note that the variable FINAL-STATE refers to what we sometimes
1449 ;; call the termination state.
1450 (setq final-state nstates)
1451 ;; Make the termination state.
1452 (setq statep (make-core))
1453 (set-core-number statep nstates)
1454 (setq nstates (1+ nstates))
1455 (set-core-next last-state statep)
1456 (setq last-state statep)))
1458 (defun wisent-save-reductions ()
1459 "Make a reductions structure.
1460 Find which rules can be used for reduction transitions from the
1461 current state and make a reductions structure for the state to record
1462 their rule numbers."
1463 (let (i item count p rules)
1464 ;; Find and count the active items that represent ends of rules.
1467 (while (< i nitemset)
1468 (setq item (aref ritem (aref itemset i)))
1470 (aset redset count (- item))
1471 (setq count (1+ count)))
1473 ;; Make a reductions structure and copy the data into it.
1475 (setq p (make-reductions)
1476 rules (make-vector count 0))
1477 (set-reductions-number p (core-number this-state))
1478 (set-reductions-nreds p count)
1479 (set-reductions-rules p rules)
1482 ;; (p->rules)[i] = redset[i]
1483 (aset rules i (aref redset i))
1486 (set-reductions-next last-reduction p)
1487 (setq first-reduction p))
1488 (setq last-reduction p))))
1490 (defun wisent-generate-states ()
1491 "Compute the nondeterministic finite state machine from the grammar."
1492 (wisent-allocate-storage)
1493 (wisent-initialize-closure nitems)
1494 (wisent-initialize-states)
1496 ;; Set up RULESET and ITEMSET for the transitions out of this
1497 ;; state. RULESET gets a 1 bit for each rule that could reduce
1498 ;; now. ITEMSET gets a vector of all the items that could be
1500 (wisent-closure (core-items this-state) (core-nitems this-state))
1501 ;; Record the reductions allowed out of this state.
1502 (wisent-save-reductions)
1503 ;; Find the itemsets of the states that shifts can reach.
1504 (wisent-new-itemsets)
1505 ;; Find or create the core structures for those states.
1506 (wisent-append-states)
1507 ;; Create the shifts structures for the shifts to those states,
1508 ;; now that the state numbers transitioning to are known.
1510 (wisent-save-shifts))
1511 ;; States are queued when they are created; process them all.
1512 (setq this-state (core-next this-state)))
1513 ;; Set up initial and final states as parser wants them.
1514 (wisent-augment-automaton))
1516 ;;;; ---------------------------
1517 ;;;; Compute look-ahead criteria
1518 ;;;; ---------------------------
1520 ;; Compute how to make the finite state machine deterministic; find
1521 ;; which rules need lookahead in each state, and which lookahead
1522 ;; tokens they accept.
1524 ;; `wisent-lalr', the entry point, builds these data structures:
1526 ;; GOTO-MAP, FROM-STATE and TO-STATE record each shift transition
1527 ;; which accepts a variable (a nonterminal). NGOTOS is the number of
1528 ;; such transitions.
1529 ;; FROM-STATE[t] is the state number which a transition leads from and
1530 ;; TO-STATE[t] is the state number it leads to.
1531 ;; All the transitions that accept a particular variable are grouped
1532 ;; together and GOTO-MAP[i - NTOKENS] is the index in FROM-STATE and
1533 ;; TO-STATE of the first of them.
1535 ;; CONSISTENT[s] is non-nil if no lookahead is needed to decide what
1536 ;; to do in state s.
1538 ;; LARULENO is a vector which records the rules that need lookahead in
1539 ;; various states. The elements of LARULENO that apply to state s are
1540 ;; those from LOOKAHEADS[s] through LOOKAHEADS[s+1]-1. Each element
1541 ;; of LARULENO is a rule number.
1543 ;; If LR is the length of LARULENO, then a number from 0 to LR-1 can
1544 ;; specify both a rule and a state where the rule might be applied.
1545 ;; LA is a LR by NTOKENS matrix of bits.
1546 ;; LA[l, i] is 1 if the rule LARULENO[l] is applicable in the
1547 ;; appropriate state when the next token is symbol i.
1548 ;; If LA[l, i] and LA[l, j] are both 1 for i != j, it is a conflict.
1550 (wisent-defcontext digraph
1554 (defun wisent-traverse (i)
1556 (let (j k height Ri Fi break)
1559 (aset VERTICES top i) ;; VERTICES[++top] = i
1560 (aset INDEX i top) ;; INDEX[i] = height = top
1562 (setq Ri (aref R i))
1565 (while (>= (aref Ri j) 0)
1566 (if (zerop (aref INDEX (aref Ri j)))
1567 (wisent-traverse (aref Ri j)))
1568 ;; if (INDEX[i] > INDEX[R[i][j]])
1569 (if (> (aref INDEX i) (aref INDEX (aref Ri j)))
1570 ;; INDEX[i] = INDEX[R[i][j]];
1571 (aset INDEX i (aref INDEX (aref Ri j))))
1574 (while (< k tokensetsize)
1575 ;; F (i)[k] |= F (R[i][j])[k];
1576 (aset Fi k (logior (aref Fi k)
1577 (aref (aref F (aref Ri j)) k)))
1581 (when (= (aref INDEX i) height)
1584 (setq j (aref VERTICES top) ;; j = VERTICES[top--]
1586 (aset INDEX j infinity)
1590 (while (< k tokensetsize)
1591 ;; F (j)[k] = F (i)[k];
1592 (aset (aref F j) k (aref (aref F i) k))
1596 (defun wisent-digraph (relation)
1598 (wisent-with-context digraph
1599 (setq infinity (+ ngotos 2)
1600 INDEX (make-vector (1+ ngotos) 0)
1601 VERTICES (make-vector (1+ ngotos) 0)
1606 (if (and (= (aref INDEX i) 0) (aref R i))
1607 (wisent-traverse i))
1610 (defun wisent-set-state-table ()
1611 "Build state table."
1613 (setq state-table (make-vector nstates nil)
1616 (aset state-table (core-number sp) sp)
1617 (setq sp (core-next sp)))))
1619 (defun wisent-set-accessing-symbol ()
1620 "Build accessing symbol table."
1622 (setq accessing-symbol (make-vector nstates 0)
1625 (aset accessing-symbol (core-number sp) (core-accessing-symbol sp))
1626 (setq sp (core-next sp)))))
1628 (defun wisent-set-shift-table ()
1629 "Build shift table."
1631 (setq shift-table (make-vector nstates nil)
1634 (aset shift-table (shifts-number sp) sp)
1635 (setq sp (shifts-next sp)))))
1637 (defun wisent-set-reduction-table ()
1638 "Build reduction table."
1640 (setq reduction-table (make-vector nstates nil)
1643 (aset reduction-table (reductions-number rp) rp)
1644 (setq rp (reductions-next rp)))))
1646 (defun wisent-set-maxrhs ()
1647 "Setup MAXRHS length."
1652 (while (aref ritem i)
1653 (if (> (aref ritem i) 0)
1661 (defun wisent-initialize-LA ()
1663 (let (i j k count rp sp np v)
1664 (setq consistent (make-vector nstates nil)
1665 lookaheads (make-vector (1+ nstates) 0)
1668 (while (< i nstates)
1669 (aset lookaheads i count)
1670 (setq rp (aref reduction-table i)
1671 sp (aref shift-table i))
1674 ;; || (sp && ! ISVAR(accessing-symbol[sp->shifts[0]]))))
1676 (or (> (reductions-nreds rp) 1)
1679 (aref accessing-symbol
1680 (aref (shifts-shifts sp) 0)))))))
1681 (setq count (+ count (reductions-nreds rp)))
1682 (aset consistent i t))
1686 j (shifts-nshifts sp)
1687 v (shifts-shifts sp))
1689 (when (= (aref accessing-symbol (aref v k))
1691 (aset consistent i nil)
1692 (setq k j)) ;; break
1696 (aset lookaheads nstates count)
1700 (setq LA (make-vector 1 nil)
1701 LAruleno (make-vector 1 0)
1702 lookback (make-vector 1 nil)))
1703 (setq LA (make-vector count nil)
1704 LAruleno (make-vector count 0)
1705 lookback (make-vector count nil)))
1706 (setq i 0 j (length LA))
1708 (aset LA i (make-vector tokensetsize 0))
1713 (while (< i nstates)
1714 (when (not (aref consistent i))
1715 (setq rp (aref reduction-table i))
1718 k (reductions-nreds rp)
1719 v (reductions-rules rp))
1721 (aset LAruleno np (aref v j))
1726 (defun wisent-set-goto-map ()
1728 (let (sp i j symbol k temp-map state1 state2 v)
1729 (setq goto-map (make-vector (1+ nvars) 0)
1730 temp-map (make-vector (1+ nvars) 0))
1735 (setq i (1- (shifts-nshifts sp))
1736 v (shifts-shifts sp))
1738 (setq symbol (aref accessing-symbol (aref v i)))
1739 (if (wisent-ISTOKEN symbol)
1741 (setq ngotos (1+ ngotos))
1742 ;; goto-map[symbol]++;
1743 (aset goto-map (- symbol ntokens)
1744 (1+ (aref goto-map (- symbol ntokens)))))
1746 (setq sp (shifts-next sp)))
1753 (setq k (+ k (aref goto-map j))
1759 (aset goto-map j (aref temp-map j))
1762 ;; goto-map[nsyms] = ngotos;
1763 ;; temp-map[nsyms] = ngotos;
1764 (aset goto-map j ngotos)
1765 (aset temp-map j ngotos)
1767 (setq from-state (make-vector ngotos 0)
1768 to-state (make-vector ngotos 0)
1771 (setq state1 (shifts-number sp)
1772 v (shifts-shifts sp)
1773 i (1- (shifts-nshifts sp)))
1775 (setq state2 (aref v i)
1776 symbol (aref accessing-symbol state2))
1777 (if (wisent-ISTOKEN symbol)
1779 ;; k = temp-map[symbol]++;
1780 (setq k (aref temp-map (- symbol ntokens)))
1781 (aset temp-map (- symbol ntokens) (1+ k))
1782 (aset from-state k state1)
1783 (aset to-state k state2))
1785 (setq sp (shifts-next sp)))
1788 (defun wisent-map-goto (state symbol)
1789 "Map a STATE/SYMBOL pair into its numeric representation."
1790 (let (high low middle s result)
1791 ;; low = goto-map[symbol];
1792 ;; high = goto-map[symbol + 1] - 1;
1793 (setq low (aref goto-map (- symbol ntokens))
1794 high (1- (aref goto-map (- (1+ symbol) ntokens))))
1795 (while (and (not result) (<= low high))
1796 (setq middle (/ (+ low high) 2)
1797 s (aref from-state middle))
1800 (setq result middle))
1802 (setq low (1+ middle)))
1804 (setq high (1- middle)))))
1806 (error "Internal error in `wisent-map-goto'"))
1809 (defun wisent-initialize-F ()
1811 (let (i j k sp edge rowp rp reads nedges stateno symbol v break)
1812 (setq F (make-vector ngotos nil)
1815 (aset F i (make-vector tokensetsize 0))
1818 (setq reads (make-vector ngotos nil)
1819 edge (make-vector (1+ ngotos) 0)
1824 (setq stateno (aref to-state i)
1825 sp (aref shift-table stateno))
1827 (setq k (shifts-nshifts sp)
1828 v (shifts-shifts sp)
1831 (while (and (not break) (< j k))
1832 ;; symbol = accessing-symbol[sp->shifts[j]];
1833 (setq symbol (aref accessing-symbol (aref v j)))
1834 (if (wisent-ISVAR symbol)
1835 (setq break t) ;; break
1836 (wisent-SETBIT (aref F rowp) symbol)
1840 ;; symbol = accessing-symbol[sp->shifts[j]];
1841 (setq symbol (aref accessing-symbol (aref v j)))
1842 (when (aref nullable (- symbol ntokens))
1843 (aset edge nedges (wisent-map-goto stateno symbol))
1844 (setq nedges (1+ nedges)))
1848 ;; reads[i] = rp = NEW2(nedges + 1, short);
1849 (setq rp (make-vector (1+ nedges) 0)
1854 (aset rp j (aref edge j))
1858 (setq rowp (1+ rowp))
1860 (wisent-digraph reads)
1863 (defun wisent-add-lookback-edge (stateno ruleno gotono)
1864 "Add a lookback edge.
1865 STATENO, RULENO, GOTONO are self-explanatory."
1867 (setq i (aref lookaheads stateno)
1868 k (aref lookaheads (1+ stateno))
1870 (while (and (not found) (< i k))
1871 (if (= (aref LAruleno i) ruleno)
1876 (error "Internal error in `wisent-add-lookback-edge'"))
1879 ;; lookback[i] = (gotono . lookback[i])
1880 (aset lookback i (cons gotono (aref lookback i)))))
1882 (defun wisent-transpose (R-arg n)
1883 "Return the transpose of R-ARG, of size N.
1884 Destroy R-ARG, as it is replaced with the result. R-ARG[I] is nil or
1885 a -1 terminated list of numbers. RESULT[NUM] is nil or the -1
1886 terminated list of the I such as NUM is in R-ARG[I]."
1887 (let (i j new-R end-R nedges v sp)
1888 (setq new-R (make-vector n nil)
1889 end-R (make-vector n nil)
1890 nedges (make-vector n 0))
1895 (setq v (aref R-arg i))
1898 (while (>= (aref v j) 0)
1899 (aset nedges (aref v j) (1+ (aref nedges (aref v j))))
1906 (when (> (aref nedges i) 0)
1907 (setq sp (make-vector (1+ (aref nedges i)) 0))
1908 (aset sp (aref nedges i) -1)
1916 (setq v (aref R-arg i))
1919 (while (>= (aref v j) 0)
1920 (aset (aref new-R (aref v j)) (aref end-R (aref v j)) i)
1921 (aset end-R (aref v j) (1+ (aref end-R (aref v j))))
1927 (defun wisent-build-relations ()
1929 (let (i j k rulep rp sp length nedges done state1 stateno
1930 symbol1 symbol2 edge states v)
1931 (setq includes (make-vector ngotos nil)
1932 edge (make-vector (1+ ngotos) 0)
1933 states (make-vector (1+ maxrhs) 0)
1938 state1 (aref from-state i)
1939 symbol1 (aref accessing-symbol (aref to-state i))
1940 rulep (aref derives (- symbol1 ntokens)))
1942 (while (> (car rulep) 0)
1943 (aset states 0 state1)
1946 rp (aref rrhs (car rulep))) ;; rp = ritem + rrhs[*rulep]
1947 (while (> (aref ritem rp) 0) ;; *rp > 0
1948 (setq symbol2 (aref ritem rp)
1949 sp (aref shift-table stateno)
1950 k (shifts-nshifts sp)
1951 v (shifts-shifts sp)
1954 (setq stateno (aref v j))
1955 (if (= (aref accessing-symbol stateno) symbol2)
1958 ;; states[length++] = stateno;
1959 (aset states length stateno)
1960 (setq length (1+ length))
1963 (if (not (aref consistent stateno))
1964 (wisent-add-lookback-edge stateno (car rulep) i))
1966 (setq length (1- length)
1971 (when (and (>= rp 0) (wisent-ISVAR (aref ritem rp)))
1972 ;; stateno = states[--length];
1973 (setq length (1- length)
1974 stateno (aref states length))
1975 (aset edge nedges (wisent-map-goto stateno (aref ritem rp)))
1976 (setq nedges (1+ nedges))
1977 (if (aref nullable (- (aref ritem rp) ntokens))
1979 (setq rulep (cdr rulep)))
1982 (setq v (make-vector (1+ nedges) 0)
1986 (aset v j (aref edge j))
1991 (setq includes (wisent-transpose includes ngotos))
1994 (defun wisent-compute-FOLLOWS ()
1996 (wisent-digraph includes))
1998 (defun wisent-compute-lookaheads ()
1999 "Compute lookaheads."
2000 (let (i j n v1 v2 sp)
2001 (setq n (aref lookaheads nstates)
2004 (setq sp (aref lookback i))
2006 (setq v1 (aref LA i)
2007 v2 (aref F (car sp))
2009 (while (< j tokensetsize)
2010 ;; LA (i)[j] |= F (sp->value)[j]
2011 (aset v1 j (logior (aref v1 j) (aref v2 j)))
2016 (defun wisent-lalr ()
2017 "Make the nondeterministic finite state machine deterministic."
2018 (setq tokensetsize (wisent-WORDSIZE ntokens))
2019 (wisent-set-state-table)
2020 (wisent-set-accessing-symbol)
2021 (wisent-set-shift-table)
2022 (wisent-set-reduction-table)
2024 (wisent-initialize-LA)
2025 (wisent-set-goto-map)
2026 (wisent-initialize-F)
2027 (wisent-build-relations)
2028 (wisent-compute-FOLLOWS)
2029 (wisent-compute-lookaheads))
2031 ;;;; -----------------------------------------------
2032 ;;;; Find and resolve or report look-ahead conflicts
2033 ;;;; -----------------------------------------------
2035 (defsubst wisent-log-resolution (state LAno token resolution)
2036 "Log a shift-reduce conflict resolution.
2037 In specified STATE between rule pointed by lookahead number LANO and
2038 TOKEN, resolved as RESOLUTION."
2039 (if (or wisent-verbose-flag wisent-debug-flag)
2041 "Conflict in state %d between rule %d and token %s resolved as %s.\n"
2042 state (aref LAruleno LAno) (wisent-tag token) resolution)))
2044 (defun wisent-flush-shift (state token)
2045 "Turn off the shift recorded in the specified STATE for TOKEN.
2046 Used when we resolve a shift-reduce conflict in favor of the reduction."
2048 (when (setq shiftp (aref shift-table state))
2049 (setq k (shifts-nshifts shiftp)
2050 v (shifts-shifts shiftp)
2053 (if (and (not (zerop (aref v i)))
2054 (= token (aref accessing-symbol (aref v i))))
2058 (defun wisent-resolve-sr-conflict (state lookaheadnum)
2059 "Attempt to resolve shift-reduce conflict for one rule.
2060 Resolve by means of precedence declarations. The conflict occurred in
2061 specified STATE for the rule pointed by the lookahead symbol
2062 LOOKAHEADNUM. It has already been checked that the rule has a
2063 precedence. A conflict is resolved by modifying the shift or reduce
2064 tables so that there is no longer a conflict."
2065 (let (i redprec errp errs nerrs token sprec sassoc)
2066 ;; Find the rule to reduce by to get precedence of reduction
2067 (setq token (aref tags (aref rprec (aref LAruleno lookaheadnum)))
2068 redprec (wisent-prec token)
2070 errs (make-vector ntokens 0)
2073 (set-errs-errs errp errs)
2074 (while (< i ntokens)
2075 (setq token (aref tags i))
2076 (when (and (wisent-BITISSET (aref LA lookaheadnum) i)
2077 (wisent-BITISSET lookaheadset i)
2078 (setq sprec (wisent-prec token)))
2079 ;; Shift-reduce conflict occurs for token number I and it has
2080 ;; a precedence. The precedence of shifting is that of token
2084 (wisent-log-resolution state lookaheadnum i "reduce")
2085 ;; Flush the shift for this token
2086 (wisent-RESETBIT lookaheadset i)
2087 (wisent-flush-shift state i)
2090 (wisent-log-resolution state lookaheadnum i "shift")
2091 ;; Flush the reduce for this token
2092 (wisent-RESETBIT (aref LA lookaheadnum) i)
2095 ;; Matching precedence levels.
2096 ;; For left association, keep only the reduction.
2097 ;; For right association, keep only the shift.
2098 ;; For nonassociation, keep neither.
2099 (setq sassoc (wisent-assoc token))
2102 (wisent-log-resolution state lookaheadnum i "shift"))
2104 (wisent-log-resolution state lookaheadnum i "reduce"))
2105 ((eq sassoc 'nonassoc)
2106 (wisent-log-resolution state lookaheadnum i "an error"))
2108 (when (not (eq sassoc 'right))
2109 ;; Flush the shift for this token
2110 (wisent-RESETBIT lookaheadset i)
2111 (wisent-flush-shift state i))
2112 (when (not (eq sassoc 'left))
2113 ;; Flush the reduce for this token
2114 (wisent-RESETBIT (aref LA lookaheadnum) i))
2115 (when (eq sassoc 'nonassoc)
2116 ;; Record an explicit error for this token
2118 (setq nerrs (1+ nerrs)))
2122 (set-errs-nerrs errp nerrs)
2123 (aset err-table state errp))
2126 (defun wisent-set-conflicts (state)
2127 "Find and attempt to resolve conflicts in specified STATE."
2128 (let (i j k v shiftp symbol)
2129 (unless (aref consistent state)
2130 (fillarray lookaheadset 0)
2132 (when (setq shiftp (aref shift-table state))
2133 (setq k (shifts-nshifts shiftp)
2134 v (shifts-shifts shiftp)
2138 (setq symbol (aref accessing-symbol (aref v i)))))
2139 (or (zerop (aref v i))
2140 (wisent-SETBIT lookaheadset symbol))
2143 ;; Loop over all rules which require lookahead in this state
2144 ;; first check for shift-reduce conflict, and try to resolve
2146 (setq i (aref lookaheads state)
2147 k (aref lookaheads (1+ state)))
2149 (when (aref rprec (aref LAruleno i))
2152 (while (< j tokensetsize)
2153 (if (zerop (logand (aref v j) (aref lookaheadset j)))
2155 ;; if (LA (i)[j] & lookaheadset[j])
2156 (wisent-resolve-sr-conflict state i)
2157 (setq j tokensetsize)))) ;; break
2160 ;; Loop over all rules which require lookahead in this state
2161 ;; Check for conflicts not resolved above.
2162 (setq i (aref lookaheads state))
2166 (while (< j tokensetsize)
2167 ;; if (LA (i)[j] & lookaheadset[j])
2168 (if (not (zerop (logand (aref v j) (aref lookaheadset j))))
2169 (aset conflicts state t))
2172 (while (< j tokensetsize)
2173 ;; lookaheadset[j] |= LA (i)[j];
2174 (aset lookaheadset j (logior (aref lookaheadset j)
2180 (defun wisent-resolve-conflicts ()
2181 "Find and resolve conflicts."
2183 (setq conflicts (make-vector nstates nil)
2184 shiftset (make-vector tokensetsize 0)
2185 lookaheadset (make-vector tokensetsize 0)
2186 err-table (make-vector nstates nil)
2188 (while (< i nstates)
2189 (wisent-set-conflicts i)
2192 (defun wisent-count-sr-conflicts (state)
2193 "Count the number of shift/reduce conflicts in specified STATE."
2194 (let (i j k shiftp symbol v)
2196 shiftp (aref shift-table state))
2198 (fillarray shiftset 0)
2199 (fillarray lookaheadset 0)
2200 (setq k (shifts-nshifts shiftp)
2201 v (shifts-shifts shiftp)
2204 (when (not (zerop (aref v i)))
2205 (setq symbol (aref accessing-symbol (aref v i)))
2206 (if (wisent-ISVAR symbol)
2208 (wisent-SETBIT shiftset symbol)))
2211 (setq k (aref lookaheads (1+ state))
2212 i (aref lookaheads state))
2216 (while (< j tokensetsize)
2217 ;; lookaheadset[j] |= LA (i)[j]
2218 (aset lookaheadset j (logior (aref lookaheadset j)
2224 (while (< k tokensetsize)
2225 ;; lookaheadset[k] &= shiftset[k];
2226 (aset lookaheadset k (logand (aref lookaheadset k)
2231 (while (< i ntokens)
2232 (if (wisent-BITISSET lookaheadset i)
2233 (setq src-count (1+ src-count)))
2237 (defun wisent-count-rr-conflicts (state)
2238 "Count the number of reduce/reduce conflicts in specified STATE."
2239 (let (i j count n m)
2241 m (aref lookaheads state)
2242 n (aref lookaheads (1+ state)))
2243 (when (>= (- n m) 2)
2245 (while (< i ntokens)
2249 (if (wisent-BITISSET (aref LA j) i)
2250 (setq count (1+ count)))
2254 (setq rrc-count (1+ rrc-count)))
2258 (defvar wisent-expected-conflicts nil
2259 "*If non-nil suppress the warning about shift/reduce conflicts.
2260 It is a decimal integer N that says there should be no warning if
2261 there are N shift/reduce conflicts and no reduce/reduce conflicts. A
2262 warning is given if there are either more or fewer conflicts, or if
2263 there are any reduce/reduce conflicts.")
2265 (defun wisent-total-conflicts ()
2266 "Report the total number of conflicts."
2267 (unless (and (zerop rrc-total)
2268 (or (zerop src-total)
2269 (= src-total (or wisent-expected-conflicts 0))))
2270 (let* ((src (wisent-source))
2271 (src (if src (concat " in " src) ""))
2272 (msg (format "Grammar%s contains" src)))
2274 (setq msg (format "%s %d shift/reduce conflict%s"
2275 msg src-total (if (> src-total 1)
2277 (if (and (> src-total 0) (> rrc-total 0))
2278 (setq msg (format "%s and" msg)))
2280 (setq msg (format "%s %d reduce/reduce conflict%s"
2281 msg rrc-total (if (> rrc-total 1)
2285 (defun wisent-print-conflicts ()
2291 (while (< i nstates)
2292 (when (aref conflicts i)
2293 (wisent-count-sr-conflicts i)
2294 (wisent-count-rr-conflicts i)
2295 (setq src-total (+ src-total src-count)
2296 rrc-total (+ rrc-total rrc-count))
2297 (when (or wisent-verbose-flag wisent-debug-flag)
2298 (wisent-log "State %d contains" i)
2300 (wisent-log " %d shift/reduce conflict%s"
2301 src-count (if (> src-count 1) "s" "")))
2303 (if (and (> src-count 0) (> rrc-count 0))
2304 (wisent-log " and"))
2307 (wisent-log " %d reduce/reduce conflict%s"
2308 rrc-count (if (> rrc-count 1) "s" "")))
2310 (wisent-log ".\n")))
2312 (wisent-total-conflicts)))
2314 ;;;; --------------------------------------
2315 ;;;; Report information on generated parser
2316 ;;;; --------------------------------------
2317 (defun wisent-print-grammar ()
2319 (let (i j r break left-count right-count)
2321 (wisent-log "\n\nGrammar\n\n Number, Rule\n")
2323 (while (<= i nrules)
2324 ;; Don't print rules disabled in `wisent-reduce-grammar-tables'.
2325 (when (aref ruseful i)
2326 (wisent-log " %s %s ->"
2327 (wisent-pad-string (number-to-string i) 6)
2328 (wisent-tag (aref rlhs i)))
2329 (setq r (aref rrhs i))
2330 (if (> (aref ritem r) 0)
2331 (while (> (aref ritem r) 0)
2332 (wisent-log " %s" (wisent-tag (aref ritem r)))
2334 (wisent-log " /* empty */"))
2338 (wisent-log "\n\nTerminals, with rules where they appear\n\n")
2339 (wisent-log "%s (-1)\n" (wisent-tag 0))
2341 (while (< i ntokens)
2342 (wisent-log "%s (%d)" (wisent-tag i) i)
2344 (while (<= j nrules)
2345 (setq r (aref rrhs j)
2347 (while (and (not break) (> (aref ritem r) 0))
2348 (if (setq break (= (aref ritem r) i))
2349 (wisent-log " %d" j)
2355 (wisent-log "\n\nNonterminals, with rules where they appear\n\n")
2361 (while (<= j nrules)
2362 (if (= (aref rlhs j) i)
2363 (setq left-count (1+ left-count)))
2364 (setq r (aref rrhs j)
2366 (while (and (not break) (> (aref ritem r) 0))
2367 (if (= (aref ritem r) i)
2368 (setq right-count (1+ right-count)
2372 (wisent-log "%s (%d)\n " (wisent-tag i) i)
2373 (when (> left-count 0)
2374 (wisent-log " on left:")
2376 (while (<= j nrules)
2377 (if (= (aref rlhs j) i)
2378 (wisent-log " %d" j))
2380 (when (> right-count 0)
2381 (if (> left-count 0)
2383 (wisent-log " on right:")
2385 (while (<= j nrules)
2386 (setq r (aref rrhs j)
2388 (while (and (not break) (> (aref ritem r) 0))
2389 (if (setq break (= (aref ritem r) i))
2390 (wisent-log " %d" j)
2397 (defun wisent-print-reductions (state)
2398 "Print reductions on STATE."
2399 (let (i j k v symbol m n defaulted
2400 default-LA default-rule cmax count shiftp errp nodefault)
2403 (fillarray shiftset 0)
2405 (setq shiftp (aref shift-table state))
2407 (setq k (shifts-nshifts shiftp)
2408 v (shifts-shifts shiftp)
2411 (when (not (zerop (aref v i)))
2412 (setq symbol (aref accessing-symbol (aref v i)))
2413 (if (wisent-ISVAR symbol)
2415 ;; If this state has a shift for the error token, don't
2416 ;; use a default rule.
2417 (if (= symbol error-token-number)
2419 (wisent-SETBIT shiftset symbol)))
2422 (setq errp (aref err-table state))
2424 (setq k (errs-nerrs errp)
2428 (if (not (zerop (setq symbol (aref v i))))
2429 (wisent-SETBIT shiftset symbol))
2432 (setq m (aref lookaheads state)
2433 n (aref lookaheads (1+ state)))
2436 ((and (= (- n m) 1) (not nodefault))
2437 (setq default-rule (aref LAruleno m)
2440 (while (< k tokensetsize)
2441 (aset lookaheadset k (logand (aref v k)
2446 (while (< i ntokens)
2447 (if (wisent-BITISSET lookaheadset i)
2448 (wisent-log " %s\t[reduce using rule %d (%s)]\n"
2449 (wisent-tag i) default-rule
2450 (wisent-tag (aref rlhs default-rule))))
2452 (wisent-log " $default\treduce using rule %d (%s)\n\n"
2454 (wisent-tag (aref rlhs default-rule)))
2460 (when (not nodefault)
2466 (while (< k tokensetsize)
2467 ;; lookaheadset[k] = LA (i)[k] & ~shiftset[k]
2468 (aset lookaheadset k
2470 (lognot (aref shiftset k))))
2473 (while (< j ntokens)
2474 (if (wisent-BITISSET lookaheadset j)
2475 (setq count (1+ count)))
2480 default-rule (aref LAruleno i)))
2482 (while (< k tokensetsize)
2483 (aset shiftset k (logior (aref shiftset k)
2484 (aref lookaheadset k)))
2488 (fillarray shiftset 0)
2491 (setq k (shifts-nshifts shiftp)
2492 v (shifts-shifts shiftp)
2495 (when (not (zerop (aref v i)))
2496 (setq symbol (aref accessing-symbol (aref v i)))
2497 (if (wisent-ISVAR symbol)
2499 (wisent-SETBIT shiftset symbol)))
2503 (while (< i ntokens)
2505 count (if (wisent-BITISSET shiftset i) 1 0)
2508 (when (wisent-BITISSET (aref LA j) i)
2511 (if (not (= j default-LA))
2513 " %s\treduce using rule %d (%s)\n"
2514 (wisent-tag i) (aref LAruleno j)
2515 (wisent-tag (aref rlhs (aref LAruleno j))))
2517 (setq count (1+ count)))
2520 " %s\treduce using rule %d (%s)\n"
2521 (wisent-tag i) (aref LAruleno default-LA)
2522 (wisent-tag (aref rlhs (aref LAruleno default-LA)))))
2523 (setq defaulted nil)
2525 " %s\t[reduce using rule %d (%s)]\n"
2526 (wisent-tag i) (aref LAruleno j)
2527 (wisent-tag (aref rlhs (aref LAruleno j))))))
2531 (if (>= default-LA 0)
2533 " $default\treduce using rule %d (%s)\n"
2535 (wisent-tag (aref rlhs default-rule))))
2538 (defun wisent-print-actions (state)
2539 "Print actions on STATE."
2540 (let (i j k v state1 symbol shiftp errp redp rule nerrs break)
2541 (setq shiftp (aref shift-table state)
2542 redp (aref reduction-table state)
2543 errp (aref err-table state))
2544 (if (and (not shiftp) (not redp))
2545 (if (= final-state state)
2546 (wisent-log " $default\taccept\n")
2547 (wisent-log " NO ACTIONS\n"))
2551 (setq k (shifts-nshifts shiftp)
2552 v (shifts-shifts shiftp)
2555 (while (and (not break) (< i k))
2556 (if (zerop (setq state1 (aref v i)))
2558 (setq symbol (aref accessing-symbol state1))
2559 ;; The following line used to be turned off.
2560 (if (wisent-ISVAR symbol)
2561 (setq break t) ;; break
2562 (wisent-log " %s\tshift, and go to state %d\n"
2563 (wisent-tag symbol) state1)
2569 (setq nerrs (errs-nerrs errp)
2574 (wisent-log " %s\terror (nonassociative)\n"
2575 (wisent-tag (aref v j))))
2581 ((and (aref consistent state) redp)
2582 (setq rule (aref (reductions-rules redp) 0)
2583 symbol (aref rlhs rule))
2584 (wisent-log " $default\treduce using rule %d (%s)\n\n"
2585 rule (wisent-tag symbol))
2588 (wisent-print-reductions state)
2592 (setq v (shifts-shifts shiftp))
2594 (when (setq state1 (aref v i))
2595 (setq symbol (aref accessing-symbol state1))
2596 (wisent-log " %s\tgo to state %d\n"
2597 (wisent-tag symbol) state1))
2602 (defun wisent-print-core (state)
2604 (let (i k rule statep sp sp1)
2605 (setq statep (aref state-table state)
2606 k (core-nitems statep))
2610 ;; sp1 = sp = ritem + statep->items[i];
2611 (setq sp1 (aref (core-items statep) i)
2613 (while (> (aref ritem sp) 0)
2616 (setq rule (- (aref ritem sp)))
2617 (wisent-log " %s -> " (wisent-tag (aref rlhs rule)))
2619 (setq sp (aref rrhs rule))
2621 (wisent-log "%s " (wisent-tag (aref ritem sp)))
2624 (while (> (aref ritem sp) 0)
2625 (wisent-log " %s" (wisent-tag (aref ritem sp)))
2627 (wisent-log " (rule %d)\n" rule)
2629 (wisent-log "\n"))))
2631 (defun wisent-print-state (state)
2632 "Print information on STATE."
2633 (wisent-log "\n\nstate %d\n\n" state)
2634 (wisent-print-core state)
2635 (wisent-print-actions state))
2637 (defun wisent-print-states ()
2638 "Print information on states."
2640 (while (< i nstates)
2641 (wisent-print-state i)
2644 (defun wisent-print-results ()
2645 "Print information on generated parser.
2646 Report detailed information if `wisent-verbose-flag' or
2647 `wisent-debug-flag' are non-nil."
2648 (when (or wisent-verbose-flag wisent-debug-flag)
2649 (wisent-print-useless))
2650 (wisent-print-conflicts)
2651 (when (or wisent-verbose-flag wisent-debug-flag)
2652 (wisent-print-grammar)
2653 (wisent-print-states))
2654 ;; Append output to log file when running in batch mode
2655 (when (wisent-noninteractive)
2656 (wisent-append-to-log-file)
2657 (wisent-clear-log)))
2659 ;;;; ---------------------------------
2660 ;;;; Build the generated parser tables
2661 ;;;; ---------------------------------
2663 (defun wisent-action-row (state actrow)
2664 "Figure out the actions for the specified STATE.
2665 Decide what to do for each type of token if seen as the lookahead
2666 token in specified state. The value returned is used as the default
2667 action for the state. In addition, ACTROW is filled with what to do
2668 for each kind of token, index by symbol number, with nil meaning do
2669 the default action. The value 'error, means this situation is an
2670 error. The parser recognizes this value specially.
2672 This is where conflicts are resolved. The loop over lookahead rules
2673 considered lower-numbered rules last, and the last rule considered
2674 that likes a token gets to handle it."
2675 (let (i j k m n v default-rule nreds rule max count
2676 shift-state symbol redp shiftp errp nodefault)
2678 (fillarray actrow nil)
2680 (setq default-rule 0
2681 nodefault nil ;; nil inhibit having any default reduction
2685 redp (aref reduction-table state))
2688 (setq nreds (reductions-nreds redp))
2690 ;; loop over all the rules available here which require
2692 (setq m (aref lookaheads state)
2693 n (aref lookaheads (1+ state))
2696 ;; and find each token which the rule finds acceptable to
2699 (while (< j ntokens)
2700 ;; and record this rule as the rule to use if that token
2702 (if (wisent-BITISSET (aref LA i) j)
2703 (aset actrow j (- (aref LAruleno i)))
2708 ;; Now see which tokens are allowed for shifts in this state. For
2709 ;; them, record the shift as the thing to do. So shift is
2710 ;; preferred to reduce.
2711 (setq shiftp (aref shift-table state))
2713 (setq k (shifts-nshifts shiftp)
2714 v (shifts-shifts shiftp)
2717 (setq shift-state (aref v i))
2718 (if (zerop shift-state)
2720 (setq symbol (aref accessing-symbol shift-state))
2721 (if (wisent-ISVAR symbol)
2723 (aset actrow symbol shift-state)
2724 ;; Do not use any default reduction if there is a shift
2726 (if (= symbol error-token-number)
2727 (setq nodefault t))))
2730 ;; See which tokens are an explicit error in this state (due to
2731 ;; %nonassoc). For them, record error as the action.
2732 (setq errp (aref err-table state))
2734 (setq k (errs-nerrs errp)
2738 (aset actrow (aref v i) wisent-error-tag)
2741 ;; Now find the most common reduction and make it the default
2742 ;; action for this state.
2743 (when (and (>= nreds 1) (not nodefault))
2744 (if (aref consistent state)
2745 (setq default-rule (- (aref (reductions-rules redp) 0)))
2750 rule (- (aref LAruleno i))
2752 (while (< j ntokens)
2753 (if (and (numberp (aref actrow j))
2754 (= (aref actrow j) rule))
2755 (setq count (1+ count)))
2761 ;; actions which match the default are replaced with zero,
2762 ;; which means "use the default"
2765 (while (< j ntokens)
2766 (if (and (numberp (aref actrow j))
2767 (= (aref actrow j) default-rule))
2768 (aset actrow j nil))
2772 ;; If have no default rule, if this is the final state the default
2773 ;; is accept else it is an error. So replace any action which
2774 ;; says "error" with "use default".
2775 (when (zerop default-rule)
2776 (if (= final-state state)
2777 (setq default-rule wisent-accept-tag)
2779 (while (< j ntokens)
2780 (if (eq (aref actrow j) wisent-error-tag)
2781 (aset actrow j nil))
2783 (setq default-rule wisent-error-tag)))
2786 (defconst wisent-default-tag 'default
2787 "Tag used in an action table to indicate a default action.")
2789 ;; These variables only exist locally in the function
2790 ;; `wisent-state-actions' and are shared by all other nested callees.
2791 (wisent-defcontext semantic-actions
2792 ;; Uninterned symbols used in code generation.
2793 stack sp gotos state
2794 ;; Name of the current semantic action
2797 (defun wisent-state-actions ()
2798 "Figure out the actions for every state.
2799 Return the action table."
2800 ;; Store the semantic action obarray in (unused) RCODE[0].
2801 (aset rcode 0 (make-vector 13 0))
2802 (let (i j action-table actrow action)
2803 (setq action-table (make-vector nstates nil)
2804 actrow (make-vector ntokens nil)
2806 (wisent-with-context semantic-actions
2807 (setq stack (make-symbol "stack")
2808 sp (make-symbol "sp")
2809 gotos (make-symbol "gotos")
2810 state (make-symbol "state"))
2811 (while (< i nstates)
2812 (setq action (wisent-action-row i actrow))
2813 ;; Translate a reduction into semantic action
2814 (and (integerp action) (< action 0)
2815 (setq action (wisent-semantic-action (- action))))
2816 (aset action-table i (list (cons wisent-default-tag action)))
2818 (while (< j ntokens)
2819 (when (setq action (aref actrow j))
2820 ;; Translate a reduction into semantic action
2821 (and (integerp action) (< action 0)
2822 (setq action (wisent-semantic-action (- action))))
2823 (aset action-table i (cons (cons (aref tags j) action)
2824 (aref action-table i)))
2827 (aset action-table i (nreverse (aref action-table i)))
2831 (defun wisent-goto-actions ()
2832 "Figure out what to do after reducing with each rule.
2833 Depending on the saved state from before the beginning of parsing the
2834 data that matched this rule. Return the goto table."
2835 (let (i j m n symbol state goto-table)
2836 (setq goto-table (make-vector nstates nil)
2839 (setq symbol (- i ntokens)
2840 m (aref goto-map symbol)
2841 n (aref goto-map (1+ symbol))
2844 (setq state (aref from-state j))
2845 (aset goto-table state
2846 (cons (cons (aref tags i) (aref to-state j))
2847 (aref goto-table state)))
2852 (defsubst wisent-quote-p (sym)
2853 "Return non-nil if SYM is bound to the `quote' function."
2855 (eq (indirect-function sym)
2856 (indirect-function 'quote))
2859 (defsubst wisent-backquote-p (sym)
2860 "Return non-nil if SYM is bound to the `backquote' function."
2862 (eq (indirect-function sym)
2863 (indirect-function 'backquote))
2866 (defun wisent-check-$N (x m)
2867 "Return non-nil if X is a valid $N or $regionN symbol.
2868 That is if X is a $N or $regionN symbol with N >= 1 and N <= M.
2869 Also warn if X is a $N or $regionN symbol with N < 1 or N > M."
2871 (let* ((n (symbol-name x))
2872 (i (and (string-match "\\`\\$\\(region\\)?\\([0-9]+\\)\\'" n)
2873 (string-to-number (match-string 2 n)))))
2875 (if (and (>= i 1) (<= i m))
2878 "*** In %s, %s might be a free variable (rule has %s)"
2879 NAME x (format (cond ((< m 1) "no component")
2880 ((= m 1) "%d component")
2885 (defun wisent-semantic-action-expand-body (body n &optional found)
2886 "Parse BODY of semantic action.
2887 N is the maximum number of $N variables that can be referenced in
2888 BODY. Warn on references out of permitted range.
2889 Optional argument FOUND is the accumulated list of '$N' references
2891 Return a cons (FOUND . XBODY), where FOUND is the list of $N
2892 references found in BODY, and XBODY is BODY expression with
2893 `backquote' forms expanded."
2894 (if (not (listp body))
2895 ;; BODY is an atom, no expansion needed
2897 (if (wisent-check-$N body n)
2898 ;; Accumulate $i symbol
2899 (add-to-list 'found body))
2901 ;; BODY is a list, expand inside it
2903 ;; If backquote expand it first
2904 (if (wisent-backquote-p (car body))
2905 (setq body (macroexpand body)))
2907 (setq sexpr (car body)
2910 ;; Function call excepted quote expression
2912 (not (wisent-quote-p (car sexpr))))
2913 (setq sexpr (wisent-semantic-action-expand-body sexpr n found)
2917 ((wisent-check-$N sexpr n)
2918 ;; Accumulate $i symbol
2919 (add-to-list 'found sexpr))
2921 ;; Accumulate expanded forms
2922 (setq xbody (nconc xbody (list sexpr))))
2923 (cons found xbody))))
2925 (defun wisent-semantic-action (r)
2926 "Set up the Elisp function for semantic action at rule R.
2927 On entry RCODE[R] contains a vector [BODY N (NTERM I)] where BODY is the
2928 body of the semantic action, N is the maximum number of values
2929 available in the parser's stack, NTERM is the nonterminal the semantic
2930 action belongs to, and I is the index of the semantic action inside
2931 NTERM definition. Return the semantic action symbol.
2932 The semantic action function accepts three arguments:
2934 - the state/value stack
2935 - the top-of-stack index
2938 And returns the updated top-of-stack index."
2939 (if (not (aref ruseful r))
2941 (let* ((actn (aref rcode r))
2942 (n (aref actn 1)) ; nb of val avail. in stack
2943 (NAME (apply 'format "%s:%d" (aref actn 2)))
2944 (form (wisent-semantic-action-expand-body (aref actn 0) n))
2945 ($l (car form)) ; list of $vars used in body
2946 (form (cdr form)) ; expanded form of body
2947 (nt (aref rlhs r)) ; nonterminal item no.
2948 (bl nil) ; `let*' binding list
2951 ;; Compute $N and $regionN bindings
2954 (setq j (1+ (* 2 (- n i))))
2955 ;; Only bind $regionI if used in action
2956 (setq $v (intern (format "$region%d" i)))
2958 (setq bl (cons `(,$v (cdr (aref ,stack (- ,sp ,j)))) bl)))
2959 ;; Only bind $I if used in action
2960 (setq $v (intern (format "$%d" i)))
2962 (setq bl (cons `(,$v (car (aref ,stack (- ,sp ,j)))) bl)))
2965 ;; Compute J, the length of rule's RHS. It will give the
2966 ;; current parser state at STACK[SP - 2*J], and where to push
2967 ;; the new semantic value and the next state, respectively at:
2968 ;; STACK[SP - 2*J + 1] and STACK[SP - 2*J + 2]. Generally N,
2969 ;; the maximum number of values available in the stack, is equal
2970 ;; to J. But, for mid-rule actions, N is the number of rule
2971 ;; elements before the action and J is always 0 (empty rule).
2972 (setq i (aref rrhs r)
2974 (while (> (aref ritem i) 0)
2978 ;; Create the semantic action symbol.
2979 (setq actn (intern NAME (aref rcode 0)))
2981 ;; Store source code in function cell of the semantic action
2982 ;; symbol. It will be byte-compiled at automaton's compilation
2983 ;; time. Using a byte-compiled automaton can significantly
2984 ;; speed up parsing!
2986 `(lambda (,stack ,sp ,gotos)
2991 (if (assq '$region1 bl)
2993 `(cdr (aref ,stack (1- ,sp)))))
2995 `(wisent-production-bounds
2996 ,stack (- ,sp ,(1- (* 2 n))) (1- ,sp)))))
2998 ($nterm ',(aref tags nt))
2999 ,@(and (> j 0) `((,sp (- ,sp ,(* j 2)))))
3000 (,state (cdr (assq $nterm
3002 (aref ,stack ,sp))))))
3003 (setq ,sp (+ ,sp 2))
3004 ;; push semantic value
3005 (aset ,stack (1- ,sp) (cons ,form $region))
3007 (aset ,stack ,sp ,state)
3008 ;; return new top of stack
3011 ;; Return the semantic action symbol
3014 ;;;; ----------------------------
3015 ;;;; Build parser LALR automaton.
3016 ;;;; ----------------------------
3018 (defun wisent-parser-automaton ()
3019 "Compute and return LALR(1) automaton from GRAMMAR.
3020 GRAMMAR is in internal format. GRAM/ACTS are grammar rules
3021 in internal format. STARTS defines the start symbols."
3022 ;; Check for useless stuff
3023 (wisent-reduce-grammar)
3025 (wisent-set-derives)
3026 (wisent-set-nullable)
3027 ;; convert to nondeterministic finite state machine.
3028 (wisent-generate-states)
3029 ;; make it deterministic.
3031 ;; Find and record any conflicts: places where one token of
3032 ;; lookahead is not enough to disambiguate the parsing. Also
3033 ;; resolve s/r conflicts based on precedence declarations.
3034 (wisent-resolve-conflicts)
3035 (wisent-print-results)
3037 (vector (wisent-state-actions) ; action table
3038 (wisent-goto-actions) ; goto table
3039 start-table ; start symbols
3040 (aref rcode 0) ; sem. action symbol obarray
3044 ;;;; -------------------
3045 ;;;; Parse input grammar
3046 ;;;; -------------------
3048 (defconst wisent-reserved-symbols (list wisent-error-term)
3049 "The list of reserved symbols.
3050 Also all symbols starting with a character defined in
3051 `wisent-reserved-capitals' are reserved for internal use.")
3053 (defconst wisent-reserved-capitals '(?\$ ?\@)
3054 "The list of reserved capital letters.
3055 All symbol starting with one of these letters are reserved for
3058 (defconst wisent-starts-nonterm '$STARTS
3060 It gives the rules for start symbols.")
3062 (defvar wisent-single-start-flag nil
3063 "Non-nil means allows only one start symbol like in Bison.
3064 That is don't add extra start rules to the grammar. This is
3065 useful to compare the Wisent's generated automaton with the Bison's
3068 (defsubst wisent-ISVALID-VAR (x)
3069 "Return non-nil if X is a character or an allowed symbol."
3071 (not (memq (aref (symbol-name x) 0) wisent-reserved-capitals))
3072 (not (memq x wisent-reserved-symbols))))
3074 (defsubst wisent-ISVALID-TOKEN (x)
3075 "Return non-nil if X is a character or an allowed symbol."
3076 (or (wisent-char-p x)
3077 (wisent-ISVALID-VAR x)))
3079 (defun wisent-push-token (symbol &optional nocheck)
3080 "Push a new SYMBOL in the list of tokens.
3081 Bypass checking if NOCHECK is non-nil."
3083 (or nocheck (wisent-ISVALID-TOKEN symbol)
3084 (error "Invalid terminal symbol: %S" symbol))
3085 (if (memq symbol token-list)
3086 (message "*** duplicate terminal `%s' ignored" symbol)
3087 ;; Set up properties
3088 (wisent-set-prec symbol nil)
3089 (wisent-set-assoc symbol nil)
3090 (wisent-set-item-number symbol ntokens)
3092 (setq ntokens (1+ ntokens)
3093 token-list (cons symbol token-list))))
3095 (defun wisent-push-var (symbol &optional nocheck)
3096 "Push a new SYMBOL in the list of nonterminals.
3097 Bypass checking if NOCHECK is non-nil."
3100 (or (wisent-ISVALID-VAR symbol)
3101 (error "Invalid nonterminal symbol: %S" symbol))
3102 (if (memq symbol var-list)
3103 (error "Nonterminal `%s' already defined" symbol)))
3104 ;; Set up properties
3105 (wisent-set-item-number symbol nvars)
3107 (setq nvars (1+ nvars)
3108 var-list (cons symbol var-list)))
3110 (defun wisent-parse-nonterminals (defs)
3111 "Parse nonterminal definitions in DEFS.
3112 Fill in each element of the global arrays RPREC, RCODE, RUSEFUL with
3113 respectively rule precedence level, semantic action code and
3114 usefulness flag. Return a list of rules of the form (LHS . RHS) where
3115 LHS and RHS are respectively the Left Hand Side and Right Hand Side of
3121 (let (def nonterm rlist rule rules rhs rest item items
3122 rhl plevel semact @n @count iactn)
3125 (setq def (car defs)
3131 (error "Invalid nonterminal definition syntax: %S" def))
3133 (setq rule (car rlist)
3140 ;; Check & count items
3141 (setq nitems (1+ nitems)) ;; LHS item
3143 (setq item (car items)
3145 nitems (1+ nitems)) ;; RHS items
3149 (setq @count (1+ @count)
3150 @n (intern (format "@%d" @count)))
3151 (wisent-push-var @n t)
3152 ;; Push a new empty rule with the mid-rule action
3153 (setq semact (vector item rhl (list nonterm iactn))
3156 rcode (cons semact rcode)
3157 rprec (cons plevel rprec)
3158 item @n ;; Replace action by @N nonterminal
3159 rules (cons (list item) rules)
3161 nrules (1+ nrules)))
3162 ;; Check terminal or nonterminal symbol
3164 ((or (memq item token-list) (memq item var-list)))
3165 ;; Create new literal character token
3166 ((wisent-char-p item) (wisent-push-token item t))
3167 ((error "Symbol `%s' is used, but is not defined as a token and has no rules"
3170 rhs (cons item rhs)))
3172 ;; Check & collect rule precedence level
3173 (setq plevel (when (vectorp (car rest))
3174 (setq item (car rest)
3176 (if (and (= (length item) 1)
3177 (memq (aref item 0) token-list)
3178 (wisent-prec (aref item 0)))
3179 (wisent-item-number (aref item 0))
3180 (error "Invalid rule precedence level syntax: %S" item)))
3181 rprec (cons plevel rprec))
3183 ;; Check & collect semantic action body
3184 (setq semact (vector
3187 (error "Invalid semantic action syntax: %S" rest)
3189 ;; Give a default semantic action body: nil
3190 ;; for an empty rule or $1, the value of the
3191 ;; first symbol in the rule, otherwise.
3192 (if (> rhl 0) '$1 '()))
3194 (list nonterm iactn))
3196 rcode (cons semact rcode))
3197 (setq rules (cons (cons nonterm (nreverse rhs)) rules)
3198 nrules (1+ nrules))))
3200 (setq ruseful (make-vector (1+ nrules) t)
3201 rprec (vconcat (cons nil (nreverse rprec)))
3202 rcode (vconcat (cons nil (nreverse rcode))))
3206 (defun wisent-parse-grammar (grammar &optional start-list)
3207 "Parse GRAMMAR and build a suitable internal representation.
3208 Optional argument START-LIST defines the start symbols.
3209 GRAMMAR is a list of form: (TOKENS ASSOCS . NONTERMS)
3211 TOKENS is a list of terminal symbols (tokens).
3213 ASSOCS is nil or an alist of (ASSOC-TYPE . ASSOC-VALUE) elements
3214 describing the associativity of TOKENS. ASSOC-TYPE must be one of the
3215 `default-prec' `nonassoc', `left' or `right' symbols. When ASSOC-TYPE
3216 is `default-prec', ASSOC-VALUE must be nil or t (the default).
3217 Otherwise it is a list of tokens which must have been previously
3220 NONTERMS is the list of non terminal definitions (see function
3221 `wisent-parse-nonterminals')."
3222 (or (and (consp grammar) (> (length grammar) 2))
3223 (error "Bad input grammar"))
3225 (let (i r rhs pre dpre lst start-var assoc rules item
3226 token var def tokens defs ep-token ep-var ep-def)
3229 (setq ntokens 0 nvars 0)
3230 (wisent-push-token wisent-eoi-term t)
3231 (wisent-push-token wisent-error-term t)
3233 ;; Check/collect terminals
3234 (setq lst (car grammar))
3236 (wisent-push-token (car lst))
3237 (setq lst (cdr lst)))
3239 ;; Check/Set up tokens precedence & associativity
3240 (setq lst (nth 1 grammar)
3250 (if (eq assoc 'default-prec)
3252 (or (null (cdr tokens))
3253 (memq (car tokens) '(t nil))
3254 (error "Invalid default-prec value: %S" tokens))
3255 (setq default-prec (car tokens))
3257 (message "*** redefining default-prec to %s"
3260 (or (memq assoc '(left right nonassoc))
3261 (error "Invalid associativity syntax: %S" assoc))
3264 (setq token (car tokens)
3265 tokens (cdr tokens))
3266 (if (memq token defs)
3267 (message "*** redefining precedence of `%s'" token))
3268 (or (memq token token-list)
3269 ;; Define token not previously declared.
3270 (wisent-push-token token))
3271 (setq defs (cons token defs))
3272 ;; Record the precedence and associativity of the terminal.
3273 (wisent-set-prec token pre)
3274 (wisent-set-assoc token assoc))))
3276 ;; Check/Collect nonterminals
3277 (setq lst (nthcdr 2 grammar)
3283 (error "Invalid nonterminal definition: %S" def))
3284 (if (memq (car def) token-list)
3285 (error "Nonterminal `%s' already defined as token" (car def)))
3286 (wisent-push-var (car def))
3287 (setq defs (cons def defs)))
3289 (error "No input grammar"))
3290 (setq defs (nreverse defs))
3292 ;; Set up the start symbol.
3293 (setq start-table nil)
3296 ;; 1. START-LIST is nil, the start symbol is the first
3297 ;; nonterminal defined in the grammar (Bison like).
3299 (setq start-var (caar defs)))
3301 ;; 2. START-LIST contains only one element, it is the start
3302 ;; symbol (Bison like).
3303 ((or wisent-single-start-flag (null (cdr start-list)))
3304 (setq start-var (car start-list))
3305 (or (assq start-var defs)
3306 (error "Start symbol `%s' has no rule" start-var)))
3308 ;; 3. START-LIST contains more than one element. All defines
3309 ;; potential start symbols. One of them (the first one by
3310 ;; default) will be given at parse time to be the parser goal.
3311 ;; If `wisent-single-start-flag' is non-nil that feature is
3312 ;; disabled and the first nonterminal in START-LIST defines
3313 ;; the start symbol, like in case 2 above.
3314 ((not wisent-single-start-flag)
3316 ;; START-LIST is a list of nonterminals '(nt0 ... ntN).
3317 ;; Build and push ad hoc start rules in the grammar:
3319 ;; ($STARTS ((nt0) $1) ((nt1) $1) ... ((ntN) $1))
3320 ;; ($nt1 (($$nt1 nt1) $2))
3322 ;; ($ntN (($$ntN ntN) $2))
3324 ;; Where internal symbols $ntI and $$ntI are respectively
3325 ;; nonterminals and terminals.
3327 ;; The internal start symbol $STARTS is used to build the
3328 ;; LALR(1) automaton. The true default start symbol used by the
3329 ;; parser is the first nonterminal in START-LIST (nt0).
3330 (setq start-var wisent-starts-nonterm
3331 lst (nreverse start-list))
3335 (or (memq var var-list)
3336 (error "Start symbol `%s' has no rule" var))
3337 (unless (assq var start-table) ;; Ignore duplicates
3338 ;; For each nt start symbol
3339 (setq ep-var (intern (format "$%s" var))
3340 ep-token (intern (format "$$%s" var)))
3341 (wisent-push-token ep-token t)
3342 (wisent-push-var ep-var t)
3344 ;; Add entry (nt . $$nt) to start-table
3345 start-table (cons (cons var ep-token) start-table)
3346 ;; Add rule ($nt (($$nt nt) $2))
3347 defs (cons (list ep-var (list (list ep-token var) '$2)) defs)
3348 ;; Add start rule (($nt) $1)
3349 ep-def (cons (list (list ep-var) '$1) ep-def))
3351 (wisent-push-var start-var t)
3352 (setq defs (cons (cons start-var ep-def) defs))))
3354 ;; Set up rules main data structure & RPREC, RCODE, RUSEFUL
3355 (setq rules (wisent-parse-nonterminals defs))
3357 ;; Set up the terminal & nonterminal lists.
3358 (setq nsyms (+ ntokens nvars)
3359 token-list (nreverse token-list)
3365 var-list (cons var var-list))
3366 (wisent-set-item-number ;; adjust nonterminal item number to
3367 var (+ ntokens (wisent-item-number var)))) ;; I += NTOKENS
3369 ;; Store special item numbers
3370 (setq error-token-number (wisent-item-number wisent-error-term)
3371 start-symbol (wisent-item-number start-var))
3373 ;; Keep symbols in the TAGS vector so that TAGS[I] is the symbol
3374 ;; associated to item number I.
3375 (setq tags (vconcat token-list var-list))
3376 ;; Set up RLHS RRHS & RITEM data structures from list of rules
3377 ;; (LHS . RHS) received from `wisent-parse-nonterminals'.
3378 (setq rlhs (make-vector (1+ nrules) nil)
3379 rrhs (make-vector (1+ nrules) nil)
3380 ritem (make-vector (1+ nitems) nil)
3384 (aset rlhs r (wisent-item-number (caar rules)))
3386 (setq rhs (cdar rules)
3389 (setq item (wisent-item-number (car rhs)))
3390 ;; Get default precedence level of rule, that is the
3391 ;; precedence of the last terminal in it.
3392 (and (wisent-ISTOKEN item)
3399 ;; Setup the precedence level of the rule, that is the one
3400 ;; specified by %prec or the default one.
3401 (and (not (aref rprec r)) ;; Already set by %prec
3403 (wisent-prec (aref tags pre))
3405 (aset ritem i (- r))
3408 (setq rules (cdr rules)))
3411 ;;;; ---------------------
3412 ;;;; Compile input grammar
3413 ;;;; ---------------------
3415 (defun wisent-compile-grammar (grammar &optional start-list)
3416 "Compile the LALR(1) GRAMMAR.
3418 GRAMMAR is a list (TOKENS ASSOCS . NONTERMS) where:
3420 - TOKENS is a list of terminal symbols (tokens).
3422 - ASSOCS is nil, or an alist of (ASSOC-TYPE . ASSOC-VALUE) elements
3423 describing the associativity of TOKENS. ASSOC-TYPE must be one of
3424 the `default-prec' `nonassoc', `left' or `right' symbols. When
3425 ASSOC-TYPE is `default-prec', ASSOC-VALUE must be nil or t (the
3426 default). Otherwise it is a list of tokens which must have been
3427 previously declared in TOKENS.
3429 - NONTERMS is a list of nonterminal definitions.
3431 Optional argument START-LIST specify the possible grammar start
3432 symbols. This is a list of nonterminals which must have been
3433 previously declared in GRAMMAR's NONTERMS form. By default, the start
3434 symbol is the first nonterminal defined. When START-LIST contains
3435 only one element, it is the start symbol. Otherwise, all elements are
3436 possible start symbols, unless `wisent-single-start-flag' is non-nil.
3437 In that case, the first element is the start symbol, and others are
3440 Return an automaton as a vector: [ACTIONS GOTOS STARTS FUNCTIONS]
3443 - ACTIONS is a state/token matrix telling the parser what to do at
3444 every state based on the current lookahead token. That is shift,
3445 reduce, accept or error.
3447 - GOTOS is a state/nonterminal matrix telling the parser the next
3448 state to go to after reducing with each rule.
3450 - STARTS is an alist which maps the allowed start nonterminal symbols
3451 to tokens that will be first shifted into the parser stack.
3453 - FUNCTIONS is an obarray of semantic action symbols. Each symbol's
3454 function definition is the semantic action lambda expression."
3455 (if (wisent-automaton-p grammar)
3456 grammar ;; Grammar already compiled just return it
3457 (wisent-with-context compile-grammar
3458 (let* ((gc-cons-threshold 1000000))
3460 (setq wisent-new-log-flag t)
3461 ;; Parse input grammar
3462 (wisent-parse-grammar grammar start-list)
3463 ;; Generate the LALR(1) automaton
3464 (wisent-parser-automaton)))))
3466 ;;;; --------------------------
3467 ;;;; Byte compile input grammar
3468 ;;;; --------------------------
3472 (defun wisent-byte-compile-grammar (form)
3473 "Byte compile the `wisent-compile-grammar' FORM.
3474 Automatically called by the Emacs Lisp byte compiler as a
3475 `byte-compile' handler."
3476 ;; Eval the `wisent-compile-grammar' form to obtain an LALR
3477 ;; automaton internal data structure. Then, because the internal
3478 ;; data structure contains an obarray, convert it to a lisp form so
3479 ;; it can be byte-compiled.
3481 ;; FIXME: we macroexpand here since `byte-compile-form' expects
3482 ;; macroexpanded code, but that's just a workaround: for lexical-binding
3483 ;; the lisp form should have to pass through closure-conversion and
3484 ;; `wisent-byte-compile-grammar' is called much too late for that.
3485 ;; Why isn't this `wisent-automaton-lisp-form' performed at
3486 ;; macroexpansion time? --Stef
3488 (wisent-automaton-lisp-form (eval form)))))
3490 ;; FIXME: We shouldn't use a `byte-compile' handler. Maybe using a hash-table
3491 ;; instead of an obarray would work around the problem that obarrays
3492 ;; aren't printable. Then (put 'wisent-compile-grammar 'side-effect-free t).
3493 (put 'wisent-compile-grammar 'byte-compile 'wisent-byte-compile-grammar)
3495 (defun wisent-automaton-lisp-form (automaton)
3496 "Return a Lisp form that produces AUTOMATON.
3497 See also `wisent-compile-grammar' for more details on AUTOMATON."
3498 (or (wisent-automaton-p automaton)
3499 (signal 'wrong-type-argument
3500 (list 'wisent-automaton-p automaton)))
3501 (let ((obn (make-symbol "ob")) ; Generated obarray name
3502 (obv (aref automaton 3)) ; Semantic actions obarray
3504 `(let ((,obn (make-vector 13 0)))
3505 ;; Generate code to initialize the semantic actions obarray,
3506 ;; in local variable OBN.
3511 (cons `(fset (intern ,(symbol-name s) ,obn)
3512 #',(symbol-function s))
3516 ;; Generate code to create the automaton.
3518 ;; In code generated to initialize the action table, take
3519 ;; care of symbols that are interned in the semantic actions
3523 #'(lambda (state) ;; for each state
3526 #'(lambda (tr) ;; for each transition
3527 (let ((k (car tr)) ; token
3528 (a (cdr tr))) ; action
3529 (if (and (symbolp a)
3530 (intern-soft (symbol-name a) obv))
3531 `(cons ,(if (symbolp k) `(quote ,k) k)
3532 (intern-soft ,(symbol-name a) ,obn))
3535 (aref automaton 0)))
3536 ;; The code of the goto table is unchanged.
3538 ;; The code of the alist of start symbols is unchanged.
3539 ',(aref automaton 2)
3540 ;; The semantic actions obarray is in the local variable OBN.
3543 (provide 'semantic/wisent/comp)
3545 ;; Disable messages with regards to lexical scoping, since this will
3546 ;; produce a bunch of 'lacks a prefix' warnings with the
3547 ;; `wisent-defcontext' trickery above.
3550 ;; byte-compile-warnings: (not lexical)
3551 ;; generated-autoload-load-name: "semantic/wisent/comp"
3554 ;;; semantic/wisent/comp.el ends here