1 ;;; wisent-comp.el --- GNU Bison for Emacs - Grammar compiler
3 ;; Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2009, 2010 David Ponce
4 ;; Copyright (C) 1984, 1986, 1989, 1992, 1995, 2000, 2001
5 ;; Free Software Foundation, Inc. (Bison)
7 ;; Author: David Ponce <david@dponce.com>
8 ;; Maintainer: David Ponce <david@dponce.com>
9 ;; Created: 30 January 2002
11 ;; X-RCS: $Id: wisent-comp.el,v 1.30 2010-04-09 02:08:59 zappo Exp $
13 ;; This file is not part of GNU Emacs.
15 ;; This program is free software; you can redistribute it and/or
16 ;; modify it under the terms of the GNU General Public License as
17 ;; published by the Free Software Foundation; either version 2, or (at
18 ;; your option) any later version.
20 ;; This program is distributed in the hope that it will be useful, but
21 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 ;; General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with this program; see the file COPYING. If not, write to
27 ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
28 ;; Boston, MA 02110-1301, USA.
32 ;; Grammar compiler that produces Wisent's LALR automatons.
34 ;; Wisent (the European Bison ;-) is an Elisp implementation of the
35 ;; GNU Compiler Compiler Bison. The Elisp code is a port of the C
36 ;; code of GNU Bison 1.28 & 1.31.
38 ;; For more details on the basic concepts for understanding Wisent,
39 ;; read the Bison manual ;)
41 ;; For more details on Wisent itself read the Wisent manual.
50 ;;;; -------------------
51 ;;;; Misc. useful things
52 ;;;; -------------------
54 ;; As much as possible I would like to keep the name of global
55 ;; variables used in Bison without polluting too much the Elisp global
56 ;; name space. Elisp dynamic binding allows that ;-)
58 ;; Here are simple macros to easily define and use set of variables
59 ;; binded locally, without all these "reference to free variable"
62 (defmacro wisent-context-name (name)
63 "Return the context name from NAME."
64 `(if (and ,name (symbolp ,name))
65 (intern (format "wisent-context-%s" ,name))
66 (error "Invalid context name: %S" ,name)))
68 (defmacro wisent-context-bindings (name)
69 "Return the variables in context NAME."
70 `(symbol-value (wisent-context-name ,name)))
72 (defmacro wisent-defcontext (name &rest vars)
73 "Define a context NAME that will bind variables VARS."
74 (let* ((context (wisent-context-name name))
75 (bindings (mapcar #'(lambda (v) (list 'defvar v)) vars)))
78 (defvar ,context ',vars))))
79 (put 'wisent-defcontext 'lisp-indent-function 1)
81 (defmacro wisent-with-context (name &rest body)
82 "Bind variables in context NAME then eval BODY."
83 `(let* ,(wisent-context-bindings name)
85 (put 'wisent-with-context 'lisp-indent-function 1)
87 ;; A naive implementation of data structures! But it suffice here ;-)
89 (defmacro wisent-struct (name &rest fields)
90 "Define a simple data structure called NAME.
91 Which contains data stored in FIELDS. FIELDS is a list of symbols
92 which are field names or pairs (FIELD INITIAL-VALUE) where
93 INITIAL-VALUE is a constant used as the initial value of FIELD when
94 the data structure is created. INITIAL-VALUE defaults to nil.
96 This defines a `make-NAME' constructor, get-able `NAME-FIELD' and
97 set-able `set-NAME-FIELD' accessors."
98 (let ((size (length fields))
100 accors field sufx fun ivals)
102 (setq field (car fields)
105 (setq ivals (cons (cadr field) ivals)
107 (setq ivals (cons nil ivals)))
108 (setq sufx (format "%s-%s" name field)
109 fun (intern (format "%s" sufx))
110 accors (cons `(defmacro ,fun (s)
113 fun (intern (format "set-%s" sufx))
114 accors (cons `(defmacro ,fun (s v)
119 (defmacro ,(intern (format "make-%s" name)) ()
120 (cons 'vector ',(nreverse ivals)))
122 (put 'wisent-struct 'lisp-indent-function 1)
126 (defsubst wisent-pad-string (s n &optional left)
127 "Fill string S with spaces.
128 Return a new string of at least N characters. Insert spaces on right.
129 If optional LEFT is non-nil insert spaces on left."
130 (let ((i (length s)))
133 (concat (make-string (- n i) ?\ ) s)
134 (concat s (make-string (- n i) ?\ )))
137 ;;;; ------------------------
138 ;;;; Environment dependencies
139 ;;;; ------------------------
141 (defconst wisent-BITS-PER-WORD
143 (while (not (zerop (lsh 1 i)))
147 (defsubst wisent-WORDSIZE (n)
148 "(N + BITS-PER-WORD - 1) / BITS-PER-WORD."
149 (/ (1- (+ n wisent-BITS-PER-WORD)) wisent-BITS-PER-WORD))
151 (defsubst wisent-SETBIT (x i)
152 "X[I/BITS-PER-WORD] |= 1 << (I % BITS-PER-WORD)."
153 (let ((k (/ i wisent-BITS-PER-WORD)))
154 (aset x k (logior (aref x k)
155 (lsh 1 (% i wisent-BITS-PER-WORD))))))
157 (defsubst wisent-RESETBIT (x i)
158 "X[I/BITS-PER-WORD] &= ~(1 << (I % BITS-PER-WORD))."
159 (let ((k (/ i wisent-BITS-PER-WORD)))
160 (aset x k (logand (aref x k)
161 (lognot (lsh 1 (% i wisent-BITS-PER-WORD)))))))
163 (defsubst wisent-BITISSET (x i)
164 "(X[I/BITS-PER-WORD] & (1 << (I % BITS-PER-WORD))) != 0."
165 (not (zerop (logand (aref x (/ i wisent-BITS-PER-WORD))
166 (lsh 1 (% i wisent-BITS-PER-WORD))))))
169 (or (fboundp 'noninteractive)
170 ;; Silence the Emacs byte compiler
171 (defun noninteractive nil))
174 (defsubst wisent-noninteractive ()
175 "Return non-nil if running without interactive terminal."
176 (if (featurep 'xemacs)
180 (defvar wisent-debug-flag nil
181 "Non-nil means enable some debug stuff.")
186 (defconst wisent-log-buffer-name "*wisent-log*"
187 "Name of the log buffer.")
189 (defvar wisent-new-log-flag nil
190 "Non-nil means to start a new report.")
193 (defvar wisent-verbose-flag nil
194 "*Non-nil means to report verbose information on generated parser.")
197 (defun wisent-toggle-verbose-flag ()
198 "Toggle whether to report verbose information on generated parser."
200 (setq wisent-verbose-flag (not wisent-verbose-flag))
201 (when (cedet-called-interactively-p 'interactive)
202 (message "Verbose report %sabled"
203 (if wisent-verbose-flag "en" "dis"))))
205 (defmacro wisent-log-buffer ()
206 "Return the log buffer.
207 Its name is defined in constant `wisent-log-buffer-name'."
208 `(get-buffer-create wisent-log-buffer-name))
210 (defmacro wisent-clear-log ()
211 "Delete the entire contents of the log buffer."
212 `(with-current-buffer (wisent-log-buffer)
215 (eval-when-compile (defvar byte-compile-current-file))
217 (defun wisent-source ()
218 "Return the current source file name or nil."
219 (let ((source (or (and (boundp 'byte-compile-current-file)
220 byte-compile-current-file)
221 load-file-name (buffer-file-name))))
223 (file-relative-name source))))
225 (defun wisent-new-log ()
226 "Start a new entry into the log buffer."
227 (setq wisent-new-log-flag nil)
228 (let ((text (format "\n\n*** Wisent %s - %s\n\n"
229 (or (wisent-source) (buffer-name))
230 (format-time-string "%Y-%m-%d %R"))))
231 (with-current-buffer (wisent-log-buffer)
232 (goto-char (point-max))
235 (defsubst wisent-log (&rest args)
236 "Insert text into the log buffer.
237 `format' is applied to ARGS and the result string is inserted into the
238 log buffer returned by the function `wisent-log-buffer'."
239 (and wisent-new-log-flag (wisent-new-log))
240 (with-current-buffer (wisent-log-buffer)
241 (insert (apply 'format args))))
243 (defconst wisent-log-file "wisent.output"
245 Used when running without interactive terminal.")
247 (defun wisent-append-to-log-file ()
248 "Append contents of logging buffer to `wisent-log-file'."
249 (if (get-buffer wisent-log-buffer-name)
251 (with-current-buffer (wisent-log-buffer)
253 (if (> (point-max) (point-min))
254 (write-region (point-min) (point-max)
257 (message "*** %s" (error-message-string err))))))
259 ;;;; -----------------------------------
260 ;;;; Representation of the grammar rules
261 ;;;; -----------------------------------
263 ;; ntokens is the number of tokens, and nvars is the number of
264 ;; variables (nonterminals). nsyms is the total number, ntokens +
267 ;; Each symbol (either token or variable) receives a symbol number.
268 ;; Numbers 0 to ntokens-1 are for tokens, and ntokens to nsyms-1 are
269 ;; for variables. Symbol number zero is the end-of-input token. This
270 ;; token is counted in ntokens.
272 ;; The rules receive rule numbers 1 to nrules in the order they are
273 ;; written. Actions and guards are accessed via the rule number.
275 ;; The rules themselves are described by three arrays: rrhs, rlhs and
276 ;; ritem. rlhs[R] is the symbol number of the left hand side of rule
277 ;; R. The right hand side is stored as symbol numbers in a portion of
278 ;; ritem. rrhs[R] contains the index in ritem of the beginning of the
279 ;; portion for rule R.
281 ;; The length of the portion is one greater than the number of symbols
282 ;; in the rule's right hand side. The last element in the portion
283 ;; contains minus R, which identifies it as the end of a portion and
284 ;; says which rule it is for.
286 ;; The portions of ritem come in order of increasing rule number and
287 ;; are followed by an element which is nil to mark the end. nitems is
288 ;; the total length of ritem, not counting the final nil. Each
289 ;; element of ritem is called an "item" and its index in ritem is an
292 ;; Item numbers are used in the finite state machine to represent
293 ;; places that parsing can get to.
295 ;; The vector rprec contains for each rule, the item number of the
296 ;; symbol giving its precedence level to this rule. The precedence
297 ;; level and associativity of each symbol is recorded in respectively
298 ;; the properties 'wisent--prec and 'wisent--assoc.
300 ;; Precedence levels are assigned in increasing order starting with 1
301 ;; so that numerically higher precedence values mean tighter binding
302 ;; as they ought to. nil as a symbol or rule's precedence means none
305 (defcustom wisent-state-table-size 1009
306 "The size of the state table."
310 ;; These variables only exist locally in the function
311 ;; `wisent-compile-grammar' and are shared by all other nested
313 (wisent-defcontext compile-grammar
314 F LA LAruleno accessing-symbol conflicts consistent default-prec
315 derives err-table fderives final-state first-reduction first-shift
316 first-state firsts from-state goto-map includes itemset nitemset
317 kernel-base kernel-end kernel-items last-reduction last-shift
318 last-state lookaheads lookaheadset lookback maxrhs ngotos nitems
319 nrules nshifts nstates nsyms ntokens nullable nvars rassoc redset
320 reduction-table ritem rlhs rprec rrc-count rrc-total rrhs ruseful
321 rcode ruleset rulesetsize shift-symbol shift-table shiftset
322 src-count src-total start-table state-table tags this-state to-state
323 tokensetsize ;; nb of words req. to hold a bit for each rule
324 varsetsize ;; nb of words req. to hold a bit for each variable
325 error-token-number start-symbol token-list var-list
326 N P V V1 nuseless-nonterminals nuseless-productions
327 ptable ;; symbols & characters properties
330 (defmacro wisent-ISTOKEN (s)
331 "Return non-nil if item number S defines a token (terminal).
332 That is if S < `ntokens'."
335 (defmacro wisent-ISVAR(s)
336 "Return non-nil if item number S defines a nonterminal.
337 That is if S >= `ntokens'."
340 (defsubst wisent-tag (s)
341 "Return printable form of item number S."
342 (wisent-item-to-string (aref tags s)))
344 ;; Symbol and character properties
346 (defsubst wisent-put (object propname value)
347 "Store OBJECT's PROPNAME property with value VALUE.
348 Use `eq' to locate OBJECT."
349 (let ((entry (assq object ptable)))
350 (or entry (setq entry (list object) ptable (cons entry ptable)))
351 (setcdr entry (plist-put (cdr entry) propname value))))
353 (defsubst wisent-get (object propname)
354 "Return the value of OBJECT's PROPNAME property.
355 Use `eq' to locate OBJECT."
356 (plist-get (cdr (assq object ptable)) propname))
358 (defsubst wisent-item-number (x)
359 "Return the item number of symbol X."
360 (wisent-get x 'wisent--item-no))
362 (defsubst wisent-set-item-number (x n)
363 "Set the item number of symbol X to N."
364 (wisent-put x 'wisent--item-no n))
366 (defsubst wisent-assoc (x)
367 "Return the associativity of symbol X."
368 (wisent-get x 'wisent--assoc))
370 (defsubst wisent-set-assoc (x a)
371 "Set the associativity of symbol X to A."
372 (wisent-put x 'wisent--assoc a))
374 (defsubst wisent-prec (x)
375 "Return the precedence level of symbol X."
376 (wisent-get x 'wisent--prec))
378 (defsubst wisent-set-prec (x p)
379 "Set the precedence level of symbol X to P."
380 (wisent-put x 'wisent--prec p))
382 ;;;; ----------------------------------------------------------
383 ;;;; Type definitions for nondeterministic finite state machine
384 ;;;; ----------------------------------------------------------
386 ;; These type definitions are used to represent a nondeterministic
387 ;; finite state machine that parses the specified grammar. This
388 ;; information is generated by the function `wisent-generate-states'.
390 ;; Each state of the machine is described by a set of items --
391 ;; particular positions in particular rules -- that are the possible
392 ;; places where parsing could continue when the machine is in this
393 ;; state. These symbols at these items are the allowable inputs that
396 ;; A core represents one state. States are numbered in the number
397 ;; field. When `wisent-generate-states' is finished, the starting
398 ;; state is state 0 and `nstates' is the number of states. (A
399 ;; transition to a state whose state number is `nstates' indicates
400 ;; termination.) All the cores are chained together and `first-state'
401 ;; points to the first one (state 0).
403 ;; For each state there is a particular symbol which must have been
404 ;; the last thing accepted to reach that state. It is the
405 ;; accessing-symbol of the core.
407 ;; Each core contains a vector of `nitems' items which are the indices
408 ;; in the `ritems' vector of the items that are selected in this
411 ;; The link field is used for chaining buckets that hash states by
412 ;; their itemsets. This is for recognizing equivalent states and
413 ;; combining them when the states are generated.
415 ;; The two types of transitions are shifts (push the lookahead token
416 ;; and read another) and reductions (combine the last n things on the
417 ;; stack via a rule, replace them with the symbol that the rule
418 ;; derives, and leave the lookahead token alone). When the states are
419 ;; generated, these transitions are represented in two other lists.
421 ;; Each shifts structure describes the possible shift transitions out
422 ;; of one state, the state whose number is in the number field. The
423 ;; shifts structures are linked through next and first-shift points to
424 ;; them. Each contains a vector of numbers of the states that shift
425 ;; transitions can go to. The accessing-symbol fields of those
426 ;; states' cores say what kind of input leads to them.
428 ;; A shift to state zero should be ignored. Conflict resolution
429 ;; deletes shifts by changing them to zero.
431 ;; Each reductions structure describes the possible reductions at the
432 ;; state whose number is in the number field. The data is a list of
433 ;; nreds rules, represented by their rule numbers. `first-reduction'
434 ;; points to the list of these structures.
436 ;; Conflict resolution can decide that certain tokens in certain
437 ;; states should explicitly be errors (for implementing %nonassoc).
438 ;; For each state, the tokens that are errors for this reason are
439 ;; recorded in an errs structure, which has the state number in its
440 ;; number field. The rest of the errs structure is full of token
443 ;; There is at least one shift transition present in state zero. It
444 ;; leads to a next-to-final state whose accessing-symbol is the
445 ;; grammar's start symbol. The next-to-final state has one shift to
446 ;; the final state, whose accessing-symbol is zero (end of input).
447 ;; The final state has one shift, which goes to the termination state
448 ;; (whose number is `nstates'-1).
449 ;; The reason for the extra state at the end is to placate the
450 ;; parser's strategy of making all decisions one token ahead of its
461 (wisent-struct shifts
467 (wisent-struct reductions
477 ;;;; --------------------------------------------------------
478 ;;;; Find unreachable terminals, nonterminals and productions
479 ;;;; --------------------------------------------------------
481 (defun wisent-bits-equal (L R n)
482 "Visit L and R and return non-nil if their first N elements are `='.
483 L and R must be vectors of integers."
486 (while (and iseq (natnump i))
487 (setq iseq (= (aref L i) (aref R i))
491 (defun wisent-nbits (i)
492 "Return number of bits set in integer I."
494 (while (not (zerop i))
495 ;; i ^= (i & ((unsigned) (-(int) i)))
496 (setq i (logxor i (logand i (- i)))
500 (defun wisent-bits-size (S n)
501 "In vector S count the total of bits set in first N elements.
502 S must be a vector of integers."
506 (setq count (+ count (wisent-nbits (aref S i)))
510 (defun wisent-useful-production (i N0)
511 "Return non-nil if production I is in useful set N0."
515 (while (and useful (> (setq n (aref ritem r)) 0))
517 (setq useful (wisent-BITISSET N0 (- n ntokens))))
521 (defun wisent-useless-nonterminals ()
522 "Find out which nonterminals are used."
523 (let (Np Ns i n break)
524 ;; N is set as built. Np is set being built this iteration. P is
525 ;; set of all productions which have a RHS all in N.
526 (setq n (wisent-WORDSIZE nvars)
527 Np (make-vector n 0))
529 ;; The set being computed is a set of nonterminals which can
530 ;; derive the empty string or strings consisting of all
531 ;; terminals. At each iteration a nonterminal is added to the set
532 ;; if there is a production with that nonterminal as its LHS for
533 ;; which all the nonterminals in its RHS are already in the set.
534 ;; Iterate until the set being computed remains unchanged. Any
535 ;; nonterminals not in the set at that point are useless in that
536 ;; they will never be used in deriving a sentence of the language.
538 ;; This iteration doesn't use any special traversal over the
539 ;; productions. A set is kept of all productions for which all
540 ;; the nonterminals in the RHS are in useful. Only productions
541 ;; not in this set are scanned on each iteration. At the end,
542 ;; this set is saved to be used when finding useful productions:
543 ;; only productions in this set will appear in the final grammar.
549 (aset Np i (aref N i))
554 (if (not (wisent-BITISSET P i))
555 (when (wisent-useful-production i N)
556 (wisent-SETBIT Np (- (aref rlhs i) ntokens))
557 (wisent-SETBIT P i)))
559 (if (wisent-bits-equal N Np n)
566 (defun wisent-inaccessable-symbols ()
567 "Find out which productions are reachable and which symbols are used."
568 ;; Starting with an empty set of productions and a set of symbols
569 ;; which only has the start symbol in it, iterate over all
570 ;; productions until the set of productions remains unchanged for an
571 ;; iteration. For each production which has a LHS in the set of
572 ;; reachable symbols, add the production to the set of reachable
573 ;; productions, and add all of the nonterminals in the RHS of the
574 ;; production to the set of reachable symbols.
576 ;; Consider only the (partially) reduced grammar which has only
577 ;; nonterminals in N and productions in P.
579 ;; The result is the set P of productions in the reduced grammar,
580 ;; and the set V of symbols in the reduced grammar.
582 ;; Although this algorithm also computes the set of terminals which
583 ;; are reachable, no terminal will be deleted from the grammar. Some
584 ;; terminals might not be in the grammar but might be generated by
585 ;; semantic routines, and so the user might want them available with
586 ;; specified numbers. (Is this true?) However, the non reachable
587 ;; terminals are printed (if running in verbose mode) so that the
589 (let (Vp Vs Pp i tt r n m break)
590 (setq n (wisent-WORDSIZE nsyms)
591 m (wisent-WORDSIZE (1+ nrules))
593 Pp (make-vector m 0))
595 ;; If the start symbol isn't useful, then nothing will be useful.
596 (when (wisent-BITISSET N (- start-symbol ntokens))
597 (wisent-SETBIT V start-symbol)
601 (aset Vp i (aref V i))
605 (when (and (not (wisent-BITISSET Pp i))
606 (wisent-BITISSET P i)
607 (wisent-BITISSET V (aref rlhs i)))
608 (setq r (aref rrhs i))
609 (while (natnump (setq tt (aref ritem r)))
610 (if (or (wisent-ISTOKEN tt)
611 (wisent-BITISSET N (- tt ntokens)))
612 (wisent-SETBIT Vp tt))
614 (wisent-SETBIT Pp i))
616 (if (wisent-bits-equal V Vp n)
623 ;; Tokens 0, 1 are internal to Wisent. Consider them useful.
624 (wisent-SETBIT V 0) ;; end-of-input token
625 (wisent-SETBIT V 1) ;; error token
628 (setq nuseless-productions (- nrules (wisent-bits-size P m))
629 nuseless-nonterminals nvars
632 (if (wisent-BITISSET V i)
633 (setq nuseless-nonterminals (1- nuseless-nonterminals)))
636 ;; A token that was used in %prec should not be warned about.
640 (wisent-SETBIT V1 (aref rprec i)))
644 (defun wisent-reduce-grammar-tables ()
645 "Disable useless productions."
646 (if (> nuseless-productions 0)
648 (while (<= pn nrules)
649 (aset ruseful pn (wisent-BITISSET P pn))
650 (setq pn (1+ pn))))))
652 (defun wisent-nonterminals-reduce ()
653 "Remove useless nonterminals."
654 (let (i n r item nontermmap tags-sorted)
655 ;; Map the nonterminals to their new index: useful first, useless
656 ;; afterwards. Kept for later report.
657 (setq nontermmap (make-vector nvars 0)
661 (when (wisent-BITISSET V i)
662 (aset nontermmap (- i ntokens) n)
667 (unless (wisent-BITISSET V i)
668 (aset nontermmap (- i ntokens) n)
671 ;; Shuffle elements of tables indexed by symbol number
672 (setq tags-sorted (make-vector nvars nil)
675 (setq n (aref nontermmap (- i ntokens)))
676 (aset tags-sorted (- n ntokens) (aref tags i))
680 (aset tags i (aref tags-sorted (- i ntokens)))
682 ;; Replace all symbol numbers in valid data structures.
685 (aset rlhs i (aref nontermmap (- (aref rlhs i) ntokens)))
688 (while (setq item (aref ritem r))
689 (if (wisent-ISVAR item)
690 (aset ritem r (aref nontermmap (- item ntokens))))
692 (setq start-symbol (aref nontermmap (- start-symbol ntokens))
693 nsyms (- nsyms nuseless-nonterminals)
694 nvars (- nvars nuseless-nonterminals))
697 (defun wisent-total-useless ()
698 "Report number of useless nonterminals and productions."
699 (let* ((src (wisent-source))
700 (src (if src (concat " in " src) ""))
701 (msg (format "Grammar%s contains" src)))
702 (if (> nuseless-nonterminals 0)
703 (setq msg (format "%s %d useless nonterminal%s"
704 msg nuseless-nonterminals
705 (if (> nuseless-nonterminals 0) "s" ""))))
706 (if (and (> nuseless-nonterminals 0) (> nuseless-productions 0))
707 (setq msg (format "%s and" msg)))
708 (if (> nuseless-productions 0)
709 (setq msg (format "%s %d useless rule%s"
710 msg nuseless-productions
711 (if (> nuseless-productions 0) "s" ""))))
714 (defun wisent-reduce-grammar ()
715 "Find unreachable terminals, nonterminals and productions."
716 ;; Allocate the global sets used to compute the reduced grammar
717 (setq N (make-vector (wisent-WORDSIZE nvars) 0)
718 P (make-vector (wisent-WORDSIZE (1+ nrules)) 0)
719 V (make-vector (wisent-WORDSIZE nsyms) 0)
720 V1 (make-vector (wisent-WORDSIZE nsyms) 0)
721 nuseless-nonterminals 0
722 nuseless-productions 0)
724 (wisent-useless-nonterminals)
725 (wisent-inaccessable-symbols)
727 (when (> (+ nuseless-nonterminals nuseless-productions) 0)
728 (wisent-total-useless)
729 (or (wisent-BITISSET N (- start-symbol ntokens))
730 (error "Start symbol `%s' does not derive any sentence"
731 (wisent-tag start-symbol)))
732 (wisent-reduce-grammar-tables)
733 (if (> nuseless-nonterminals 0)
734 (wisent-nonterminals-reduce))))
736 (defun wisent-print-useless ()
737 "Output the detailed results of the reductions."
739 (when (> nuseless-nonterminals 0)
740 ;; Useless nonterminals have been moved after useful ones.
741 (wisent-log "\n\nUseless nonterminals:\n\n")
743 (while (< i nuseless-nonterminals)
744 (wisent-log " %s\n" (wisent-tag (+ nsyms i)))
749 (unless (or (wisent-BITISSET V i) (wisent-BITISSET V1 i))
751 (wisent-log "\n\nTerminals which are not used:\n\n"))
753 (wisent-log " %s\n" (wisent-tag i)))
755 (when (> nuseless-productions 0)
756 (wisent-log "\n\nUseless rules:\n\n")
759 (unless (aref ruseful i)
760 (wisent-log "#%s " (wisent-pad-string (format "%d" i) 4))
761 (wisent-log "%s:" (wisent-tag (aref rlhs i)))
762 (setq r (aref rrhs i))
763 (while (natnump (aref ritem r))
764 (wisent-log " %s" (wisent-tag (aref ritem r)))
768 (if (or b (> nuseless-nonterminals 0) (> nuseless-productions 0))
772 ;;;; -----------------------------
773 ;;;; Match rules with nonterminals
774 ;;;; -----------------------------
776 (defun wisent-set-derives ()
777 "Find, for each variable (nonterminal), which rules can derive it.
778 It sets up the value of DERIVES so that DERIVES[i - NTOKENS] points to
779 a list of rule numbers, terminated with -1."
780 (let (i lhs p q dset delts)
781 (setq dset (make-vector nvars nil)
782 delts (make-vector (1+ nrules) 0))
783 (setq p 0 ;; p = delts
786 (when (aref ruseful i)
787 (setq lhs (aref rlhs i))
788 ;; p->next = dset[lhs];
790 (aset delts p (cons i (aref dset (- lhs ntokens)))) ;; (value . next)
791 (aset dset (- lhs ntokens) p) ;; dset[lhs] = p
792 (setq p (1+ p)) ;; p++
796 (setq derives (make-vector nvars nil)
801 p (aref dset (- i ntokens))) ;; p = dset[i]
804 (setq p (aref delts p)
805 q (cons (car p) q) ;;q++ = p->value
806 p (cdr p))) ;; p = p->next
807 (setq q (nreverse (cons -1 q))) ;; *q++ = -1
808 (aset derives (- i ntokens) q) ;; derives[i] = q
812 ;;;; --------------------------------------------------------
813 ;;;; Find which nonterminals can expand into the null string.
814 ;;;; --------------------------------------------------------
816 (defun wisent-print-nullable ()
819 (wisent-log "NULLABLE\n")
822 (wisent-log "\t%s: %s\n" (wisent-tag i)
823 (if (aref nullable (- i ntokens))
826 (wisent-log "\n\n")))
828 (defun wisent-set-nullable ()
830 A vector saying which nonterminals can expand into the null string.
831 NULLABLE[i - NTOKENS] is nil if symbol I can do so."
832 (let (ruleno s1 s2 p r squeue rcount rsets relts item any-tokens)
833 (setq squeue (make-vector nvars 0)
834 rcount (make-vector (1+ nrules) 0)
835 rsets (make-vector nvars nil) ;; - ntokens
836 relts (make-vector (+ nitems nvars 1) nil)
837 nullable (make-vector nvars nil)) ;; - ntokens
838 (setq s1 0 s2 0 ;; s1 = s2 = squeue
841 (while (<= ruleno nrules)
842 (when (aref ruseful ruleno)
843 (if (> (aref ritem (aref rrhs ruleno)) 0)
845 ;; This rule has a non empty RHS.
847 r (aref rrhs ruleno))
848 (while (> (aref ritem r) 0)
849 (if (wisent-ISTOKEN (aref ritem r))
853 ;; This rule has only nonterminals: schedule it for the
856 (setq r (aref rrhs ruleno))
857 (while (> (setq item (aref ritem r)) 0)
858 (aset rcount ruleno (1+ (aref rcount ruleno)))
859 ;; p->next = rsets[item];
860 ;; p->value = ruleno;
861 (aset relts p (cons ruleno (aref rsets (- item ntokens))))
863 (aset rsets (- item ntokens) p)
866 ;; This rule has an empty RHS.
867 ;; assert (ritem[rrhs[ruleno]] == -ruleno)
868 (when (and (aref ruseful ruleno)
869 (setq item (aref rlhs ruleno))
870 (not (aref nullable (- item ntokens))))
871 (aset nullable (- item ntokens) t)
872 (aset squeue s2 item)
876 (setq ruleno (1+ ruleno)))
880 (setq p (aref rsets (- (aref squeue s1) ntokens))
883 (setq p (aref relts p)
885 p (cdr p)) ;; p = p->next
886 ;; if (--rcount[ruleno] == 0)
887 (when (zerop (aset rcount ruleno (1- (aref rcount ruleno))))
888 (setq item (aref rlhs ruleno))
889 (aset nullable (- item ntokens) t)
890 (aset squeue s2 item)
893 (if wisent-debug-flag
894 (wisent-print-nullable))
901 (defun wisent-print-fderives ()
904 (wisent-log "\n\n\nFDERIVES\n")
907 (wisent-log "\n\n%s derives\n\n" (wisent-tag i))
908 (setq rp (aref fderives (- i ntokens))
911 (if (wisent-BITISSET rp j)
912 (wisent-log " %d\n" j))
916 (defun wisent-set-fderives ()
918 An NVARS by NRULES matrix of bits indicating which rules can help
919 derive the beginning of the data for each nonterminal. For example,
920 if symbol 5 can be derived as the sequence of symbols 8 3 20, and one
921 of the rules for deriving symbol 8 is rule 4, then the
922 \[5 - NTOKENS, 4] bit in FDERIVES is set."
924 (setq fderives (make-vector nvars nil))
927 (aset fderives i (make-vector rulesetsize 0))
936 ;; if (BITISSET (FIRSTS (i), j - ntokens))
937 (when (wisent-BITISSET (aref firsts (- i ntokens)) (- j ntokens))
938 (setq k (aref derives (- j ntokens)))
939 (while (> (car k) 0) ;; derives[j][k] > 0
940 ;; SETBIT (FDERIVES (i), derives[j][k]);
941 (wisent-SETBIT (aref fderives (- i ntokens)) (car k))
946 (if wisent-debug-flag
947 (wisent-print-fderives))
950 (defun wisent-print-firsts ()
953 (wisent-log "\n\n\nFIRSTS\n\n")
956 (wisent-log "\n\n%s firsts\n\n" (wisent-tag i))
957 (setq v (aref firsts (- i ntokens))
960 (if (wisent-BITISSET v j)
961 (wisent-log "\t\t%d (%s)\n"
962 (+ j ntokens) (wisent-tag (+ j ntokens))))
966 (defun wisent-TC (R n)
968 Given R an N by N matrix of bits, modify its contents to be the
969 transitive closure of what was given."
971 ;; R (J, I) && R (I, K) => R (J, K).
972 ;; I *must* be the outer loop.
977 (when (wisent-BITISSET (aref R j) i)
980 (if (wisent-BITISSET (aref R i) k)
981 (wisent-SETBIT (aref R j) k))
986 (defun wisent-RTC (R n)
987 "Reflexive Transitive Closure.
988 Same as `wisent-TC' and then set all the bits on the diagonal of R, an
989 N by N matrix of bits."
994 (wisent-SETBIT (aref R i) i)
997 (defun wisent-set-firsts ()
999 An NVARS by NVARS bit matrix indicating which items can represent the
1000 beginning of the input corresponding to which other items. For
1001 example, if some rule expands symbol 5 into the sequence of symbols 8
1002 3 20, the symbol 8 can be the beginning of the data for symbol 5, so
1003 the bit [8 - NTOKENS, 5 - NTOKENS] in FIRSTS is set."
1004 (let (row symbol sp rowsize i)
1005 (setq rowsize (wisent-WORDSIZE nvars)
1007 firsts (make-vector nvars nil)
1010 (aset firsts i (make-vector rowsize 0))
1013 (setq row 0 ;; row = firsts
1016 (setq sp (aref derives (- i ntokens)))
1017 (while (>= (car sp) 0)
1018 (setq symbol (aref ritem (aref rrhs (car sp)))
1020 (when (wisent-ISVAR symbol)
1021 (setq symbol (- symbol ntokens))
1022 (wisent-SETBIT (aref firsts row) symbol)
1027 (wisent-RTC firsts nvars)
1029 (if wisent-debug-flag
1030 (wisent-print-firsts))
1033 (defun wisent-initialize-closure (n)
1034 "Allocate the ITEMSET and RULESET vectors.
1035 And precompute useful data so that `wisent-closure' can be called.
1036 N is the number of elements to allocate for ITEMSET."
1037 (setq itemset (make-vector n 0)
1038 rulesetsize (wisent-WORDSIZE (1+ nrules))
1039 ruleset (make-vector rulesetsize 0))
1041 (wisent-set-fderives))
1043 (defun wisent-print-closure ()
1046 (wisent-log "\n\nclosure n = %d\n\n" nitemset)
1047 (setq i 0) ;; isp = itemset
1048 (while (< i nitemset)
1049 (wisent-log " %d\n" (aref itemset i))
1052 (defun wisent-closure (core n)
1053 "Set up RULESET and ITEMSET for the transitions out of CORE state.
1054 Given a vector of item numbers items, of length N, set up RULESET and
1055 ITEMSET to indicate what rules could be run and which items could be
1056 accepted when those items are the active ones.
1058 RULESET contains a bit for each rule. `wisent-closure' sets the bits
1059 for all rules which could potentially describe the next input to be
1062 ITEMSET is a vector of item numbers; NITEMSET is the number of items
1063 in ITEMSET. `wisent-closure' places there the indices of all items
1064 which represent units of input that could arrive next."
1065 (let (c r v symbol ruleno itemno)
1069 v (aref fderives (- start-symbol ntokens)))
1070 (while (< r rulesetsize)
1071 ;; ruleset[r] = FDERIVES (start-symbol)[r];
1072 (aset ruleset r (aref v r))
1075 (fillarray ruleset 0)
1078 (setq symbol (aref ritem (aref core c)))
1079 (when (wisent-ISVAR symbol)
1081 v (aref fderives (- symbol ntokens)))
1082 (while (< r rulesetsize)
1083 ;; ruleset[r] |= FDERIVES (ritem[core[c]])[r];
1084 (aset ruleset r (logior (aref ruleset r) (aref v r)))
1091 r (* rulesetsize wisent-BITS-PER-WORD))
1093 (when (wisent-BITISSET ruleset ruleno)
1094 (setq itemno (aref rrhs ruleno))
1095 (while (and (< c n) (< (aref core c) itemno))
1096 (aset itemset nitemset (aref core c))
1097 (setq nitemset (1+ nitemset)
1099 (aset itemset nitemset itemno)
1100 (setq nitemset (1+ nitemset)))
1101 (setq ruleno (1+ ruleno)))
1104 (aset itemset nitemset (aref core c))
1105 (setq nitemset (1+ nitemset)
1108 (if wisent-debug-flag
1109 (wisent-print-closure))
1112 ;;;; --------------------------------------------------
1113 ;;;; Generate the nondeterministic finite state machine
1114 ;;;; --------------------------------------------------
1116 (defun wisent-allocate-itemsets ()
1117 "Allocate storage for itemsets."
1118 (let (symbol i count symbol-count)
1119 ;; Count the number of occurrences of all the symbols in RITEMS.
1120 ;; Note that useless productions (hence useless nonterminals) are
1121 ;; browsed too, hence we need to allocate room for _all_ the
1124 symbol-count (make-vector (+ nsyms nuseless-nonterminals) 0)
1126 (while (setq symbol (aref ritem i))
1128 (setq count (1+ count))
1129 (aset symbol-count symbol (1+ (aref symbol-count symbol))))
1131 ;; See comments before `wisent-new-itemsets'. All the vectors of
1132 ;; items live inside kernel-items. The number of active items
1133 ;; after some symbol cannot be more than the number of times that
1134 ;; symbol appears as an item, which is symbol-count[symbol]. We
1135 ;; allocate that much space for each symbol.
1136 (setq kernel-base (make-vector nsyms nil)
1137 kernel-items (make-vector count 0)
1141 (aset kernel-base i count)
1142 (setq count (+ count (aref symbol-count i))
1144 (setq shift-symbol symbol-count
1145 kernel-end (make-vector nsyms nil))
1148 (defun wisent-allocate-storage ()
1149 "Allocate storage for the state machine."
1150 (wisent-allocate-itemsets)
1151 (setq shiftset (make-vector nsyms 0)
1152 redset (make-vector (1+ nrules) 0)
1153 state-table (make-vector wisent-state-table-size nil)))
1155 (defun wisent-new-itemsets ()
1156 "Find which symbols can be shifted in the current state.
1157 And for each one record which items would be active after that shift.
1158 Uses the contents of ITEMSET. SHIFT-SYMBOL is set to a vector of the
1159 symbols that can be shifted. For each symbol in the grammar,
1160 KERNEL-BASE[symbol] points to a vector of item numbers activated if
1161 that symbol is shifted, and KERNEL-END[symbol] points after the end of
1163 (let (i shiftcount isp ksp symbol)
1164 (fillarray kernel-end nil)
1167 (while (< isp nitemset)
1168 (setq i (aref itemset isp)
1170 symbol (aref ritem i))
1172 (setq ksp (aref kernel-end symbol))
1174 ;; shift-symbol[shiftcount++] = symbol;
1175 (aset shift-symbol shiftcount symbol)
1176 (setq shiftcount (1+ shiftcount)
1177 ksp (aref kernel-base symbol)))
1179 (aset kernel-items ksp (1+ i))
1181 (aset kernel-end symbol ksp)))
1182 (setq nshifts shiftcount)))
1184 (defun wisent-new-state (symbol)
1185 "Create a new state for those items, if necessary.
1186 SYMBOL is the core accessing-symbol.
1187 Subroutine of `wisent-get-state'."
1188 (let (n p isp1 isp2 iend items)
1189 (setq isp1 (aref kernel-base symbol)
1190 iend (aref kernel-end symbol)
1193 items (make-vector n 0))
1194 (set-core-accessing-symbol p symbol)
1195 (set-core-number p nstates)
1196 (set-core-nitems p n)
1197 (set-core-items p items)
1198 (setq isp2 0) ;; isp2 = p->items
1199 (while (< isp1 iend)
1200 ;; *isp2++ = *isp1++;
1201 (aset items isp2 (aref kernel-items isp1))
1202 (setq isp1 (1+ isp1)
1204 (set-core-next last-state p)
1206 nstates (1+ nstates))
1209 (defun wisent-get-state (symbol)
1210 "Find the state we would get to by shifting SYMBOL.
1211 Return the state number for the state we would get to (from the
1212 current state) by shifting SYMBOL. Create a new state if no
1213 equivalent one exists already. Used by `wisent-append-states'."
1214 (let (key isp1 isp2 iend sp sp2 found n)
1215 (setq isp1 (aref kernel-base symbol)
1216 iend (aref kernel-end symbol)
1219 ;; Add up the target state's active item numbers to get a hash key
1220 (while (< isp1 iend)
1221 (setq key (+ key (aref kernel-items isp1))
1223 (setq key (% key wisent-state-table-size)
1224 sp (aref state-table key))
1229 (when (= (core-nitems sp) n)
1231 isp1 (aref kernel-base symbol)
1232 ;; isp2 = sp->items;
1236 (while (and found (< isp1 iend))
1237 ;; if (*isp1++ != *isp2++)
1238 (if (not (= (aref kernel-items isp1)
1241 (setq isp1 (1+ isp1)
1245 (setq sp (core-link sp))
1246 ;; sp = sp->link = new-state(symbol)
1247 (setq sp (set-core-link sp (wisent-new-state symbol))
1250 ;; state-table[key] = sp = new-state(symbol)
1251 (setq sp (wisent-new-state symbol))
1252 (aset state-table key sp))
1253 ;; return (sp->number);
1256 (defun wisent-append-states ()
1257 "Find or create the core structures for states.
1258 Use the information computed by `wisent-new-itemsets' to find the
1259 state numbers reached by each shift transition from the current state.
1260 SHIFTSET is set up as a vector of state numbers of those states."
1262 ;; First sort shift-symbol into increasing order
1264 (while (< i nshifts)
1265 (setq symbol (aref shift-symbol i)
1267 (while (and (> j 0) (> (aref shift-symbol (1- j)) symbol))
1268 (aset shift-symbol j (aref shift-symbol (1- j)))
1270 (aset shift-symbol j symbol)
1273 (while (< i nshifts)
1274 (setq symbol (aref shift-symbol i))
1275 (aset shiftset i (wisent-get-state symbol))
1279 (defun wisent-initialize-states ()
1280 "Initialize states."
1281 (let ((p (make-core)))
1287 (defun wisent-save-shifts ()
1288 "Save the NSHIFTS of SHIFTSET into the current linked list."
1290 (setq p (make-shifts)
1291 shifts (make-vector nshifts 0)
1293 (set-shifts-number p (core-number this-state))
1294 (set-shifts-nshifts p nshifts)
1295 (set-shifts-shifts p shifts)
1296 (while (< i nshifts)
1297 ;; (p->shifts)[i] = shiftset[i];
1298 (aset shifts i (aref shiftset i))
1302 (set-shifts-next last-shift p)
1303 (setq first-shift p))
1304 (setq last-shift p)))
1306 (defun wisent-insert-start-shift ()
1307 "Create the next-to-final state.
1308 That is the state to which a shift has already been made in the
1309 initial state. Subroutine of `wisent-augment-automaton'."
1311 (setq statep (make-core))
1312 (set-core-number statep nstates)
1313 (set-core-accessing-symbol statep start-symbol)
1314 (set-core-next last-state statep)
1315 (setq last-state statep)
1316 ;; Make a shift from this state to (what will be) the final state.
1317 (setq sp (make-shifts))
1318 (set-shifts-number sp nstates)
1319 (setq nstates (1+ nstates))
1320 (set-shifts-nshifts sp 1)
1321 (set-shifts-shifts sp (vector nstates))
1322 (set-shifts-next last-shift sp)
1323 (setq last-shift sp)))
1325 (defun wisent-augment-automaton ()
1326 "Set up initial and final states as parser wants them.
1327 Make sure that the initial state has a shift that accepts the
1328 grammar's start symbol and goes to the next-to-final state, which has
1329 a shift going to the final state, which has a shift to the termination
1330 state. Create such states and shifts if they don't happen to exist
1332 (let (i k statep sp sp2 sp1 shifts)
1333 (setq sp first-shift)
1336 (if (zerop (shifts-number sp))
1338 (setq k (shifts-nshifts sp)
1339 statep (core-next first-state))
1340 ;; The states reached by shifts from first-state are
1341 ;; numbered 1...K. Look for one reached by
1343 (while (and (< (core-accessing-symbol statep) start-symbol)
1344 (< (core-number statep) k))
1345 (setq statep (core-next statep)))
1346 (if (= (core-accessing-symbol statep) start-symbol)
1348 ;; We already have a next-to-final state. Make
1349 ;; sure it has a shift to what will be the final
1351 (setq k (core-number statep))
1352 (while (and sp (< (shifts-number sp) k))
1354 sp (shifts-next sp)))
1355 (if (and sp (= (shifts-number sp) k))
1357 (setq i (shifts-nshifts sp)
1359 shifts (make-vector (1+ i) 0))
1360 (set-shifts-number sp2 k)
1361 (set-shifts-nshifts sp2 (1+ i))
1362 (set-shifts-shifts sp2 shifts)
1363 (aset shifts 0 nstates)
1365 ;; sp2->shifts[i] = sp->shifts[i - 1];
1366 (aset shifts i (aref (shifts-shifts sp) (1- i)))
1368 ;; Patch sp2 into the chain of shifts in
1369 ;; place of sp, following sp1.
1370 (set-shifts-next sp2 (shifts-next sp))
1371 (set-shifts-next sp1 sp2)
1372 (if (eq sp last-shift)
1373 (setq last-shift sp2))
1375 (setq sp2 (make-shifts))
1376 (set-shifts-number sp2 k)
1377 (set-shifts-nshifts sp2 1)
1378 (set-shifts-shifts sp2 (vector nstates))
1379 ;; Patch sp2 into the chain of shifts between
1381 (set-shifts-next sp2 sp)
1382 (set-shifts-next sp1 sp2)
1384 (setq last-shift sp2))
1387 ;; There is no next-to-final state as yet.
1388 ;; Add one more shift in FIRST-SHIFT, going to the
1389 ;; next-to-final state (yet to be made).
1390 (setq sp first-shift
1392 i (shifts-nshifts sp)
1393 shifts (make-vector (1+ i) 0))
1394 (set-shifts-nshifts sp2 (1+ i))
1395 (set-shifts-shifts sp2 shifts)
1396 ;; Stick this shift into the vector at the proper place.
1397 (setq statep (core-next first-state)
1400 (while (< i (shifts-nshifts sp))
1401 (when (and (> (core-accessing-symbol statep) start-symbol)
1403 (aset shifts k nstates)
1405 (aset shifts k (aref (shifts-shifts sp) i))
1406 (setq statep (core-next statep))
1410 (aset shifts k nstates)
1412 ;; Patch sp2 into the chain of shifts in place of
1413 ;; sp, at the beginning.
1414 (set-shifts-next sp2 (shifts-next sp))
1415 (setq first-shift sp2)
1416 (if (eq last-shift sp)
1417 (setq last-shift sp2))
1418 ;; Create the next-to-final state, with shift to
1419 ;; what will be the final state.
1420 (wisent-insert-start-shift)))
1421 ;; The initial state didn't even have any shifts. Give it
1422 ;; one shift, to the next-to-final state.
1423 (setq sp (make-shifts))
1424 (set-shifts-nshifts sp 1)
1425 (set-shifts-shifts sp (vector nstates))
1426 ;; Patch sp into the chain of shifts at the beginning.
1427 (set-shifts-next sp first-shift)
1428 (setq first-shift sp)
1429 ;; Create the next-to-final state, with shift to what will
1430 ;; be the final state.
1431 (wisent-insert-start-shift)))
1432 ;; There are no shifts for any state. Make one shift, from the
1433 ;; initial state to the next-to-final state.
1434 (setq sp (make-shifts))
1435 (set-shifts-nshifts sp 1)
1436 (set-shifts-shifts sp (vector nstates))
1437 ;; Initialize the chain of shifts with sp.
1438 (setq first-shift sp
1440 ;; Create the next-to-final state, with shift to what will be
1442 (wisent-insert-start-shift))
1443 ;; Make the final state--the one that follows a shift from the
1444 ;; next-to-final state. The symbol for that shift is 0
1446 (setq statep (make-core))
1447 (set-core-number statep nstates)
1448 (set-core-next last-state statep)
1449 (setq last-state statep)
1450 ;; Make the shift from the final state to the termination state.
1451 (setq sp (make-shifts))
1452 (set-shifts-number sp nstates)
1453 (setq nstates (1+ nstates))
1454 (set-shifts-nshifts sp 1)
1455 (set-shifts-shifts sp (vector nstates))
1456 (set-shifts-next last-shift sp)
1457 (setq last-shift sp)
1458 ;; Note that the variable FINAL-STATE refers to what we sometimes
1459 ;; call the termination state.
1460 (setq final-state nstates)
1461 ;; Make the termination state.
1462 (setq statep (make-core))
1463 (set-core-number statep nstates)
1464 (setq nstates (1+ nstates))
1465 (set-core-next last-state statep)
1466 (setq last-state statep)))
1468 (defun wisent-save-reductions ()
1469 "Make a reductions structure.
1470 Find which rules can be used for reduction transitions from the
1471 current state and make a reductions structure for the state to record
1472 their rule numbers."
1473 (let (i item count p rules)
1474 ;; Find and count the active items that represent ends of rules.
1477 (while (< i nitemset)
1478 (setq item (aref ritem (aref itemset i)))
1480 (aset redset count (- item))
1481 (setq count (1+ count)))
1483 ;; Make a reductions structure and copy the data into it.
1485 (setq p (make-reductions)
1486 rules (make-vector count 0))
1487 (set-reductions-number p (core-number this-state))
1488 (set-reductions-nreds p count)
1489 (set-reductions-rules p rules)
1492 ;; (p->rules)[i] = redset[i]
1493 (aset rules i (aref redset i))
1496 (set-reductions-next last-reduction p)
1497 (setq first-reduction p))
1498 (setq last-reduction p))))
1500 (defun wisent-generate-states ()
1501 "Compute the nondeterministic finite state machine from the grammar."
1502 (working-dynamic-status "(compute nondeterministic finite state machine)")
1503 (wisent-allocate-storage)
1504 (wisent-initialize-closure nitems)
1505 (wisent-initialize-states)
1507 ;; Set up RULESET and ITEMSET for the transitions out of this
1508 ;; state. RULESET gets a 1 bit for each rule that could reduce
1509 ;; now. ITEMSET gets a vector of all the items that could be
1511 (wisent-closure (core-items this-state) (core-nitems this-state))
1512 ;; Record the reductions allowed out of this state.
1513 (wisent-save-reductions)
1514 ;; Find the itemsets of the states that shifts can reach.
1515 (wisent-new-itemsets)
1516 ;; Find or create the core structures for those states.
1517 (wisent-append-states)
1518 ;; Create the shifts structures for the shifts to those states,
1519 ;; now that the state numbers transitioning to are known.
1521 (wisent-save-shifts))
1522 ;; States are queued when they are created; process them all.
1523 (setq this-state (core-next this-state)))
1524 ;; Set up initial and final states as parser wants them.
1525 (wisent-augment-automaton))
1527 ;;;; ---------------------------
1528 ;;;; Compute look-ahead criteria
1529 ;;;; ---------------------------
1531 ;; Compute how to make the finite state machine deterministic; find
1532 ;; which rules need lookahead in each state, and which lookahead
1533 ;; tokens they accept.
1535 ;; `wisent-lalr', the entry point, builds these data structures:
1537 ;; GOTO-MAP, FROM-STATE and TO-STATE record each shift transition
1538 ;; which accepts a variable (a nonterminal). NGOTOS is the number of
1539 ;; such transitions.
1540 ;; FROM-STATE[t] is the state number which a transition leads from and
1541 ;; TO-STATE[t] is the state number it leads to.
1542 ;; All the transitions that accept a particular variable are grouped
1543 ;; together and GOTO-MAP[i - NTOKENS] is the index in FROM-STATE and
1544 ;; TO-STATE of the first of them.
1546 ;; CONSISTENT[s] is non-nil if no lookahead is needed to decide what
1547 ;; to do in state s.
1549 ;; LARULENO is a vector which records the rules that need lookahead in
1550 ;; various states. The elements of LARULENO that apply to state s are
1551 ;; those from LOOKAHEADS[s] through LOOKAHEADS[s+1]-1. Each element
1552 ;; of LARULENO is a rule number.
1554 ;; If LR is the length of LARULENO, then a number from 0 to LR-1 can
1555 ;; specify both a rule and a state where the rule might be applied.
1556 ;; LA is a LR by NTOKENS matrix of bits.
1557 ;; LA[l, i] is 1 if the rule LARULENO[l] is applicable in the
1558 ;; appropriate state when the next token is symbol i.
1559 ;; If LA[l, i] and LA[l, j] are both 1 for i != j, it is a conflict.
1561 (wisent-defcontext digraph
1565 (defun wisent-traverse (i)
1567 (let (j k height Ri Fi break)
1570 (aset VERTICES top i) ;; VERTICES[++top] = i
1571 (aset INDEX i top) ;; INDEX[i] = height = top
1573 (setq Ri (aref R i))
1576 (while (>= (aref Ri j) 0)
1577 (if (zerop (aref INDEX (aref Ri j)))
1578 (wisent-traverse (aref Ri j)))
1579 ;; if (INDEX[i] > INDEX[R[i][j]])
1580 (if (> (aref INDEX i) (aref INDEX (aref Ri j)))
1581 ;; INDEX[i] = INDEX[R[i][j]];
1582 (aset INDEX i (aref INDEX (aref Ri j))))
1585 (while (< k tokensetsize)
1586 ;; F (i)[k] |= F (R[i][j])[k];
1587 (aset Fi k (logior (aref Fi k)
1588 (aref (aref F (aref Ri j)) k)))
1592 (when (= (aref INDEX i) height)
1595 (setq j (aref VERTICES top) ;; j = VERTICES[top--]
1597 (aset INDEX j infinity)
1601 (while (< k tokensetsize)
1602 ;; F (j)[k] = F (i)[k];
1603 (aset (aref F j) k (aref (aref F i) k))
1607 (defun wisent-digraph (relation)
1609 (wisent-with-context digraph
1610 (setq infinity (+ ngotos 2)
1611 INDEX (make-vector (1+ ngotos) 0)
1612 VERTICES (make-vector (1+ ngotos) 0)
1617 (if (and (= (aref INDEX i) 0) (aref R i))
1618 (wisent-traverse i))
1621 (defun wisent-set-state-table ()
1622 "Build state table."
1624 (setq state-table (make-vector nstates nil)
1627 (aset state-table (core-number sp) sp)
1628 (setq sp (core-next sp)))))
1630 (defun wisent-set-accessing-symbol ()
1631 "Build accessing symbol table."
1633 (setq accessing-symbol (make-vector nstates 0)
1636 (aset accessing-symbol (core-number sp) (core-accessing-symbol sp))
1637 (setq sp (core-next sp)))))
1639 (defun wisent-set-shift-table ()
1640 "Build shift table."
1642 (setq shift-table (make-vector nstates nil)
1645 (aset shift-table (shifts-number sp) sp)
1646 (setq sp (shifts-next sp)))))
1648 (defun wisent-set-reduction-table ()
1649 "Build reduction table."
1651 (setq reduction-table (make-vector nstates nil)
1654 (aset reduction-table (reductions-number rp) rp)
1655 (setq rp (reductions-next rp)))))
1657 (defun wisent-set-maxrhs ()
1658 "Setup MAXRHS length."
1663 (while (aref ritem i)
1664 (if (> (aref ritem i) 0)
1672 (defun wisent-initialize-LA ()
1674 (let (i j k count rp sp np v)
1675 (setq consistent (make-vector nstates nil)
1676 lookaheads (make-vector (1+ nstates) 0)
1679 (while (< i nstates)
1680 (aset lookaheads i count)
1681 (setq rp (aref reduction-table i)
1682 sp (aref shift-table i))
1685 ;; || (sp && ! ISVAR(accessing-symbol[sp->shifts[0]]))))
1687 (or (> (reductions-nreds rp) 1)
1690 (aref accessing-symbol
1691 (aref (shifts-shifts sp) 0)))))))
1692 (setq count (+ count (reductions-nreds rp)))
1693 (aset consistent i t))
1697 j (shifts-nshifts sp)
1698 v (shifts-shifts sp))
1700 (when (= (aref accessing-symbol (aref v k))
1702 (aset consistent i nil)
1703 (setq k j)) ;; break
1707 (aset lookaheads nstates count)
1711 (setq LA (make-vector 1 nil)
1712 LAruleno (make-vector 1 0)
1713 lookback (make-vector 1 nil)))
1714 (setq LA (make-vector count nil)
1715 LAruleno (make-vector count 0)
1716 lookback (make-vector count nil)))
1717 (setq i 0 j (length LA))
1719 (aset LA i (make-vector tokensetsize 0))
1724 (while (< i nstates)
1725 (when (not (aref consistent i))
1726 (setq rp (aref reduction-table i))
1729 k (reductions-nreds rp)
1730 v (reductions-rules rp))
1732 (aset LAruleno np (aref v j))
1737 (defun wisent-set-goto-map ()
1739 (let (sp i j symbol k temp-map state1 state2 v)
1740 (setq goto-map (make-vector (1+ nvars) 0)
1741 temp-map (make-vector (1+ nvars) 0))
1746 (setq i (1- (shifts-nshifts sp))
1747 v (shifts-shifts sp))
1749 (setq symbol (aref accessing-symbol (aref v i)))
1750 (if (wisent-ISTOKEN symbol)
1752 (setq ngotos (1+ ngotos))
1753 ;; goto-map[symbol]++;
1754 (aset goto-map (- symbol ntokens)
1755 (1+ (aref goto-map (- symbol ntokens)))))
1757 (setq sp (shifts-next sp)))
1764 (setq k (+ k (aref goto-map j))
1770 (aset goto-map j (aref temp-map j))
1773 ;; goto-map[nsyms] = ngotos;
1774 ;; temp-map[nsyms] = ngotos;
1775 (aset goto-map j ngotos)
1776 (aset temp-map j ngotos)
1778 (setq from-state (make-vector ngotos 0)
1779 to-state (make-vector ngotos 0)
1782 (setq state1 (shifts-number sp)
1783 v (shifts-shifts sp)
1784 i (1- (shifts-nshifts sp)))
1786 (setq state2 (aref v i)
1787 symbol (aref accessing-symbol state2))
1788 (if (wisent-ISTOKEN symbol)
1790 ;; k = temp-map[symbol]++;
1791 (setq k (aref temp-map (- symbol ntokens)))
1792 (aset temp-map (- symbol ntokens) (1+ k))
1793 (aset from-state k state1)
1794 (aset to-state k state2))
1796 (setq sp (shifts-next sp)))
1799 (defun wisent-map-goto (state symbol)
1800 "Map a STATE/SYMBOL pair into its numeric representation."
1801 (let (high low middle s result)
1802 ;; low = goto-map[symbol];
1803 ;; high = goto-map[symbol + 1] - 1;
1804 (setq low (aref goto-map (- symbol ntokens))
1805 high (1- (aref goto-map (- (1+ symbol) ntokens))))
1806 (while (and (not result) (<= low high))
1807 (setq middle (/ (+ low high) 2)
1808 s (aref from-state middle))
1811 (setq result middle))
1813 (setq low (1+ middle)))
1815 (setq high (1- middle)))))
1817 (error "Internal error in `wisent-map-goto'"))
1820 (defun wisent-initialize-F ()
1822 (let (i j k sp edge rowp rp reads nedges stateno symbol v break)
1823 (setq F (make-vector ngotos nil)
1826 (aset F i (make-vector tokensetsize 0))
1829 (setq reads (make-vector ngotos nil)
1830 edge (make-vector (1+ ngotos) 0)
1835 (setq stateno (aref to-state i)
1836 sp (aref shift-table stateno))
1838 (setq k (shifts-nshifts sp)
1839 v (shifts-shifts sp)
1842 (while (and (not break) (< j k))
1843 ;; symbol = accessing-symbol[sp->shifts[j]];
1844 (setq symbol (aref accessing-symbol (aref v j)))
1845 (if (wisent-ISVAR symbol)
1846 (setq break t) ;; break
1847 (wisent-SETBIT (aref F rowp) symbol)
1851 ;; symbol = accessing-symbol[sp->shifts[j]];
1852 (setq symbol (aref accessing-symbol (aref v j)))
1853 (when (aref nullable (- symbol ntokens))
1854 (aset edge nedges (wisent-map-goto stateno symbol))
1855 (setq nedges (1+ nedges)))
1859 ;; reads[i] = rp = NEW2(nedges + 1, short);
1860 (setq rp (make-vector (1+ nedges) 0)
1865 (aset rp j (aref edge j))
1869 (setq rowp (1+ rowp))
1871 (wisent-digraph reads)
1874 (defun wisent-add-lookback-edge (stateno ruleno gotono)
1875 "Add a lookback edge.
1876 STATENO, RULENO, GOTONO are self-explanatory."
1878 (setq i (aref lookaheads stateno)
1879 k (aref lookaheads (1+ stateno))
1881 (while (and (not found) (< i k))
1882 (if (= (aref LAruleno i) ruleno)
1887 (error "Internal error in `wisent-add-lookback-edge'"))
1890 ;; lookback[i] = (gotono . lookback[i])
1891 (aset lookback i (cons gotono (aref lookback i)))))
1893 (defun wisent-transpose (R-arg n)
1894 "Return the transpose of R-ARG, of size N.
1895 Destroy R-ARG, as it is replaced with the result. R-ARG[I] is nil or
1896 a -1 terminated list of numbers. RESULT[NUM] is nil or the -1
1897 terminated list of the I such as NUM is in R-ARG[I]."
1898 (let (i j new-R end-R nedges v sp)
1899 (setq new-R (make-vector n nil)
1900 end-R (make-vector n nil)
1901 nedges (make-vector n 0))
1906 (setq v (aref R-arg i))
1909 (while (>= (aref v j) 0)
1910 (aset nedges (aref v j) (1+ (aref nedges (aref v j))))
1917 (when (> (aref nedges i) 0)
1918 (setq sp (make-vector (1+ (aref nedges i)) 0))
1919 (aset sp (aref nedges i) -1)
1927 (setq v (aref R-arg i))
1930 (while (>= (aref v j) 0)
1931 (aset (aref new-R (aref v j)) (aref end-R (aref v j)) i)
1932 (aset end-R (aref v j) (1+ (aref end-R (aref v j))))
1938 (defun wisent-build-relations ()
1940 (let (i j k rulep rp sp length nedges done state1 stateno
1941 symbol1 symbol2 edge states v)
1942 (setq includes (make-vector ngotos nil)
1943 edge (make-vector (1+ ngotos) 0)
1944 states (make-vector (1+ maxrhs) 0)
1949 state1 (aref from-state i)
1950 symbol1 (aref accessing-symbol (aref to-state i))
1951 rulep (aref derives (- symbol1 ntokens)))
1953 (while (> (car rulep) 0)
1954 (aset states 0 state1)
1957 rp (aref rrhs (car rulep))) ;; rp = ritem + rrhs[*rulep]
1958 (while (> (aref ritem rp) 0) ;; *rp > 0
1959 (setq symbol2 (aref ritem rp)
1960 sp (aref shift-table stateno)
1961 k (shifts-nshifts sp)
1962 v (shifts-shifts sp)
1965 (setq stateno (aref v j))
1966 (if (= (aref accessing-symbol stateno) symbol2)
1969 ;; states[length++] = stateno;
1970 (aset states length stateno)
1971 (setq length (1+ length))
1974 (if (not (aref consistent stateno))
1975 (wisent-add-lookback-edge stateno (car rulep) i))
1977 (setq length (1- length)
1982 (when (and (>= rp 0) (wisent-ISVAR (aref ritem rp)))
1983 ;; stateno = states[--length];
1984 (setq length (1- length)
1985 stateno (aref states length))
1986 (aset edge nedges (wisent-map-goto stateno (aref ritem rp)))
1987 (setq nedges (1+ nedges))
1988 (if (aref nullable (- (aref ritem rp) ntokens))
1990 (setq rulep (cdr rulep)))
1993 (setq v (make-vector (1+ nedges) 0)
1997 (aset v j (aref edge j))
2002 (setq includes (wisent-transpose includes ngotos))
2005 (defun wisent-compute-FOLLOWS ()
2007 (wisent-digraph includes))
2009 (defun wisent-compute-lookaheads ()
2010 "Compute lookaheads."
2011 (let (i j n v1 v2 sp)
2012 (setq n (aref lookaheads nstates)
2015 (setq sp (aref lookback i))
2017 (setq v1 (aref LA i)
2018 v2 (aref F (car sp))
2020 (while (< j tokensetsize)
2021 ;; LA (i)[j] |= F (sp->value)[j]
2022 (aset v1 j (logior (aref v1 j) (aref v2 j)))
2027 (defun wisent-lalr ()
2028 "Make the nondeterministic finite state machine deterministic."
2029 (working-dynamic-status "(make finite state machine deterministic)")
2030 (setq tokensetsize (wisent-WORDSIZE ntokens))
2031 (wisent-set-state-table)
2032 (wisent-set-accessing-symbol)
2033 (wisent-set-shift-table)
2034 (wisent-set-reduction-table)
2036 (wisent-initialize-LA)
2037 (wisent-set-goto-map)
2038 (wisent-initialize-F)
2039 (wisent-build-relations)
2040 (wisent-compute-FOLLOWS)
2041 (wisent-compute-lookaheads))
2043 ;;;; -----------------------------------------------
2044 ;;;; Find and resolve or report look-ahead conflicts
2045 ;;;; -----------------------------------------------
2047 (defsubst wisent-log-resolution (state LAno token resolution)
2048 "Log a shift-reduce conflict resolution.
2049 In specified STATE between rule pointed by lookahead number LANO and
2050 TOKEN, resolved as RESOLUTION."
2051 (if (or wisent-verbose-flag wisent-debug-flag)
2053 "Conflict in state %d between rule %d and token %s resolved as %s.\n"
2054 state (aref LAruleno LAno) (wisent-tag token) resolution)))
2056 (defun wisent-flush-shift (state token)
2057 "Turn off the shift recorded in the specified STATE for TOKEN.
2058 Used when we resolve a shift-reduce conflict in favor of the reduction."
2060 (when (setq shiftp (aref shift-table state))
2061 (setq k (shifts-nshifts shiftp)
2062 v (shifts-shifts shiftp)
2065 (if (and (not (zerop (aref v i)))
2066 (= token (aref accessing-symbol (aref v i))))
2070 (defun wisent-resolve-sr-conflict (state lookaheadnum)
2071 "Attempt to resolve shift-reduce conflict for one rule.
2072 Resolve by means of precedence declarations. The conflict occurred in
2073 specified STATE for the rule pointed by the lookahead symbol
2074 LOOKAHEADNUM. It has already been checked that the rule has a
2075 precedence. A conflict is resolved by modifying the shift or reduce
2076 tables so that there is no longer a conflict."
2077 (let (i redprec errp errs nerrs token sprec sassoc)
2078 ;; Find the rule to reduce by to get precedence of reduction
2079 (setq token (aref tags (aref rprec (aref LAruleno lookaheadnum)))
2080 redprec (wisent-prec token)
2082 errs (make-vector ntokens 0)
2085 (set-errs-errs errp errs)
2086 (while (< i ntokens)
2087 (setq token (aref tags i))
2088 (when (and (wisent-BITISSET (aref LA lookaheadnum) i)
2089 (wisent-BITISSET lookaheadset i)
2090 (setq sprec (wisent-prec token)))
2091 ;; Shift-reduce conflict occurs for token number I and it has
2092 ;; a precedence. The precedence of shifting is that of token
2096 (wisent-log-resolution state lookaheadnum i "reduce")
2097 ;; Flush the shift for this token
2098 (wisent-RESETBIT lookaheadset i)
2099 (wisent-flush-shift state i)
2102 (wisent-log-resolution state lookaheadnum i "shift")
2103 ;; Flush the reduce for this token
2104 (wisent-RESETBIT (aref LA lookaheadnum) i)
2107 ;; Matching precedence levels.
2108 ;; For left association, keep only the reduction.
2109 ;; For right association, keep only the shift.
2110 ;; For nonassociation, keep neither.
2111 (setq sassoc (wisent-assoc token))
2114 (wisent-log-resolution state lookaheadnum i "shift"))
2116 (wisent-log-resolution state lookaheadnum i "reduce"))
2117 ((eq sassoc 'nonassoc)
2118 (wisent-log-resolution state lookaheadnum i "an error"))
2120 (when (not (eq sassoc 'right))
2121 ;; Flush the shift for this token
2122 (wisent-RESETBIT lookaheadset i)
2123 (wisent-flush-shift state i))
2124 (when (not (eq sassoc 'left))
2125 ;; Flush the reduce for this token
2126 (wisent-RESETBIT (aref LA lookaheadnum) i))
2127 (when (eq sassoc 'nonassoc)
2128 ;; Record an explicit error for this token
2130 (setq nerrs (1+ nerrs)))
2134 (set-errs-nerrs errp nerrs)
2135 (aset err-table state errp))
2138 (defun wisent-set-conflicts (state)
2139 "Find and attempt to resolve conflicts in specified STATE."
2140 (let (i j k v shiftp symbol)
2141 (unless (aref consistent state)
2142 (fillarray lookaheadset 0)
2144 (when (setq shiftp (aref shift-table state))
2145 (setq k (shifts-nshifts shiftp)
2146 v (shifts-shifts shiftp)
2150 (setq symbol (aref accessing-symbol (aref v i)))))
2151 (or (zerop (aref v i))
2152 (wisent-SETBIT lookaheadset symbol))
2155 ;; Loop over all rules which require lookahead in this state
2156 ;; first check for shift-reduce conflict, and try to resolve
2158 (setq i (aref lookaheads state)
2159 k (aref lookaheads (1+ state)))
2161 (when (aref rprec (aref LAruleno i))
2164 (while (< j tokensetsize)
2165 (if (zerop (logand (aref v j) (aref lookaheadset j)))
2167 ;; if (LA (i)[j] & lookaheadset[j])
2168 (wisent-resolve-sr-conflict state i)
2169 (setq j tokensetsize)))) ;; break
2172 ;; Loop over all rules which require lookahead in this state
2173 ;; Check for conflicts not resolved above.
2174 (setq i (aref lookaheads state))
2178 (while (< j tokensetsize)
2179 ;; if (LA (i)[j] & lookaheadset[j])
2180 (if (not (zerop (logand (aref v j) (aref lookaheadset j))))
2181 (aset conflicts state t))
2184 (while (< j tokensetsize)
2185 ;; lookaheadset[j] |= LA (i)[j];
2186 (aset lookaheadset j (logior (aref lookaheadset j)
2192 (defun wisent-resolve-conflicts ()
2193 "Find and resolve conflicts."
2194 (working-dynamic-status "(resolve conflicts)")
2196 (setq conflicts (make-vector nstates nil)
2197 shiftset (make-vector tokensetsize 0)
2198 lookaheadset (make-vector tokensetsize 0)
2199 err-table (make-vector nstates nil)
2201 (while (< i nstates)
2202 (wisent-set-conflicts i)
2205 (defun wisent-count-sr-conflicts (state)
2206 "Count the number of shift/reduce conflicts in specified STATE."
2207 (let (i j k shiftp symbol v)
2209 shiftp (aref shift-table state))
2211 (fillarray shiftset 0)
2212 (fillarray lookaheadset 0)
2213 (setq k (shifts-nshifts shiftp)
2214 v (shifts-shifts shiftp)
2217 (when (not (zerop (aref v i)))
2218 (setq symbol (aref accessing-symbol (aref v i)))
2219 (if (wisent-ISVAR symbol)
2221 (wisent-SETBIT shiftset symbol)))
2224 (setq k (aref lookaheads (1+ state))
2225 i (aref lookaheads state))
2229 (while (< j tokensetsize)
2230 ;; lookaheadset[j] |= LA (i)[j]
2231 (aset lookaheadset j (logior (aref lookaheadset j)
2237 (while (< k tokensetsize)
2238 ;; lookaheadset[k] &= shiftset[k];
2239 (aset lookaheadset k (logand (aref lookaheadset k)
2244 (while (< i ntokens)
2245 (if (wisent-BITISSET lookaheadset i)
2246 (setq src-count (1+ src-count)))
2250 (defun wisent-count-rr-conflicts (state)
2251 "Count the number of reduce/reduce conflicts in specified STATE."
2252 (let (i j count n m)
2254 m (aref lookaheads state)
2255 n (aref lookaheads (1+ state)))
2256 (when (>= (- n m) 2)
2258 (while (< i ntokens)
2262 (if (wisent-BITISSET (aref LA j) i)
2263 (setq count (1+ count)))
2267 (setq rrc-count (1+ rrc-count)))
2271 (defvar wisent-expected-conflicts nil
2272 "*If non-nil suppress the warning about shift/reduce conflicts.
2273 It is a decimal integer N that says there should be no warning if
2274 there are N shift/reduce conflicts and no reduce/reduce conflicts. A
2275 warning is given if there are either more or fewer conflicts, or if
2276 there are any reduce/reduce conflicts.")
2278 (defun wisent-total-conflicts ()
2279 "Report the total number of conflicts."
2280 (unless (and (zerop rrc-total)
2281 (or (zerop src-total)
2282 (= src-total (or wisent-expected-conflicts 0))))
2283 (let* ((src (wisent-source))
2284 (src (if src (concat " in " src) ""))
2285 (msg (format "Grammar%s contains" src)))
2287 (setq msg (format "%s %d shift/reduce conflict%s"
2288 msg src-total (if (> src-total 1)
2290 (if (and (> src-total 0) (> rrc-total 0))
2291 (setq msg (format "%s and" msg)))
2293 (setq msg (format "%s %d reduce/reduce conflict%s"
2294 msg rrc-total (if (> rrc-total 1)
2298 (defun wisent-print-conflicts ()
2304 (while (< i nstates)
2305 (when (aref conflicts i)
2306 (wisent-count-sr-conflicts i)
2307 (wisent-count-rr-conflicts i)
2308 (setq src-total (+ src-total src-count)
2309 rrc-total (+ rrc-total rrc-count))
2310 (when (or wisent-verbose-flag wisent-debug-flag)
2311 (wisent-log "State %d contains" i)
2313 (wisent-log " %d shift/reduce conflict%s"
2314 src-count (if (> src-count 1) "s" "")))
2316 (if (and (> src-count 0) (> rrc-count 0))
2317 (wisent-log " and"))
2320 (wisent-log " %d reduce/reduce conflict%s"
2321 rrc-count (if (> rrc-count 1) "s" "")))
2323 (wisent-log ".\n")))
2325 (wisent-total-conflicts)))
2327 ;;;; --------------------------------------
2328 ;;;; Report information on generated parser
2329 ;;;; --------------------------------------
2330 (defun wisent-print-grammar ()
2332 (let (i j r break left-count right-count)
2334 (wisent-log "\n\nGrammar\n\n Number, Rule\n")
2336 (while (<= i nrules)
2337 ;; Don't print rules disabled in `wisent-reduce-grammar-tables'.
2338 (when (aref ruseful i)
2339 (wisent-log " %s %s ->"
2340 (wisent-pad-string (number-to-string i) 6)
2341 (wisent-tag (aref rlhs i)))
2342 (setq r (aref rrhs i))
2343 (if (> (aref ritem r) 0)
2344 (while (> (aref ritem r) 0)
2345 (wisent-log " %s" (wisent-tag (aref ritem r)))
2347 (wisent-log " /* empty */"))
2351 (wisent-log "\n\nTerminals, with rules where they appear\n\n")
2352 (wisent-log "%s (-1)\n" (wisent-tag 0))
2354 (while (< i ntokens)
2355 (wisent-log "%s (%d)" (wisent-tag i) i)
2357 (while (<= j nrules)
2358 (setq r (aref rrhs j)
2360 (while (and (not break) (> (aref ritem r) 0))
2361 (if (setq break (= (aref ritem r) i))
2362 (wisent-log " %d" j)
2368 (wisent-log "\n\nNonterminals, with rules where they appear\n\n")
2374 (while (<= j nrules)
2375 (if (= (aref rlhs j) i)
2376 (setq left-count (1+ left-count)))
2377 (setq r (aref rrhs j)
2379 (while (and (not break) (> (aref ritem r) 0))
2380 (if (= (aref ritem r) i)
2381 (setq right-count (1+ right-count)
2385 (wisent-log "%s (%d)\n " (wisent-tag i) i)
2386 (when (> left-count 0)
2387 (wisent-log " on left:")
2389 (while (<= j nrules)
2390 (if (= (aref rlhs j) i)
2391 (wisent-log " %d" j))
2393 (when (> right-count 0)
2394 (if (> left-count 0)
2396 (wisent-log " on right:")
2398 (while (<= j nrules)
2399 (setq r (aref rrhs j)
2401 (while (and (not break) (> (aref ritem r) 0))
2402 (if (setq break (= (aref ritem r) i))
2403 (wisent-log " %d" j)
2410 (defun wisent-print-reductions (state)
2411 "Print reductions on STATE."
2412 (let (i j k v symbol m n defaulted
2413 default-LA default-rule cmax count shiftp errp nodefault)
2416 (fillarray shiftset 0)
2418 (setq shiftp (aref shift-table state))
2420 (setq k (shifts-nshifts shiftp)
2421 v (shifts-shifts shiftp)
2424 (when (not (zerop (aref v i)))
2425 (setq symbol (aref accessing-symbol (aref v i)))
2426 (if (wisent-ISVAR symbol)
2428 ;; If this state has a shift for the error token, don't
2429 ;; use a default rule.
2430 (if (= symbol error-token-number)
2432 (wisent-SETBIT shiftset symbol)))
2435 (setq errp (aref err-table state))
2437 (setq k (errs-nerrs errp)
2441 (if (not (zerop (setq symbol (aref v i))))
2442 (wisent-SETBIT shiftset symbol))
2445 (setq m (aref lookaheads state)
2446 n (aref lookaheads (1+ state)))
2449 ((and (= (- n m) 1) (not nodefault))
2450 (setq default-rule (aref LAruleno m)
2453 (while (< k tokensetsize)
2454 (aset lookaheadset k (logand (aref v k)
2459 (while (< i ntokens)
2460 (if (wisent-BITISSET lookaheadset i)
2461 (wisent-log " %s\t[reduce using rule %d (%s)]\n"
2462 (wisent-tag i) default-rule
2463 (wisent-tag (aref rlhs default-rule))))
2465 (wisent-log " $default\treduce using rule %d (%s)\n\n"
2467 (wisent-tag (aref rlhs default-rule)))
2473 (when (not nodefault)
2479 (while (< k tokensetsize)
2480 ;; lookaheadset[k] = LA (i)[k] & ~shiftset[k]
2481 (aset lookaheadset k
2483 (lognot (aref shiftset k))))
2486 (while (< j ntokens)
2487 (if (wisent-BITISSET lookaheadset j)
2488 (setq count (1+ count)))
2493 default-rule (aref LAruleno i)))
2495 (while (< k tokensetsize)
2496 (aset shiftset k (logior (aref shiftset k)
2497 (aref lookaheadset k)))
2501 (fillarray shiftset 0)
2504 (setq k (shifts-nshifts shiftp)
2505 v (shifts-shifts shiftp)
2508 (when (not (zerop (aref v i)))
2509 (setq symbol (aref accessing-symbol (aref v i)))
2510 (if (wisent-ISVAR symbol)
2512 (wisent-SETBIT shiftset symbol)))
2516 (while (< i ntokens)
2518 count (if (wisent-BITISSET shiftset i) 1 0)
2521 (when (wisent-BITISSET (aref LA j) i)
2524 (if (not (= j default-LA))
2526 " %s\treduce using rule %d (%s)\n"
2527 (wisent-tag i) (aref LAruleno j)
2528 (wisent-tag (aref rlhs (aref LAruleno j))))
2530 (setq count (1+ count)))
2533 " %s\treduce using rule %d (%s)\n"
2534 (wisent-tag i) (aref LAruleno default-LA)
2535 (wisent-tag (aref rlhs (aref LAruleno default-LA)))))
2536 (setq defaulted nil)
2538 " %s\t[reduce using rule %d (%s)]\n"
2539 (wisent-tag i) (aref LAruleno j)
2540 (wisent-tag (aref rlhs (aref LAruleno j))))))
2544 (if (>= default-LA 0)
2546 " $default\treduce using rule %d (%s)\n"
2548 (wisent-tag (aref rlhs default-rule))))
2551 (defun wisent-print-actions (state)
2552 "Print actions on STATE."
2553 (let (i j k v state1 symbol shiftp errp redp rule nerrs break)
2554 (setq shiftp (aref shift-table state)
2555 redp (aref reduction-table state)
2556 errp (aref err-table state))
2557 (if (and (not shiftp) (not redp))
2558 (if (= final-state state)
2559 (wisent-log " $default\taccept\n")
2560 (wisent-log " NO ACTIONS\n"))
2564 (setq k (shifts-nshifts shiftp)
2565 v (shifts-shifts shiftp)
2568 (while (and (not break) (< i k))
2569 (if (zerop (setq state1 (aref v i)))
2571 (setq symbol (aref accessing-symbol state1))
2572 ;; The following line used to be turned off.
2573 (if (wisent-ISVAR symbol)
2574 (setq break t) ;; break
2575 (wisent-log " %s\tshift, and go to state %d\n"
2576 (wisent-tag symbol) state1)
2582 (setq nerrs (errs-nerrs errp)
2587 (wisent-log " %s\terror (nonassociative)\n"
2588 (wisent-tag (aref v j))))
2594 ((and (aref consistent state) redp)
2595 (setq rule (aref (reductions-rules redp) 0)
2596 symbol (aref rlhs rule))
2597 (wisent-log " $default\treduce using rule %d (%s)\n\n"
2598 rule (wisent-tag symbol))
2601 (wisent-print-reductions state)
2605 (setq v (shifts-shifts shiftp))
2607 (when (setq state1 (aref v i))
2608 (setq symbol (aref accessing-symbol state1))
2609 (wisent-log " %s\tgo to state %d\n"
2610 (wisent-tag symbol) state1))
2615 (defun wisent-print-core (state)
2617 (let (i k rule statep sp sp1)
2618 (setq statep (aref state-table state)
2619 k (core-nitems statep))
2623 ;; sp1 = sp = ritem + statep->items[i];
2624 (setq sp1 (aref (core-items statep) i)
2626 (while (> (aref ritem sp) 0)
2629 (setq rule (- (aref ritem sp)))
2630 (wisent-log " %s -> " (wisent-tag (aref rlhs rule)))
2632 (setq sp (aref rrhs rule))
2634 (wisent-log "%s " (wisent-tag (aref ritem sp)))
2637 (while (> (aref ritem sp) 0)
2638 (wisent-log " %s" (wisent-tag (aref ritem sp)))
2640 (wisent-log " (rule %d)\n" rule)
2642 (wisent-log "\n"))))
2644 (defun wisent-print-state (state)
2645 "Print information on STATE."
2646 (wisent-log "\n\nstate %d\n\n" state)
2647 (wisent-print-core state)
2648 (wisent-print-actions state))
2650 (defun wisent-print-states ()
2651 "Print information on states."
2653 (while (< i nstates)
2654 (wisent-print-state i)
2657 (defun wisent-print-results ()
2658 "Print information on generated parser.
2659 Report detailed informations if `wisent-verbose-flag' or
2660 `wisent-debug-flag' are non-nil."
2661 (when (or wisent-verbose-flag wisent-debug-flag)
2662 (wisent-print-useless))
2663 (wisent-print-conflicts)
2664 (when (or wisent-verbose-flag wisent-debug-flag)
2665 (wisent-print-grammar)
2666 (wisent-print-states))
2667 ;; Append output to log file when running in batch mode
2668 (when (wisent-noninteractive)
2669 (wisent-append-to-log-file)
2670 (wisent-clear-log)))
2672 ;;;; ---------------------------------
2673 ;;;; Build the generated parser tables
2674 ;;;; ---------------------------------
2676 (defun wisent-action-row (state actrow)
2677 "Figure out the actions for the specified STATE.
2678 Decide what to do for each type of token if seen as the lookahead
2679 token in specified state. The value returned is used as the default
2680 action for the state. In addition, ACTROW is filled with what to do
2681 for each kind of token, index by symbol number, with nil meaning do
2682 the default action. The value 'error, means this situation is an
2683 error. The parser recognizes this value specially.
2685 This is where conflicts are resolved. The loop over lookahead rules
2686 considered lower-numbered rules last, and the last rule considered
2687 that likes a token gets to handle it."
2688 (let (i j k m n v default-rule nreds rule max count
2689 shift-state symbol redp shiftp errp nodefault)
2691 (fillarray actrow nil)
2693 (setq default-rule 0
2694 nodefault nil ;; nil inhibit having any default reduction
2698 redp (aref reduction-table state))
2701 (setq nreds (reductions-nreds redp))
2703 ;; loop over all the rules available here which require
2705 (setq m (aref lookaheads state)
2706 n (aref lookaheads (1+ state))
2709 ;; and find each token which the rule finds acceptable to
2712 (while (< j ntokens)
2713 ;; and record this rule as the rule to use if that token
2715 (if (wisent-BITISSET (aref LA i) j)
2716 (aset actrow j (- (aref LAruleno i)))
2721 ;; Now see which tokens are allowed for shifts in this state. For
2722 ;; them, record the shift as the thing to do. So shift is
2723 ;; preferred to reduce.
2724 (setq shiftp (aref shift-table state))
2726 (setq k (shifts-nshifts shiftp)
2727 v (shifts-shifts shiftp)
2730 (setq shift-state (aref v i))
2731 (if (zerop shift-state)
2733 (setq symbol (aref accessing-symbol shift-state))
2734 (if (wisent-ISVAR symbol)
2736 (aset actrow symbol shift-state)
2737 ;; Do not use any default reduction if there is a shift
2739 (if (= symbol error-token-number)
2740 (setq nodefault t))))
2743 ;; See which tokens are an explicit error in this state (due to
2744 ;; %nonassoc). For them, record error as the action.
2745 (setq errp (aref err-table state))
2747 (setq k (errs-nerrs errp)
2751 (aset actrow (aref v i) wisent-error-tag)
2754 ;; Now find the most common reduction and make it the default
2755 ;; action for this state.
2756 (when (and (>= nreds 1) (not nodefault))
2757 (if (aref consistent state)
2758 (setq default-rule (- (aref (reductions-rules redp) 0)))
2763 rule (- (aref LAruleno i))
2765 (while (< j ntokens)
2766 (if (and (numberp (aref actrow j))
2767 (= (aref actrow j) rule))
2768 (setq count (1+ count)))
2774 ;; actions which match the default are replaced with zero,
2775 ;; which means "use the default"
2778 (while (< j ntokens)
2779 (if (and (numberp (aref actrow j))
2780 (= (aref actrow j) default-rule))
2781 (aset actrow j nil))
2785 ;; If have no default rule, if this is the final state the default
2786 ;; is accept else it is an error. So replace any action which
2787 ;; says "error" with "use default".
2788 (when (zerop default-rule)
2789 (if (= final-state state)
2790 (setq default-rule wisent-accept-tag)
2792 (while (< j ntokens)
2793 (if (eq (aref actrow j) wisent-error-tag)
2794 (aset actrow j nil))
2796 (setq default-rule wisent-error-tag)))
2799 (defconst wisent-default-tag 'default
2800 "Tag used in an action table to indicate a default action.")
2802 ;; These variables only exist locally in the function
2803 ;; `wisent-state-actions' and are shared by all other nested callees.
2804 (wisent-defcontext semantic-actions
2805 ;; Uninterned symbols used in code generation.
2806 stack sp gotos state
2807 ;; Name of the current semantic action
2810 (defun wisent-state-actions ()
2811 "Figure out the actions for every state.
2812 Return the action table."
2813 (working-dynamic-status "(build state actions)")
2814 ;; Store the semantic action obarray in (unused) RCODE[0].
2815 (aset rcode 0 (make-vector 13 0))
2816 (let (i j action-table actrow action)
2817 (setq action-table (make-vector nstates nil)
2818 actrow (make-vector ntokens nil)
2820 (wisent-with-context semantic-actions
2821 (setq stack (make-symbol "stack")
2822 sp (make-symbol "sp")
2823 gotos (make-symbol "gotos")
2824 state (make-symbol "state"))
2825 (while (< i nstates)
2826 (setq action (wisent-action-row i actrow))
2827 ;; Translate a reduction into semantic action
2828 (and (integerp action) (< action 0)
2829 (setq action (wisent-semantic-action (- action))))
2830 (aset action-table i (list (cons wisent-default-tag action)))
2832 (while (< j ntokens)
2833 (when (setq action (aref actrow j))
2834 ;; Translate a reduction into semantic action
2835 (and (integerp action) (< action 0)
2836 (setq action (wisent-semantic-action (- action))))
2837 (aset action-table i (cons (cons (aref tags j) action)
2838 (aref action-table i)))
2841 (aset action-table i (nreverse (aref action-table i)))
2845 (defun wisent-goto-actions ()
2846 "Figure out what to do after reducing with each rule.
2847 Depending on the saved state from before the beginning of parsing the
2848 data that matched this rule. Return the goto table."
2849 (working-dynamic-status "(build goto actions)")
2850 (let (i j m n symbol state goto-table)
2851 (setq goto-table (make-vector nstates nil)
2854 (setq symbol (- i ntokens)
2855 m (aref goto-map symbol)
2856 n (aref goto-map (1+ symbol))
2859 (setq state (aref from-state j))
2860 (aset goto-table state
2861 (cons (cons (aref tags i) (aref to-state j))
2862 (aref goto-table state)))
2867 (defsubst wisent-quote-p (sym)
2868 "Return non-nil if SYM is bound to the `quote' function."
2870 (eq (indirect-function sym)
2871 (indirect-function 'quote))
2874 (defsubst wisent-backquote-p (sym)
2875 "Return non-nil if SYM is bound to the `backquote' function."
2877 (eq (indirect-function sym)
2878 (indirect-function 'backquote))
2881 (defun wisent-check-$N (x m)
2882 "Return non-nil if X is a valid $N or $regionN symbol.
2883 That is if X is a $N or $regionN symbol with N >= 1 and N <= M.
2884 Also warn if X is a $N or $regionN symbol with N < 1 or N > M."
2886 (let* ((n (symbol-name x))
2887 (i (and (string-match "\\`\\$\\(region\\)?\\([0-9]+\\)\\'" n)
2888 (string-to-number (match-string 2 n)))))
2890 (if (and (>= i 1) (<= i m))
2893 "*** In %s, %s might be a free variable (rule has %s)"
2894 NAME x (format (cond ((< m 1) "no component")
2895 ((= m 1) "%d component")
2900 (defun wisent-semantic-action-expand-body (body n &optional found)
2901 "Parse BODY of semantic action.
2902 N is the maximum number of $N variables that can be referenced in
2903 BODY. Warn on references out of permitted range.
2904 Optional argument FOUND is the accumulated list of '$N' references
2906 Return a cons (FOUND . XBODY), where FOUND is the list of $N
2907 references found in BODY, and XBODY is BODY expression with
2908 `backquote' forms expanded."
2909 (if (not (listp body))
2910 ;; BODY is an atom, no expansion needed
2912 (if (wisent-check-$N body n)
2913 ;; Accumulate $i symbol
2914 (add-to-list 'found body))
2916 ;; BODY is a list, expand inside it
2918 ;; If backquote expand it first
2919 (if (wisent-backquote-p (car body))
2920 (setq body (macroexpand body)))
2922 (setq sexpr (car body)
2925 ;; Function call excepted quote expression
2927 (not (wisent-quote-p (car sexpr))))
2928 (setq sexpr (wisent-semantic-action-expand-body sexpr n found)
2932 ((wisent-check-$N sexpr n)
2933 ;; Accumulate $i symbol
2934 (add-to-list 'found sexpr))
2936 ;; Accumulate expanded forms
2937 (setq xbody (nconc xbody (list sexpr))))
2938 (cons found xbody))))
2940 (defun wisent-semantic-action (r)
2941 "Set up the Elisp function for semantic action at rule R.
2942 On entry RCODE[R] contains a vector [BODY N (NTERM I)] where BODY is the
2943 body of the semantic action, N is the maximum number of values
2944 available in the parser's stack, NTERM is the nonterminal the semantic
2945 action belongs to, and I is the index of the semantic action inside
2946 NTERM definition. Return the semantic action symbol.
2947 The semantic action function accepts three arguments:
2949 - the state/value stack
2950 - the top-of-stack index
2953 And returns the updated top-of-stack index."
2954 (if (not (aref ruseful r))
2956 (let* ((actn (aref rcode r))
2957 (n (aref actn 1)) ; nb of val avail. in stack
2958 (NAME (apply 'format "%s:%d" (aref actn 2)))
2959 (form (wisent-semantic-action-expand-body (aref actn 0) n))
2960 ($l (car form)) ; list of $vars used in body
2961 (form (cdr form)) ; expanded form of body
2962 (nt (aref rlhs r)) ; nonterminal item no.
2963 (bl nil) ; `let*' binding list
2966 ;; Compute $N and $regionN bindings
2969 (setq j (1+ (* 2 (- n i))))
2970 ;; Only bind $regionI if used in action
2971 (setq $v (intern (format "$region%d" i)))
2973 (setq bl (cons `(,$v (cdr (aref ,stack (- ,sp ,j)))) bl)))
2974 ;; Only bind $I if used in action
2975 (setq $v (intern (format "$%d" i)))
2977 (setq bl (cons `(,$v (car (aref ,stack (- ,sp ,j)))) bl)))
2980 ;; Compute J, the length of rule's RHS. It will give the
2981 ;; current parser state at STACK[SP - 2*J], and where to push
2982 ;; the new semantic value and the next state, respectively at:
2983 ;; STACK[SP - 2*J + 1] and STACK[SP - 2*J + 2]. Generally N,
2984 ;; the maximum number of values available in the stack, is equal
2985 ;; to J. But, for mid-rule actions, N is the number of rule
2986 ;; elements before the action and J is always 0 (empty rule).
2987 (setq i (aref rrhs r)
2989 (while (> (aref ritem i) 0)
2993 ;; Create the semantic action symbol.
2994 (setq actn (intern NAME (aref rcode 0)))
2996 ;; Store source code in function cell of the semantic action
2997 ;; symbol. It will be byte-compiled at automaton's compilation
2998 ;; time. Using a byte-compiled automaton can significantly
2999 ;; speed up parsing!
3001 `(lambda (,stack ,sp ,gotos)
3006 (if (assq '$region1 bl)
3008 `(cdr (aref ,stack (1- ,sp)))))
3010 `(wisent-production-bounds
3011 ,stack (- ,sp ,(1- (* 2 n))) (1- ,sp)))))
3013 ($nterm ',(aref tags nt))
3014 ,@(and (> j 0) `((,sp (- ,sp ,(* j 2)))))
3015 (,state (cdr (assq $nterm
3017 (aref ,stack ,sp))))))
3018 (setq ,sp (+ ,sp 2))
3019 ;; push semantic value
3020 (aset ,stack (1- ,sp) (cons ,form $region))
3022 (aset ,stack ,sp ,state)
3023 ;; return new top of stack
3026 ;; Return the semantic action symbol
3029 ;;;; ----------------------------
3030 ;;;; Build parser LALR automaton.
3031 ;;;; ----------------------------
3033 (defun wisent-parser-automaton ()
3034 "Compute and return LALR(1) automaton from GRAMMAR.
3035 GRAMMAR is in internal format. GRAM/ACTS are grammar rules
3036 in internal format. STARTS defines the start symbols."
3037 ;; Check for useless stuff
3038 (wisent-reduce-grammar)
3040 (wisent-set-derives)
3041 (wisent-set-nullable)
3042 ;; convert to nondeterministic finite state machine.
3043 (wisent-generate-states)
3044 ;; make it deterministic.
3046 ;; Find and record any conflicts: places where one token of
3047 ;; lookahead is not enough to disambiguate the parsing. Also
3048 ;; resolve s/r conflicts based on precedence declarations.
3049 (wisent-resolve-conflicts)
3050 (wisent-print-results)
3052 (vector (wisent-state-actions) ; action table
3053 (wisent-goto-actions) ; goto table
3054 start-table ; start symbols
3055 (aref rcode 0) ; sem. action symbol obarray
3059 ;;;; -------------------
3060 ;;;; Parse input grammar
3061 ;;;; -------------------
3063 (defconst wisent-reserved-symbols (list wisent-error-term)
3064 "The list of reserved symbols.
3065 Also all symbols starting with a character defined in
3066 `wisent-reserved-capitals' are reserved for internal use.")
3068 (defconst wisent-reserved-capitals '(?\$ ?\@)
3069 "The list of reserved capital letters.
3070 All symbol starting with one of these letters are reserved for
3073 (defconst wisent-starts-nonterm '$STARTS
3075 It gives the rules for start symbols.")
3077 (defvar wisent-single-start-flag nil
3078 "Non-nil means allows only one start symbol like in Bison.
3079 That is don't add extra start rules to the grammar. This is
3080 useful to compare the Wisent's generated automaton with the Bison's
3083 (defsubst wisent-ISVALID-VAR (x)
3084 "Return non-nil if X is a character or an allowed symbol."
3086 (not (memq (aref (symbol-name x) 0) wisent-reserved-capitals))
3087 (not (memq x wisent-reserved-symbols))))
3089 (defsubst wisent-ISVALID-TOKEN (x)
3090 "Return non-nil if X is a character or an allowed symbol."
3091 (or (wisent-char-p x)
3092 (wisent-ISVALID-VAR x)))
3094 (defun wisent-push-token (symbol &optional nocheck)
3095 "Push a new SYMBOL in the list of tokens.
3096 Bypass checking if NOCHECK is non-nil."
3098 (or nocheck (wisent-ISVALID-TOKEN symbol)
3099 (error "Invalid terminal symbol: %S" symbol))
3100 (if (memq symbol token-list)
3101 (message "*** duplicate terminal `%s' ignored" symbol)
3102 ;; Set up properties
3103 (wisent-set-prec symbol nil)
3104 (wisent-set-assoc symbol nil)
3105 (wisent-set-item-number symbol ntokens)
3107 (setq ntokens (1+ ntokens)
3108 token-list (cons symbol token-list))))
3110 (defun wisent-push-var (symbol &optional nocheck)
3111 "Push a new SYMBOL in the list of nonterminals.
3112 Bypass checking if NOCHECK is non-nil."
3115 (or (wisent-ISVALID-VAR symbol)
3116 (error "Invalid nonterminal symbol: %S" symbol))
3117 (if (memq symbol var-list)
3118 (error "Nonterminal `%s' already defined" symbol)))
3119 ;; Set up properties
3120 (wisent-set-item-number symbol nvars)
3122 (setq nvars (1+ nvars)
3123 var-list (cons symbol var-list)))
3125 (defun wisent-parse-nonterminals (defs)
3126 "Parse nonterminal definitions in DEFS.
3127 Fill in each element of the global arrays RPREC, RCODE, RUSEFUL with
3128 respectively rule precedence level, semantic action code and
3129 usefulness flag. Return a list of rules of the form (LHS . RHS) where
3130 LHS and RHS are respectively the Left Hand Side and Right Hand Side of
3136 (let (def nonterm rlist rule rules rhs rest item items
3137 rhl plevel semact @n @count iactn)
3140 (setq def (car defs)
3146 (error "Invalid nonterminal definition syntax: %S" def))
3148 (setq rule (car rlist)
3155 ;; Check & count items
3156 (setq nitems (1+ nitems)) ;; LHS item
3158 (setq item (car items)
3160 nitems (1+ nitems)) ;; RHS items
3164 (setq @count (1+ @count)
3165 @n (intern (format "@%d" @count)))
3166 (wisent-push-var @n t)
3167 ;; Push a new empty rule with the mid-rule action
3168 (setq semact (vector item rhl (list nonterm iactn))
3171 rcode (cons semact rcode)
3172 rprec (cons plevel rprec)
3173 item @n ;; Replace action by @N nonterminal
3174 rules (cons (list item) rules)
3176 nrules (1+ nrules)))
3177 ;; Check terminal or nonterminal symbol
3179 ((or (memq item token-list) (memq item var-list)))
3180 ;; Create new literal character token
3181 ((wisent-char-p item) (wisent-push-token item t))
3182 ((error "Symbol `%s' is used, but is not defined as a token and has no rules"
3185 rhs (cons item rhs)))
3187 ;; Check & collect rule precedence level
3188 (setq plevel (when (vectorp (car rest))
3189 (setq item (car rest)
3191 (if (and (= (length item) 1)
3192 (memq (aref item 0) token-list)
3193 (wisent-prec (aref item 0)))
3194 (wisent-item-number (aref item 0))
3195 (error "Invalid rule precedence level syntax: %S" item)))
3196 rprec (cons plevel rprec))
3198 ;; Check & collect semantic action body
3199 (setq semact (vector
3202 (error "Invalid semantic action syntax: %S" rest)
3204 ;; Give a default semantic action body: nil
3205 ;; for an empty rule or $1, the value of the
3206 ;; first symbol in the rule, otherwise.
3207 (if (> rhl 0) '$1 '()))
3209 (list nonterm iactn))
3211 rcode (cons semact rcode))
3212 (setq rules (cons (cons nonterm (nreverse rhs)) rules)
3213 nrules (1+ nrules))))
3215 (setq ruseful (make-vector (1+ nrules) t)
3216 rprec (vconcat (cons nil (nreverse rprec)))
3217 rcode (vconcat (cons nil (nreverse rcode))))
3221 (defun wisent-parse-grammar (grammar &optional start-list)
3222 "Parse GRAMMAR and build a suitable internal representation.
3223 Optional argument START-LIST defines the start symbols.
3224 GRAMMAR is a list of form: (TOKENS ASSOCS . NONTERMS)
3226 TOKENS is a list of terminal symbols (tokens).
3228 ASSOCS is nil or an alist of (ASSOC-TYPE . ASSOC-VALUE) elements
3229 describing the associativity of TOKENS. ASSOC-TYPE must be one of the
3230 `default-prec' `nonassoc', `left' or `right' symbols. When ASSOC-TYPE
3231 is `default-prec', ASSOC-VALUE must be nil or t (the default).
3232 Otherwise it is a list of tokens which must have been previously
3235 NONTERMS is the list of non terminal definitions (see function
3236 `wisent-parse-nonterminals')."
3237 (working-dynamic-status "(parse input grammar)")
3238 (or (and (consp grammar) (> (length grammar) 2))
3239 (error "Bad input grammar"))
3241 (let (i r rhs pre dpre lst start-var assoc rules item
3242 token var def tokens defs ep-token ep-var ep-def)
3245 (setq ntokens 0 nvars 0)
3246 (wisent-push-token wisent-eoi-term t)
3247 (wisent-push-token wisent-error-term t)
3249 ;; Check/collect terminals
3250 (setq lst (car grammar))
3252 (wisent-push-token (car lst))
3253 (setq lst (cdr lst)))
3255 ;; Check/Set up tokens precedence & associativity
3256 (setq lst (nth 1 grammar)
3266 (if (eq assoc 'default-prec)
3268 (or (null (cdr tokens))
3269 (memq (car tokens) '(t nil))
3270 (error "Invalid default-prec value: %S" tokens))
3271 (setq default-prec (car tokens))
3273 (message "*** redefining default-prec to %s"
3276 (or (memq assoc '(left right nonassoc))
3277 (error "Invalid associativity syntax: %S" assoc))
3280 (setq token (car tokens)
3281 tokens (cdr tokens))
3282 (if (memq token defs)
3283 (message "*** redefining precedence of `%s'" token))
3284 (or (memq token token-list)
3285 ;; Define token not previously declared.
3286 (wisent-push-token token))
3287 (setq defs (cons token defs))
3288 ;; Record the precedence and associativity of the terminal.
3289 (wisent-set-prec token pre)
3290 (wisent-set-assoc token assoc))))
3292 ;; Check/Collect nonterminals
3293 (setq lst (nthcdr 2 grammar)
3299 (error "Invalid nonterminal definition: %S" def))
3300 (if (memq (car def) token-list)
3301 (error "Nonterminal `%s' already defined as token" (car def)))
3302 (wisent-push-var (car def))
3303 (setq defs (cons def defs)))
3305 (error "No input grammar"))
3306 (setq defs (nreverse defs))
3308 ;; Set up the start symbol.
3309 (setq start-table nil)
3312 ;; 1. START-LIST is nil, the start symbol is the first
3313 ;; nonterminal defined in the grammar (Bison like).
3315 (setq start-var (caar defs)))
3317 ;; 2. START-LIST contains only one element, it is the start
3318 ;; symbol (Bison like).
3319 ((or wisent-single-start-flag (null (cdr start-list)))
3320 (setq start-var (car start-list))
3321 (or (assq start-var defs)
3322 (error "Start symbol `%s' has no rule" start-var)))
3324 ;; 3. START-LIST contains more than one element. All defines
3325 ;; potential start symbols. One of them (the first one by
3326 ;; default) will be given at parse time to be the parser goal.
3327 ;; If `wisent-single-start-flag' is non-nil that feature is
3328 ;; disabled and the first nonterminal in START-LIST defines
3329 ;; the start symbol, like in case 2 above.
3330 ((not wisent-single-start-flag)
3332 ;; START-LIST is a list of nonterminals '(nt0 ... ntN).
3333 ;; Build and push ad hoc start rules in the grammar:
3335 ;; ($STARTS ((nt0) $1) ((nt1) $1) ... ((ntN) $1))
3336 ;; ($nt1 (($$nt1 nt1) $2))
3338 ;; ($ntN (($$ntN ntN) $2))
3340 ;; Where internal symbols $ntI and $$ntI are respectively
3341 ;; nonterminals and terminals.
3343 ;; The internal start symbol $STARTS is used to build the
3344 ;; LALR(1) automaton. The true default start symbol used by the
3345 ;; parser is the first nonterminal in START-LIST (nt0).
3346 (setq start-var wisent-starts-nonterm
3347 lst (nreverse start-list))
3351 (or (memq var var-list)
3352 (error "Start symbol `%s' has no rule" var))
3353 (unless (assq var start-table) ;; Ignore duplicates
3354 ;; For each nt start symbol
3355 (setq ep-var (intern (format "$%s" var))
3356 ep-token (intern (format "$$%s" var)))
3357 (wisent-push-token ep-token t)
3358 (wisent-push-var ep-var t)
3360 ;; Add entry (nt . $$nt) to start-table
3361 start-table (cons (cons var ep-token) start-table)
3362 ;; Add rule ($nt (($$nt nt) $2))
3363 defs (cons (list ep-var (list (list ep-token var) '$2)) defs)
3364 ;; Add start rule (($nt) $1)
3365 ep-def (cons (list (list ep-var) '$1) ep-def))
3367 (wisent-push-var start-var t)
3368 (setq defs (cons (cons start-var ep-def) defs))))
3370 ;; Set up rules main data structure & RPREC, RCODE, RUSEFUL
3371 (setq rules (wisent-parse-nonterminals defs))
3373 ;; Set up the terminal & nonterminal lists.
3374 (setq nsyms (+ ntokens nvars)
3375 token-list (nreverse token-list)
3381 var-list (cons var var-list))
3382 (wisent-set-item-number ;; adjust nonterminal item number to
3383 var (+ ntokens (wisent-item-number var)))) ;; I += NTOKENS
3385 ;; Store special item numbers
3386 (setq error-token-number (wisent-item-number wisent-error-term)
3387 start-symbol (wisent-item-number start-var))
3389 ;; Keep symbols in the TAGS vector so that TAGS[I] is the symbol
3390 ;; associated to item number I.
3391 (setq tags (vconcat token-list var-list))
3392 ;; Set up RLHS RRHS & RITEM data structures from list of rules
3393 ;; (LHS . RHS) received from `wisent-parse-nonterminals'.
3394 (setq rlhs (make-vector (1+ nrules) nil)
3395 rrhs (make-vector (1+ nrules) nil)
3396 ritem (make-vector (1+ nitems) nil)
3400 (aset rlhs r (wisent-item-number (caar rules)))
3402 (setq rhs (cdar rules)
3405 (setq item (wisent-item-number (car rhs)))
3406 ;; Get default precedence level of rule, that is the
3407 ;; precedence of the last terminal in it.
3408 (and (wisent-ISTOKEN item)
3415 ;; Setup the precedence level of the rule, that is the one
3416 ;; specified by %prec or the default one.
3417 (and (not (aref rprec r)) ;; Already set by %prec
3419 (wisent-prec (aref tags pre))
3421 (aset ritem i (- r))
3424 (setq rules (cdr rules)))
3427 ;;;; ---------------------
3428 ;;;; Compile input grammar
3429 ;;;; ---------------------
3432 (defun wisent-compile-grammar (grammar &optional start-list)
3433 "Compile the LALR(1) GRAMMAR.
3435 GRAMMAR is a list (TOKENS ASSOCS . NONTERMS) where:
3437 - TOKENS is a list of terminal symbols (tokens).
3439 - ASSOCS is nil, or an alist of (ASSOC-TYPE . ASSOC-VALUE) elements
3440 describing the associativity of TOKENS. ASSOC-TYPE must be one of
3441 the `default-prec' `nonassoc', `left' or `right' symbols. When
3442 ASSOC-TYPE is `default-prec', ASSOC-VALUE must be nil or t (the
3443 default). Otherwise it is a list of tokens which must have been
3444 previously declared in TOKENS.
3446 - NONTERMS is a list of nonterminal definitions.
3448 Optional argument START-LIST specify the possible grammar start
3449 symbols. This is a list of nonterminals which must have been
3450 previously declared in GRAMMAR's NONTERMS form. By default, the start
3451 symbol is the first nonterminal defined. When START-LIST contains
3452 only one element, it is the start symbol. Otherwise, all elements are
3453 possible start symbols, unless `wisent-single-start-flag' is non-nil.
3454 In that case, the first element is the start symbol, and others are
3457 Return an automaton as a vector: [ACTIONS GOTOS STARTS FUNCTIONS]
3460 - ACTIONS is a state/token matrix telling the parser what to do at
3461 every state based on the current lookahead token. That is shift,
3462 reduce, accept or error.
3464 - GOTOS is a state/nonterminal matrix telling the parser the next
3465 state to go to after reducing with each rule.
3467 - STARTS is an alist which maps the allowed start nonterminal symbols
3468 to tokens that will be first shifted into the parser stack.
3470 - FUNCTIONS is an obarray of semantic action symbols. Each symbol's
3471 function definition is the semantic action lambda expression."
3472 (if (wisent-automaton-p grammar)
3473 grammar ;; Grammar already compiled just return it
3474 (wisent-with-context compile-grammar
3475 (let* ((working-status-dynamic-type 'working-text-display)
3476 (gc-cons-threshold 1000000)
3479 (working-status-forms "Compiling grammar" "done"
3480 (setq wisent-new-log-flag t)
3481 ;; Parse input grammar
3482 (wisent-parse-grammar grammar start-list)
3483 ;; Generate the LALR(1) automaton
3484 (setq automaton (wisent-parser-automaton))
3485 (working-dynamic-status t)
3488 ;;;; --------------------------
3489 ;;;; Byte compile input grammar
3490 ;;;; --------------------------
3495 (defun wisent-byte-compile-grammar (form)
3496 "Byte compile the `wisent-compile-grammar' FORM.
3497 Automatically called by the Emacs Lisp byte compiler as a
3498 `byte-compile' handler."
3499 ;; Eval the `wisent-compile-grammar' form to obtain an LALR
3500 ;; automaton internal data structure. Then, because the internal
3501 ;; data structure contains an obarray, convert it to a lisp form so
3502 ;; it can be byte-compiled.
3503 (byte-compile-form (wisent-automaton-lisp-form (eval form))))
3506 (put 'wisent-compile-grammar 'byte-compile 'wisent-byte-compile-grammar)
3508 (defun wisent-automaton-lisp-form (automaton)
3509 "Return a Lisp form that produces AUTOMATON.
3510 See also `wisent-compile-grammar' for more details on AUTOMATON."
3511 (or (wisent-automaton-p automaton)
3512 (signal 'wrong-type-argument
3513 (list 'wisent-automaton-p automaton)))
3514 (let ((obn (make-symbol "ob")) ; Generated obarray name
3515 (obv (aref automaton 3)) ; Semantic actions obarray
3517 `(let ((,obn (make-vector 13 0)))
3518 ;; Generate code to initialize the semantic actions obarray,
3519 ;; in local variable OBN.
3524 (cons `(fset (intern ,(symbol-name s) ,obn)
3525 #',(symbol-function s))
3529 ;; Generate code to create the automaton.
3531 ;; In code generated to initialize the action table, take
3532 ;; care of symbols that are interned in the semantic actions
3536 #'(lambda (state) ;; for each state
3539 #'(lambda (tr) ;; for each transition
3540 (let ((k (car tr)) ; token
3541 (a (cdr tr))) ; action
3542 (if (and (symbolp a)
3543 (intern-soft (symbol-name a) obv))
3544 `(cons ,(if (symbolp k) `(quote ,k) k)
3545 (intern-soft ,(symbol-name a) ,obn))
3548 (aref automaton 0)))
3549 ;; The code of the goto table is unchanged.
3551 ;; The code of the alist of start symbols is unchanged.
3552 ',(aref automaton 2)
3553 ;; The semantic actions obarray is in the local variable OBN.
3556 (provide 'wisent-comp)
3558 ;;; wisent-comp.el ends here