codeBackend.ml 54.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
(******************************************************************************)
(*                                                                            *)
(*                                   Menhir                                   *)
(*                                                                            *)
(*                       François Pottier, Inria Paris                        *)
(*              Yann Régis-Gianas, PPS, Université Paris Diderot              *)
(*                                                                            *)
(*  Copyright Inria. All rights reserved. This file is distributed under the  *)
(*  terms of the GNU General Public License version 2, as described in the    *)
(*  file LICENSE.                                                             *)
(*                                                                            *)
(******************************************************************************)

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
(* The code generator. *)

module Run (T : sig end) = struct

open Grammar
open IL
open CodeBits
open CodePieces
open TokenType
open Interface

(* ------------------------------------------------------------------------ *)
(* Here is a description of our code generation mechanism.

   Every internal function that we produce is parameterized by the
   parser environment [env], which contains (pointers to) the lexer,
   the lexing buffer, the last token read, etc. No global variables
   are exploited, so our parsers are reentrant. The functions that we
   export do not expect an environment as a parameter; they create a
   fresh one when invoked.

POTTIER Francois's avatar
POTTIER Francois committed
35 36 37 38 39 40
   Every state [s] is translated to a [run] function. To a first
   approximation, the only parameter of the [run] function, besides [env],
   is the stack. However, in some cases (consult the predicate [runpushes]),
   the top stack cell is not yet allocated when [run s] is called. The
   cell's contents are passed as extra parameters, and it is [run]'s
   responsibility to allocate that cell.
41 42 43 44 45 46 47 48

   (When [run] is the target of a shift transition, the position
   parameters [startp] and [endp] are redundant with the [env]
   parameter, because they are always equal to [env.startp] and
   [env.endp]. However, this does not appear to make a great
   difference in terms of code size, and makes our life easier, so we
   do not attempt to eliminate this redundancy.)

49 50 51 52 53 54 55 56
   The first thing in [run] is to discard a token, if the state was entered
   through a shift transition, and to peek at the lookahead token. When the
   current token is to be discarded, the [discard] function is invoked. It
   discards the current token, invokes the lexer to obtain a new token, and
   returns an updated environment. When we only wish to peek at the current
   token, without discarding it, we simply read [env.token]. (We have to be
   careful in cases where the current lookahead token might be [error],
   since, in those cases, [env.token] is meaningless; see below.)
57

POTTIER Francois's avatar
POTTIER Francois committed
58 59 60 61 62 63 64
   Once the lookahead token is obtained, [run] performs a case analysis of
   the lookahead token. Each branch performs one of the following. In shift
   branches, control is dispatched to another [run] function, with
   appropriate parameters, typically the current stack plus the information
   that should go into the new top stack cell (a state, a semantic value,
   locations).  In reduce branches, a [reduce] function is invoked. In the
   default branch, error handling is initiated (see below).
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

   The [reduce] function associated with production [prod] pops as
   many stack cells as necessary, retrieving semantic values and the
   state [s] that initiated the reduction. It then evaluates the
   semantic action, which yields a new semantic value. (This is the
   only place where semantic actions are evaluated, so that semantic
   actions are never duplicated.) It then passes control on to the
   [goto] function associated with the nonterminal [nt], where [nt]
   is the left-hand side of the production [prod].

   The [goto] function associated with nonterminal [nt] expects just
   one parameter besides the environment -- namely, the
   stack. However, in some cases (consult the predicate [gotopushes]),
   the top stack cell is not allocated yet, so its contents are passed
   as extra parameters. In that case, [goto] first allocates that
   cell. Then, it examines the state found in that cell and performs a
   goto transition, that is, a shift transition on the nonterminal
   symbol [nt]. This simply consists in passing control to the [run]
   function associated with the transition's target state. If this
   case analysis only has one branch, because all transitions for [nt]
   lead to the same target state, then no case analysis is required.

   In principle, a stack cell contains a state, a semantic value, and
   start and end positions. However, the state can be omitted if it is
   never consulted by a [goto] function. The semantic value can be
   omitted if it is associated with a token that was declared not to
   carry a semantic value. (One could also omit semantic values for
   nonterminals whose type was declared to be [unit], but that does
   not seem very useful.) The start or end position can be omitted if
   they are associated with a symbol that does not require keeping
   track of positions. When all components of a stack cell are
   omitted, the entire cell disappears, so that no memory allocation
   is required.

   For each start symbol [nt], an entry point function, named after
   [nt], is generated. Its parameters are a lexer and a lexing buffer.
   The function allocates and initializes a parser environment and
   transfers control to the appropriate [run] function.

   Our functions are grouped into one huge [let rec] definition. The
   inliner, implemented as a separate module, will inline functions
   that are called at most once, remove dead code (although there
   should be none or next to none), and possibly perform other
   transformations.

   I note that, if a state can be entered only through (nondefault)
   reductions, then, in that state, the lookahead token must be a
   member of the set of tokens that allow these reductions, and by
   construction, there must exist an action on that token in that
   state. Thus, the default branch (which signals an error when
   the lookahead token is not a member of the expected set) is in
   fact dead. It would be nice (but difficult) to exploit types
   to prove that. However, one could at least replace the code of
   that branch with a simple [assert false]. TEMPORARY do it *)

