comp.el 124 KB
Newer Older
1 2
;;; semantic/wisent/comp.el --- GNU Bison for Emacs - Grammar compiler

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1984, 1986, 1989, 1992, 1995, 2000-2007, 2009-2019 Free
4
;; Software Foundation, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

;; Author: David Ponce <david@dponce.com>
;; Created: 30 January 2002
;; Keywords: syntax

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
23
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

;;; Commentary:
;;
;; Grammar compiler that produces Wisent's LALR automatons.
;;
;; Wisent (the European Bison ;-) is an Elisp implementation of the
;; GNU Compiler Compiler Bison.  The Elisp code is a port of the C
;; code of GNU Bison 1.28 & 1.31.
;;
;; For more details on the basic concepts for understanding Wisent,
;; read the Bison manual ;)
;;
;; For more details on Wisent itself read the Wisent manual.

;;; History:
;;

;;; Code:
(require 'semantic/wisent)
Glenn Morris's avatar
Glenn Morris committed
43
(eval-when-compile (require 'cl-lib))
44 45 46 47 48 49 50 51 52 53

;;;; -------------------
;;;; Misc. useful things
;;;; -------------------

;; As much as possible I would like to keep the name of global
;; variables used in Bison without polluting too much the Elisp global
;; name space.  Elisp dynamic binding allows that ;-)

;; Here are simple macros to easily define and use set of variables
Paul Eggert's avatar
Paul Eggert committed
54
;; bound locally, without all these "reference to free variable"
55 56 57 58 59 60 61 62 63 64 65 66 67 68
;; compiler warnings!

(defmacro wisent-context-name (name)
  "Return the context name from NAME."
  `(if (and ,name (symbolp ,name))
       (intern (format "wisent-context-%s" ,name))
     (error "Invalid context name: %S" ,name)))

(defmacro wisent-context-bindings (name)
  "Return the variables in context NAME."
  `(symbol-value (wisent-context-name ,name)))

(defmacro wisent-defcontext (name &rest vars)
  "Define a context NAME that will bind variables VARS."
69
  (declare (indent 1))
70
  (let* ((context (wisent-context-name name))
71 72 73 74 75
         (declarations (mapcar #'(lambda (v) (list 'defvar v)) vars)))
    `(progn
       ,@declarations
       (eval-when-compile
         (defvar ,context ',vars)))))
76 77 78

(defmacro wisent-with-context (name &rest body)
  "Bind variables in context NAME then eval BODY."
79 80 81 82 83 84 85
  (declare (indent 1))
  (let ((bindings (wisent-context-bindings name)))
    `(progn
       ,@(mapcar (lambda (binding) `(defvar ,(or (car-safe binding) binding)))
                 bindings)
       (let* ,bindings
         ,@body))))
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

;; Other utilities

(defsubst wisent-pad-string (s n &optional left)
  "Fill string S with spaces.
Return a new string of at least N characters.  Insert spaces on right.
If optional LEFT is non-nil insert spaces on left."
  (let ((i (length s)))
    (if (< i n)
        (if left
            (concat (make-string (- n i) ?\ ) s)
          (concat s (make-string (- n i) ?\ )))
      s)))

;;;; ------------------------
;;;; Environment dependencies
;;;; ------------------------

104
(defconst wisent-BITS-PER-WORD (logcount most-positive-fixnum))
105 106 107 108 109 110 111 112 113

(defsubst wisent-WORDSIZE (n)
  "(N + BITS-PER-WORD - 1) / BITS-PER-WORD."
  (/ (1- (+ n wisent-BITS-PER-WORD)) wisent-BITS-PER-WORD))

(defsubst wisent-SETBIT (x i)
  "X[I/BITS-PER-WORD] |= 1 << (I % BITS-PER-WORD)."
  (let ((k (/ i wisent-BITS-PER-WORD)))
    (aset x k (logior (aref x k)
114
                      (ash 1 (% i wisent-BITS-PER-WORD))))))
115 116 117 118 119

(defsubst wisent-RESETBIT (x i)
  "X[I/BITS-PER-WORD] &= ~(1 << (I % BITS-PER-WORD))."
  (let ((k (/ i wisent-BITS-PER-WORD)))
    (aset x k (logand (aref x k)
120
                      (lognot (ash 1 (% i wisent-BITS-PER-WORD)))))))
121 122 123 124

(defsubst wisent-BITISSET (x i)
  "(X[I/BITS-PER-WORD] & (1 << (I % BITS-PER-WORD))) != 0."
  (not (zerop (logand (aref x (/ i wisent-BITS-PER-WORD))
125
                      (ash 1 (% i wisent-BITS-PER-WORD))))))
126 127 128 129 130 131 132 133 134 135 136 137 138

(defvar wisent-debug-flag nil
  "Non-nil means enable some debug stuff.")

;;;; --------------
;;;; Logging/Output
;;;; --------------
(defconst wisent-log-buffer-name "*wisent-log*"
  "Name of the log buffer.")

(defvar wisent-new-log-flag nil
  "Non-nil means to start a new report.")

139 140 141 142
(defcustom wisent-verbose-flag nil
  "Non-nil means to report verbose information on generated parser."
  :group 'wisent
  :type 'boolean)
143 144 145 146 147

(defun wisent-toggle-verbose-flag ()
  "Toggle whether to report verbose information on generated parser."
  (interactive)
  (setq wisent-verbose-flag (not wisent-verbose-flag))
148
  (when (called-interactively-p 'interactive)
149 150 151 152 153 154
    (message "Verbose report %sabled"
             (if wisent-verbose-flag "en" "dis"))))

(defmacro wisent-log-buffer ()
  "Return the log buffer.
Its name is defined in constant `wisent-log-buffer-name'."
155
  '(get-buffer-create wisent-log-buffer-name))
156 157 158

(defmacro wisent-clear-log ()
  "Delete the entire contents of the log buffer."
159
  '(with-current-buffer (wisent-log-buffer)
160 161
     (erase-buffer)))

162
(defvar byte-compile-current-file)
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

(defun wisent-source ()
  "Return the current source file name or nil."
  (let ((source (or (and (boundp 'byte-compile-current-file)
                         byte-compile-current-file)
                    load-file-name (buffer-file-name))))
    (if source
        (file-relative-name source))))

(defun wisent-new-log ()
  "Start a new entry into the log buffer."
  (setq wisent-new-log-flag nil)
  (let ((text (format "\n\n*** Wisent %s - %s\n\n"
                      (or (wisent-source) (buffer-name))
                      (format-time-string "%Y-%m-%d %R"))))
    (with-current-buffer (wisent-log-buffer)
      (goto-char (point-max))
      (insert text))))

(defsubst wisent-log (&rest args)
  "Insert text into the log buffer.
184
`format-message' is applied to ARGS and the result string is inserted into the
185 186 187
log buffer returned by the function `wisent-log-buffer'."
  (and wisent-new-log-flag (wisent-new-log))
  (with-current-buffer (wisent-log-buffer)
188
    (insert (apply #'format-message args))))
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399

(defconst wisent-log-file "wisent.output"
  "The log file.
Used when running without interactive terminal.")

(defun wisent-append-to-log-file ()
  "Append contents of logging buffer to `wisent-log-file'."
  (if (get-buffer wisent-log-buffer-name)
      (condition-case err
          (with-current-buffer (wisent-log-buffer)
            (widen)
            (if (> (point-max) (point-min))
                (write-region (point-min) (point-max)
                              wisent-log-file t)))
        (error
         (message "*** %s" (error-message-string err))))))

;;;; -----------------------------------
;;;; Representation of the grammar rules
;;;; -----------------------------------

;; ntokens is the number of tokens, and nvars is the number of
;; variables (nonterminals).  nsyms is the total number, ntokens +
;; nvars.

;; Each symbol (either token or variable) receives a symbol number.
;; Numbers 0 to ntokens-1 are for tokens, and ntokens to nsyms-1 are
;; for variables.  Symbol number zero is the end-of-input token.  This
;; token is counted in ntokens.

;; The rules receive rule numbers 1 to nrules in the order they are
;; written.  Actions and guards are accessed via the rule number.

;; The rules themselves are described by three arrays: rrhs, rlhs and
;; ritem.  rlhs[R] is the symbol number of the left hand side of rule
;; R.  The right hand side is stored as symbol numbers in a portion of
;; ritem.  rrhs[R] contains the index in ritem of the beginning of the
;; portion for rule R.

;; The length of the portion is one greater than the number of symbols
;; in the rule's right hand side.  The last element in the portion
;; contains minus R, which identifies it as the end of a portion and
;; says which rule it is for.

;; The portions of ritem come in order of increasing rule number and
;; are followed by an element which is nil to mark the end.  nitems is
;; the total length of ritem, not counting the final nil.  Each
;; element of ritem is called an "item" and its index in ritem is an
;; item number.

;; Item numbers are used in the finite state machine to represent
;; places that parsing can get to.

;; The vector rprec contains for each rule, the item number of the
;; symbol giving its precedence level to this rule.  The precedence
;; level and associativity of each symbol is recorded in respectively
;; the properties 'wisent--prec and 'wisent--assoc.

;; Precedence levels are assigned in increasing order starting with 1
;; so that numerically higher precedence values mean tighter binding
;; as they ought to.  nil as a symbol or rule's precedence means none
;; is assigned.

(defcustom wisent-state-table-size 1009
  "The size of the state table."
  :type 'integer
  :group 'wisent)

;; These variables only exist locally in the function
;; `wisent-compile-grammar' and are shared by all other nested
;; callees.
(wisent-defcontext compile-grammar
  F LA LAruleno accessing-symbol conflicts consistent default-prec
  derives err-table fderives final-state first-reduction first-shift
  first-state firsts from-state goto-map includes itemset nitemset
  kernel-base kernel-end kernel-items last-reduction last-shift
  last-state lookaheads lookaheadset lookback maxrhs ngotos nitems
  nrules nshifts nstates nsyms ntokens nullable nvars rassoc redset
  reduction-table ritem rlhs rprec rrc-count rrc-total rrhs ruseful
  rcode ruleset rulesetsize shift-symbol shift-table shiftset
  src-count src-total start-table state-table tags this-state to-state
  tokensetsize ;; nb of words req. to hold a bit for each rule
  varsetsize ;; nb of words req. to hold a bit for each variable
  error-token-number start-symbol token-list var-list
  N P V V1 nuseless-nonterminals nuseless-productions
  ptable ;; symbols & characters properties
  )

(defmacro wisent-ISTOKEN (s)
  "Return non-nil if item number S defines a token (terminal).
That is if S < `ntokens'."
  `(< ,s ntokens))

(defmacro wisent-ISVAR(s)
  "Return non-nil if item number S defines a nonterminal.
That is if S >= `ntokens'."
  `(>= ,s ntokens))

(defsubst wisent-tag (s)
  "Return printable form of item number S."
  (wisent-item-to-string (aref tags s)))

;; Symbol and character properties

(defsubst wisent-put (object propname value)
  "Store OBJECT's PROPNAME property with value VALUE.
Use `eq' to locate OBJECT."
  (let ((entry (assq object ptable)))
    (or entry (setq entry (list object) ptable (cons entry ptable)))
    (setcdr entry (plist-put (cdr entry) propname value))))

(defsubst wisent-get (object propname)
  "Return the value of OBJECT's PROPNAME property.
Use `eq' to locate OBJECT."
  (plist-get (cdr (assq object ptable)) propname))

(defsubst wisent-item-number (x)
  "Return the item number of symbol X."
  (wisent-get x 'wisent--item-no))

(defsubst wisent-set-item-number (x n)
  "Set the item number of symbol X to N."
  (wisent-put x 'wisent--item-no n))

(defsubst wisent-assoc (x)
  "Return the associativity of symbol X."
  (wisent-get x 'wisent--assoc))

(defsubst wisent-set-assoc (x a)
  "Set the associativity of symbol X to A."
  (wisent-put x 'wisent--assoc a))

(defsubst wisent-prec (x)
  "Return the precedence level of symbol X."
  (wisent-get x 'wisent--prec))

(defsubst wisent-set-prec (x p)
  "Set the precedence level of symbol X to P."
  (wisent-put x 'wisent--prec p))

;;;; ----------------------------------------------------------
;;;; Type definitions for nondeterministic finite state machine
;;;; ----------------------------------------------------------

;; These type definitions are used to represent a nondeterministic
;; finite state machine that parses the specified grammar.  This
;; information is generated by the function `wisent-generate-states'.

;; Each state of the machine is described by a set of items --
;; particular positions in particular rules -- that are the possible
;; places where parsing could continue when the machine is in this
;; state.  These symbols at these items are the allowable inputs that
;; can follow now.

;; A core represents one state.  States are numbered in the number
;; field.  When `wisent-generate-states' is finished, the starting
;; state is state 0 and `nstates' is the number of states.  (A
;; transition to a state whose state number is `nstates' indicates
;; termination.)  All the cores are chained together and `first-state'
;; points to the first one (state 0).

;; For each state there is a particular symbol which must have been
;; the last thing accepted to reach that state.  It is the
;; accessing-symbol of the core.

;; Each core contains a vector of `nitems' items which are the indices
;; in the `ritems' vector of the items that are selected in this
;; state.

;; The link field is used for chaining buckets that hash states by
;; their itemsets.  This is for recognizing equivalent states and
;; combining them when the states are generated.

;; The two types of transitions are shifts (push the lookahead token
;; and read another) and reductions (combine the last n things on the
;; stack via a rule, replace them with the symbol that the rule
;; derives, and leave the lookahead token alone).  When the states are
;; generated, these transitions are represented in two other lists.

;; Each shifts structure describes the possible shift transitions out
;; of one state, the state whose number is in the number field.  The
;; shifts structures are linked through next and first-shift points to
;; them.  Each contains a vector of numbers of the states that shift
;; transitions can go to.  The accessing-symbol fields of those
;; states' cores say what kind of input leads to them.

;; A shift to state zero should be ignored.  Conflict resolution
;; deletes shifts by changing them to zero.

;; Each reductions structure describes the possible reductions at the
;; state whose number is in the number field.  The data is a list of
;; nreds rules, represented by their rule numbers.  `first-reduction'
;; points to the list of these structures.

;; Conflict resolution can decide that certain tokens in certain
;; states should explicitly be errors (for implementing %nonassoc).
;; For each state, the tokens that are errors for this reason are
;; recorded in an errs structure, which has the state number in its
;; number field.  The rest of the errs structure is full of token
;; numbers.

;; There is at least one shift transition present in state zero.  It
;; leads to a next-to-final state whose accessing-symbol is the
;; grammar's start symbol.  The next-to-final state has one shift to
;; the final state, whose accessing-symbol is zero (end of input).
;; The final state has one shift, which goes to the termination state
;; (whose number is `nstates'-1).
;; The reason for the extra state at the end is to placate the
;; parser's strategy of making all decisions one token ahead of its
;; actions.

400 401 402 403
;; FIXME: Use `wisent-' prefix to fix namespace pollution!

(cl-defstruct (core
               (:constructor make-core ()))
404 405 406 407 408 409 410
  next                                  ; -> core
  link                                  ; -> core
  (number 0)
  (accessing-symbol 0)
  (nitems 0)
  (items [0]))

411 412
(cl-defstruct (shifts
               (:constructor make-shifts ()))
413 414 415 416 417
  next                                  ; -> shifts
  (number 0)
  (nshifts 0)
  (shifts [0]))

418 419
(cl-defstruct (reductions
               (:constructor make-reductions ()))
420 421 422 423 424
  next                                  ; -> reductions
  (number 0)
  (nreds 0)
  (rules [0]))

425 426
(cl-defstruct (errs
               (:constructor make-errs ()))
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
  (nerrs 0)
  (errs [0]))

;;;; --------------------------------------------------------
;;;; Find unreachable terminals, nonterminals and productions
;;;; --------------------------------------------------------

(defun wisent-bits-equal (L R n)
  "Visit L and R and return non-nil if their first N elements are `='.
L and R must be vectors of integers."
  (let* ((i    (1- n))
         (iseq t))
    (while (and iseq (natnump i))
      (setq iseq (= (aref L i) (aref R i))
            i (1- i)))
    iseq))

(defun wisent-nbits (i)
  "Return number of bits set in integer I."
  (let ((count 0))
    (while (not (zerop i))
      ;; i ^= (i & ((unsigned) (-(int) i)))
      (setq i (logxor i (logand i (- i)))
            count (1+ count)))
    count))

(defun wisent-bits-size (S n)
  "In vector S count the total of bits set in first N elements.
S must be a vector of integers."
  (let* ((i (1- n))
         (count 0))
    (while (natnump i)
      (setq count (+ count (wisent-nbits (aref S i)))
            i (1- i)))
    count))

(defun wisent-useful-production (i N0)
  "Return non-nil if production I is in useful set N0."
  (let* ((useful t)
         (r (aref rrhs i))
         n)
    (while (and useful (> (setq n (aref ritem r)) 0))
      (if (wisent-ISVAR n)
          (setq useful (wisent-BITISSET N0 (- n ntokens))))
      (setq r (1+ r)))
    useful))

(defun wisent-useless-nonterminals ()
  "Find out which nonterminals are used."
  (let (Np Ns i n break)
    ;; N is set as built.  Np is set being built this iteration. P is
    ;; set of all productions which have a RHS all in N.
    (setq n  (wisent-WORDSIZE nvars)
          Np (make-vector n 0))

    ;; The set being computed is a set of nonterminals which can
    ;; derive the empty string or strings consisting of all
    ;; terminals. At each iteration a nonterminal is added to the set
    ;; if there is a production with that nonterminal as its LHS for
    ;; which all the nonterminals in its RHS are already in the set.
    ;; Iterate until the set being computed remains unchanged.  Any
    ;; nonterminals not in the set at that point are useless in that
    ;; they will never be used in deriving a sentence of the language.

    ;; This iteration doesn't use any special traversal over the
    ;; productions.  A set is kept of all productions for which all
    ;; the nonterminals in the RHS are in useful.  Only productions
    ;; not in this set are scanned on each iteration.  At the end,
    ;; this set is saved to be used when finding useful productions:
    ;; only productions in this set will appear in the final grammar.

    (while (not break)
      (setq i (1- n))
      (while (natnump i)
        ;; Np[i] = N[i]
        (aset Np i (aref N i))
        (setq i (1- i)))

      (setq i 1)
      (while (<= i nrules)
        (if (not (wisent-BITISSET P i))
            (when (wisent-useful-production i N)
              (wisent-SETBIT Np (- (aref rlhs i) ntokens))
              (wisent-SETBIT P i)))
        (setq i (1+ i)))
      (if (wisent-bits-equal N Np n)
          (setq break t)
        (setq Ns Np
              Np N
              N  Ns)))
    (setq N Np)))

519
(defun wisent-inaccessible-symbols ()
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
  "Find out which productions are reachable and which symbols are used."
  ;; Starting with an empty set of productions and a set of symbols
  ;; which only has the start symbol in it, iterate over all
  ;; productions until the set of productions remains unchanged for an
  ;; iteration.  For each production which has a LHS in the set of
  ;; reachable symbols, add the production to the set of reachable
  ;; productions, and add all of the nonterminals in the RHS of the
  ;; production to the set of reachable symbols.

  ;; Consider only the (partially) reduced grammar which has only
  ;; nonterminals in N and productions in P.

  ;; The result is the set P of productions in the reduced grammar,
  ;; and the set V of symbols in the reduced grammar.

  ;; Although this algorithm also computes the set of terminals which
  ;; are reachable, no terminal will be deleted from the grammar. Some
  ;; terminals might not be in the grammar but might be generated by
  ;; semantic routines, and so the user might want them available with
  ;; specified numbers.  (Is this true?)  However, the non reachable
  ;; terminals are printed (if running in verbose mode) so that the
  ;; user can know.
  (let (Vp Vs Pp i tt r n m break)
    (setq n  (wisent-WORDSIZE nsyms)
          m  (wisent-WORDSIZE (1+ nrules))
          Vp (make-vector n 0)
          Pp (make-vector m 0))

    ;; If the start symbol isn't useful, then nothing will be useful.
    (when (wisent-BITISSET N (- start-symbol ntokens))
      (wisent-SETBIT V start-symbol)
      (while (not break)
        (setq i (1- n))
        (while (natnump i)
          (aset Vp i (aref V i))
          (setq i (1- i)))
        (setq i 1)
        (while (<= i nrules)
          (when (and (not (wisent-BITISSET Pp i))
                     (wisent-BITISSET P i)
                     (wisent-BITISSET V (aref rlhs i)))
            (setq r (aref rrhs i))
            (while (natnump (setq tt (aref ritem r)))
              (if (or (wisent-ISTOKEN tt)
                      (wisent-BITISSET N (- tt ntokens)))
                  (wisent-SETBIT Vp tt))
              (setq r (1+ r)))
            (wisent-SETBIT Pp i))
          (setq i (1+ i)))
        (if (wisent-bits-equal V Vp n)
            (setq break t)
          (setq Vs Vp
                Vp V
                V  Vs))))
    (setq V Vp)

    ;; Tokens 0, 1 are internal to Wisent.  Consider them useful.
    (wisent-SETBIT V 0) ;; end-of-input token
    (wisent-SETBIT V 1) ;; error token
    (setq P Pp)

    (setq nuseless-productions  (- nrules (wisent-bits-size P m))
          nuseless-nonterminals nvars
          i ntokens)
    (while (< i nsyms)
      (if (wisent-BITISSET V i)
          (setq nuseless-nonterminals (1- nuseless-nonterminals)))
      (setq i (1+ i)))

    ;; A token that was used in %prec should not be warned about.
    (setq i 1)
    (while (<= i nrules)
      (if (aref rprec i)
          (wisent-SETBIT V1 (aref rprec i)))
      (setq i (1+ i)))
    ))

(defun wisent-reduce-grammar-tables ()
  "Disable useless productions."
  (if (> nuseless-productions 0)
      (let ((pn 1))
        (while (<= pn nrules)
          (aset ruseful pn (wisent-BITISSET P pn))
          (setq pn (1+ pn))))))

(defun wisent-nonterminals-reduce ()
  "Remove useless nonterminals."
  (let (i n r item nontermmap tags-sorted)
    ;; Map the nonterminals to their new index: useful first, useless
    ;; afterwards.  Kept for later report.
    (setq nontermmap (make-vector nvars 0)
          n ntokens
          i ntokens)
    (while (< i nsyms)
      (when (wisent-BITISSET V i)
        (aset nontermmap (- i ntokens) n)
        (setq n (1+ n)))
      (setq i (1+ i)))
    (setq i ntokens)
    (while (< i nsyms)
      (unless (wisent-BITISSET V i)
        (aset nontermmap (- i ntokens) n)
        (setq n (1+ n)))
      (setq i (1+ i)))
    ;; Shuffle elements of tables indexed by symbol number
    (setq tags-sorted (make-vector nvars nil)
          i ntokens)
    (while (< i nsyms)
      (setq n (aref nontermmap (- i ntokens)))
      (aset tags-sorted (- n ntokens) (aref tags i))
      (setq i (1+ i)))
    (setq i ntokens)
    (while (< i nsyms)
      (aset tags i (aref tags-sorted (- i ntokens)))
      (setq i (1+ i)))
    ;; Replace all symbol numbers in valid data structures.
    (setq i 1)
    (while (<= i nrules)
      (aset rlhs i (aref nontermmap (- (aref rlhs i) ntokens)))
      (setq i (1+ i)))
    (setq r 0)
    (while (setq item (aref ritem r))
      (if (wisent-ISVAR item)
          (aset ritem r (aref nontermmap (- item ntokens))))
      (setq r (1+ r)))
    (setq start-symbol (aref nontermmap (- start-symbol ntokens))
          nsyms (- nsyms nuseless-nonterminals)
          nvars (- nvars nuseless-nonterminals))
    ))

(defun wisent-total-useless ()
  "Report number of useless nonterminals and productions."
  (let* ((src (wisent-source))
         (src (if src (concat " in " src) ""))
         (msg (format "Grammar%s contains" src)))
    (if (> nuseless-nonterminals 0)
        (setq msg (format "%s %d useless nonterminal%s"
                          msg nuseless-nonterminals
                          (if (> nuseless-nonterminals 0) "s" ""))))
    (if (and (> nuseless-nonterminals 0) (> nuseless-productions 0))
        (setq msg (format "%s and" msg)))
    (if (> nuseless-productions 0)
        (setq msg (format "%s %d useless rule%s"
                          msg nuseless-productions
                          (if (> nuseless-productions 0) "s" ""))))
    (message msg)))

(defun wisent-reduce-grammar ()
  "Find unreachable terminals, nonterminals and productions."
  ;; Allocate the global sets used to compute the reduced grammar
  (setq N  (make-vector (wisent-WORDSIZE nvars) 0)
        P  (make-vector (wisent-WORDSIZE (1+ nrules)) 0)
        V  (make-vector (wisent-WORDSIZE nsyms) 0)
        V1 (make-vector (wisent-WORDSIZE nsyms) 0)
        nuseless-nonterminals 0
        nuseless-productions  0)

  (wisent-useless-nonterminals)
678
  (wisent-inaccessible-symbols)
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

  (when (> (+ nuseless-nonterminals nuseless-productions) 0)
    (wisent-total-useless)
    (or (wisent-BITISSET N (- start-symbol ntokens))
        (error "Start symbol `%s' does not derive any sentence"
               (wisent-tag start-symbol)))
    (wisent-reduce-grammar-tables)
    (if (> nuseless-nonterminals 0)
        (wisent-nonterminals-reduce))))

(defun wisent-print-useless ()
  "Output the detailed results of the reductions."
  (let (i b r)
    (when (> nuseless-nonterminals 0)
      ;; Useless nonterminals have been moved after useful ones.
      (wisent-log "\n\nUseless nonterminals:\n\n")
      (setq i 0)
      (while (< i nuseless-nonterminals)
        (wisent-log "   %s\n" (wisent-tag (+ nsyms i)))
        (setq i (1+ i))))
    (setq b nil
          i 0)
    (while (< i ntokens)
      (unless (or (wisent-BITISSET V i) (wisent-BITISSET V1 i))
        (or b
            (wisent-log "\n\nTerminals which are not used:\n\n"))
        (setq b t)
        (wisent-log "   %s\n" (wisent-tag i)))
      (setq i (1+ i)))
    (when (> nuseless-productions 0)
      (wisent-log "\n\nUseless rules:\n\n")
      (setq i 1)
      (while (<= i nrules)
        (unless (aref ruseful i)
          (wisent-log "#%s  " (wisent-pad-string (format "%d" i) 4))
          (wisent-log "%s:" (wisent-tag (aref rlhs i)))
          (setq r (aref rrhs i))
          (while (natnump (aref ritem r))
            (wisent-log " %s" (wisent-tag (aref ritem r)))
            (setq r (1+ r)))
          (wisent-log ";\n"))
        (setq i (1+ i))))
    (if (or b (> nuseless-nonterminals 0) (> nuseless-productions 0))
        (wisent-log "\n\n"))
    ))

;;;; -----------------------------
;;;; Match rules with nonterminals
;;;; -----------------------------

(defun wisent-set-derives ()
  "Find, for each variable (nonterminal), which rules can derive it.
It sets up the value of DERIVES so that DERIVES[i - NTOKENS] points to
a list of rule numbers, terminated with -1."
  (let (i lhs p q dset delts)
    (setq dset (make-vector nvars nil)
          delts (make-vector (1+ nrules) 0))
    (setq p 0 ;; p = delts
          i nrules)
    (while (> i 0)
      (when (aref ruseful i)
        (setq lhs (aref rlhs i))
        ;; p->next = dset[lhs];
        ;; p->value = i;
        (aset delts p (cons i (aref dset (- lhs ntokens)))) ;; (value . next)
        (aset dset (- lhs ntokens) p) ;; dset[lhs] = p
        (setq p (1+ p)) ;; p++
        )
      (setq i (1- i)))

    (setq derives (make-vector nvars nil)
          i       ntokens)

    (while (< i nsyms)
      (setq q nil
            p (aref dset (- i ntokens))) ;; p = dset[i]

      (while p
        (setq p (aref delts p)
              q (cons (car p) q) ;;q++ = p->value
              p (cdr p))) ;; p = p->next
      (setq q (nreverse (cons -1 q))) ;; *q++ = -1
      (aset derives (- i ntokens) q) ;; derives[i] = q
      (setq i (1+ i)))
    ))

;;;; --------------------------------------------------------
;;;; Find which nonterminals can expand into the null string.
;;;; --------------------------------------------------------

(defun wisent-print-nullable ()
  "Print NULLABLE."
  (let (i)
    (wisent-log "NULLABLE\n")
    (setq i ntokens)
    (while (< i nsyms)
      (wisent-log "\t%s: %s\n" (wisent-tag i)
                  (if (aref nullable (- i ntokens))
                      "yes" : "no"))
      (setq i (1+ i)))
    (wisent-log "\n\n")))

(defun wisent-set-nullable ()
  "Set up NULLABLE.
A vector saying which nonterminals can expand into the null string.
NULLABLE[i - NTOKENS] is nil if symbol I can do so."
  (let (ruleno s1 s2 p r squeue rcount rsets relts item any-tokens)
    (setq squeue (make-vector nvars 0)
          rcount (make-vector (1+ nrules) 0)
          rsets  (make-vector nvars nil) ;; - ntokens
          relts  (make-vector (+ nitems nvars 1) nil)
          nullable (make-vector nvars nil)) ;; - ntokens
    (setq s1 0 s2 0 ;; s1 = s2 = squeue
          p 0 ;; p = relts
          ruleno 1)
    (while (<= ruleno nrules)
      (when (aref ruseful ruleno)
        (if (> (aref ritem (aref rrhs ruleno)) 0)
            (progn
              ;; This rule has a non empty RHS.
              (setq any-tokens nil
                    r (aref rrhs ruleno))
              (while (> (aref ritem r) 0)
                (if (wisent-ISTOKEN (aref ritem r))
                    (setq any-tokens t))
                (setq r (1+ r)))

              ;; This rule has only nonterminals: schedule it for the
              ;; second pass.
              (unless any-tokens
                (setq r (aref rrhs ruleno))
                (while (> (setq item (aref ritem r)) 0)
                  (aset rcount ruleno (1+ (aref rcount ruleno)))
                  ;; p->next = rsets[item];
                  ;; p->value = ruleno;
                  (aset relts p (cons ruleno (aref rsets (- item ntokens))))
                  ;; rsets[item] = p;
                  (aset rsets (- item ntokens) p)
                  (setq p (1+ p)
                        r (1+ r)))))
          ;; This rule has an empty RHS.
          ;; assert (ritem[rrhs[ruleno]] == -ruleno)
          (when (and (aref ruseful ruleno)
                     (setq item (aref rlhs ruleno))
                     (not (aref nullable (- item ntokens))))
            (aset nullable (- item ntokens) t)
            (aset squeue s2 item)
            (setq s2 (1+ s2)))
          )
        )
      (setq ruleno (1+ ruleno)))

    (while (< s1 s2)
      ;; p = rsets[*s1++]
      (setq p (aref rsets (- (aref squeue s1) ntokens))
            s1 (1+ s1))
      (while p
        (setq p (aref relts p)
              ruleno (car p)
              p (cdr p)) ;; p = p->next
        ;; if (--rcount[ruleno] == 0)
        (when (zerop (aset rcount ruleno (1- (aref rcount ruleno))))
          (setq item (aref rlhs ruleno))
          (aset nullable (- item ntokens) t)
          (aset squeue s2 item)
          (setq s2 (1+ s2)))))

    (if wisent-debug-flag
        (wisent-print-nullable))
    ))

;;;; -----------
;;;; Subroutines
;;;; -----------

(defun wisent-print-fderives ()
  "Print FDERIVES."
  (let (i j rp)
    (wisent-log "\n\n\nFDERIVES\n")
    (setq i ntokens)
    (while (< i nsyms)
      (wisent-log "\n\n%s derives\n\n" (wisent-tag i))
      (setq rp (aref fderives (- i ntokens))
            j  0)
      (while (<= j nrules)
        (if (wisent-BITISSET rp j)
            (wisent-log "   %d\n" j))
        (setq j (1+ j)))
      (setq i (1+ i)))))

(defun wisent-set-fderives ()
  "Set up FDERIVES.
An NVARS by NRULES matrix of bits indicating which rules can help
derive the beginning of the data for each nonterminal.  For example,
if symbol 5 can be derived as the sequence of symbols 8 3 20, and one
of the rules for deriving symbol 8 is rule 4, then the
875
[5 - NTOKENS, 4] bit in FDERIVES is set."
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  (let (i j k)
    (setq fderives (make-vector nvars nil))
    (setq i 0)
    (while (< i nvars)
      (aset fderives i (make-vector rulesetsize 0))
      (setq i (1+ i)))

    (wisent-set-firsts)

    (setq i ntokens)
    (while (< i nsyms)
      (setq j ntokens)
      (while (< j nsyms)
        ;; if (BITISSET (FIRSTS (i), j - ntokens))
        (when (wisent-BITISSET (aref firsts (- i ntokens)) (- j ntokens))
          (setq k (aref derives (- j ntokens)))
          (while (> (car k) 0) ;; derives[j][k] > 0
            ;; SETBIT (FDERIVES (i), derives[j][k]);
            (wisent-SETBIT (aref fderives (- i ntokens)) (car k))
            (setq k (cdr k))))
        (setq j (1+ j)))
      (setq i (1+ i)))

    (if wisent-debug-flag
        (wisent-print-fderives))
    ))

(defun wisent-print-firsts ()
  "Print FIRSTS."
  (let (i j v)
    (wisent-log "\n\n\nFIRSTS\n\n")
    (setq i ntokens)
    (while (< i nsyms)
      (wisent-log "\n\n%s firsts\n\n" (wisent-tag i))
      (setq v (aref firsts (- i ntokens))
            j 0)
      (while (< j nvars)
        (if (wisent-BITISSET v j)
            (wisent-log "\t\t%d (%s)\n"
                        (+ j ntokens) (wisent-tag (+ j ntokens))))
        (setq j (1+ j)))
      (setq i (1+ i)))))

(defun wisent-TC (R n)
  "Transitive closure.
Given R an N by N matrix of bits, modify its contents to be the
transitive closure of what was given."
  (let (i j k)
    ;; R (J, I) && R (I, K) => R (J, K).
    ;; I *must* be the outer loop.
    (setq i 0)
    (while (< i n)
      (setq j 0)
      (while (< j n)
        (when (wisent-BITISSET (aref R j) i)
          (setq k 0)
          (while (< k n)
            (if (wisent-BITISSET (aref R i) k)
                (wisent-SETBIT (aref R j) k))
            (setq k (1+ k))))
        (setq j (1+ j)))
      (setq i (1+ i)))))

(defun wisent-RTC (R n)
  "Reflexive Transitive Closure.
Same as `wisent-TC' and then set all the bits on the diagonal of R, an
N by N matrix of bits."
  (let (i)
    (wisent-TC R n)
    (setq i 0)
    (while (< i n)
      (wisent-SETBIT (aref R i) i)
      (setq i (1+ i)))))

(defun wisent-set-firsts ()
  "Set up FIRSTS.
An NVARS by NVARS bit matrix indicating which items can represent the
beginning of the input corresponding to which other items.  For
example, if some rule expands symbol 5 into the sequence of symbols 8
3 20, the symbol 8 can be the beginning of the data for symbol 5, so
the bit [8 - NTOKENS, 5 - NTOKENS] in FIRSTS is set."
  (let (row symbol sp rowsize i)
    (setq rowsize (wisent-WORDSIZE nvars)
          varsetsize rowsize
          firsts (make-vector nvars nil)
          i 0)
    (while (< i nvars)
      (aset firsts i (make-vector rowsize 0))
      (setq i (1+ i)))

    (setq row 0 ;; row = firsts
          i ntokens)
    (while (< i nsyms)
      (setq sp (aref derives (- i ntokens)))
      (while (>= (car sp) 0)
        (setq symbol (aref ritem (aref rrhs (car sp)))
              sp (cdr sp))
        (when (wisent-ISVAR symbol)
          (setq symbol (- symbol ntokens))
          (wisent-SETBIT (aref firsts row) symbol)
          ))
      (setq row (1+ row)
            i   (1+ i)))

    (wisent-RTC firsts nvars)

    (if wisent-debug-flag
        (wisent-print-firsts))
    ))

(defun wisent-initialize-closure (n)
  "Allocate the ITEMSET and RULESET vectors.
And precompute useful data so that `wisent-closure' can be called.
N is the number of elements to allocate for ITEMSET."
  (setq itemset (make-vector n 0)
        rulesetsize (wisent-WORDSIZE (1+ nrules))
        ruleset (make-vector rulesetsize 0))

  (wisent-set-fderives))

(defun wisent-print-closure ()
  "Print ITEMSET."
  (let (i)
    (wisent-log "\n\nclosure n = %d\n\n" nitemset)
    (setq i 0) ;; isp = itemset
    (while (< i nitemset)
      (wisent-log "   %d\n" (aref itemset i))
      (setq i (1+ i)))))

(defun wisent-closure (core n)
  "Set up RULESET and ITEMSET for the transitions out of CORE state.
Given a vector of item numbers items, of length N, set up RULESET and
ITEMSET to indicate what rules could be run and which items could be
accepted when those items are the active ones.

RULESET contains a bit for each rule.  `wisent-closure' sets the bits
for all rules which could potentially describe the next input to be
read.

ITEMSET is a vector of item numbers; NITEMSET is the number of items
in ITEMSET.  `wisent-closure' places there the indices of all items
which represent units of input that could arrive next."
  (let (c r v symbol ruleno itemno)
    (if (zerop n)
        (progn
          (setq r 0
                v (aref fderives (- start-symbol ntokens)))
          (while (< r rulesetsize)
            ;; ruleset[r] = FDERIVES (start-symbol)[r];
            (aset ruleset r (aref v r))
            (setq r (1+ r)))
          )
      (fillarray ruleset 0)
      (setq c 0)
      (while (< c n)
        (setq symbol (aref ritem (aref core c)))
        (when (wisent-ISVAR symbol)
          (setq r 0
                v (aref fderives (- symbol ntokens)))
          (while (< r rulesetsize)
            ;; ruleset[r] |= FDERIVES (ritem[core[c]])[r];
            (aset ruleset r (logior (aref ruleset r) (aref v r)))
            (setq r (1+ r))))
        (setq c (1+ c)))
      )
    (setq nitemset 0
          c 0
          ruleno 0
          r (* rulesetsize wisent-BITS-PER-WORD))
    (while (< ruleno r)
      (when (wisent-BITISSET ruleset ruleno)
        (setq itemno (aref rrhs ruleno))
        (while (and (< c n) (< (aref core c) itemno))
          (aset itemset nitemset (aref core c))
          (setq nitemset (1+ nitemset)
                c (1+ c)))
        (aset itemset nitemset itemno)
        (setq nitemset (1+ nitemset)))
      (setq ruleno (1+ ruleno)))

    (while (< c n)
      (aset itemset nitemset (aref core c))
      (setq nitemset (1+ nitemset)
            c (1+ c)))

    (if wisent-debug-flag
        (wisent-print-closure))
    ))

;;;; --------------------------------------------------
;;;; Generate the nondeterministic finite state machine
;;;; --------------------------------------------------

(defun wisent-allocate-itemsets ()
  "Allocate storage for itemsets."
  (let (symbol i count symbol-count)
    ;; Count the number of occurrences of all the symbols in RITEMS.
    ;; Note that useless productions (hence useless nonterminals) are
    ;; browsed too, hence we need to allocate room for _all_ the
    ;; symbols.
    (setq count 0
          symbol-count (make-vector (+ nsyms nuseless-nonterminals) 0)
          i 0)
    (while (setq symbol (aref ritem i))
      (when (> symbol 0)
        (setq count (1+ count))
        (aset symbol-count symbol (1+ (aref symbol-count symbol))))
      (setq i (1+ i)))
    ;; See comments before `wisent-new-itemsets'.  All the vectors of
    ;; items live inside kernel-items.  The number of active items
    ;; after some symbol cannot be more than the number of times that
    ;; symbol appears as an item, which is symbol-count[symbol].  We
    ;; allocate that much space for each symbol.
    (setq kernel-base (make-vector nsyms nil)
          kernel-items (make-vector count 0)
          count 0
          i 0)
    (while (< i nsyms)
      (aset kernel-base i count)
      (setq count (+ count (aref symbol-count i))
            i (1+ i)))
    (setq shift-symbol symbol-count
          kernel-end (make-vector nsyms nil))
    ))

(defun wisent-allocate-storage ()
  "Allocate storage for the state machine."
  (wisent-allocate-itemsets)
  (setq shiftset (make-vector nsyms 0)
        redset (make-vector (1+ nrules) 0)
        state-table (make-vector wisent-state-table-size nil)))

(defun wisent-new-itemsets ()
  "Find which symbols can be shifted in the current state.
And for each one record which items would be active after that shift.
Uses the contents of ITEMSET.  SHIFT-SYMBOL is set to a vector of the
symbols that can be shifted.  For each symbol in the grammar,
KERNEL-BASE[symbol] points to a vector of item numbers activated if
that symbol is shifted, and KERNEL-END[symbol] points after the end of
that vector."
  (let (i shiftcount isp ksp symbol)
    (fillarray kernel-end nil)
    (setq shiftcount 0
          isp 0)
    (while (< isp nitemset)
      (setq i (aref itemset isp)
            isp (1+ isp)
            symbol (aref ritem i))
      (when (> symbol 0)
        (setq ksp (aref kernel-end symbol))
        (when (not ksp)
          ;; shift-symbol[shiftcount++] = symbol;
          (aset shift-symbol shiftcount symbol)
          (setq shiftcount (1+ shiftcount)
                ksp (aref kernel-base symbol)))
        ;; *ksp++ = i + 1;
        (aset kernel-items ksp (1+ i))
        (setq ksp (1+ ksp))
        (aset kernel-end symbol ksp)))
    (setq nshifts shiftcount)))

(defun wisent-new-state (symbol)
  "Create a new state for those items, if necessary.
SYMBOL is the core accessing-symbol.
Subroutine of `wisent-get-state'."
  (let (n p isp1 isp2 iend items)
    (setq isp1  (aref kernel-base symbol)
          iend  (aref kernel-end symbol)
          n     (- iend isp1)
          p     (make-core)
          items (make-vector n 0))
1147 1148 1149 1150
    (setf (core-accessing-symbol p) symbol)
    (setf (core-number p) nstates)
    (setf (core-nitems p) n)
    (setf (core-items  p) items)
1151 1152 1153 1154 1155 1156
    (setq isp2 0) ;; isp2 = p->items
    (while (< isp1 iend)
      ;; *isp2++ = *isp1++;
      (aset items isp2 (aref kernel-items isp1))
      (setq isp1 (1+ isp1)
            isp2 (1+ isp2)))
1157
    (setf (core-next last-state) p)
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    (setq last-state p
          nstates (1+ nstates))
    p))

(defun wisent-get-state (symbol)
  "Find the state we would get to by shifting SYMBOL.
Return the state number for the state we would get to (from the
current state) by shifting SYMBOL.  Create a new state if no
equivalent one exists already.  Used by `wisent-append-states'."
  (let (key isp1 isp2 iend sp sp2 found n)
    (setq isp1 (aref kernel-base symbol)
          iend (aref kernel-end symbol)
          n    (- iend isp1)
          key  0)
    ;; Add up the target state's active item numbers to get a hash key
    (while (< isp1 iend)
      (setq key (+ key (aref kernel-items isp1))
            isp1 (1+ isp1)))
    (setq key (% key wisent-state-table-size)
          sp (aref state-table key))
    (if sp
        (progn
          (setq found nil)
          (while (not found)
            (when (= (core-nitems sp) n)
              (setq found t
                    isp1 (aref kernel-base symbol)
                    ;; isp2 = sp->items;
                    sp2  (core-items sp)
                    isp2 0)

              (while (and found (< isp1 iend))
                ;; if (*isp1++ != *isp2++)
                (if (not (= (aref kernel-items isp1)
                            (aref sp2 isp2)))
                    (setq found nil))
                (setq isp1 (1+ isp1)
                      isp2 (1+ isp2))))
            (if (not found)
                (if (core-link sp)
                    (setq sp (core-link sp))
                  ;; sp = sp->link = new-state(symbol)
1200
                  (setq sp (setf (core-link sp) (wisent-new-state symbol))
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
                        found t)))))
      ;; bucket is empty
      ;; state-table[key] = sp = new-state(symbol)
      (setq sp (wisent-new-state symbol))
      (aset state-table key sp))
    ;; return (sp->number);
    (core-number sp)))

(defun wisent-append-states ()
  "Find or create the core structures for states.
Use the information computed by `wisent-new-itemsets' to find the
state numbers reached by each shift transition from the current state.
SHIFTSET is set up as a vector of state numbers of those states."
  (let (i j symbol)
    ;; First sort shift-symbol into increasing order
    (setq i 1)
    (while (< i nshifts)
      (setq symbol (aref shift-symbol i)
            j i)
      (while (and (> j 0) (> (aref shift-symbol (1- j)) symbol))
        (aset shift-symbol j (aref shift-symbol (1- j)))
        (setq j (1- j)))
      (aset shift-symbol j symbol)
      (setq i (1+ i)))
    (setq i 0)
    (while (< i nshifts)
      (setq symbol (aref shift-symbol i))
      (aset shiftset i (wisent-get-state symbol))
      (setq i (1+ i)))
    ))

(defun wisent-initialize-states ()
  "Initialize states."
  (let ((p (make-core)))
    (setq first-state p
          last-state  p
          this-state  p
          nstates     1)))

(defun wisent-save-shifts ()
  "Save the NSHIFTS of SHIFTSET into the current linked list."
  (let (p i shifts)
    (setq p      (make-shifts)
          shifts (make-vector nshifts 0)
          i 0)
1246 1247 1248
    (setf (shifts-number p) (core-number this-state))
    (setf (shifts-nshifts p) nshifts)
    (setf (shifts-shifts  p) shifts)
1249 1250 1251 1252 1253
    (while (< i nshifts)
      ;; (p->shifts)[i] = shiftset[i];
      (aset shifts i (aref shiftset i))
      (setq i (1+ i)))

1254 1255 1256 1257
    (setf (if last-shift
              (shifts-next last-shift)
            first-shift)
          p)
1258 1259 1260 1261 1262 1263 1264 1265
    (setq last-shift p)))

(defun wisent-insert-start-shift ()
  "Create the next-to-final state.
That is the state to which a shift has already been made in the
initial state.  Subroutine of `wisent-augment-automaton'."
  (let (statep sp)
    (setq statep (make-core))
1266 1267 1268
    (setf (core-number statep) nstates)
    (setf (core-accessing-symbol statep) start-symbol)
    (setf (core-next last-state) statep)
1269 1270 1271
    (setq last-state statep)
    ;; Make a shift from this state to (what will be) the final state.
    (setq sp (make-shifts))
1272
    (setf (shifts-number sp) nstates)
1273
    (setq nstates (1+ nstates))
1274 1275 1276
    (setf (shifts-nshifts sp) 1)
    (setf (shifts-shifts sp) (vector nstates))
    (setf (shifts-next last-shift) sp)
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    (setq last-shift sp)))

(defun wisent-augment-automaton ()
  "Set up initial and final states as parser wants them.
Make sure that the initial state has a shift that accepts the
grammar's start symbol and goes to the next-to-final state, which has
a shift going to the final state, which has a shift to the termination
state.  Create such states and shifts if they don't happen to exist
already."
  (let (i k statep sp sp2 sp1 shifts)
    (setq sp first-shift)
    (if sp
        (progn
          (if (zerop (shifts-number sp))
              (progn
                (setq k (shifts-nshifts sp)
                      statep (core-next first-state))
                ;; The states reached by shifts from first-state are
                ;; numbered 1...K.  Look for one reached by
                ;; START-SYMBOL.
                (while (and (< (core-accessing-symbol statep) start-symbol)
                            (< (core-number statep) k))
                  (setq statep (core-next statep)))
                (if (= (core-accessing-symbol statep) start-symbol)
                    (progn
                      ;; We already have a next-to-final state.  Make
                      ;; sure it has a shift to what will be the final
                      ;; state.
                      (setq k (core-number statep))
                      (while (and sp (< (shifts-number sp) k))
                        (setq sp1 sp
                              sp (shifts-next sp)))
                      (if (and sp (= (shifts-number sp) k))
                          (progn
                            (setq i (shifts-nshifts sp)
                                  sp2 (make-shifts)
                                  shifts (make-vector (1+ i) 0))
1314 1315 1316
                            (setf (shifts-number sp2) k)
                            (setf (shifts-nshifts sp2) (1+ i))
                            (setf (shifts-shifts sp2) shifts)
1317 1318 1319 1320 1321 1322 1323
                            (aset shifts 0 nstates)
                            (while (> i 0)
                              ;; sp2->shifts[i] = sp->shifts[i - 1];
                              (aset shifts i (aref (shifts-shifts sp) (1- i)))
                              (setq i (1- i)))
                            ;; Patch sp2 into the chain of shifts in
                            ;; place of sp, following sp1.
1324 1325
                            (setf (shifts-next sp2) (shifts-next sp))
                            (setf (shifts-next sp1) sp2)
1326 1327 1328 1329
                            (if (eq sp last-shift)
                                (setq last-shift sp2))
                            )
                        (setq sp2 (make-shifts))
1330 1331 1332
                        (setf (shifts-number sp2) k)
                        (setf (shifts-nshifts sp2) 1)
                        (setf (shifts-shifts sp2) (vector nstates))
1333 1334
                        ;; Patch sp2 into the chain of shifts between
                        ;; sp1 and sp.
1335 1336
                        (setf (shifts-next sp2) sp)
                        (setf (shifts-next sp1) sp2)
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
                        (if (not sp)
                            (setq last-shift sp2))
                        )
                      )
                  ;; There is no next-to-final state as yet.
                  ;; Add one more shift in FIRST-SHIFT, going to the
                  ;; next-to-final state (yet to be made).
                  (setq sp first-shift
                        sp2 (make-shifts)
                        i   (shifts-nshifts sp)
                        shifts (make-vector (1+ i) 0))
1348 1349
                  (setf (shifts-nshifts sp2) (1+ i))
                  (setf (shifts-shifts sp2) shifts)
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
                  ;; Stick this shift into the vector at the proper place.
                  (setq statep (core-next first-state)
                        k 0
                        i 0)
                  (while (< i (shifts-nshifts sp))
                    (when (and (> (core-accessing-symbol statep) start-symbol)
                               (= i k))
                      (aset shifts k nstates)
                      (setq k (1+ k)))
                    (aset shifts k (aref (shifts-shifts sp) i))
                    (setq statep (core-next statep))
                    (setq i (1+ i)
                          k (1+ k)))
                  (when (= i k)
                    (aset shifts k nstates)
                    (setq k (1+ k)))
                  ;; Patch sp2 into the chain of shifts in place of
                  ;; sp, at the beginning.
1368
                  (setf (shifts-next sp2) (shifts-next sp))
1369 1370 1371 1372 1373 1374 1375 1376 1377
                  (setq first-shift sp2)
                  (if (eq last-shift sp)
                      (setq last-shift sp2))
                  ;; Create the next-to-final state, with shift to
                  ;; what will be the final state.
                  (wisent-insert-start-shift)))
            ;; The initial state didn't even have any shifts.  Give it
            ;; one shift, to the next-to-final state.
            (setq sp (make-shifts))
1378 1379
            (setf (shifts-nshifts sp) 1)
            (setf (shifts-shifts sp) (vector nstates))
1380
            ;; Patch sp into the chain of shifts at the beginning.
1381
            (setf (shifts-next sp) first-shift)
1382 1383 1384 1385 1386 1387 1388
            (setq first-shift sp)
            ;; Create the next-to-final state, with shift to what will
            ;; be the final state.
            (wisent-insert-start-shift)))
      ;; There are no shifts for any state.  Make one shift, from the
      ;; initial state to the next-to-final state.
      (setq sp (make-shifts))
1389 1390
      (setf (shifts-nshifts sp) 1)
      (setf (shifts-shifts sp) (vector nstates))
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
      ;; Initialize the chain of shifts with sp.
      (setq first-shift sp
            last-shift sp)
      ;; Create the next-to-final state, with shift to what will be
      ;; the final state.
      (wisent-insert-start-shift))
    ;; Make the final state--the one that follows a shift from the
    ;; next-to-final state.  The symbol for that shift is 0
    ;; (end-of-file).
    (setq statep (make-core))
1401 1402
    (setf (core-number statep) nstates)
    (setf (core-next last-state) statep)
1403 1404 1405
    (setq last-state statep)
    ;; Make the shift from the final state to the termination state.
    (setq sp (make-shifts))
1406
    (setf (shifts-number sp) nstates)
1407
    (setq nstates (1+ nstates))
1408 1409 1410
    (setf (shifts-nshifts sp) 1)
    (setf (shifts-shifts sp) (vector nstates))
    (setf (shifts-next last-shift) sp)
1411 1412 1413 1414 1415 1416
    (setq last-shift sp)
    ;; Note that the variable FINAL-STATE refers to what we sometimes
    ;; call the termination state.
    (setq final-state nstates)
    ;; Make the termination state.
    (setq statep (make-core))
1417
    (setf (core-number statep) nstates)
1418
    (setq nstates (1+ nstates))
1419
    (setf (core-next last-state) statep)
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
    (setq last-state statep)))

(defun wisent-save-reductions ()
  "Make a reductions structure.
Find which rules can be used for reduction transitions from the
current state and make a reductions structure for the state to record
their rule numbers."
  (let (i item count p rules)
    ;; Find and count the active items that represent ends of rules.
    (setq count 0
          i 0)
    (while (< i nitemset)
      (setq item (aref ritem (aref itemset i)))
      (when (< item 0)
        (aset redset count (- item))
        (setq count (1+ count)))
      (setq i (1+ i)))
    ;; Make a reductions structure and copy the data into it.
    (when (> count 0)
      (setq p (make-reductions)
            rules (make-vector count 0))
1441 1442 1443
      (setf (reductions-number p) (core-number this-state))
      (setf (reductions-nreds  p) count)
      (setf (reductions-rules  p) rules)
1444 1445 1446 1447 1448
      (setq i 0)
      (while (< i count)
        ;; (p->rules)[i] = redset[i]
        (aset rules i (aref redset i))
        (setq i (1+ i)))
1449 1450 1451 1452
      (setf (if last-reduction
                (reductions-next last-reduction)
              first-reduction)
            p)
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
      (setq last-reduction p))))

(defun wisent-generate-states ()
  "Compute the nondeterministic finite state machine from the grammar."
  (wisent-allocate-storage)
  (wisent-initialize-closure nitems)
  (wisent-initialize-states)
  (while this-state
    ;; Set up RULESET and ITEMSET for the transitions out of this
    ;; state.  RULESET gets a 1 bit for each rule that could reduce
    ;; now.  ITEMSET gets a vector of all the items that could be
    ;; accepted next.
    (wisent-closure (core-items this-state) (core-nitems this-state))
    ;; Record the reductions allowed out of this state.
    (wisent-save-reductions)
    ;; Find the itemsets of the states that shifts can reach.
    (wisent-new-itemsets)
    ;; Find or create the core structures for those states.
    (wisent-append-states)
    ;; Create the shifts structures for the shifts to those states,
    ;; now that the state numbers transitioning to are known.
    (if (> nshifts 0)
        (wisent-save-shifts))
    ;; States are queued when they are created; process them all.
    (setq this-state (core-next this-state)))
  ;; Set up initial and final states as parser wants them.
  (wisent-augment-automaton))

;;;; ---------------------------
;;;; Compute look-ahead criteria
;;;; ---------------------------

;; Compute how to make the finite state machine deterministic; find
;; which rules need lookahead in each state, and which lookahead
;; tokens they accept.

;; `wisent-lalr', the entry point, builds these data structures:

;; GOTO-MAP, FROM-STATE and TO-STATE record each shift transition
;; which accepts a variable (a nonterminal).  NGOTOS is the number of
;; such transitions.
;; FROM-STATE[t] is the state number which a transition leads from and
;; TO-STATE[t] is the state number it leads to.
;; All the transitions that accept a particular variable are grouped
;; together and GOTO-MAP[i - NTOKENS] is the index in FROM-STATE and
;; TO-STATE of the first of them.

;; CONSISTENT[s] is non-nil if no lookahead is needed to decide what
;; to do in state s.

;; LARULENO is a vector which records the rules that need lookahead in
;; various states.  The elements of LARULENO that apply to state s are
;; those from LOOKAHEADS[s] through LOOKAHEADS[s+1]-1.  Each element
;; of LARULENO is a rule number.

;; If LR is the length of LARULENO, then a number from 0 to LR-1 can
;; specify both a rule and a state where the rule might be applied.
;; LA is a LR by NTOKENS matrix of bits.
;; LA[l, i] is 1 if the rule LARULENO[l] is applicable in the
;; appropriate state when the next token is symbol i.
;; If LA[l, i] and LA[l, j] are both 1 for i != j, it is a conflict.

(wisent-defcontext digraph
  INDEX R VERTICES
  infinity top)

(defun wisent-traverse (i)
  "Traverse I."
  (let (j k height Ri Fi break)
    (setq top (1+ top)
          height top)
    (aset VERTICES top i) ;; VERTICES[++top] = i
    (aset INDEX i top) ;; INDEX[i] = height = top

    (setq Ri (aref R i))
    (when Ri
      (setq j 0)
      (while (>= (aref Ri j) 0)
        (if (zerop (aref INDEX (aref Ri j)))
            (wisent-traverse (aref Ri j)))
        ;; if (INDEX[i] > INDEX[R[i][j]])
        (if (> (aref INDEX i) (aref INDEX (aref Ri j)))
            ;; INDEX[i] = INDEX[R[i][j]];
            (aset INDEX i (aref INDEX (aref Ri j))))
        (setq Fi (aref F i)
              k 0)
        (while (< k tokensetsize)
          ;; F (i)[k] |= F (R[i][j])[k];
          (aset Fi k (logior (aref Fi k)
                             (aref (aref F (aref Ri j)) k)))
           (setq k (1+ k)))
        (setq j (1+ j))))

    (when (= (aref INDEX i) height)
      (setq break nil)
      (while (not break)
        (setq j (aref VERTICES top) ;; j = VERTICES[top--]
              top (1- top))
        (aset INDEX j infinity)
        (if (= i j)
            (setq break t)
          (setq k 0)
          (while (< k tokensetsize)
            ;; F (j)[k] = F (i)[k];
            (aset (aref F j) k (aref (aref F i) k))
            (setq k (1+ k))))))
    ))

(defun wisent-digraph (relation)
  "Digraph RELATION."
  (wisent-with-context digraph
    (setq infinity (+ ngotos 2)
          INDEX    (make-vector (1+ ngotos) 0)
          VERTICES (make-vector (1+ ngotos) 0)
          top      0
          R        relation)
    (let ((i 0))
      (while (< i ngotos)
        (if (and (= (aref INDEX i) 0) (aref R i))
            (wisent-traverse i))
        (setq i (1+ i))))))

(defun wisent-set-state-table ()
  "Build state table."
  (let (sp)
    (setq state-table (make-vector nstates nil)
          sp first-state)
    (while sp
      (aset state-table (core-number sp) sp)
      (setq sp (core-next sp)))))

(defun wisent-set-accessing-symbol ()
  "Build accessing symbol table."
  (let (sp)
    (setq accessing-symbol (make-vector nstates 0)
          sp first-state)
    (while sp
      (aset accessing-symbol (core-number sp) (core-accessing-symbol sp))
      (setq sp (core-next sp)))))

(defun wisent-set-shift-table ()
  "Build shift table."
  (let (sp)
    (setq shift-table (make-vector nstates nil)
          sp first-shift)
    (while sp
      (aset shift-table (shifts-number sp) sp)
      (setq sp (shifts-next sp)))))

(defun wisent-set-reduction-table ()
  "Build reduction table."
  (let (rp)
    (setq reduction-table (make-vector nstates nil)
          rp first-reduction)
    (while rp
      (aset reduction-table (reductions-number rp) rp)
      (setq rp (reductions-next rp)))))

(defun wisent-set-maxrhs ()
  "Setup MAXRHS length."
  (let (i len max)
    (setq len 0
          max 0
          i   0)
    (while (aref ritem i)
      (if (> (aref ritem i) 0)
          (setq len (1+ len))
        (if (> len max)
            (setq max len))
        (setq len 0))
      (setq i (1+ i)))
    (setq maxrhs max)))

(defun wisent-initialize-LA ()
  "Set up LA."
  (let (i j k count rp sp np v)
    (setq consistent (make-vector nstates nil)
          lookaheads (make-vector (1+ nstates) 0)
          count 0
          i 0)
    (while (< i nstates)
      (aset lookaheads i count)
      (setq rp (aref reduction-table i)
            sp (aref shift-table i))
      ;; if (rp &&
      ;;     (rp->nreds > 1
      ;;      || (sp && ! ISVAR(accessing-symbol[sp->shifts[0]]))))
      (if (and rp
               (or (> (reductions-nreds rp) 1)
                   (and sp
                        (not (wisent-ISVAR
                              (aref accessing-symbol
                                    (aref (shifts-shifts sp) 0)))))))
          (setq count (+ count (reductions-nreds rp)))
        (aset consistent i t))

      (when sp
        (setq k 0
              j (shifts-nshifts sp)
              v (shifts-shifts sp))
        (while (< k j)
          (when (= (aref accessing-symbol (aref v k))
                   error-token-number)
            (aset consistent i nil)
            (setq k j)) ;; break
          (setq k (1+ k))))
      (setq i (1+ i)))

    (aset lookaheads nstates count)

    (if (zerop count)
        (progn
          (setq LA (make-vector 1 nil)
                LAruleno (make-vector 1 0)
                lookback (make-vector 1 nil)))
      (setq LA (make-vector count nil)
            LAruleno (make-vector count 0)
            lookback (make-vector count nil)))
    (setq i 0 j (length LA))
    (while (< i j)
      (aset LA i (make-vector tokensetsize 0))
      (setq i (1+ i)))

    (setq np 0
          i  0)
    (while (< i nstates)
      (when (not (aref consistent i))
        (setq rp (aref reduction-table i))
        (when rp
          (setq j 0
                k (reductions-nreds rp)
                v (reductions-rules rp))
          (while (< j k)
            (aset LAruleno np (aref v j))
            (setq np (1+ np)
                  j  (1+ j)))))
      (setq i (1+ i)))))

(defun wisent-set-goto-map ()
  "Set up GOTO-MAP."
  (let (sp i j symbol k temp-map state1 state2 v)
    (setq goto-map (make-vector (1+ nvars) 0)
          temp-map (make-vector (1+ nvars) 0))

    (setq ngotos 0
          sp first-shift)
    (while sp
      (setq i (1- (shifts-nshifts sp))
            v (shifts-shifts sp))
      (while (>= i 0)
        (setq symbol (aref accessing-symbol (aref v i)))
        (if (wisent-ISTOKEN symbol)
            (setq i 0) ;; break
          (setq ngotos (1+ ngotos))
          ;; goto-map[symbol]++;
          (aset goto-map (- symbol ntokens)
                (1+ (aref goto-map (- symbol ntokens)))))
        (setq i (1- i)))
      (setq sp (shifts-next sp)))

    (setq k 0
          i ntokens
          j 0)
    (while (< i nsyms)
      (aset temp-map j k)
      (setq k (+ k (aref goto-map j))
            i (1+ i)
            j (1+ j)))
    (setq i ntokens
          j 0)
    (while (< i nsyms)
      (aset goto-map j (aref temp-map j))
      (setq i (1+ i)
            j (1+ j)))
    ;; goto-map[nsyms] = ngotos;
    ;; temp-map[nsyms] = ngotos;
    (aset goto-map j ngotos)
    (aset temp-map j ngotos)

    (setq from-state (make-vector ngotos 0)
          to-state   (make-vector ngotos 0)
          sp first-shift)
    (while sp
      (setq state1 (shifts-number sp)
            v      (shifts-shifts sp)
            i      (1- (shifts-nshifts sp)))
      (while (>= i 0)
        (setq state2 (aref v i)
              symbol (aref accessing-symbol state2))
        (if (wisent-ISTOKEN symbol)
            (setq i 0) ;; break
          ;; k = temp-map[symbol]++;
          (setq k (aref temp-map (- symbol ntokens)))
          (aset temp-map (- symbol ntokens) (1+ k))
          (aset from-state k state1)
          (aset to-state k state2))
        (setq i (1- i)))
      (setq sp (shifts-next sp)))
  ))

(defun wisent-map-goto (state symbol)
  "Map a STATE/SYMBOL pair into its numeric representation."
  (let (high low middle s result)
    ;; low = goto-map[symbol];
    ;; high = goto-map[symbol + 1] - 1;
    (setq low (aref goto-map (- symbol ntokens))
          high (1- (aref goto-map (- (1+ symbol) ntokens))))
    (while (and (not result) (<= low high))
      (setq middle (/ (+ low high) 2)
            s (aref from-state middle))
      (cond
       ((= s state)
        (setq result middle))
       ((< s state)
        (setq low (1+ middle)))
       (t
        (setq high (1- middle)))))
    (or result
        (error "Internal error in `wisent-map-goto'"))
    ))

(defun wisent-initialize-F ()
  "Set up F."
  (let (i j k sp edge rowp rp reads nedges stateno symbol v break)
    (setq F (make-vector ngotos nil)
          i 0)
    (while (< i ngotos)
      (aset F i (make-vector tokensetsize 0))
      (setq i (1+ i)))

    (setq reads (make-vector ngotos nil)
          edge  (make-vector (1+ ngotos) 0)
          nedges 0
          rowp 0 ;; rowp = F
          i 0)
    (while (< i ngotos)
      (setq stateno (aref to-state i)
            sp (aref shift-table stateno))
      (when sp
        (setq k (shifts-nshifts sp)
              v (shifts-shifts sp)
              j 0
              break nil)
        (while (and (not break) (< j k))
          ;; symbol = accessing-symbol[sp->shifts[j]];
          (setq symbol (aref accessing-symbol (aref v j)))
          (if (wisent-ISVAR symbol)
              (setq break t) ;; break
            (wisent-SETBIT (aref F rowp) symbol)
            (setq j (1+ j))))

        (while (< j k)
          ;; symbol = accessing-symbol[sp->shifts[j]];
          (setq symbol (aref accessing-symbol (aref v j)))
          (when (aref nullable (- symbol ntokens))
            (aset edge nedges (wisent-map-goto stateno symbol))
            (setq nedges (1+ nedges)))
          (setq j (1+ j)))

        (when (> nedges 0)
          ;; reads[i] = rp = NEW2(nedges + 1, short);
          (setq rp (make-vector (1+ nedges) 0)
                j 0)
          (aset reads i rp)
          (while (< j nedges)
            ;; rp[j] = edge[j];
            (aset rp j (aref edge j))
            (setq j (1+ j)))
          (aset rp nedges -1)
          (setq nedges 0)))
      (setq rowp (1+ rowp))
      (setq i (1+ i)))
    (wisent-digraph reads)
    ))

(defun wisent-add-lookback-edge (stateno ruleno gotono)
  "Add a lookback edge.
STATENO, RULENO, GOTONO are self-explanatory."
  (let (i k found)
    (setq i (aref lookaheads stateno)
          k (aref lookaheads (1+ stateno))
          found nil)
    (while (and (not found) (< i k))
      (if (= (aref LAruleno i) ruleno)
          (setq found t)
        (setq i (1+ i))))

    (or found
        (error "Internal error in `wisent-add-lookback-edge'"))

    ;;                value  . next
    ;; lookback[i] = (gotono . lookback[i])
    (aset lookback i (cons gotono (aref lookback i)))))

(defun wisent-transpose (R-arg n)
  "Return the transpose of R-ARG, of size N.
Destroy R-ARG, as it is replaced with the result.  R-ARG[I] is nil or
a -1 terminated list of numbers.  RESULT[NUM] is nil or the -1
terminated list of the I such as NUM is in R-ARG[I]."
  (let (i j new-R end-R nedges v sp)
    (setq new-R  (make-vector n nil)
          end-R  (make-vector n nil)
          nedges (make-vector n 0))

    ;; Count.
    (setq i 0)
    (while (< i n)
      (setq v (aref R-arg i))
      (when v
        (setq j 0)
        (while (>= (aref v j) 0)
          (aset nedges (aref v j) (1+ (aref nedges (aref v j))))
          (setq j (1+ j))))
      (setq i (1+ i)))

    ;; Allocate.
    (setq i 0)
    (while (< i n)
      (when (> (aref nedges i) 0)
        (setq sp (make-vector (1+ (aref nedges i)) 0))
        (aset sp (aref nedges i) -1)
        (aset new-R i sp)
        (aset end-R i 0))
      (setq i (1+ i)))

    ;; Store.
    (setq i 0)
    (while (< i n)
      (setq v (aref R-arg i))
      (when v
        (setq j 0)
        (while (>= (aref v j) 0)
          (aset (aref new-R (aref v j)) (aref end-R (aref v j)) i)
          (aset end-R (aref v