codeBackend.ml 51.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
(* 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
22 23 24 25 26 27
   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.
28 29 30 31 32 33 34 35

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

36 37 38 39 40 41 42 43
   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.)
44

POTTIER Francois's avatar
POTTIER Francois committed
45 46 47 48 49 50 51
   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).
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

   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 *)

(* ------------------------------------------------------------------------ *)
108
(* Here is a description of our error handling mechanism.
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

   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.)

124 125 126 127 128 129
   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.
130 131

   Whenever we attempt to consult the current token, we check whether
132
   [env.error] is set and, if that is the case, resume error handling
133 134 135
   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
136 137
   to statically prove that [env.error] cannot be set. In that case,
   we produce a lookup of [env.token] without checking [env.error].
138

139
   The flag [env.error] is cleared when a token is shifted.
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

   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
155
   reduction must in fact have a reduction action on [error]. *)
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

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

245 246
let ferror =
  prefix "error"
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

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

279
(* The following assertion checks that [env.error] is [false]. *)
280

281
let assertnoerror : pattern * expr =
282
  PUnit,
283
  EApp (EVar "assert", [ EApp (EVar "not", [ ERecordAccess (EVar env, ferror) ]) ])
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

let etuple = function
  | [] ->
      assert false
  | [ e ] ->
      e
  | es ->
      ETuple es

let ptuple = function
  | [] ->
      assert false
  | [ p ] ->
      p
  | ps ->
      PTuple ps

let trace (format : string) (args : expr list) : (pattern * expr) list =
  if Settings.trace then
    [ PUnit, EApp (EVar "Printf.fprintf", (EVar "Pervasives.stderr") :: (EStringConst (format ^"\n%!")) :: args) ]
  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

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
(* ------------------------------------------------------------------------ *)
(* 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")

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
(* ------------------------------------------------------------------------ *)
(* 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 ->
	accu &&
	match Invariant.has_default_reduction target with
	| Some (prod, _) ->
	    Production.length prod > 0
	| None -> false
      ) 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. *)

    Invariant.fold_reduced (fun s accu ->
      accu && (match Invariant.has_default_reduction s with None -> false | Some _ -> true)
           && (runpushes s)
    ) prod true

  )

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
	true
      else
	Lr1.targets (fun accu _ target ->
	  accu &&
	  match Invariant.has_default_reduction target with
	  | Some (prod, _) ->
	      shiftreduce prod
	  | None ->
	      false
        ) 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 (
		     Lr1.fold (fun defs s ->
		       if Invariant.represented s then {
			 dataname =       statecon s;
			 datavalparams =  [];
			 datatypeparams = None
		       } :: defs
		       else defs
		     ) []
                   );
  typeconstraint = None
}

495 496 497 498 499
(* The type of lexers. *)

let tlexer =
  TypArrow (tlexbuf, ttoken)