(* ------------------------------------------------------------------------ *)
121
(* Here is a description of our error handling mechanism.
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

   With every state [s], we associate an [error] function.

   If [s] is willing to act when the lookahead token is [error], then
   this function tells how. This includes *both* shift *and* reduce
   actions. (For some reason, yacc/ocamlyacc/mule/bison can only shift
   on [error].)

   If [s] is unable to act when the lookahead token is [error], then
   this function pops a stack cell, extracts a state [s'] out of it,
   and transfers control, via a global [errorcase] dispatch function,
   to the [error] function associated with [s']. (Because some stack
   cells do not physically hold a state, this description is somewhat
   simpler than the truth, but that's the idea.)

137 138 139 140 141 142
   When an error is detected in state [s], then (see [initiate]) the [error]
   function associated with [s] is invoked. Immediately before invoking the
   [error] function, the flag [env.error] is set.  By convention, this means
   that the current token is discarded and replaced with an [error] token. The
   [error] token transparently inherits the positions associated with the
   underlying concrete token.
143 144

   Whenever we attempt to consult the current token, we check whether
145
   [env.error] is set and, if that is the case, resume error handling
146 147 148
   by calling the [error] function associated with the current state.
   This allows a series of reductions to correctly take place when the
   lookahead token is [error]. In many states, though, it is possible
149 150
   to statically prove that [env.error] cannot be set. In that case,
   we produce a lookup of [env.token] without checking [env.error].
151

152
   The flag [env.error] is cleared when a token is shifted.
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

   States with default reductions perform a reduction regardless of
   the current lookahead token, which can be either [error] or a
   regular token.

   A question that bothered me for a while was, when unwinding the
   stack, do we stop at a state that has a default reduction? Should
   it be considered able to handle the error token? I now believe that
   the answer is, this cannot happen. Indeed, if a state has a default
   reduction, then, whenever it is entered, reduction is performed and
   that state is exited, which means that it is never pushed onto the
   stack. So, it is fine to consider that a state with a default
   reduction is unable to handle errors.

   I note that a state that can handle [error] and has a default
168
   reduction must in fact have a reduction action on [error]. *)
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

(* The type of environments. *)

let tcenv =
  env

let tenv =
  TypApp (tcenv, [])

(* The [assertfalse] function. We have just one of these, in order to
   save code size. It should become unnecessary when we add GADTs. *)

let assertfalse =
  prefix "fail"

(* The [discard] function. *)

let discard =
  prefix "discard"

(* The [initenv] function. *)

let initenv =
  prefix "init"

(* The [run] function associated with a state [s]. *)

let run s =
  prefix (Printf.sprintf "run%d" (Lr1.number s))

(* The [goto] function associated with a nonterminal [nt]. *)

let goto nt =
  prefix (Printf.sprintf "goto_%s" (Nonterminal.print true nt))

(* The [reduce] function associated with a production [prod]. *)

let reduce prod =
  prefix (Printf.sprintf "reduce%d" (Production.p2i prod))

(* The [errorcase] function. *)

let errorcase =
  prefix "errorcase"

(* The [error] function associated with a state [s]. *)

let error s =
  prefix (Printf.sprintf "error%d" (Lr1.number s))

(* The constant associated with a state [s]. *)

let statecon s =
  dataprefix (Printf.sprintf "State%d" (Lr1.number s))

let estatecon s =
  EData (statecon s, [])

let pstatecon s =
  PData (statecon s, [])

let pstatescon ss =
  POr (List.map pstatecon ss)

(* The type of states. *)

let tcstate =
  prefix "state"

let tstate =
  TypApp (tcstate, [])

(* The [print_token] function. This automatically generated function
   is used in [--trace] mode. *)

let print_token =
  prefix "print_token"

(* Fields in the environment record. *)

let flexer =
  prefix "lexer"

let flexbuf =
  prefix "lexbuf"

let ftoken =
  prefix "token"

258 259
let ferror =
  prefix "error"
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

(* The type variable that represents the stack tail. *)

let tvtail =
  tvprefix "tail"

let ttail =
  TypVar tvtail

(* The result type for every function. TEMPORARY *)

let tvresult =
  tvprefix "return"

let tresult =
  TypVar tvresult

(* ------------------------------------------------------------------------ *)
(* Helpers for code production. *)

let var x : expr =
  EVar x

let pvar x : pattern =
  PVar x

let magic e : expr =
  EMagic e

let nomagic e =
  e

292
(* The following assertion checks that [env.error] is [false]. *)
293

294
let assertnoerror : pattern * expr =
295
  PUnit,
296
  EApp (EVar "assert", [ EApp (EVar "not", [ ERecordAccess (EVar env, ferror) ]) ])
297 298 299

let trace (format : string) (args : expr list) : (pattern * expr) list =
  if Settings.trace then
300
    [ PUnit, EApp (EVar "Printf.fprintf", (EVar "stderr") :: (EStringConst (format ^"\n%!")) :: args) ]
301 302 303 304 305 306 307 308 309 310 311 312
  else
    []

let tracecomment (comment : string) (body : expr) : expr =
  if Settings.trace then
    blet (trace comment [], body)
  else
    EComment (comment, body)

let auto2scheme t =
  scheme [ tvtail; tvresult ] t

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
(* ------------------------------------------------------------------------ *)
(* Accessing the positions of the current token. *)

(* There are two ways we can go about this. We can read the positions
   from the lexbuf immediately after we request a new token, or we can
   wait until we need the positions and read them at that point. As of
   2014/12/12, we switch to the latter approach. The speed difference
   in a micro-benchmark is not measurable, but this allows us to save
   two fields in the [env] record, which should be a good thing, as it
   implies less frequent minor collections. *)

let getstartp =
  ERecordAccess (ERecordAccess (EVar env, flexbuf), "Lexing.lex_start_p")

let getendp =
  ERecordAccess (ERecordAccess (EVar env, flexbuf), "Lexing.lex_curr_p")

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
(* ------------------------------------------------------------------------ *)
(* Determine whether the [goto] function for nonterminal [nt] will push
   a new cell onto the stack. If it doesn't, then that job is delegated
   to the [run] functions called by [goto].

   One could decide that [gotopushes] always returns true, and produce
   decent code. As a refinement, we decide to drive the [push]
   operation inside the [run] functions if all of them are able to
   eliminate this operation via shiftreduce optimization. This will be
   the case if all of these [run] functions implement a default
   reduction of a non-epsilon production.

   If that is not the case, then [gotopushes] returns true. In
   general, it is good to place the [push] operation inside [goto],
   because multiple [reduce] functions transfer control to [goto], and
   [goto] in turn transfers control to multiple [run] functions. Hence,
   this is where code sharing is maximal. All of the [run] functions
   that [goto] can transfer control to expect a stack cell of the same
   shape (indeed, the symbol [nt] is the same in every case, and the
   state is always represented), which makes this decision possible. *)

let gotopushes : Nonterminal.t -> bool =
  Nonterminal.tabulate (fun nt ->
    not (
      Lr1.targets (fun accu _ target ->
355
        accu &&
356
        match Default.has_default_reduction target with
357 358 359
        | Some (prod, _) ->
            Production.length prod > 0
        | None -> false
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
      ) true (Symbol.N nt)
    )
  )

(* ------------------------------------------------------------------------ *)
(* Determine whether the [run] function for state [s] will push a new cell
   onto the stack.

   Our convention is this. If this [run] function is entered via a shift
   transition, then it is in charge of pushing a new stack cell. If it
   is entered via a goto transition, then it is in charge of pushing a
   new cell if and only if the [goto] function that invoked it did not
   do so. Last, if this [run] function is invoked directly by an entry
   point, then it does not push a stack cell. *)

let runpushes s =
  match Lr1.incoming_symbol s with
  | Some (Symbol.T _) ->
      true
  | Some (Symbol.N nt) ->
      not (gotopushes nt)
  | None ->
      false

(* ------------------------------------------------------------------------ *)
(* In some situations, we are able to fuse a shift (or goto)
   transition with a reduce transition, which means that we save the
   cost (in speed and in code size) of pushing and popping the top
   stack cell.

   This involves creating a modified version of the [reduce] function
   associated with a production [prod], where the contents of the top
   stack cell are passed as extra parameters. Because we wish to avoid
   code duplication, we perform this change only if all call sites for
   [reduce] agree on this modified calling convention.

   At the call site, the optimization is possible only if a stack cell
   allocation exists and is immediately followed by a call to
   [reduce]. This is the case inside the [run] function for state [s]
   when [run] pushes a stack cell and performs a default reduction.

   This optimization amounts to coalescing the push operation inside
   [run] with the pop operation that follows inside [reduce].

   Unit production elimination, on the other hand, would coalesce the
   pop operation inside [reduce] with the push operation that follows
   inside [goto]. For this reason, the two are contradictory. As a
   result, we do not attempt to perform unit production elimination.
   In fact, we did implement it at one point and found that it was
   seldom applicable, because preference was given to the shiftreduce
   optimization.

   There are cases where shiftreduce optimization does not make any
   difference, for instance, if production [prod] is never reduced, or
   if the top stack cell is in fact nonexistent. *)

let (shiftreduce : Production.index -> bool), shiftreducecount =
  Production.tabulateb (fun prod ->

    (* Check that this production pops at least one stack cell. *)

    Production.length prod > 0 &&

    (* Check that all call sites push a stack cell and have a
       default reduction. *)

POTTIER Francois's avatar
POTTIER Francois committed
426
    Lr1.NodeSet.fold (fun s accu ->
427
      accu && (match Default.has_default_reduction s with None -> false | Some _ -> true)
428
           && (runpushes s)
POTTIER Francois's avatar
POTTIER Francois committed
429
    ) (Lr1.production_where prod) true
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

  )

let () =
  Error.logC 1 (fun f ->
    Printf.fprintf f
       "%d out of %d productions exploit shiftreduce optimization.\n"
       shiftreducecount Production.n)

(* Check that, as predicted above, [gotopushes nt] returns [false]
   only when all of the [run] functions that follow it perform
   shiftreduce optimization.

   This can be proved as follows. If [gotopushes nt] returns [false],
   then every successor state [s] has a default reduction for some
   non-epsilon production [prod]. Furthermore, all states that can
   reduce [prod] must be successors of that same [goto] function:
   indeed, because the right-hand side of the production ends with
   symbol [nt], every state that can reduce [prod] must be entered
   through [nt]. So, at all such states, [runpushes] is true, which
   guarantees that [shiftreduce prod] is true as well. *)

let () =
  assert (
    Nonterminal.fold (fun nt accu ->
      accu &&
      if gotopushes nt then
457
        true
458
      else
459 460
        Lr1.targets (fun accu _ target ->
          accu &&
461
          match Default.has_default_reduction target with
462 463 464 465
          | Some (prod, _) ->
              shiftreduce prod
          | None ->
              false
466 467 468 469 470 471 472 473 474 475 476 477 478 479
        ) true (Symbol.N nt)
    ) true
  )

(* ------------------------------------------------------------------------ *)
(* Type production. *)

(* This is the type of states. Only states that are represented are
   declared. *)

let statetypedef = {
  typename =       tcstate;
  typeparams =     [];
  typerhs =        TDefSum (
480 481 482 483 484 485 486 487
                     Lr1.fold (fun defs s ->
                       if Invariant.represented s then {
                         dataname =       statecon s;
                         datavalparams =  [];
                         datatypeparams = None
                       } :: defs
                       else defs
                     ) []
488 489 490 491
                   );
  typeconstraint = None
}

492 493 494 495 496
(* The type of lexers. *)

let tlexer =
  TypArrow (tlexbuf, ttoken)

497 498 499 500 501 502 503 504 505 506 507 508 509
(* This is the type of parser environments. *)

let field modifiable name t =
  {
    modifiable = modifiable;
    fieldname = name;
    fieldtype = type2scheme t
  }

let envtypedef = {
  typename = tcenv;
  typeparams = [];
  typerhs =
510
    TDefRecord [
511 512 513 514 515 516 517 518 519 520

      (* The lexer itself. *)

      field false flexer tlexer;

      (* The lexing buffer. *)

      field false flexbuf tlexbuf;

      (* The last token that was read from the lexer. This is the
521
         head of the token stream, unless [env.error] is set. *)
522

523
      field false ftoken ttoken;
524

525 526
      (* A flag which tells whether we currently have an [error] token
         at the head of the stream. When this flag is set, the head
527 528 529
         of the token stream is the [error] token, and the contents of
         the [token] field is irrelevant. The token following [error]
         is obtained by invoking the lexer again. *)
530

531
      field true ferror tbool;
532

533
    ];
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
  typeconstraint = None
}

(* [curry] curries the top stack cell in a type [t] of the form
   [(stack type) arrow (result type)]. [t] remains unchanged if the
   stack type does not make at least one cell explicit. *)

let curry = function
  | TypArrow (TypTuple (tstack :: tcell), tresult) ->
      TypArrow (tstack, marrow tcell tresult)
  | TypArrow _ as t ->
      t
  | _ ->
      assert false

(* [curryif true] is [curry], [curryif false] is the identity. *)

let curryif flag t =
  if flag then curry t else t

POTTIER Francois's avatar
POTTIER Francois committed
554
(* Types for stack cells.
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

   [celltype tailtype holds_state symbol] returns the type of a stack
   cell. The parameter [tailtype] is the type of the tail of the
   stack. The flag [holds_state] tells whether the cell holds a state.
   The parameter [symbol] is used to determine whether the cell holds
   a semantic value and what its type is.

   A subtlety here and in [curry] above is that singleton stack cells
   give rise to singleton tuple types, which the type printer
   eliminates, but which do exist internally. As a result, [curry]
   always correctly removes the top stack cell, even if it is a
   singleton tuple cell. *)

let celltype tailtype holds_state symbol _ =
  TypTuple (
    tailtype ::
571
    elementif (Invariant.endp symbol) tposition @
572
    elementif holds_state tstate @
573
    semvtype symbol @
574
    elementif (Invariant.startp symbol) tposition
575 576
  )

POTTIER Francois's avatar
POTTIER Francois committed
577
(* Types for stacks.
578

POTTIER Francois's avatar
POTTIER Francois committed
579 580 581 582
   [stacktype s] is the type of the stack at state [s]. [reducestacktype prod]
   is the type of the stack when about to reduce production [prod].
   [gotostacktype nt] is the type of the stack when the [goto]
   function associated with [nt] is called.
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

   In all cases, the tail (that is, the unknown part) of the stack is
   represented by [ttail], currently a type variable.

   These stack types are obtained by folding [celltype] over a
   description of the stack provided by module [Invariant]. *)

let stacktype s =
  Invariant.fold celltype ttail (Invariant.stack s)

let reducestacktype prod =
  Invariant.fold celltype ttail (Invariant.prodstack prod)

let gotostacktype nt =
  Invariant.fold celltype ttail (Invariant.gotostack nt)

(* The type of the [run] function. As announced earlier, if [s] is the
   target of shift transitions, the type of the stack is curried, that
   is, the top stack cell is not yet allocated, so its contents are
   passed as extra parameters. If [s] is the target of goto
   transitions, the top stack cell is allocated. If [s] is a start
   state, this issue makes no difference. *)

let runtypescheme s =
  auto2scheme (
    arrow tenv (
      curryif (runpushes s) (
        arrow (stacktype s) tresult
      )
    )
  )

(* The type of the [goto] function. The top stack cell is curried. *)

let gototypescheme nt =
  auto2scheme (arrow tenv (curry (arrow (gotostacktype nt) tresult)))

(* If [prod] is an epsilon production and if the [goto] function
   associated with it expects a state parameter, then the [reduce]
   function associated with [prod] also requires a state parameter. *)

let reduce_expects_state_param prod =
  let nt = Production.nt prod in
POTTIER Francois's avatar
POTTIER Francois committed
626
  Production.length prod = 0 &&
627 628 629 630 631 632 633 634 635 636
  Invariant.fold (fun _ holds_state _ _ -> holds_state) false (Invariant.gotostack nt)

(* The type of the [reduce] function. If shiftreduce optimization
   is performed for this production, then the top stack cell is
   not explicitly allocated. *)

let reducetypescheme prod =
  auto2scheme (
    arrow tenv (
      curryif (shiftreduce prod) (
637 638 639
        arrow (reducestacktype prod) (
          arrowif (reduce_expects_state_param prod) tstate tresult
        )
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
      )
    )
  )

(* The type of the [errorcase] function. The shape of the stack is
   unknown, and is determined by examining the state parameter. *)

let errorcasetypescheme =
  auto2scheme (marrow [ tenv; ttail; tstate ] tresult)

(* The type of the [error] function. The shape of the stack is the
   one associated with state [s]. *)

let errortypescheme s =
  auto2scheme ( marrow [ tenv; stacktype s ] tresult)

(* ------------------------------------------------------------------------ *)
(* Code production preliminaries. *)

(* This flag will be set to [true] if we ever raise the [Error]
   exception. This happens when we unwind the entire stack without
   finding a state that can handle errors. *)

let can_die =
  ref false

POTTIER Francois's avatar
POTTIER Francois committed
666 667 668 669 670 671
(* A code pattern for an exception handling construct where both alternatives
   are in tail position. Concrete syntax in OCaml 4.02 is [match e with x ->
   e1 | exception Error -> e2]. Earlier versions of OCaml do not support this
   construct. We continue to emulate it using a combination of [try/with],
   [match/with], and an [option] value. It is used only in a very rare case
   anyway. *)
672 673 674 675 676 677 678 679 680 681 682 683 684 685

let letunless e x e1 e2 =
  EMatch (
    ETry (
      EData ("Some", [ e ]),
      [ { branchpat = PData (excdef.excname, []); branchbody = EData ("None", []) } ]
    ),
    [ { branchpat = PData ("Some", [ PVar x ]); branchbody = e1 };
      { branchpat = PData ("None", []); branchbody = e2 } ]
  )

(* ------------------------------------------------------------------------ *)
(* Calling conventions. *)

686 687 688 689 690 691 692 693 694
(* The layout of a stack cell is determined here. The first field in a stack
   cell is always a pointer to the rest of the stack; it is followed by the
   fields listed below, each of which may or may not appear. [runpushcell] and
   [gotopushcell] are the two places where stack cells are allocated. *)

(* 2015/11/04. We make [endp] the first element in the list of optional fields,
   so we are able to access it at a fixed offset, provided we know that it
   exists. This is exploited when reducing an epsilon production. *)

POTTIER Francois's avatar
POTTIER Francois committed
695 696 697
(* The contents of a stack cell, exposed as individual parameters. The choice of
   identifiers is suitable for use in the definition of [run]. *)

698
let runcellparams var holds_state symbol =
699
  elementif (Invariant.endp symbol) (var endp) @
700
  elementif holds_state (var state) @
701
  symval symbol (var semv) @
702
  elementif (Invariant.startp symbol) (var startp)
703 704 705 706 707 708 709 710 711 712

(* The contents of a stack cell, exposed as individual parameters, again.
   The choice of identifiers is suitable for use in the definition of a
   [reduce] function.

   [prod] is the production's index. The integer [i] tells which
   symbol on the right-hand side we are focusing on, that is, which
   symbol this stack cell is associated with. *)

let reducecellparams prod i holds_state symbol =
713
  let ids = Production.identifiers prod in
714

715 716 717 718 719 720 721 722
  (* The semantic value is bound to the variable [ids.(i)]. Its type is [t]. As
     of 2016/03/11, we generate a type annotation. Indeed, because of our use of
     [magic], the semantic value would otherwise have an unknown type; and, if
     it is a function, the OCaml compiler could warn (incorrectly) that this
     function does not use its argument. *)

  let semvpat t =
    PAnnot (PVar ids.(i), t)
723 724
  in

725
  elementif (Invariant.endp symbol) (PVar (Printf.sprintf "_endpos_%s_" ids.(i))) @
726
  elementif holds_state (if i = 0 then PVar state else PWildcard) @
727
  symvalt symbol semvpat @
728
  elementif (Invariant.startp symbol) (PVar (Printf.sprintf "_startpos_%s_" ids.(i)))
729 730 731 732 733 734 735 736 737

(* The contents of a stack cell, exposed as individual parameters,
   again. The choice of identifiers is suitable for use in the
   definition of [error]. *)

let errorcellparams (i, pat) holds_state symbol _ =
  i + 1,
  ptuple (
    pat ::
738
    elementif (Invariant.endp symbol) PWildcard @
739
    elementif holds_state (if i = 0 then PVar state else PWildcard) @
740
    symval symbol PWildcard @
741
    elementif (Invariant.startp symbol) PWildcard
742 743 744 745 746 747 748
  )

(* Calls to [run]. *)

let runparams magic var s =
  var env ::
  magic (var stack) ::
749
  listif (runpushes s) (Invariant.fold_top (runcellparams var) [] (Invariant.stack s))
750 751 752 753 754 755 756 757 758 759 760 761 762

let call_run s actuals =
  EApp (EVar (run s), actuals)

(* The parameters to [reduce]. When shiftreduce optimization is in
   effect, the top stack cell is not allocated, so extra parameters
   are required. Note that [shiftreduce prod] and
   [reduce_expects_state_param prod] are mutually exclusive
   conditions, so the [state] parameter is never bound twice. *)

let reduceparams prod =
  PVar env ::
  PVar stack ::
763
  listif (shiftreduce prod) (
764 765 766 767
    Invariant.fold_top
      (reducecellparams prod (Production.length prod - 1))
    [] (Invariant.prodstack prod)
  ) @
768
  elementif (reduce_expects_state_param prod) (PVar state)
769 770 771 772 773 774 775 776

(* Calls to [reduce]. One must specify the production [prod] as well
   as the current state [s]. *)

let call_reduce prod s =
  let actuals =
    (EVar env) ::
    (EMagic (EVar stack)) ::
777
    listif (shiftreduce prod)
778 779
      (Invariant.fold_top (runcellparams var) [] (Invariant.stack s))
      (* compare with [runpushcell s] *) @
780
    elementif (reduce_expects_state_param prod) (estatecon s)
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
  in
  EApp (EVar (reduce prod), actuals)

(* Calls to [goto]. *)

let gotoparams var nt =
  var env ::
  var stack ::
  Invariant.fold_top (runcellparams var) [] (Invariant.gotostack nt)

let call_goto nt =
  EApp (EVar (goto nt), gotoparams var nt)

(* Calls to [errorcase]. *)

let errorcaseparams magic var =
  [ var env; magic (var stack); var state ]

let call_errorcase =
  EApp (EVar errorcase, errorcaseparams magic var)

(* Calls to [error]. *)

let errorparams magic var =
  [ var env; magic (var stack) ]

let call_error magic s =
  EApp (EVar (error s), errorparams magic var)

let call_error_via_errorcase magic s = (* TEMPORARY document *)
  if Invariant.represented s then
    EApp (EVar errorcase, [ var env; magic (var stack); estatecon s ])
  else
    call_error magic s

(* Calls to [assertfalse]. *)

let call_assertfalse =
  EApp (EVar assertfalse, [ EVar "()" ])

(* ------------------------------------------------------------------------ *)
(* Code production for the automaton functions. *)

824
(* Count how many states actually can peek at an error token. This
825 826 827 828 829 830 831 832 833 834
   figure is, in general, inferior or equal to the number of states at
   which [Invariant.errorpeeker] is true, because some of these states
   have a default reduction and will not consult the lookahead
   token. *)

let errorpeekers =
  ref 0

(* Code for calling the reduction function for token [prod] upon
   finding a token within [toks]. This produces a branch, to be
835
   inserted in a [run] function for state [s]. *)
836 837 838 839 840 841 842

let reducebranch toks prod s =
  {
    branchpat =
      tokspat toks;
    branchbody =
      call_reduce prod s
POTTIER Francois's avatar
POTTIER Francois committed
843
  }
844 845

(* Code for shifting from state [s] to state [s'] via the token [tok].
846
   This produces a branch, to be inserted in a [run] function for
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
   state [s].

   The callee, [run s'], is responsible for taking the current token
   off the input stream. (There is actually a case where the token is
   *not* taken off the stream: when [s'] has a default reduction on
   [#].)

   It is also responsible for pushing a new stack cell. The rationale
   behind this decision is that there may be multiple shift
   transitions into [s'], so we actually share that code by placing it
   inside [run s'] rather than inside every transition. *)

let shiftbranchbody s tok s' =

  (* Construct the actual parameters for [run s']. *)

  let actuals =
    (EVar env) ::
    (EMagic (EVar stack)) ::
    Invariant.fold_top (fun holds_state symbol ->
      assert (Symbol.equal (Symbol.T tok) symbol);
868
      elementif (Invariant.endp symbol) getendp @
869
      elementif holds_state (estatecon s) @
870
      tokval tok (EVar semv) @
871
      elementif (Invariant.startp symbol) getstartp
872 873 874 875 876 877 878 879 880 881 882 883 884
    ) [] (Invariant.stack s')
  in

  (* Call [run s']. *)

  tracecomment
   (Printf.sprintf "Shifting (%s) to state %d" (Terminal.print tok) (Lr1.number s'))
   (call_run s' actuals)

let shiftbranch s tok s' =
  assert (not (Terminal.pseudo tok));
  {
    branchpat =
885
      PData (tokendata (Terminal.print tok), tokval tok (PVar semv));
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
    branchbody =
      shiftbranchbody s tok s'
  }

(* This generates code for pushing a new stack cell upon entering the
   [run] function for state [s]. *)

let runpushcell s e =
  if runpushes s then
    let contents = var stack :: Invariant.fold_top (runcellparams var) [] (Invariant.stack s) in
    mlet [ pvar stack ] [ etuple contents ] e
  else
    e

let runpushcellunless shiftreduce s e =
  if shiftreduce then
    EComment ("Not allocating top stack cell", e)
  else
    runpushcell s e

(* This generates code for dealing with the lookahead token upon
   entering the [run] function for state [s]. If [s] is the target of
   a shift transition, then we must take the current token (which was
   consumed in the shift transition) off the input stream. Whether [s]
   was entered through a shift or a goto transition, we want to peek
   at the next token, unless we are performing a default reduction.
   The parameter [defred] tells which default reduction, if any, we
   are about to perform. *)

915 916 917 918 919
(* 2014/12/06 New convention regarding initial states (i.e., states
   which have no incoming symbol). The function [initenv] does not
   invoke the lexer, so the [run] function for an initial state must
   do it. (Except in the very special case where the initial state
   has a default reduction on [#] -- this means the grammar recognizes
920
   only the empty word. We have ruled out this case.) *)
921

922 923 924
let gettoken s defred e =
  match Lr1.incoming_symbol s, defred with

925
  | (Some (Symbol.T _) | None), Some (_, toks)
926 927 928 929
    when TerminalSet.mem Terminal.sharp toks ->
      assert (TerminalSet.cardinal toks = 1);

      (* There is a default reduction on token [#]. We cannot
930 931 932
         request the next token, since that might drive the
         lexer off the end of the input stream, so we cannot
         call [discard]. Do nothing. *)
933 934 935

      e

936
  | (Some (Symbol.T _) | None), Some _ ->
937 938

      (* There is some other default reduction. Discard the first
939
         input token. *)
940

941 942 943 944
      blet ([
        PVar env, EApp (EVar discard, [ EVar env ])
        (* Note that we do not read [env.token]. *)
      ], e)
945

946
  | (Some (Symbol.T _) | None), None ->
947 948

      (* There is no default reduction. Discard the first input token
949
         and peek at the next one. *)
950

951 952 953 954
      blet ([
        PVar env, EApp (EVar discard, [ EVar env ]);
        PVar token, ERecordAccess (EVar env, ftoken)
      ], e)
955

956
  | Some (Symbol.N _), Some _ ->
957 958

      (* There is some default reduction. Do not peek at the input
959
         token. *)
960 961 962

      e

963
  | Some (Symbol.N _), None ->
964 965

      (* There is no default reduction. Peek at the first input token,
966 967 968
         without taking it off the input stream. This is normally done
         by reading [env.token], unless the token might be [error]:
         then, we check [env.error] first. *)
969 970

      if Invariant.errorpeeker s then begin
971 972 973 974 975
        incr errorpeekers;
        EIfThenElse (
          ERecordAccess (EVar env, ferror),
          tracecomment "Resuming error handling" (call_error_via_errorcase magic s),
          blet ([ PVar token, ERecordAccess (EVar env, ftoken) ], e)
976 977 978
        )
      end
      else
979 980
        blet ([ assertnoerror;
                PVar token, ERecordAccess (EVar env, ftoken) ], e)
981

982
(* This produces the header of a [run] function. *)
983

984
let runheader s body =
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
  let body =
    tracecomment (Printf.sprintf "State %d:" (Lr1.number s)) body
  in {
    valpublic = false;
    valpat = PVar (run s);
    valval = EAnnot (EFun (runparams nomagic pvar s, body), runtypescheme s)
  }

(* This produces the comment attached with a default reduction. *)

let defaultreductioncomment toks e =
  EPatComment (
    "Reducing without looking ahead at ",
    tokspat toks,
    e
  )

1002 1003 1004 1005 1006 1007
(* This produces some bookkeeping code that is used when initiating error
   handling. We set the flag [env.error]. By convention, the field [env.token]
   becomes meaningless and one considers that the first token on the input
   stream is [error]. As a result, the next peek at the lookahead token will
   cause error handling to be resumed. The next call to [discard] will take
   the [error] token off the input stream and clear [env.error]. *)
1008

1009 1010 1011 1012
(* It seems convenient for [env.error] to be a mutable field, as this allows
   us to generate compact code. Re-allocating the whole record would produce
   less compact code. And speed is not an issue in this error-handling code. *)

1013 1014 1015 1016
let errorbookkeeping e =
  tracecomment
    "Initiating error handling"
    (blet (
POTTIER Francois's avatar
POTTIER Francois committed
1017
      [ PUnit, ERecordWrite (EVar env, ferror, etrue) ],
1018 1019 1020 1021
      e
    ))

(* This code is used to indicate that a new error has been detected in
1022
   state [s].
1023

POTTIER Francois's avatar
POTTIER Francois committed
1024 1025 1026 1027 1028 1029
   If I am correct, [env.error] is never set here. Indeed, that would mean
   that we first found an error, and then signaled another error before
   being able to shift the first error token. My understanding is that this
   cannot happen: when the first error is signaled, we end up at a state
   that is willing to handle the error token, by a series of reductions
   followed by a shift.
1030

POTTIER Francois's avatar
POTTIER Francois committed
1031 1032 1033
   We initiate error handling by first performing the standard bookkeeping
   described above, then transferring control to the [error] function
   associated with [s]. *)
1034

1035
let initiate s =
1036 1037

  blet (
1038
    [ assertnoerror ],
1039
    errorbookkeeping (call_error_via_errorcase magic s)
1040 1041
  )

1042
(* This produces the body of the [run] function for state [s]. *)
1043

1044
let rundef s : valdef =
1045

1046
  match Default.has_default_reduction s with
1047 1048
  | Some (prod, toks) as defred ->

1049
      (* Perform reduction without looking ahead.
1050

1051
         If shiftreduce optimization is being performed, then no
1052 1053 1054
         stack cell is allocated. The contents of the top stack
         cell are passed do [reduce] as extra parameters. *)

POTTIER Francois's avatar
POTTIER Francois committed
1055 1056 1057 1058 1059 1060 1061 1062 1063
      runheader s (
        runpushcellunless (shiftreduce prod) s (
          gettoken s defred (
            defaultreductioncomment toks (
              call_reduce prod s
            )
          )
        )
      )
1064 1065 1066 1067

  | None ->

      (* If this state is willing to act on the error token, ignore
1068
         that -- this is taken care of elsewhere. *)
1069 1070

      let transitions =
1071
        SymbolMap.remove (Symbol.T Terminal.error) (Lr1.transitions s)
1072
      and reductions =
1073
        TerminalMap.remove Terminal.error (Lr1.reductions s)
1074 1075 1076
      in

      (* Construct the main case analysis that determines what action
1077
         should be taken next.
1078

1079 1080 1081
         A default branch, where an error is detected, is added if the
         analysis is not exhaustive. In the default branch, we
         initiate error handling. *)
1082 1083

      let covered, branches =
1084 1085 1086 1087 1088
        ProductionMap.fold (fun prod toks (covered, branches) ->
          (* There is a reduction for these tokens. *)
          TerminalSet.union toks covered,
          reducebranch toks prod s :: branches
        ) (Lr1.invert reductions) (TerminalSet.empty, [])
1089 1090 1091
      in

      let covered, branches =
1092 1093 1094 1095 1096 1097 1098 1099 1100
        SymbolMap.fold (fun symbol s' (covered, branches) ->
          match symbol with
          | Symbol.T tok ->
              (* There is a shift transition for this token. *)
              TerminalSet.add tok covered,
              shiftbranch s tok s' :: branches
          | Symbol.N _ ->
              covered, branches
        ) transitions (covered, branches)
1101 1102 1103
      in

      let branches =
1104 1105 1106 1107
        if TerminalSet.subset TerminalSet.universe covered then
          branches
        else
          branches @ [ { branchpat = PWildcard; branchbody = initiate s } ]
1108 1109
      in

POTTIER Francois's avatar
POTTIER Francois committed
1110 1111 1112 1113 1114
      (* Finally, construct the code for [run]. The former pushes things
         onto the stack, obtains the lookahead token, then performs the main
         case analysis on the lookahead token. *)

      runheader s (
1115 1116
        runpushcell s (
          gettoken s None (
POTTIER Francois's avatar
POTTIER Francois committed
1117 1118 1119 1120
            EMatch (
              EVar token,
              branches
            )
1121 1122
          )
        )
POTTIER Francois's avatar
POTTIER Francois committed
1123
      )
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150

(* This is the body of the [reduce] function associated with
   production [prod]. *)

let reducebody prod =

  (* Find out about the left-hand side of this production and about
     the identifiers that have been bound to the symbols in the
     right-hand side. These represent variables that we should bind to
     semantic values before invoking the semantic action. *)

  let nt, rhs = Production.def prod
  and ids = Production.identifiers prod
  and length = Production.length prod in

  (* Build a pattern that represents the shape of the stack. Out of
     the stack, we extract a state (except when the production is an
     epsilon production) and a number of semantic values.

     If shiftreduce optimization is being performed, then the top
     stack cell is not explicitly allocated, so we do not include
     it in the pattern that is built. *)

  let (_ : int), pat =
    Invariant.fold (fun (i, pat) holds_state symbol _ ->
      i + 1,
      if i = length - 1 && shiftreduce prod then
1151
        pat
1152
      else
1153
        ptuple (pat :: reducecellparams prod i holds_state symbol)
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    ) (0, PVar stack) (Invariant.prodstack prod)
  in

  (* If any identifiers refer to terminal symbols without a semantic
     value, then bind these identifiers to the unit value. This
     provides the illusion that every symbol, terminal or nonterminal,
     has a semantic value. This is more regular and allows applying
     operators such as ? to terminal symbols without a semantic
     value. *)

  let unitbindings =
    Misc.foldi length (fun i unitbindings ->
1166 1167
      match semvtype rhs.(i) with
      | [] ->
1168
          (PVar ids.(i), EUnit) :: unitbindings
1169
      | _ ->
1170
          unitbindings
1171 1172 1173 1174 1175 1176
    ) []
  in

  (* If necessary, determine start and end positions for the left-hand
     side of the production. If the right-hand side is nonempty, this
     is done by extracting position information out of the first and
1177 1178 1179 1180 1181 1182 1183 1184
     last symbols of the right-hand side. If it is empty, then (as of
     2015/11/04) this is done by taking the end position stored in the
     top stack cell (whatever it is). The constraints imposed by the
     module [Invariant], the layout of cells, and our creation of a
     sentinel cell (see [entrydef] further on), ensure that this cell
     exists and has an [endp] field at offset 1. Yes, we live
     dangerously. You only live once. *)

POTTIER Francois's avatar
POTTIER Francois committed
1185 1186 1187 1188 1189
  let extract x =
    (* Extract the end position (i.e., the field at offset 1) in the top
       stack cell and bind it to the variable [x]. *)
    PTuple [ PWildcard; PVar x ],
    EMagic (EVar stack)
1190 1191
  in

POTTIER Francois's avatar
POTTIER Francois committed
1192 1193
  let symbol = Symbol.N nt in

1194
  let posbindings action =
1195 1196
    let bind_startp = Invariant.startp symbol in
    elementif (Action.has_beforeend action)
POTTIER Francois's avatar
POTTIER Francois committed
1197
      ( extract beforeendp
1198
      ) @
1199
    elementif bind_startp
1200
      ( if length > 0 then
1201 1202
          PVar startp,
          EVar (Printf.sprintf "_startpos_%s_" ids.(0))
1203
        else
POTTIER Francois's avatar
POTTIER Francois committed
1204
          extract startp
1205
      ) @
1206
    elementif (Invariant.endp symbol)
1207
      ( if length > 0 then
1208 1209
          PVar endp,
          EVar (Printf.sprintf "_endpos_%s_" ids.(length - 1))
1210 1211
        else if bind_startp then
          PVar endp,
1212
          EVar startp
1213
        else
POTTIER Francois's avatar
POTTIER Francois committed
1214
          extract endp
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
      )
  in

  (* If this production is one of the start productions, then reducing
     it means accepting the input. In that case, we return a final
     semantic value and stop. Otherwise, we transfer control to the
     [goto] function, unless the semantic action raises [Error], in
     which case we transfer control to [errorcase]. *)

  if Production.is_start prod then

      tracecomment
        "Accepting"
        (blet (
1229 1230 1231
          [ pat, EVar stack ],
          EMagic (EVar ids.(0))
        ))
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244

  else

    let action =
      Production.action prod
    in
    let act =
      EAnnot (Action.to_il_expr action, type2scheme (semvtypent nt))
    in

    tracecomment
      (Printf.sprintf "Reducing production %s" (Production.print prod))
      (blet (
1245 1246 1247
        (pat, EVar stack) ::
        unitbindings @
        posbindings action,
1248

1249 1250
        (* If the semantic action is susceptible of raising [Error],
           use a [let/unless] construct, otherwise use [let]. *)
1251

1252 1253 1254 1255
        if Action.has_syntaxerror action then
          letunless act semv (call_goto nt) (errorbookkeeping call_errorcase)
        else
          blet ([ PVar semv, act ], call_goto nt)
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
      ))

(* This is the definition of the [reduce] function associated with
   production [prod]. *)

let reducedef prod =
  {
    valpublic =
      false;
    valpat =
      PVar (reduce prod);
    valval =
      EAnnot (
        EFun (
          reduceparams prod,
          reducebody prod
        ),
        reducetypescheme prod
      )
  }

(* This generates code for pushing a new stack cell inside [goto]. *)

let gotopushcell nt e =
  if gotopushes nt then
    let contents = var stack :: Invariant.fold_top (runcellparams var) [] (Invariant.gotostack nt) in
    mlet [ pvar stack ] [ etuple contents ] e
  else
    e

(* This is the heart of the [goto] function associated with
   nonterminal [nt]. *)

let gotobody nt =

  (* Examine the current state to determine where to go next. *)

  let branches =
    Lr1.targets (fun branches sources target ->
      {
1296 1297 1298 1299
        branchpat =
          pstatescon sources;
        branchbody =
          call_run target (runparams magic var target)
1300 1301 1302 1303 1304 1305 1306 1307
      } :: branches
    ) [] (Symbol.N nt)
  in

  match branches with
  | [] ->

      (* If there are no branches, then this [goto] function is never
1308 1309
         invoked. The inliner will drop it, so whatever we generate
         here is unimportant. *)
1310 1311 1312 1313 1314

      call_assertfalse

  | [ branch ] ->

POTTIER Francois's avatar
POTTIER Francois committed
1315
      (* If there is only one branch, no case analysis is required. This
1316 1317 1318 1319
         optimization is not strictly necessary if GADTs are used by the
         compiler to prove that the case analysis is exhaustive. It does
         improve readability, though, and is also useful if the compiler
         does not have GADTs. *)
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329

      EPatComment (
        "State should be ",
        branch.branchpat,
        branch.branchbody
      )

  | _ ->

      (* In the general case, we keep the branches computed above and,
1330 1331 1332
         unless [nt] is universal, add a default branch, which is
         theoretically useless but helps avoid warnings if the
         compiler does not have GADTs. *)
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

      let default = {
        branchpat = PWildcard;
        branchbody = call_assertfalse
      } in
      EMatch (
        EVar state,
        branches @ (if Invariant.universal (Symbol.N nt) then [] else [ default ])
      )

(* This the [goto] function associated with nonterminal [nt]. *)

let gotodef nt = {
  valpublic =
    false;
  valpat =
    PVar (goto nt);
POTTIER Francois's avatar
POTTIER Francois committed
1350
  valval =
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    EAnnot (EFun (gotoparams pvar nt, gotopushcell nt (gotobody nt)), gototypescheme nt)
}

(* ------------------------------------------------------------------------ *)
(* Code production for the error handling functions. *)

(* This is the body of the [error] function associated with state [s]. *)

let handle s e =
  tracecomment (Printf.sprintf "Handling error in state %d" (Lr1.number s)) e

let errorbody s =
  try
    let s' = SymbolMap.find (Symbol.T Terminal.error) (Lr1.transitions s) in

    (* There is a shift transition on error. *)

    handle s (
      shiftbranchbody s Terminal.error s'
    )

  with Not_found ->
    try
      let prods = TerminalMap.lookup Terminal.error (Lr1.reductions s) in
      let prod = Misc.single prods in

      (* There is a reduce transition on error. If shiftreduce
1378 1379
         optimization is enabled for this production, then we must pop
         an extra cell for [reduce]'s calling convention to be met. *)
1380 1381

      let extrapop e =
1382 1383 1384 1385 1386 1387 1388
        if shiftreduce prod then
          let pat =
            ptuple (PVar stack :: Invariant.fold_top (runcellparams pvar) [] (Invariant.stack s))
          in
          blet ([ pat, EVar stack ], e)
        else
          e
1389
      in
POTTIER Francois's avatar
POTTIER Francois committed
1390

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
      handle s (
        extrapop (
          call_reduce prod s
        )
      )

    with Not_found ->

      (* This state is unable to handle errors. Pop the stack to find
         a state that does handle errors, a state that can further pop
1401
         the stack, or die. *)
1402 1403 1404

      match Invariant.rewind s with
      | Invariant.Die ->
1405
          can_die := true;
1406 1407
          ERaise errorval
      | Invariant.DownTo (w, st) ->
1408 1409 1410 1411 1412 1413 1414 1415
          let _, pat = Invariant.fold errorcellparams (0, PVar stack) w in
          blet (
            [ pat, EVar stack ],
            match st with
            | Invariant.Represented ->
                call_errorcase
            | Invariant.UnRepresented s ->
                call_error magic s
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
          )

(* This is the [error] function associated with state [s]. *)

let errordef s = {
  valpublic =
    false;
  valpat =
    PVar (error s);
  valval =
    EAnnot (
      EFun (
        errorparams nomagic pvar,
        errorbody s
      ),
      errortypescheme s
    )
}

(* This is the [errorcase] function. It examines its state parameter
   and dispatches control to an appropriate [error] function. *)

let errorcasedef =
  let branches =
    Lr1.fold (fun branches s ->
      if Invariant.represented s then
1442 1443 1444
        {
          branchpat  = pstatecon s;
          branchbody = EApp (EVar (error s), [ EVar env; EMagic (EVar stack) ])
1445 1446
        } :: branches
      else
1447
        branches
1448 1449 1450 1451 1452 1453 1454 1455 1456
    ) []
  in
  {
    valpublic =
      false;
    valpat =
      PVar errorcase;
    valval =
      EAnnot (
1457 1458 1459 1460 1461 1462 1463 1464
        EFun (
          errorcaseparams nomagic pvar,
          EMatch (
            EVar state,
            branches
          )
        ),
        errorcasetypescheme
1465 1466 1467 1468 1469 1470
      )
  }

(* ------------------------------------------------------------------------ *)
(* Code production for the entry points. *)

POTTIER Francois's avatar
POTTIER Francois committed
1471 1472 1473
(* This is the entry point associated with a start state [s]. By convention,
   it is named after the nonterminal [nt] that corresponds to this state.
   This is a public definition.
1474

POTTIER Francois's avatar
POTTIER Francois committed
1475
   The code initializes a parser environment, an empty stack, and invokes
POTTIER Francois's avatar
POTTIER Francois committed
1476 1477
   [run].

1478 1479 1480 1481 1482
   2015/11/11. If the state [s] can reduce an epsilon production whose left-hand
   symbol keeps track of its start or end position, or if [s] can reduce any
   production that mentions [$endpos($0)], then the initial stack should contain
   a sentinel cell with a valid [endp] field at offset 1. For simplicity, we
   always create a sentinel cell. *)
1483

POTTIER Francois's avatar
POTTIER Francois committed
1484
let entrydef s =
1485 1486 1487
  let nt = Item.startnt (Lr1.start2item s) in
  let lexer = "lexer"
  and lexbuf = "lexbuf" in
1488 1489

  let initial_stack =
1490 1491
    let initial_position = getendp in
    etuple [ EUnit; initial_position ]
1492 1493
  in

1494 1495 1496 1497 1498
  {
    valpublic = true;
    valpat = PVar (Nonterminal.print true nt);
    valval = EAnnot (
               EFun ( [ PVar lexer; PVar lexbuf ],
1499 1500 1501 1502 1503
                 blet (
                   [ PVar env, EApp (EVar initenv, [ EVar lexer; EVar lexbuf ]) ],
                   EMagic (EApp (EVar (run s), [ EVar env; initial_stack ]))
                 )
               ),
1504
               entrytypescheme Front.grammar (Nonterminal.print true nt)
1505
             )
POTTIER Francois's avatar
POTTIER Francois committed
1506
  }
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516

(* ------------------------------------------------------------------------ *)
(* Code production for auxiliary functions. *)

(* This is [assertfalse], used when internal failure is detected.
   This should never happen if our tool is correct. *)

let assertfalsedef = {
  valpublic = false;
  valpat = PVar assertfalse;
POTTIER Francois's avatar
POTTIER Francois committed
1517
  valval =
1518 1519
    EAnnot (
      EFun ([ PUnit ],
1520 1521
        blet ([
            PUnit, EApp (EVar "Printf.fprintf",
1522
                       [ EVar "stderr";
1523 1524 1525 1526
                         EStringConst "Internal failure -- please contact the parser generator's developers.\n%!" ]);
          ],
          EApp (EVar "assert", [ efalse ])
        )
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
      ),
      scheme [ "a" ] (arrow tunit (tvar "a"))
    )
}

(* This is [print_token], used to print tokens in [--trace] mode. *)

let printtokendef =
  destructuretokendef
    print_token
    tstring
    false
    (fun tok -> EStringConst (Terminal.print tok))

(* This is [discard], used to take a token off the input stream and
   query the lexer for a new one. The code queries the lexer for a new
   token and stores it into [env.token], overwriting the previous
   token. It also stores the start and positions of the new token.
1545
   Last, [env.error] is cleared.
1546 1547 1548 1549 1550 1551 1552

   We use the lexer's [lex_start_p] and [lex_curr_p] fields to extract
   the start and end positions of the token that we just read. In
   practice, it seems that [lex_start_p] can be inaccurate (that is
   the case when the lexer calls itself recursively, instead of simply
   recognizing an atomic pattern and returning immediately). However,
   we are 100% compatible with ocamlyacc here, and there is no better
1553 1554 1555 1556 1557 1558 1559 1560
   solution anyway.

   As of 2014/12/12, we re-allocate the environment record instead of
   updating it. Perhaps surprisingly, this makes the code TWICE FASTER
   overall. The write barrier is really costly! *)

let discardbody =
  let lexer = "lexer"
1561
  and lexbuf = "lexbuf" in
1562 1563 1564 1565 1566 1567 1568 1569 1570
  EFun (
    [ PVar env ],
    blet ([</