lr1.ml 43.5 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
open Grammar

(* This module constructs an LR(1) automaton by following Pager's method, that
   is, by merging states on the fly when they are weakly compatible. *)

19 20 21 22 23 24
(* ------------------------------------------------------------------------ *)
(* Run the SLR(1) check first. *)

let () =
  Slr.check()

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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
(* ------------------------------------------------------------------------ *)
(* Nodes. *)

type node = {

    (* A node number, assigned during construction. *)

    raw_number: int;

    (* A node number, assigned after conflict resolution has taken
       place and after inacessible nodes have been removed. This
       yields sequential numbers, from the client's point of view. *)

    mutable number: int;

    (* Each node is associated with a state. This state can change
       during construction as nodes are merged. *)

    mutable state: Lr0.lr1state;

    (* Each node carries information about its outgoing transitions
       and about its reductions. *)

    mutable transitions: node SymbolMap.t;
    mutable reductions: Production.index list TerminalMap.t;

    (* Tokens for which there are several possible behaviors are
       conflict tokens. *)

    mutable conflict_tokens: TerminalSet.t;

    (* Transitions are also stored in reverse, so as to allow reverse
       traversals of the automaton. *)

    mutable predecessors: node list;

    (* Transient marks are used during construction and traversal. *)

    mutable mark: Mark.t;

    (* (New as of 2012/01/23.) This flag records whether a shift/reduce
       conflict in this node was solved in favor of neither (%nonassoc).
       This is later used to forbid a default reduction at this node. *)

    mutable forbid_default_reduction: bool;

  }

module Node = struct
  type t = node
  let compare node1 node2 =
    node1.number - node2.number
end

module NodeSet =
  Set.Make (Node)

module NodeMap =
  Map.Make (Node)

(* ------------------------------------------------------------------------ *)

(* Output debugging information if [--follow-construction] is enabled. *)

let follow_transition (again : bool) (source : node) (symbol : Symbol.t) (state : Lr0.lr1state) =
  if Settings.follow then
    Printf.fprintf stderr
      "%s transition out of state r%d along symbol %s.\nProposed target state:\n%s"
      (if again then "Re-examining" else "Examining")
      source.raw_number
      (Symbol.print symbol)
96
      (Lr0.print_closure "" state)
97 98 99 100 101 102 103

let follow_state (msg : string) (node : node) (print : bool) =
  if Settings.follow then
    Printf.fprintf stderr
      "%s: r%d.\n%s\n"
      msg
      node.raw_number
104
      (if print then Lr0.print_closure "" node.state else "")
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

(* ------------------------------------------------------------------------ *)

(* The following two mutually recursive functions are invoked when the state
   associated with an existing node grows. The node's descendants are examined
   and grown into a fixpoint is reached.

   This work is performed in an eager manner: we do not attempt to build any
   new transitions until all existing nodes have been suitably grown. Indeed,
   building new transitions requires making merging decisions, and such
   decisions cannot be made on a sound basis unless all existing nodes have
   been suitably grown. Otherwise, one could run into a dead end where two
   successive, incompatible merging decisions are made, because the
   consequences of the first decision (growing descendant nodes) were not made
   explicit before the second decision was taken. This was a bug in versions
   of Menhir ante 20070520.

   Although I wrote this code independently, I later found out that it seems
   quite similar to the code in Karl Schimpf's Ph.D. thesis (1981), page 35.

   It is necessary that all existing transitions be explicit before the [grow]
   functions are called. In other words, if it has been decided that there will
   be a transition from [node1] to [node2], then [node1.transitions] must be
   updated before [grow] is invoked. *)

(* [grow node state] grows the existing node [node], if necessary, so that its
   associated state subsumes [state]. If this represents an actual (strict)
   growth, then [node]'s descendants are grown as well. *)

let rec grow node state =
  if Lr0.subsume state node.state then
    follow_state "Target state is unaffected" node false
   else begin

     (* In versions of Menhir prior to June 2008, I wrote this:

141 142 143 144
          If I know what I am doing, then the new state that is being
          merged into the existing state should be compatible, in
          Pager's sense, with the existing node. In other words,
          compatibility should be preserved through transitions.
145 146 147

        and the code contained this assertion:

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
          assert (Lr0.compatible state node.state);
          assert (Lr0.eos_compatible state node.state);

        However, this was wrong. See, for instance, the sample grammars
        cocci.mly and boris-mini.mly. The problem is particularly clearly
        apparent in boris-mini.mly, where it only involves inclusion of
        states -- the definition of Pager's weak compatibility does not
        enter the picture. Here is, roughly, what is going on.

        Assume we have built some state A, which, along some symbol S,
        has a transition to itself. This means, in fact, that computing
        the successor of A along S yields a *subset* of A, that is,
        succ(A, S) <= A.

        Then, we wish to build a new state A', which turns out to be a
        superset of A, so we decide to grow A. (The fact that A is a
        subset of A' implies that A and A' are Pager-compatible.) As
        per the code below, we immediately update the state A in place,
        to become A'. Then, we inspect the transition along symbol S.
        We find that the state succ(A', S) must be merged into A'.

        In this situation, the assertions above require succ(A', S)
        to be compatible with A'. However, this is not necessarily
        the case. By monotonicity of succ, we do have succ(A, S) <=
        succ(A', S). But nothing says that succ(A', S) are related
        with respect to inclusion, or even Pager-compatible. The
        grammar in boris-mini.mly shows that they are not.
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

     *)

    (* Grow [node]. *)

    node.state <- Lr0.union state node.state;
    follow_state "Growing existing state" node true;

    (* Grow [node]'s successors. *)

    grow_successors node

  end

(* [grow_successors node] grows [node]'s successors. *)

(* Note that, if there is a cycle in the graph, [grow_successors] can be
   invoked several times at a single node [node], with [node.state] taking on
   a new value every time. In such a case, this code should be correct,
   although probably not very efficient. *)

and grow_successors node =
  SymbolMap.iter (fun symbol (successor_node : node) ->
    let successor_state = Lr0.transition symbol node.state in
    follow_transition true node symbol successor_state;
    grow successor_node successor_state
  ) node.transitions

(* ------------------------------------------------------------------------ *)

(* Data structures maintained during the construction of the automaton. *)

(* A queue of pending nodes, whose outgoing transitions have not yet
   been built. *)

let queue : node Queue.t =
  Queue.create()

(* A mapping of LR(0) node numbers to lists of nodes. This allows us to
   efficiently find all existing nodes that are core-compatible with a
   newly found state. *)

let map : node list array =
218
  Array.make Lr0.n []
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

(* A counter that allows assigning raw numbers to nodes. *)

let num =
  ref 0

(* ------------------------------------------------------------------------ *)

(* [create state] creates a new node that stands for the state [state].
   It is expected that [state] does not subsume, and is not subsumed by,
   any existing state. *)

let create (state : Lr0.lr1state) : node =

  (* Allocate a new node. *)

  let node = {
    state = state;
    transitions = SymbolMap.empty;
    reductions = TerminalMap.empty;
    conflict_tokens = TerminalSet.empty;
    raw_number = Misc.postincrement num;
    number = 0; (* temporary placeholder *)
    mark = Mark.none;
    predecessors = [];
    forbid_default_reduction = false;
  } in

  (* Update the mapping of LR(0) cores to lists of nodes. *)

  let k = Lr0.core state in
  assert (k < Lr0.n);
  map.(k) <- node :: map.(k);

  (* Enqueue this node for further examination. *)

  Queue.add node queue;

  (* Debugging output. *)

  follow_state "Creating a new state" node false;

  (* Return the freshly created node. *)

  node

(* ------------------------------------------------------------------------ *)

(* Materializing a transition turns its target state into a (fresh or
   existing). There are three scenarios: the proposed new state can be
   subsumed by an existing state, compatible with an existing state, or
   neither. *)

exception Subsumed of node

exception Compatible of node

let materialize (source : node) (symbol : Symbol.t) (target : Lr0.lr1state) : unit =
  try

    (* Debugging output. *)

    follow_transition false source symbol target;

    (* Find all existing core-compatible states. *)

    let k = Lr0.core target in
    assert (k < Lr0.n);
    let similar = map.(k) in

    (* Check whether we need to create a new node or can reuse an existing
       state. *)

    (* 20120525: the manner in which this check is performed depends on
       [Settings.construction_mode]. There are now three modes. *)

295 296
    (* 20150204: there are now four modes. *)

297 298 299 300
    begin match Settings.construction_mode with
    | Settings.ModeCanonical ->

        (* In a canonical automaton, two states can be merged only if they
301
           are identical. *)
302

303 304 305 306 307
        List.iter (fun node ->
          if Lr0.subsume target node.state &&
             Lr0.subsume node.state target then
            raise (Subsumed node)
        ) similar
308 309 310 311 312

    | Settings.ModeInclusionOnly
    | Settings.ModePager ->

        (* A more aggressive approach is to take subsumption into account:
313 314 315
           if the new candidate state is a subset of an existing state,
           then no new node needs to be created. Furthermore, the existing
           state does not need to be enlarged. *)
316 317 318

        (* 20110124: require error compatibility in addition to subsumption. *)

319 320 321 322 323
        List.iter (fun node ->
          if Lr0.subsume target node.state &&
             Lr0.error_compatible target node.state then
            raise (Subsumed node)
        ) similar
324

325 326 327
    | Settings.ModeLALR ->
        ()

328 329 330 331 332 333 334 335 336
    end;

    begin match Settings.construction_mode with
    | Settings.ModeCanonical
    | Settings.ModeInclusionOnly ->
        ()

    | Settings.ModePager ->

337 338 339 340 341
        (* One can be even more aggressive and check whether the existing state is
           compatible, in Pager's sense, with the new state. If so, there is no
           need to create a new state: just merge the new state into the existing
           one. The result is a state that may be larger than each of the two
           states that have been merged. *)
342

343 344
        (* 20110124: require error compatibility in addition to the existing
           compatibility criteria. *)
345

346 347 348 349 350 351
        List.iter (fun node ->
          if Lr0.compatible target node.state &&
             Lr0.eos_compatible target node.state &&
             Lr0.error_compatible target node.state then
            raise (Compatible node)
        ) similar
352

353 354 355 356 357
    | Settings.ModeLALR ->

        (* In LALR mode, as soon as there is one similar state -- i.e. one
           state that shares the same LR(0) core -- we merge the new state
           into the existing one. *)
358 359 360
        List.iter (fun node ->
          raise (Compatible node)
        ) similar
361

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    end;

    (* The above checks have failed. Create a new node. Two states that are in
       the subsumption relation are also compatible. This implies that the
       newly created node does not subsume any existing states. *)

    source.transitions <- SymbolMap.add symbol (create target) source.transitions

  with

  | Subsumed node ->

      (* Join an existing target node. *)

      follow_state "Joining existing state" node false;
      source.transitions <- SymbolMap.add symbol node source.transitions

  | Compatible node ->

      (* Join and grow an existing target node. It seems important that the
382 383
         new transition is created before [grow_successors] is invoked, so
         that all transition decisions made so far are explicit. *)
384 385

      node.state <- Lr0.union target node.state;
386
      follow_state "Joining and growing existing state" node true;
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
      source.transitions <- SymbolMap.add symbol node source.transitions;
      grow_successors node

(* ------------------------------------------------------------------------ *)

(* The actual construction process. *)

(* Populate the queue with the start nodes and store them in an array. *)

let entry : node ProductionMap.t =
  ProductionMap.map (fun (k : Lr0.node) ->
    create (Lr0.start k)
  ) Lr0.entry

(* Pick a node in the queue, that is, a node whose transitions have not yet
   been built. Build these transitions, and continue. *)

(* Note that building a transition can cause existing nodes to grow, so
   [node.state] is not necessarily invariant throughout the inner loop. *)

let () =
  Misc.qiter (fun node ->
    List.iter (fun symbol ->
      materialize node symbol (Lr0.transition symbol node.state)
    ) (Lr0.outgoing_symbols (Lr0.core node.state))
  ) queue

(* Record how many nodes were constructed. *)

let n =
  !num

let () =
  Error.logA 1 (fun f -> Printf.fprintf f "Built an LR(1) automaton with %d states.\n" !num)

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
(* ------------------------------------------------------------------------ *)

(* A mapping of symbols to lists of nodes that admit this incoming
   symbol. This mapping is constructed by [visit] below. *)

let incoming : node list SymbolMap.t ref =
  ref SymbolMap.empty

let lookup_incoming symbol =
  try
    SymbolMap.find symbol !incoming
  with Not_found ->
    []

let record_incoming osymbol target =
  Option.iter (fun symbol ->
    let targets = lookup_incoming symbol in
    incoming := SymbolMap.add symbol (target :: targets) !incoming
  ) osymbol

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
(* ------------------------------------------------------------------------ *)
(* We now perform one depth-first traversal of the automaton,
   recording predecessor edges, numbering nodes, sorting nodes
   according to their incoming symbol, building reduction tables, and
   finding out which nodes have conflicts. *)

(* A count of all nodes. *)

let () =
  num := 0

(* A list of all nodes. *)

let nodes : node list ref =
  ref []

(* A list of nodes with conflicts. *)

let conflict_nodes : node list ref =
  ref []

(* Counts of nodes with shift/reduce and reduce/reduce conflicts. *)

let shift_reduce =
  ref 0

let reduce_reduce =
  ref 0

(* Count of the shift/reduce conflicts that could be silently
   resolved. *)

let silently_solved =
  ref 0

(* Go ahead. *)

let () =

  let marked = Mark.fresh() in

483
  let rec visit osymbol node =
484 485 486
    if not (Mark.same node.mark marked) then begin
      node.mark <- marked;
      nodes := node :: !nodes;
487
      record_incoming osymbol node;
488 489 490 491 492 493 494 495 496 497

      (* Number this node. *)

      let number = !num in
      num := number + 1;
      node.number <- number;

      (* Insertion of a new reduce action into the table of reductions. *)

      let addl prod tok reductions =
498 499 500 501 502 503 504
        let prods =
          try
            TerminalMap.lookup tok reductions
          with Not_found ->
            []
        in
        TerminalMap.add tok (prod :: prods) reductions
505 506 507 508 509 510 511 512 513
      in

      (* Build the reduction table. Here, we gather all potential
         reductions, without attempting to solve shift/reduce
         conflicts on the fly, because that would potentially hide
         shift/reduce/reduce conflicts, which we want to be aware
         of. *)

      let reductions =
514 515
        List.fold_left (fun reductions (toks, prod) ->
          TerminalSet.fold (addl prod) toks reductions
516 517 518 519
        ) TerminalMap.empty (Lr0.reductions node.state)
      in

      (* Detect conflicts. Attempt to solve shift/reduce conflicts
520
         when unambiguously allowed by priorities. *)
521 522 523 524 525

      let has_shift_reduce = ref false
      and has_reduce_reduce = ref false in

      node.reductions <-
526 527
        TerminalMap.fold (fun tok prods reductions ->
          if SymbolMap.mem (Symbol.T tok) node.transitions then begin
528

529 530
            (* There is a transition in addition to the reduction(s). We
               have (at least) a shift/reduce conflict. *)
531

532 533 534 535 536 537
            assert (not (Terminal.equal tok Terminal.sharp));
            match prods with
            | [] ->
                assert false
            | [ prod ] ->
                begin
538

539 540
                  (* This is a single shift/reduce conflict. If priorities tell
                     us how to solve it, we follow that and modify the automaton. *)
541

542
                  match Precedence.shift_reduce tok prod with
543

544
                  | Precedence.ChooseShift ->
545

546
                      (* Suppress the reduce action. *)
547

548 549
                      incr silently_solved;
                      reductions
550

551
                  | Precedence.ChooseReduce ->
552

553 554 555 556
                      (* Record the reduce action and suppress the shift transition.
                         The automaton is modified in place. This can have the subtle
                         effect of making some nodes unreachable. Any conflicts in these
                         nodes will then be ignored (as they should be). *)
557

558 559 560
                      incr silently_solved;
                      node.transitions <- SymbolMap.remove (Symbol.T tok) node.transitions;
                      TerminalMap.add tok prods reductions
561

562
                  | Precedence.ChooseNeither ->
563

564
                      (* Suppress the reduce action and the shift transition. *)
565

566 567 568 569
                      incr silently_solved;
                      node.transitions <- SymbolMap.remove (Symbol.T tok) node.transitions;
                      node.forbid_default_reduction <- true;
                      reductions
570

571
                  | Precedence.DontKnow ->
572

573 574
                      (* Priorities don't allow concluding. Record the
                         existence of a shift/reduce conflict. *)
575

576 577 578
                      node.conflict_tokens <- Grammar.TerminalSet.add tok node.conflict_tokens;
                      has_shift_reduce := true;
                      TerminalMap.add tok prods reductions
579

580
                end
581

582
            | _prod1 :: _prod2 :: _ ->
583

584 585 586 587
                (* This is a shift/reduce/reduce conflict. If the priorities
                   are such that each individual shift/reduce conflict is solved
                   in favor of shifting or in favor of neither, then solve the entire
                   composite conflict in the same way. Otherwise, report the conflict. *)
588

589
                let choices = List.map (Precedence.shift_reduce tok) prods in
590

591 592 593 594
                if List.for_all (fun choice ->
                  match choice with
                  | Precedence.ChooseShift -> true
                  | _ -> false
595 596
                ) choices then begin

597
                  (* Suppress the reduce action. *)
598

599 600
                  silently_solved := !silently_solved + List.length prods;
                  reductions
601

602 603 604 605 606
                end
                else if List.for_all (fun choice ->
                  match choice with
                  | Precedence.ChooseNeither -> true
                  | _ -> false
607 608
                ) choices then begin

609
                  (* Suppress the reduce action and the shift transition. *)
610

611 612 613
                  silently_solved := !silently_solved + List.length prods;
                  node.transitions <- SymbolMap.remove (Symbol.T tok) node.transitions;
                  reductions
614

615 616
                end
                else begin
617

618
                  (* Record a shift/reduce/reduce conflict. Keep all reductions. *)
619

620 621 622 623
                  node.conflict_tokens <- Grammar.TerminalSet.add tok node.conflict_tokens;
                  has_shift_reduce := true;
                  has_reduce_reduce := true;
                  TerminalMap.add tok prods reductions
624

625
                end
626

627 628
          end
          else
629
            let () =
630 631 632 633 634
              match prods with
              | []
              | [ _ ] ->
                  ()
              | _prod1 :: _prod2 :: _ ->
635

636 637 638
                  (* There is no transition in addition to the reduction(s). We
                     have a pure reduce/reduce conflict. Do nothing about it at
                     this point. *)
639

640 641
                  node.conflict_tokens <- Grammar.TerminalSet.add tok node.conflict_tokens;
                  has_reduce_reduce := true
642

643 644
            in
            TerminalMap.add tok prods reductions
645 646 647 648 649 650

      ) reductions TerminalMap.empty;

      (* Record statistics about conflicts. *)

      if not (TerminalSet.is_empty node.conflict_tokens) then begin
651 652 653 654 655
        conflict_nodes := node :: !conflict_nodes;
        if !has_shift_reduce then
          incr shift_reduce;
        if !has_reduce_reduce then
          incr reduce_reduce
656 657 658 659 660 661 662 663
      end;

      (* Continue the depth-first traversal. Record predecessors edges
         as we go. No ancestor appears twice in a list of
         predecessors, because two nodes cannot be related by two
         edges that carry distinct symbols. *)

      SymbolMap.iter (fun symbol son ->
664 665
        son.predecessors <- node :: son.predecessors;
        visit (Some symbol) son
666 667 668
      ) node.transitions
    end
  in
669

670
  ProductionMap.iter (fun _ node -> visit None node) entry
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694

let nodes =
  List.rev !nodes (* list is now sorted by increasing node numbers *)

let conflict_nodes =
  !conflict_nodes

let () =
  if !silently_solved = 1 then
    Error.logA 1 (fun f -> Printf.fprintf f "One shift/reduce conflict was silently solved.\n")
  else if !silently_solved > 1 then
    Error.logA 1 (fun f -> Printf.fprintf f "%d shift/reduce conflicts were silently solved.\n" !silently_solved);
  if !num < n then
    Error.logA 1 (fun f -> Printf.fprintf f "Only %d states remain after resolving shift/reduce conflicts.\n" !num)

let () =
  Grammar.diagnostics()

let n =
  !num

let forbid_default_reduction node =
  node.forbid_default_reduction

695 696 697 698 699 700 701
(* ------------------------------------------------------------------------ *)
(* The incoming symbol of a node can be computed by going through its LR(0)
   core. For this reason, we do not need to explicitly record it here. *)

let incoming_symbol node =
  Lr0.incoming_symbol (Lr0.core node.state)

702 703 704 705 706 707 708 709 710 711 712 713 714 715
(* ------------------------------------------------------------------------ *)
(* Iteration over all nodes. *)

let fold f accu =
  List.fold_left f accu nodes

let iter f =
  fold (fun () node -> f node) ()

let map f =
  List.map f nodes

let foldx f =
  fold (fun accu node ->
716
          match incoming_symbol node with
717 718 719 720
            | None -> accu
            | Some _ -> f accu node)

let iterx f =
721 722 723
  iter (fun node ->
    match incoming_symbol node with
      | None -> ()
724
      | Some _ -> f node)
725

726 727 728 729 730 731 732 733 734
(* -------------------------------------------------------------------------- *)
(* Our output channel. *)

let out =
  lazy (open_out (Settings.base ^ ".automaton"))

(* ------------------------------------------------------------------------ *)
(* If requested, dump a verbose description of the automaton. *)

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
let describe out node =
  Printf.fprintf out "State %d%s:\n%s"
    node.number
    (if Settings.follow then Printf.sprintf " (r%d)" node.raw_number else "")
    (Lr0.print "" node.state);
  SymbolMap.iter (fun symbol node ->
    Printf.fprintf out "-- On %s shift to state %d\n"
      (Symbol.print symbol) node.number
  ) node.transitions;
  TerminalMap.iter (fun tok prods ->
    List.iter (fun prod ->
      (* TEMPORARY factoriser les symboles qui conduisent a reduire une meme production *)
      Printf.fprintf out "-- On %s " (Terminal.print tok);
      match Production.classify prod with
      | Some nt ->
          Printf.fprintf out "accept %s\n" (Nonterminal.print false nt)
      | None ->
          Printf.fprintf out "reduce production %s\n" (Production.print prod)
    ) prods
  ) node.reductions;
  if not (TerminalSet.is_empty node.conflict_tokens) then
    Printf.fprintf out "** Conflict on %s\n" (TerminalSet.print node.conflict_tokens);
  Printf.fprintf out "\n%!"

759 760 761
let () =
  Time.tick "Construction of the LR(1) automaton";
  if Settings.dump then begin
762
    iter (describe (Lazy.force out));
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
    Time.tick "Dumping the LR(1) automaton"
  end

(* ------------------------------------------------------------------------ *)
(* [reverse_dfs goal] performs a reverse depth-first search through
   the automaton, starting at node [goal], and marking the nodes
   traversed. It returns a function that tells whether a node is
   marked, that is, whether a path leads from that node to the goal
   node. *)

let reverse_dfs goal =

  let mark = Mark.fresh() in

  let marked node =
    Mark.same node.mark mark
  in

  let rec visit node =
     if not (marked node) then begin
       node.mark <- mark;
       List.iter visit node.predecessors
     end
  in

  visit goal;
  marked

(* ------------------------------------------------------------------------ *)
(* Iterating over all nodes that are targets of edges carrying a
   certain symbol. The sources of the corresponding edges are also
   provided. *)

let targets f accu symbol =
797 798
  (* There are no incoming transitions on the start symbols. *)
  let targets = lookup_incoming symbol in
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
  List.fold_left (fun accu target ->
    f accu target.predecessors target
  ) accu targets

(* ------------------------------------------------------------------------ *)
(* Converting a start node into the single item that it contains. *)

let start2item node =
  let state : Lr0.lr1state = node.state in
  let core : Lr0.node = Lr0.core state in
  let items : Item.Set.t = Lr0.items core in
  assert (Item.Set.cardinal items = 1);
  Item.Set.choose items

(* ------------------------------------------------------------------------ *)
(* Accessors. *)

let number node =
  node.number

let state node =
  node.state

let transitions node =
  node.transitions

let reductions node =
  node.reductions

let conflicts f =
  List.iter (fun node ->
    f node.conflict_tokens node
  ) conflict_nodes

let predecessors node =
  node.predecessors

(* ------------------------------------------------------------------------ *)

(* This inverts a mapping of tokens to productions into a mapping of
   productions to sets of tokens. *)

(* This is needed, in [CodeBackend], to avoid producing two (or more)
   separate branches that call the same [reduce] function. Instead,
   we generate just one branch, guarded by a [POr] pattern. *)

let invert reductions : TerminalSet.t ProductionMap.t =
  TerminalMap.fold (fun tok prods inverse ->
    let prod = Misc.single prods in
    let toks =
      try
850
        ProductionMap.lookup prod inverse
851
      with Not_found ->
852
        TerminalSet.empty
853 854 855
    in
    ProductionMap.add prod (TerminalSet.add tok toks) inverse
  ) reductions ProductionMap.empty
856

857
(* ------------------------------------------------------------------------ *)
858
(* [has_beforeend s] tests whether the state [s] can reduce a production
POTTIER Francois's avatar
POTTIER Francois committed
859 860 861
   whose semantic action uses [$endpos($0)]. Note that [$startpos] and
   [$endpos] have been expanded away already, so we need not worry about
   the fact that (in an epsilon production) they expand to [$endpos($0)]. *)
862 863

let has_beforeend node =
864 865 866
  TerminalMap.fold (fun _ prods accu ->
    accu ||
    let prod = Misc.single prods in
867 868
    not (Production.is_start prod) &&
    let action = Production.action prod in
869
    Action.has_beforeend action
870 871
  ) (reductions node) false

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
(* ------------------------------------------------------------------------ *)
(* Computing which terminal symbols a state is willing to act upon.

   One must keep in mind that, due to the merging of states, a state might be
   willing to perform a reduction on a certain token, yet the reduction can
   take us to another state where this token causes an error. In other words,
   the set of terminal symbols that is computed here is really an
   over-approximation of the set of symbols that will not cause an error. And
   there seems to be no way of performing an exact computation, as we would
   need to know not only the current state, but the contents of the stack as
   well. *)

let acceptable_tokens (s : node) =

  (* If this state is willing to act on the error token, ignore it -- we do
     not wish to report that an error would be accepted in this state :-) *)

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

  (* Accumulate the tokens carried by outgoing transitions. *)

  let covered =
    SymbolMap.fold (fun symbol _ covered ->
      match symbol with
      | Symbol.T tok ->
901
          TerminalSet.add tok covered
902
      | Symbol.N _ ->
903
          covered
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
    ) transitions TerminalSet.empty
  in

  (* Accumulate the tokens that permit reduction. *)

  let covered =
    ProductionMap.fold (fun _ toks covered ->
      TerminalSet.union toks covered
    ) (invert reductions) covered
  in

  (* That's it. *)

  covered

(* ------------------------------------------------------------------------ *)
(* Report statistics. *)

(* Produce the reports. *)

let () =
  if !shift_reduce = 1 then
    Error.grammar_warning [] "one state has shift/reduce conflicts."
  else if !shift_reduce > 1 then
928
    Error.grammar_warning [] "%d states have shift/reduce conflicts." !shift_reduce;
929 930 931
  if !reduce_reduce = 1 then
    Error.grammar_warning [] "one state has reduce/reduce conflicts."
  else if !reduce_reduce > 1 then
932
    Error.grammar_warning [] "%d states have reduce/reduce conflicts." !reduce_reduce
933

934 935
(* ------------------------------------------------------------------------ *)

936 937
(* For each production, compute where (that is, in which states) this
   production can be reduced. This computation is done AFTER default conflict
938 939
   resolution (see below). It is an error to call the accessor function
   [production_where] before default conflict resolution has taken place. *)
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974

let production_where : NodeSet.t ProductionMap.t option ref =
  ref None

let initialize_production_where () =
  production_where := Some (
    fold (fun accu node ->
      TerminalMap.fold (fun _ prods accu ->
        let prod = Misc.single prods in
        let nodes =
          try
            ProductionMap.lookup prod accu
          with Not_found ->
            NodeSet.empty
        in
        ProductionMap.add prod (NodeSet.add node nodes) accu
      ) (reductions node) accu
    ) ProductionMap.empty
  )

let production_where (prod : Production.index) : NodeSet.t =
  match !production_where with
  | None ->
      (* It is an error to call this function before conflict resolution. *)
      assert false
  | Some production_where ->
      try
        (* Production [prod] may be reduced at [nodes]. *)
        let nodes = ProductionMap.lookup prod production_where in
        assert (not (NodeSet.is_empty nodes));
        nodes
      with Not_found ->
        (* The production [prod] is never reduced. *)
        NodeSet.empty

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
(* ------------------------------------------------------------------------ *)
(* Warn about productions that are never reduced. *)

(* These are productions that can never, ever be reduced, because there is
   no state that is willing to reduce them. There could be other productions
   that are never reduced because the only states that are willing to reduce
   them are unreachable. We do not report those. In fact, through the use of
   the inspection API, it might be possible to bring the automaton into a
   state where one of those productions can be reduced. *)

let warn_about_productions_never_reduced () =
  let count = ref 0 in
  Production.iter (fun prod ->
    if NodeSet.is_empty (production_where prod) then
      match Production.classify prod with
      | Some nt ->
          incr count;
          Error.grammar_warning
            (Nonterminal.positions nt)
            "symbol %s is never accepted." (Nonterminal.print false nt)
      | None ->
          incr count;
          Error.grammar_warning
            (Production.positions prod)
            "production %sis never reduced." (Production.print prod)
  );
  if !count > 0 then
1002
    let plural_mark, be = if !count > 1 then ("s", "are") else ("", "is") in
1003
    Error.grammar_warning []
1004
      "in total, %d production%s %s never reduced." !count plural_mark be
1005

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
(* ------------------------------------------------------------------------ *)
(* When requested by the code generator, apply default conflict
   resolution to ensure that the automaton is deterministic. *)

(* [best prod prods] chooses which production should be reduced
   among the list [prod :: prods]. It fails if no best choice
   exists. *)

let rec best choice = function
  | [] ->
      choice
  | prod :: prods ->
      match Precedence.reduce_reduce choice prod with
      | Some choice ->
1020
          best choice prods
1021
      | None ->
1022 1023
          (* The cause for not knowing which production is best could be:
             1- the productions originate in different source files;
1024
             2- they are derived, via inlining, from the same production. *)
1025
          Error.signal Error.grammatical_error
1026 1027
            (Production.positions choice @ Production.positions prod)
               "do not know how to resolve a reduce/reduce conflict\n\
1028
                between the following two productions:\n%s\n%s"
1029
                  (Production.print choice)
1030
                  (Production.print prod);
1031
          choice (* dummy *)
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

(* Go ahead. *)

let default_conflict_resolution () =

  let shift_reduce =
    ref 0
  and reduce_reduce =
    ref 0
  in

  List.iter (fun node ->

    node.reductions <-
      TerminalMap.fold (fun tok prods reductions ->
1047 1048 1049 1050 1051 1052 1053 1054 1055
        try
          let (_ : node) =
            SymbolMap.find (Symbol.T tok) node.transitions
          in
          (* There is a transition at this symbol, so this
             is a (possibly multiway) shift/reduce conflict.
             Resolve in favor of shifting by suppressing all
             reductions. *)
          shift_reduce := List.length prods + !shift_reduce;
1056
          reductions
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        with Not_found ->
          (* There is no transition at this symbol. Check
             whether we have multiple reductions. *)
          match prods with
          | [] ->
              assert false
          | [ _ ] ->
              TerminalMap.add tok prods reductions
          | prod :: ((_ :: _) as prods) ->
              (* We have a reduce/reduce conflict. Resolve, if
                 possible, in favor of a single reduction.
                 This reduction must be preferrable to each
                 of the others. *)
              reduce_reduce := List.length prods + !reduce_reduce;
              TerminalMap.add tok [ best prod prods ] reductions
1072 1073 1074 1075 1076 1077 1078 1079

      ) node.reductions TerminalMap.empty

  ) conflict_nodes;

  if !shift_reduce = 1 then
    Error.warning [] "one shift/reduce conflict was arbitrarily resolved."
  else if !shift_reduce > 1 then
1080
    Error.warning [] "%d shift/reduce conflicts were arbitrarily resolved." !shift_reduce;
1081 1082 1083
  if !reduce_reduce = 1 then
    Error.warning [] "one reduce/reduce conflict was arbitrarily resolved."
  else if !reduce_reduce > 1 then
1084
    Error.warning [] "%d reduce/reduce conflicts were arbitrarily resolved." !reduce_reduce;
1085 1086 1087 1088 1089 1090 1091 1092 1093

  (* Now, ensure that states that have a reduce action at the
     pseudo-token "#" have no other action. *)

  let ambiguities =
    ref 0
  in

  fold (fun () node ->
1094

1095 1096 1097 1098 1099
    try
      let prods, reductions = TerminalMap.lookup_and_remove Terminal.sharp node.reductions in
      let prod = Misc.single prods in

      (* This node has a reduce action at "#". Determine whether there
1100 1101
         exist other actions. If there exist any other actions,
         suppress this reduce action, and signal an ambiguity.
1102

1103 1104 1105 1106 1107
         We signal an ambiguity even in the case where all actions at
         this node call for reducing a single production. Indeed, in
         that case, even though we know that this production must be
         reduced, we do not know whether we should first discard the
         current token (and call the lexer). *)
1108 1109 1110 1111

      let has_ambiguity = ref false in
      let toks = ref TerminalSet.empty in

1112
      TerminalMap.iter (fun tok _prods ->
1113 1114 1115
        node.reductions <- reductions;
        has_ambiguity := true;
        toks := TerminalSet.add tok !toks
1116 1117 1118
      ) reductions;

      SymbolMap.iter (fun symbol _ ->
1119 1120 1121 1122 1123 1124 1125
        match symbol with
        | Symbol.N _ ->
            ()
        | Symbol.T tok ->
            node.reductions <- reductions;
            has_ambiguity := true;
            toks := TerminalSet.add tok !toks
1126 1127 1128
      ) node.transitions;

      if !has_ambiguity then begin
1129 1130 1131 1132 1133 1134 1135
        incr ambiguities;
        if Settings.dump then begin
          Printf.fprintf (Lazy.force out)
            "State %d has an end-of-stream conflict. There is a tension between\n\
             (1) %s\n\
             without even requesting a lookahead token, and\n\
             (2) checking whether the lookahead token is %s%s,\n\
1136 1137 1138
             which would require some other action.\n\n"
            (number node)
            (match Production.classify prod with
1139 1140 1141 1142
            | Some nt ->
                Printf.sprintf "accepting %s" (Nonterminal.print false nt)
            | None ->
                Printf.sprintf "reducing production %s" (Production.print prod))
1143 1144
            (if TerminalSet.cardinal !toks > 1 then "one of " else "")
            (TerminalSet.print !toks)
1145
        end
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
      end

    with Not_found ->
      ()

  ) ();

  if !ambiguities = 1 then
    Error.grammar_warning [] "one state has an end-of-stream conflict."
  else if !ambiguities > 1 then
1156 1157 1158
    Error.grammar_warning [] "%d states have an end-of-stream conflict." !ambiguities;

  (* We can now compute where productions are reduced. *)
1159 1160
  initialize_production_where();
  warn_about_productions_never_reduced()
1161

1162
(* ------------------------------------------------------------------------ *)
1163
(* Extra reductions. *)
1164

1165 1166 1167
(* 2015/10/19 Original implementation. *)
(* 2016/07/13 Use priority levels to choose which productions to reduce
              when several productions are eligible. *)
1168

1169 1170 1171 1172 1173 1174 1175
(* If a state can reduce some productions whose left-hand symbol has been
   marked [%on_error_reduce], and if one such production [prod] is preferable
   to every other (according to the priority rules of [%on_error_reduce]
   declarations), then every error action in this state is replaced with a
   reduction of [prod]. This is done even though this state may have outgoing
   shift transitions: thus, we are forcing one interpretation of the past,
   among several possible interpretations. *)
1176 1177

(* The code below looks like the decision on a default reduction in
POTTIER Francois's avatar
POTTIER Francois committed
1178
   [Default], except we do not impose the absence of outgoing terminal
1179 1180 1181
   transitions. Also, we actually modify the automaton, so the back-ends, the
   reference interpreter, etc., need not be aware of this feature, whereas
   they are aware of default reductions. *)
1182

1183 1184
(* This code can run before we decide on the default reductions; this does
   not affect which default reductions will be permitted. *)
1185

POTTIER Francois's avatar
POTTIER Francois committed
1186 1187 1188
(* This code does not affect which productions can be reduced where. Thus,
   it is OK for it to run after [initialize_production_where()]. *)

1189 1190
(* A count of how many states receive extra reductions through this mechanism. *)

1191 1192 1193
let extra =
  ref 0

1194 1195 1196 1197 1198 1199
(* A count of how many states have more than one eligible production, but one
   is preferable to every other (so priority plays a role). *)

let prioritized =
  ref 0

1200 1201 1202
(* The set of nonterminal symbols in the left-hand side of an extra reduction. *)

let extra_nts =
1203
  ref NonterminalSet.empty
1204

1205 1206 1207 1208 1209 1210 1211 1212
let extra_reductions_in_node node =
  (* Compute the productions which this node can reduce. *)
  let productions : _ ProductionMap.t = invert (reductions node) in
  let prods : Production.index list =
    ProductionMap.fold (fun prod _ prods -> prod :: prods) productions []
  in
  (* Keep only those whose left-hand symbol is marked [%on_error_reduce]. *)
  let prods = List.filter OnErrorReduce.reduce prods in
1213 1214 1215 1216 1217
  (* Check if one of them is preferable to every other one. *)
  match Misc.best OnErrorReduce.preferable prods with
  | None ->
      (* Either no production is marked [%on_error_reduce], or several of them
         are marked and none is preferable. *)
1218
      ()
1219
  | Some prod ->
1220 1221 1222 1223 1224 1225
      let acceptable = acceptable_tokens node in
      (* An extra reduction is possible. Replace every error action with
         a reduction of [prod]. If we replace at least one error action
         with a reduction, update [extra] and [extra_nts]. *)
      let triggered = lazy (
        incr extra;
1226
        if List.length prods > 1 then incr prioritized;
1227 1228 1229 1230 1231 1232 1233 1234 1235
        extra_nts := NonterminalSet.add (Production.nt prod) !extra_nts
      ) in
      Terminal.iter_real (fun tok ->
        if not (TerminalSet.mem tok acceptable) then begin
          node.reductions <- TerminalMap.add tok [ prod ] node.reductions;
          Lazy.force triggered
        end
      )

1236
let extra_reductions () =
1237
  (* Examine every node. *)
1238
  iter (fun node ->
1239 1240
    (* Just like a default reduction, an extra reduction should be forbidden
       (it seems) if [forbid_default_reduction] is set. *)
1241 1242
    if not node.forbid_default_reduction then
      extra_reductions_in_node node
1243
  );
1244
  (* Info message. *)
1245 1246
  if !extra > 0 then
    Error.logA 1 (fun f ->
1247 1248
      Printf.fprintf f "Extra reductions on error were added in %d states.\n" !extra;
      Printf.fprintf f "Priority played a role in %d of these states.\n" !prioritized
1249
    );
1250
  (* Warn about useless %on_error_reduce declarations. *)
1251 1252
  OnErrorReduce.iter (fun nt ->
    if not (NonterminalSet.mem nt !extra_nts) then
1253
      Error.grammar_warning []
1254 1255 1256
        "the declaration %%on_error_reduce %s is never useful."
        (Nonterminal.print false nt)
  )
1257

1258 1259 1260 1261 1262 1263 1264 1265
(* ------------------------------------------------------------------------ *)
(* Define [fold_entry], which in some cases facilitates the use of [entry]. *)

let fold_entry f accu =
  ProductionMap.fold (fun prod state accu ->
    let nt : Nonterminal.t =
      match Production.classify prod with
      | Some nt ->
1266
          nt
1267
      | None ->
1268
          assert false (* this is a start production *)
1269 1270
    in
    let t : Stretch.ocamltype =
1271
      Nonterminal.ocamltype_of_start_symbol nt
1272 1273 1274 1275
    in
    f prod state nt t accu
  ) entry accu

1276
let entry_of_nt nt =
1277 1278 1279 1280 1281 1282
  (* Find the entry state that corresponds to [nt]. *)
  try
    ProductionMap.find (Production.startsymbol2startprod nt) entry
  with Not_found ->
    assert false

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
exception Found of Nonterminal.t

let nt_of_entry s =
  (* [s] should be an initial state. *)
  assert (incoming_symbol s = None);
  try
    ProductionMap.iter (fun prod entry ->
      if Node.compare s entry = 0 then
        match Production.classify prod with
        | None ->
            assert false
        | Some nt ->
            raise (Found nt)
    ) entry;
    (* This should not happen if [s] is indeed an initial state. *)
    assert false
  with Found nt ->
    nt