500 501 502 503 504 505 506 507 508 509 510 511 512
(* 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 =
513
    TDefRecord [
514 515 516 517 518 519 520 521 522 523

      (* 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
524
	 head of the token stream, unless [env.error] is set. *)
525

526
      field false ftoken ttoken;
527

528 529
      (* A flag which tells whether we currently have an [error] token
         at the head of the stream. When this flag is set, the head
530 531 532 533
	 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. *)

534
      field true ferror tbool;
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
  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

(* Types for stack cells. 

   [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 ::
574
    elementif holds_state tstate @
575
    semvtype symbol @
576 577
    elementif (Invariant.startp symbol) tposition @
    elementif (Invariant.endp symbol) tposition
578 579 580 581
  )

(* Types for stacks. 

POTTIER Francois's avatar
POTTIER Francois committed
582 583 584 585
   [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.
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

   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
  Production.length prod = 0 && 
  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) (
	arrow (reducestacktype prod) (
	  arrowif (reduce_expects_state_param prod) tstate tresult
	)
      )
    )
  )

(* 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
669 670 671 672 673 674
(* 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. *)
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693

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. *)

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

let runcellparams var holds_state symbol =
694
  elementif holds_state (var state) @
695
  symval symbol (var semv) @
696 697
  elementif (Invariant.startp symbol) (var startp) @
  elementif (Invariant.endp symbol) (var endp)
698 699 700 701 702 703 704 705 706 707

(* 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 =
708
  let ids = Production.identifiers prod in
709

710
  (* The semantic value is bound to the variable [ids.(i)]. *)
711

712
  let semvpat _t =
713
    PVar ids.(i)
714 715
  in

716
  elementif holds_state (if i = 0 then PVar state else PWildcard) @
717
  symvalt symbol semvpat @
718 719
  elementif (Invariant.startp symbol) (PVar (Printf.sprintf "_startpos_%s_" ids.(i))) @
  elementif (Invariant.endp symbol) (PVar (Printf.sprintf "_endpos_%s_" ids.(i)))
720 721 722 723 724 725 726 727 728

(* 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 ::
729
    elementif holds_state (if i = 0 then PVar state else PWildcard) @
730
    symval symbol PWildcard @
731 732
    elementif (Invariant.startp symbol) PWildcard @
    elementif (Invariant.endp symbol) PWildcard
733 734 735 736 737 738 739
  )

(* Calls to [run]. *)

let runparams magic var s =
  var env ::
  magic (var stack) ::
740
  listif (runpushes s) (Invariant.fold_top (runcellparams var) [] (Invariant.stack s))
741 742 743 744 745 746 747 748 749 750 751 752 753

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 ::
754
  listif (shiftreduce prod) (
755 756 757 758
    Invariant.fold_top
      (reducecellparams prod (Production.length prod - 1))
    [] (Invariant.prodstack prod)
  ) @
759
  elementif (reduce_expects_state_param prod) (PVar state)
760 761 762 763 764 765 766 767

(* 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)) ::
768
    listif (shiftreduce prod)
769 770
      (Invariant.fold_top (runcellparams var) [] (Invariant.stack s))
      (* compare with [runpushcell s] *) @
771
    elementif (reduce_expects_state_param prod) (estatecon s)
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
  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. *)

815
(* Count how many states actually can peek at an error token. This
816 817 818 819 820 821 822 823 824 825
   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
826
   inserted in a [run] function for state [s]. *)
827 828 829 830 831 832 833 834 835 836

let reducebranch toks prod s =
  {
    branchpat =
      tokspat toks;
    branchbody =
      call_reduce prod s
  } 

(* Code for shifting from state [s] to state [s'] via the token [tok].
837
   This produces a branch, to be inserted in a [run] function for
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
   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);
859
      elementif holds_state (estatecon s) @
860
      tokval tok (EVar semv) @
861 862
      elementif (Invariant.startp symbol) getstartp @
      elementif (Invariant.endp symbol) getendp
863 864 865 866 867 868 869 870 871 872 873 874 875
    ) [] (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 =
876
      PData (tokendata (Terminal.print tok), tokval tok (PVar semv));
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
    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. *)

906 907 908 909 910
(* 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
911
   only the empty word. We have ruled out this case.) *)
912

913 914 915
let gettoken s defred e =
  match Lr1.incoming_symbol s, defred with

916
  | (Some (Symbol.T _) | None), Some (_, toks)
917 918 919 920 921 922 923 924 925 926
    when TerminalSet.mem Terminal.sharp toks ->
      assert (TerminalSet.cardinal toks = 1);

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

      e

927
  | (Some (Symbol.T _) | None), Some _ ->
928 929 930 931

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

932 933 934 935
      blet ([
        PVar env, EApp (EVar discard, [ EVar env ])
        (* Note that we do not read [env.token]. *)
      ], e)
936

937
  | (Some (Symbol.T _) | None), None ->
938 939 940 941

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

942 943 944 945
      blet ([
        PVar env, EApp (EVar discard, [ EVar env ]);
        PVar token, ERecordAccess (EVar env, ftoken)
      ], e)
946

947
  | Some (Symbol.N _), Some _ ->
948 949 950 951 952 953

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

      e

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

      (* There is no default reduction. Peek at the first input token,
	 without taking it off the input stream. This is normally done
	 by reading [env.token], unless the token might be [error]:
959
	 then, we check [env.error] first. *)
960 961 962 963

      if Invariant.errorpeeker s then begin
	incr errorpeekers;
	EIfThenElse (
964
	  ERecordAccess (EVar env, ferror),
965 966 967 968 969
	  tracecomment "Resuming error handling" (call_error_via_errorcase magic s),
	  blet ([ PVar token, ERecordAccess (EVar env, ftoken) ], e)
        )
      end
      else
970
	blet ([ assertnoerror;
971 972
		PVar token, ERecordAccess (EVar env, ftoken) ], e)

973
(* This produces the header of a [run] function. *)
974

975
let runheader s body =
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
  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
  )

993 994 995 996 997 998
(* 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]. *)
999

1000 1001 1002 1003
(* 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. *)

1004 1005 1006 1007
let errorbookkeeping e =
  tracecomment
    "Initiating error handling"
    (blet (
POTTIER Francois's avatar
POTTIER Francois committed
1008
      [ PUnit, ERecordWrite (EVar env, ferror, etrue) ],
1009 1010 1011 1012
      e
    ))

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

POTTIER Francois's avatar
POTTIER Francois committed
1015 1016 1017 1018 1019 1020
   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.
1021

POTTIER Francois's avatar
POTTIER Francois committed
1022 1023 1024
   We initiate error handling by first performing the standard bookkeeping
   described above, then transferring control to the [error] function
   associated with [s]. *)
1025

1026
let initiate s =
1027 1028

  blet (
1029
    [ assertnoerror ],
1030
    errorbookkeeping (call_error_via_errorcase magic s)
1031 1032
  )

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

1035
let rundef s : valdef =
1036 1037 1038 1039

  match Invariant.has_default_reduction s with
  | Some (prod, toks) as defred ->

1040
      (* Perform reduction without looking ahead.
1041 1042 1043 1044 1045

	 If shiftreduce optimization is being performed, then no
         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
1046 1047 1048 1049 1050 1051 1052 1053 1054
      runheader s (
        runpushcellunless (shiftreduce prod) s (
          gettoken s defred (
            defaultreductioncomment toks (
              call_reduce prod s
            )
          )
        )
      )
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

  | None ->

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

      let transitions =
	SymbolMap.remove (Symbol.T Terminal.error) (Lr1.transitions s)
      and reductions =
	TerminalMap.remove Terminal.error (Lr1.reductions s)
      in

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

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

      let covered, branches =
	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, [])
      in

      let covered, branches =
	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)
      in

      let branches =
	if TerminalSet.subset TerminalSet.universe covered then
	  branches
	else
1098
	  branches @ [ { branchpat = PWildcard; branchbody = initiate s } ]
1099 1100
      in

POTTIER Francois's avatar
POTTIER Francois committed
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
      (* 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 (
	runpushcell s (
	  gettoken s None (
            EMatch (
              EVar token,
              branches
            )
1112 1113
	  )
	)
POTTIER Francois's avatar
POTTIER Francois committed
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 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156

(* 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
	pat
      else
	ptuple (pat :: reducecellparams prod i holds_state symbol)
    ) (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 ->
1157 1158 1159 1160 1161
      match semvtype rhs.(i) with
      | [] ->
  	  (PVar ids.(i), EUnit) :: unitbindings
      | _ ->
	  unitbindings
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    ) []
  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
     last symbols of the right-hand side. If it is empty, then both
     positions are taken to be the current lookahead token's start
     position.

     Note that [Keyword.has_leftstart keywords] does not imply
     [Invariant.startp symbol], and similarly for end positions. *)

  let symbol =
    Symbol.N nt
  in

  let posbindings action =
    let bind_startp =
      Action.has_leftstart action || Invariant.startp symbol
    and bind_endp =
      Action.has_leftend action || Invariant.endp symbol
    in
1185
    elementif bind_startp
1186 1187 1188 1189
      ( PVar startp,
	if length > 0 then
	  EVar (Printf.sprintf "_startpos_%s_" ids.(0))
        else
1190
          getstartp
1191
      ) @
1192
    elementif bind_endp
1193 1194 1195 1196
      ( PVar endp,
	if length > 0 then
	  EVar (Printf.sprintf "_endpos_%s_" ids.(length - 1))
        else
1197
          if bind_startp then EVar startp else getstartp
1198 1199 1200 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
      )
  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 (
  	  [ pat, EVar stack ],
	  EMagic (EVar ids.(0))
	))

  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 (
	(pat, EVar stack) ::
	unitbindings @
	posbindings action @
1231
	extrabindings action,
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 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 1296 1297 1298

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

	if Action.has_syntaxerror action then
	  letunless act semv (call_goto nt) (errorbookkeeping call_errorcase)
	else
	  blet ([ PVar semv, act ], call_goto nt)
      ))

(* 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 ->
      {
	branchpat =
	  pstatescon sources;
	branchbody =
	  call_run target (runparams magic var target)
      } :: branches
    ) [] (Symbol.N nt)
  in

  match branches with
  | [] ->

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

      call_assertfalse

  | [ branch ] ->

POTTIER Francois's avatar
POTTIER Francois committed
1299 1300 1301 1302 1303
      (* If there is only one branch, no case analysis is required. This
	 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. *)
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 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 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 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 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454

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

  | _ ->

      (* In the general case, we keep the branches computed above and,
	 unless [nt] is universal, add a default branch, which is
	 theoretically useless but helps avoid warnings if the
	 compiler does not have GADTs. *)

      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);
  valval = 
    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
	 optimization is enabled for this production, then we must pop
	 an extra cell for [reduce]'s calling convention to be met. *)

      let extrapop e =
	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
      in
	
      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
	 the stack, or die. *)

      match Invariant.rewind s with
      | Invariant.Die ->
	  can_die := true;
          ERaise errorval
      | Invariant.DownTo (w, st) ->
	  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
          )

(* 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
	{
	  branchpat  = pstatecon s;
	  branchbody = EApp (EVar (error s), [ EVar env; EMagic (EVar stack) ])
        } :: branches
      else
	branches
    ) []
  in
  {
    valpublic =
      false;
    valpat =
      PVar errorcase;
    valval =
      EAnnot (
	EFun (
	  errorcaseparams nomagic pvar,
	  EMatch (
	    EVar state,
	    branches
	  )
	),
	errorcasetypescheme
      )
  }

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

POTTIER Francois's avatar
POTTIER Francois committed
1455 1456 1457
(* 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.
1458

POTTIER Francois's avatar
POTTIER Francois committed
1459 1460
   The code initializes a parser environment, an empty stack, and invokes
   [run]. *)
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475

let entrydef s = 
  let nt = Item.startnt (Lr1.start2item s) in
  let lexer = "lexer"
  and lexbuf = "lexbuf" in
  {
    valpublic = true;
    valpat = PVar (Nonterminal.print true nt);
    valval = EAnnot (
               EFun ( [ PVar lexer; PVar lexbuf ],
		 blet (
		   [ PVar env, EApp (EVar initenv, [ EVar lexer; EVar lexbuf ]) ],
		   EMagic (EApp (EVar (run s), [ EVar env; EUnit ]))
		 )
	       ),
1476
               entrytypescheme Front.grammar (Nonterminal.print true nt)
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
             )
  } 

(* ------------------------------------------------------------------------ *)
(* 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;
  valval = 
    EAnnot (
      EFun ([ PUnit ],
	blet ([
	    PUnit, EApp (EVar "Printf.fprintf",
		       [ EVar "Pervasives.stderr";
			 EStringConst "Internal failure -- please contact the parser generator's developers.\n%!" ]);
	  ],
	  EApp (EVar "assert", [ efalse ])
	)
      ),
      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.
1517
   Last, [env.error] is cleared.
1518 1519 1520 1521 1522 1523 1524

   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
1525 1526 1527 1528 1529 1530 1531 1532
   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"
1533
  and lexbuf = "lexbuf" in
1534 1535 1536 1537 1538 1539 1540 1541 1542
  EFun (
    [ PVar env ],
    blet ([
      PVar lexer, ERecordAccess (EVar env, flexer);
      PVar lexbuf, ERecordAccess (EVar env, flexbuf);
      PVar token, EApp (EVar lexer, [ EVar lexbuf ]);
    ] @
      trace "Lookahead token is now %s (%d-%d)"
            [ EApp (EVar print_token, [ EVar token ]);
1543 1544
              ERecordAccess (ERecordAccess (EVar lexbuf, "Lexing.lex_start_p"), "Lexing.pos_cnum");
              ERecordAccess (ERecordAccess (EVar lexbuf, "Lexing.lex_curr_p"), "Lexing.pos_cnum") ],
1545 1546 1547 1548 1549 1550 1551 1552
      ERecord [
        flexer, EVar lexer;
        flexbuf, EVar lexbuf;
        ftoken, EVar token;
        ferror, efalse
      ]
    )
  )
1553 1554 1555 1556 1557 1558

let discarddef = {
  valpublic = false;
  valpat = PVar discard;
  valval =
    EAnnot (
1559 1560
      discardbody,
      type2scheme (arrow tenv tenv)
1561 1562 1563 1564
    )
}

(* This is [initenv], used to allocate a fresh parser environment.
1565 1566 1567 1568
   It fills in all fields in a straightforward way. The [token]
   field receives a dummy value. It will be overwritten by the
   first call to [run], which will invoke [discard]. This allows
   us to invoke the lexer in just one place. *)
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579

let initenvdef =
  let lexer = "lexer"
  and lexbuf = "lexbuf" in
  {
    valpublic = false;
    valpat = PVar initenv;
    valval = 
      EAnnot (
	EFun ( [ PVar lexer; PVar lexbuf ],
	  blet (
1580 1581 1582
            (* We do not have a dummy token at hand, so we forge one. *)
            (* It will be overwritten by the first call to the lexer. *)
	    [ PVar token, EMagic EUnit ],
1583 1584 1585 1586
	    ERecord ([
	      (flexer, EVar lexer);
	      (flexbuf, EVar lexbuf);
	      (ftoken, EVar token);
POTTIER Francois's avatar
POTTIER Francois committed
1587
	      (ferror, efalse)
1588
	    ]
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
	    )
	  )
	),
        type2scheme (marrow [ tlexer; tlexbuf ] tenv)
      )
  } 

(* ------------------------------------------------------------------------ *)
(* Here is complete code for the parser. *)

1599 1600
open UnparameterizedSyntax

1601 1602 1603
let grammar =
  Front.grammar

1604
let program =
1605

1606
  [ SIFunctor (grammar.parameters,
1607

1608
    SIExcDefs [ excdef ] ::
1609

1610 1611
    SIValDefs (false, [ excvaldef ]) ::

1612
    interface_to_structure (
1613
      tokentypedef grammar
1614
    ) @
1615

1616
    SITypeDefs [ envtypedef; statetypedef ] ::
1617

1618 1619
    SIStretch grammar.preludes ::

1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
    SIValDefs (true,
      ProductionMap.fold (fun _ s defs ->
        entrydef s :: defs
      ) Lr1.entry (
      Lr1.fold (fun defs s ->
        rundef s :: errordef s :: defs
      ) (
      Nonterminal.foldx (fun nt defs ->
        gotodef nt :: defs
      ) (Production.fold (fun prod defs ->
        if Invariant.ever_reduced prod then
          reducedef prod :: defs
        else
          defs
      ) [ discarddef; initenvdef; printtokendef; assertfalsedef; errorcasedef ])))
1635
    ) ::
1636

1637
    SIStretch grammar.postludes ::
1638

1639
  [])]
1640 1641 1642 1643 1644 1645 1646

(* ------------------------------------------------------------------------ *)
(* We are done! *)

let () =
  Error.logC 1 (fun f ->
    Printf.fprintf f
1647 1648
       "%d out of %d states can peek at an error.\n"
       !errorpeekers Lr1.n)
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659

let () =
  if not !can_die then
    Error.logC 1 (fun f -> Printf.fprintf f 
      "The generated parser cannot raise Error.\n")

let () =
  Time.tick "Producing abstract syntax"

end