LRijkstra.ml 24.7 KB
Newer Older
1 2
open Grammar

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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
(* ------------------------------------------------------------------------ *)

(* First, we implement the computation of forward shortest paths in the
   automaton. We view the automaton as a graph whose vertices are states. We
   label each edge with the minimum length of a word that it generates. This
   yields a lower bound on the actual distance to every state from any entry
   state. *)

let approximate : Lr1.node -> int =

  let module A = Astar.Make(struct

    type node =
      Lr1.node

    let equal s1 s2 =
      Lr1.Node.compare s1 s2 = 0

    let hash s =
      Hashtbl.hash (Lr1.number s)

    type label =
      unit

    let sources f =
      (* The sources are the entry states. *)
      ProductionMap.iter (fun _ s -> f s) Lr1.entry

    let successors s edge =
      SymbolMap.iter (fun sym s' ->
        (* The weight of the edge from [s] to [s'] is given by the function
           [Grammar.Analysis.minimal_symbol]. If [sym] produces the empty
           language, this could be infinite, in which case no edge exists. *)
        match Analysis.minimal_symbol sym with
        | CompletedNatWitness.Finite (w, _) ->
            edge () w s'
        | CompletedNatWitness.Infinity ->
            ()
      ) (Lr1.transitions s)

    let estimate _ =
      (* A* with a zero [estimate] behaves like Dijkstra's algorithm. *)
      0

  end) in
        
  let distance, _ = A.search (fun (_, _) -> ()) in
  distance

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

(* This returns the list of reductions of [state] on token [z]. This
   is a list of zero or one elements. *)

let reductions s z =
  assert (not (Terminal.equal z Terminal.error));
  try
    TerminalMap.find z (Lr1.reductions s)
  with Not_found ->
    []

(* This tests whether state [s] is willing to reduce some production
   when the lookahead symbol is [z]. This test takes a possible default
   reduction into account. *)

let has_reduction s z : Production.index option =
  assert (not (Terminal.equal z Terminal.error));
  match Invariant.has_default_reduction s with
  | Some (prod, _) ->
      Some prod
  | None ->
      match reductions s z with
      | prod :: prods ->
          assert (prods = []);
          Some prod
      | [] ->
          None

(* This tests whether state [s] will initiate an error on the lookahead
   symbol [z]. *)

let causes_an_error s z =
  assert (not (Terminal.equal z Terminal.error));
  match Invariant.has_default_reduction s with
  | Some _ ->
      false
  | None ->
      reductions s z = [] &&
      not (SymbolMap.mem (Symbol.T z) (Lr1.transitions s))

93 94 95 96 97 98 99 100
  let id x = x
  let some x = Some x

let update_ref r f : bool =
  let v = !r in
  let v' = f v in
  v != v' && (r := v'; true)

101 102 103 104 105 106 107 108 109 110 111 112
let update add find none some key m f =
  match find key m with
  | data ->
      let data' = f (some data) in
      if data' == data then
        m
      else
        add key data' m
  | exception Not_found ->
      let data' = f none in
      add key data' m

113 114 115
module MyMap (X : Map.OrderedType) = struct
  include Map.Make(X)
  let update none some key m f =
116
    update add find none some key m f
117 118
end

119 120 121 122 123 124 125
module W : sig

  type word
  val epsilon: word
  val singleton: Terminal.t -> word
  val append: word -> word -> word
  val length: word -> int
126
  val first: word -> Terminal.t -> Terminal.t
127
  val elements: word -> Terminal.t list
128
  val print: word -> string
129 130 131

end = struct

132 133 134 135 136 137 138
  type word = Terminal.t list
  let epsilon = []
  let singleton t = [t]
  let append = (@)
  let length = List.length
  let first w z = match w with a :: _ -> a | [] -> z
  let elements w = w
139
  let print w =
140
    string_of_int (length w) ^ " " ^
141
    String.concat " " (List.map Terminal.print (elements w))
142

143 144 145 146
end

module Q = LowIntegerPriorityQueue

147 148 149 150
module Trie = struct

  let c = ref 0

151 152
  type trie = {
    identity: int;
153 154
    source: Lr1.node;
    target: Lr1.node;
155
    productions: Production.index list;
156
    transitions: trie SymbolMap.t;
157
  }
158

159
  let mktrie source target productions transitions =
160
    let identity = Misc.postincrement c in
161
    { identity; source; target; productions; transitions }
162

163 164
  let empty source =
    mktrie source source [] SymbolMap.empty
165

166 167
  let is_empty t =
    t.productions = [] && SymbolMap.is_empty t.transitions
168

169 170
  let accepts prod t =
    List.mem prod t.productions
171

172
  let rec insert target w prod t =
173 174
    match w with
    | [] ->
175
        mktrie t.source target (prod :: t.productions) t.transitions
176
    | a :: w ->
177 178 179 180 181 182 183 184 185 186
        match SymbolMap.find a (Lr1.transitions target) with
        | successor ->
            let child = mktrie t.source successor [] SymbolMap.empty in
            mktrie t.source target t.productions
              (update SymbolMap.add SymbolMap.find child id a t.transitions (insert successor w prod))
        | exception Not_found ->
            t

  let insert w prod t =
    insert t.source w prod t
187

188
  let derivative a t =
189
    try
190
      SymbolMap.find a t.transitions
191
    with Not_found ->
192 193 194 195
      assert false

  let has_derivative a t =
    SymbolMap.mem a t.transitions
196

197 198
  let compare t1 t2 =
    Pervasives.compare (t1.identity : int) t2.identity
199

200 201
  let rec size t =
    SymbolMap.fold (fun _ child accu -> size child + accu) t.transitions 1
202

203 204
end

205 206 207
type fact = {
  source: Lr1.node;
  target: Lr1.node;
208
  future: Trie.trie;
209
  word: W.word;
210
  lookahead: Terminal.t
211 212
}

213 214
let print_fact fact =
  Printf.fprintf stderr
215
    "from state %d to state %d via %s . %s\n%!"
216 217 218 219 220
    (Lr1.number fact.source)
    (Lr1.number fact.target)
    (W.print fact.word)
    (Terminal.print fact.lookahead)

221
let extensible fact sym =
222
  Trie.has_derivative sym fact.future
223

224 225 226 227 228 229
let foreach_terminal f =
  Terminal.iter (fun t ->
    if not (Terminal.equal t Terminal.error) then
      f t
  )

230 231 232 233 234 235 236 237
let star s : Trie.trie =
  SymbolMap.fold (fun sym _ accu ->
    match sym with
    | Symbol.T _ ->
        accu
    | Symbol.N nt ->
        Production.foldnt nt accu (fun prod accu ->
          let w = Array.to_list (Production.rhs prod) in
238
          (* could insert this branch only if viable -- leads to 12600 instead of 12900 in ocaml.mly --lalr *)
239
          Trie.insert w prod accu
240
        )
241
  ) (Lr1.transitions s) (Trie.empty s)
242

243 244 245 246 247 248
let q =
  Q.create()

let add fact =
  (* The length of the word serves as the priority of this fact. *)
  Q.add q fact (W.length fact.word)
POTTIER Francois's avatar
POTTIER Francois committed
249 250
    (* In principle, there is no need to insert the fact into the queue
       if [T] already stores a comparable fact. *)
251

252 253
let stars = ref 0

254
let init s =
255
  let trie = star s in
256 257 258 259
  let size = (Trie.size trie) in
  stars := !stars + size;
  Printf.fprintf stderr "State %d has a star of size %d\n.%!"
    (Lr1.number s) size;
POTTIER Francois's avatar
POTTIER Francois committed
260
  if not (Trie.is_empty trie) then
261 262 263 264
    foreach_terminal (fun z ->
      add {
        source = s;
        target = s;
265
        future = trie;
266 267 268 269
        word = W.epsilon;
        lookahead = z
      }
    )
270 271

module T : sig
272 273

  (* [register fact] registers the fact [fact]. It returns [true] if this fact
274
     is new, i.e., no fact concerning the same quintuple of [source], [future],
275 276 277 278 279
     [target], [a], and [z] was previously known. *)
  val register: fact -> bool

  (* [query target z f] enumerates all known facts whose target state is [target]
     and whose lookahead assumption is [z]. *)
280
  val query: Lr1.node -> Terminal.t -> (fact -> unit) -> unit
281

282
  val stats: unit -> unit
283
  val debug: unit -> unit
284

285
end = struct
286

287 288 289 290 291 292
  (* We use a map of [target, z] to a map of [future, a] to facts. *)

  (* A minor and subtle optimization: we need not use [source] as part
     of the key in [M2], because [future] determines [source]. Indeed,
     [future] is (a sub-trie of) the trie generated by [init source],
     and every trie contains unique stamps. *)
293

294 295 296 297
  module M1 =
    MyMap(struct
      type t = Lr1.node * Terminal.t
      let compare (target1, z1) (target2, z2) =
298 299 300 301 302
        let c = Lr1.Node.compare target1 target2 in
        if c <> 0 then c else
        Terminal.compare z1 z2
    end)

303 304
  module M2 =
    MyMap(struct
305 306 307
      type t = fact
      let compare fact1 fact2 =
        let c = Trie.compare fact1.future fact2.future in
308
        if c <> 0 then c else
309 310
        let a1 = W.first fact1.word fact1.lookahead
        and a2 = W.first fact2.word fact2.lookahead in
311 312
        Terminal.compare a1 a2
    end)
313

314 315
  let m : fact M2.t M1.t ref =
    ref M1.empty
316

317 318
  let count = ref 0

319
  let register fact =
320 321
    assert (Lr1.Node.compare fact.source fact.future.Trie.source = 0);
    assert (Lr1.Node.compare fact.target fact.future.Trie.target = 0);
322
    let z = fact.lookahead in
323 324
    update_ref m (fun m1 ->
      M1.update M2.empty id (fact.target, z) m1 (fun m2 ->
325
        M2.update None some fact m2 (function
326
          | None ->
327
              incr count;
328 329
              fact
          | Some earlier_fact ->
330
              (* assert (W.length earlier_fact.word <= W.length fact.word); *)
331 332 333 334
              earlier_fact
        )
      )
    )
335

336 337 338 339 340 341 342 343
  let query target z f =
    match M1.find (target, z) !m with
    | m2 ->
        M2.iter (fun _ fact ->
          f fact
        ) m2
    | exception Not_found ->
        ()
344

345 346 347
  let stats () =
    Printf.fprintf stderr "T stores %d facts.\n%!" !count

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
  let iter f =
    let m1 = !m in
    M1.iter (fun _ m2 ->
      M2.iter (fun _ fact ->
        f fact
      ) m2
    ) m1

  (* Empirical verification that [future] determines [source] and [target]. *)
  let debug () =
    let module F = MyMap(struct
      type t = Trie.trie
      let compare = Trie.compare
    end) in
    let f = ref F.empty in
    let c = ref 0 in
    iter (fun fact ->
      incr c;
      try
        let older_fact = F.find fact.future !f in
        assert (Lr1.Node.compare older_fact.source fact.source = 0);
        assert (Lr1.Node.compare older_fact.target fact.target = 0);
      with Not_found ->
        f := F.add fact.future fact !f
    );
    Printf.fprintf stderr "Yes (%d facts, %d distinct futures)\n" !c (F.cardinal !f)

375 376 377 378 379 380 381 382 383
end

(* The module [E] is in charge of recording the non-terminal edges that we have
   discovered, or more precisely, the conditions under which these edges can be
   taken. *)

module E : sig

  (* [register s nt w z] records that, in state [s], the outgoing edge labeled
384 385 386
     [nt] can be taken by consuming the word [w], if the next symbol is [z].
     It returns [true] if this information is new. *)
  val register: Lr1.node -> Nonterminal.t -> W.word -> Terminal.t -> bool
387 388 389 390

  (* [query s nt a z] answers whether, in state [s], the outgoing edge labeled
     [nt] can be taken by consuming some word [w], under the assumption that
     the next symbol is [z], and under the constraint that the first symbol of
391 392
     [w.z] is [a]. *)
  val query: Lr1.node -> Nonterminal.t -> Terminal.t -> Terminal.t -> (W.word -> unit) -> unit
393

394 395
  val stats: unit -> unit

396 397 398 399 400
end = struct

  (* For now, we implement a mapping of [s, nt, a, z] to [w]. *)

  module M =
401
    MyMap(struct
402 403 404 405 406 407 408 409 410 411 412 413 414 415
      type t = Lr1.node * Nonterminal.t * Terminal.t * Terminal.t
      let compare (s1, nt1, a1, z1) (s2, nt2, a2, z2) =
        let c = Lr1.Node.compare s1 s2 in
        if c <> 0 then c else
        let c = Nonterminal.compare nt1 nt2 in
        if c <> 0 then c else
        let c = Terminal.compare a1 a2 in
        if c <> 0 then c else
        Terminal.compare z1 z2
    end)

  let m =
    ref M.empty

416 417
  let count = ref 0

418
  let register s nt w z =
419
    let a = W.first w z in
420 421 422
    update_ref m (fun m ->
      M.update None some (s, nt, a, z) m (function
      | None ->
423
          incr count;
424 425
          w
      | Some earlier_w ->
426
          (* assert (W.length earlier_w <= W.length w); *)
427 428 429
          earlier_w
      )
    )
430

431 432 433 434
  let query s nt a z f =
    match M.find (s, nt, a, z) !m with
    | w -> f w
    | exception Not_found -> ()
435

436 437 438
  let stats () =
    Printf.fprintf stderr "E stores %d facts.\n%!" !count

439 440
end

441
let extend fact target sym w z =
442
  (* assert (Terminal.equal fact.lookahead (first w z)); *)
443
  let future = Trie.derivative sym fact.future in
444 445 446
  {
    source = fact.source;
    target = target;
447
    future = future;
448
    word = W.append fact.word w;
449
    lookahead = z
450 451
  }

452
let new_edge s nt w z =
POTTIER Francois's avatar
POTTIER Francois committed
453 454 455 456
  (*
  Printf.fprintf stderr "Considering reduction on %s in state %d\n"
    (Terminal.print z) (Lr1.number s);
  *)
457
  if E.register s nt w z then
458
    let sym = (Symbol.N nt) in
459
    let s' = try SymbolMap.find sym (Lr1.transitions s) with Not_found -> assert false in
460
    T.query s (W.first w z) (fun fact ->
461
      if extensible fact sym then
462
        add (extend fact s' sym w z)
463
    )
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

(* [consequences fact] is invoked when we discover a new fact (i.e., one that
   was not previously known). It studies the consequences of this fact. These
   consequences are of two kinds:

   - As in Dijkstra's algorithm, the new fact can be viewed as a newly
   discovered vertex. We study its (currently known) outgoing edges,
   and enqueue new facts in the priority queue.

   - Sometimes, a fact can also be viewed as a newly discovered edge.
   This is the case when the word from [fact.source] to [fact.target]
   represents a production of the grammar and [fact.target] is willing
   to reduce this production. We record the existence of this edge,
   and re-inspect any previously discovered vertices which are
   interested in this outgoing edge.
*)
(**)

let consequences fact =

  (* 1. View [fact] as a vertex. Examine the transitions out of [fact.target]. *)
  
486 487
  SymbolMap.iter (fun sym s ->
    if extensible fact sym then
488 489 490
      match sym with
      | Symbol.T t ->

491 492 493 494
          (* 1a. There is a transition labeled [t] out of [fact.target]. If
             the lookahead assumption [fact.lookahead] is compatible with [t],
             then we derive a new fact, where one more edge has been taken. We
             enqueue this new fact for later examination. *)
495 496 497 498
          (**)

          if Terminal.equal fact.lookahead t then
            foreach_terminal (fun z ->
499
              add (extend fact s sym (W.singleton t) z)
500 501 502 503 504 505 506 507 508 509 510 511
            )

      | Symbol.N nt ->

          (* 1b. There is a transition labeled [nt] out of [fact.target]. We
             need to know how this nonterminal edge can be taken. We query for a
             word [w] that allows us to take this edge. The answer depends on
             the terminal symbol [z] that comes *after* this word: we try all
             such symbols. Furthermore, we need the first symbol of [w.z] to
             satisfy the lookahead assumption [fact.lookahead], so the answer
             also depends on this assumption. *)
          (**)
512

513
          foreach_terminal (fun z ->
514
            E.query fact.target nt fact.lookahead z (fun w ->
515
              add (extend fact s sym w z)
516
            )
517
          )
518

519
  ) (Lr1.transitions fact.target);
520 521 522 523

  (* 2. View [fact] as a possible edge. This is possible if the path from
     [fact.source] to [fact.target] represents a production [prod] and
     [fact.target] is willing to reduce this production. We check that
524 525 526 527 528
     [fact.future] accepts [epsilon]. This guarantees that reducing [prod]
     takes us all the way back to [fact.source]. Thus, this production gives
     rise to an edge labeled [nt] -- the left-hand side of [prod] -- out of
     [fact.source]. This edge is subject to the lookahead assumption
     [fact.lookahead], so we record that. *)
529 530
  (**)

531
  match has_reduction fact.target fact.lookahead with
532
  | Some prod when Trie.accepts prod fact.future ->
533 534 535 536
      new_edge fact.source (Production.nt prod) fact.word fact.lookahead
  | _ ->
      ()

537
let level = ref 0
538 539

let discover fact =
540
  if T.register fact then begin
541 542 543 544 545

    if W.length fact.word > ! level then begin
      Printf.fprintf stderr "Done with level %d.\n" !level;
      level := W.length fact.word;
      T.stats();
546 547
      E.stats();
      Printf.fprintf stderr "Q stores %d facts.\n%!" (Q.cardinal q)
548
    end;
549
(*
550
    incr facts;
551
    Printf.fprintf stderr "Facts = %d, current length = %d\n%!"
552
      !facts ();
553
    Printf.fprintf stderr "New fact:\n";
554
    print_fact fact;
555
*)
556
    consequences fact
557
  end
558

559
let main =
560
  Lr1.iter init;
561
  Printf.fprintf stderr "Cumulated star size: %d\n%!" !stars;
562
  Q.repeat q discover;
563 564
  Time.tick "Running LRijkstra";
  T.stats();
565 566
  E.stats();
  T.debug()
567

568 569
(* ------------------------------------------------------------------------ *)

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
(* The following code validates the fact that an error can be triggered in
   state [s'] by beginning in the initial state [s] and reading the
   sequence of terminal symbols [w]. We use this for debugging purposes. *)

let fail msg =
  Printf.fprintf stderr "coverage: internal error: %s.\n%!" msg;
  false

open ReferenceInterpreter

let validate s s' w : bool =
  match
    ReferenceInterpreter.check_error_path (Lr1.nt_of_entry s) (W.elements w)
  with
  | OInputReadPastEnd ->
      fail "input was read past its end"
  | OInputNotFullyConsumed ->
      fail "input was not fully consumed"
  | OUnexpectedAccept ->
      fail "input was unexpectedly accepted"
  | OK state ->
      Lr1.Node.compare state s' = 0 ||
      fail (
        Printf.sprintf "error occurred in state %d instead of %d"
          (Lr1.number state)
          (Lr1.number s')
      )

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

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
(* We now wish to determine, given a state [s'] and a terminal symbol [z], a
   minimal path that takes us from some entry state to state [s'] with [z] as
   the next (unconsumed) symbol. *)

(* This can be formulated as a search for a shortest path in a graph. The
   graph is not just the automaton, though. It is a (much) larger graph whose
   vertices are pairs [s, z] and whose edges are obtained by querying the
   module [E] above. Because we perform a backward search, from [s', z] to any
   entry state, we use reverse edges, from a state to its predecessors in the
   automaton. *)

(* Debugging. TEMPORARY *)
let es = ref 0

exception Success of Lr1.node * W.word

let backward (s', z) : unit =

  let module A = Astar.Make(struct

    (* A vertex is a pair [s, z].
       [z] cannot be the [error] token. *)
    type node =
        Lr1.node * Terminal.t

    let equal (s'1, z1) (s'2, z2) =
      Lr1.Node.compare s'1 s'2 = 0 && Terminal.compare z1 z2 = 0

    let hash (s, z) =
      Hashtbl.hash (Lr1.number s, z)

    (* An edge is labeled with a word. *)
    type label =
      W.word

    (* Backward search from the single source [s', z]. *)
    let sources f = f (s', z)

    let successors (s', z) edge =
      assert (not (Terminal.equal z Terminal.error));
      match Lr1.incoming_symbol s' with
      | None ->
          (* An entry state has no predecessor states. *)
          ()

      | Some (Symbol.T t) ->
          if not (Terminal.equal t Terminal.error) then
            (* There is an edge from [s] to [s'] labeled [t] in the automaton.
               Thus, our graph has an edge from [s', z] to [s, t], labeled [t]. *)
            let w = W.singleton t in
            List.iter (fun s ->
              edge w 1 (s, t)
            ) (Lr1.predecessors s')

      | Some (Symbol.N nt) ->
          (* There is an edge from [s] to [s'] labeled [nt] in the automaton.
             For every letter [a], we query [E] for a word [w] that begins in
             [s] and allows us to take the edge labeled [nt] when the
             lookahead symbol is [z]. Such a path [w] takes us from [s, a] to
             [s', z]. Thus, our graph has an edge, labeled [w], in the reverse
             direction. *)
          (**)
          List.iter (fun s ->
            foreach_terminal (fun a ->
              assert (not (Terminal.equal a Terminal.error));
              E.query s nt a z (fun w ->
                edge w (W.length w) (s, a)
              )
            )
          ) (Lr1.predecessors s')

    let estimate (s', _z) =
      approximate s'

  end) in

  (* Search backwards from [s', z], stopping as soon as an entry state [s] is
     reached. In that case, return the state [s] and the path that has been
     found. *)

680
  let _, _ = A.search (fun ((s, _), path) ->
681 682 683 684 685
    (* Debugging. TEMPORARY *)
    incr es;
    if !es mod 10000 = 0 then
      Printf.fprintf stderr "es = %d\n%!" !es;
    (* If [s] is a start state... *)
686
    let _, ws = A.reverse path in
POTTIER Francois's avatar
POTTIER Francois committed
687
    let ws = List.rev ws in
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
    if Lr1.incoming_symbol s = None then
      (* [labels] is a list of properties. Projecting onto the second
         component yields a list of paths (sequences of terminal symbols),
         which we concatenate to obtain a path. Because the edges that were
         followed last are in front of the list, and because this is a
         reverse graph, we obtain a path that makes direct sense: it is a
         sequence of terminal symbols that will take the automaton into
         state [s'] if the next (unconsumed) symbol is [z]. We append [z]
         at the end of this path. *)
      let w = List.fold_right W.append ws (W.singleton z) in
      raise (Success (s, w))
  ) in
  ()

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

704
(* Forward search. *)
705

706
let forward () =
707

708
  let module A = Astar.Make(struct
709

710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    (* A vertex is a pair [s, z].
       [z] cannot be the [error] token. *)
    type node =
        Lr1.node * Terminal.t

    let equal (s'1, z1) (s'2, z2) =
      Lr1.Node.compare s'1 s'2 = 0 && Terminal.compare z1 z2 = 0

    let hash (s, z) =
      Hashtbl.hash (Lr1.number s, z)

    (* An edge is labeled with a word. *)
    type label =
      W.word

    (* Forward search from every [s, z], where [s] is an initial state. *)
    let sources f =
      foreach_terminal (fun z ->
        ProductionMap.iter (fun _ s ->
          f (s, z)
        ) Lr1.entry
731 732
      )

733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
    let successors (s, z) edge =
      assert (not (Terminal.equal z Terminal.error));
      SymbolMap.iter (fun sym s' ->
        match sym with
        | Symbol.T t ->
            if Terminal.equal z t then
              let w = W.singleton t in
              foreach_terminal (fun z ->
                edge w 1 (s', z)
              )
        | Symbol.N nt ->
           foreach_terminal (fun z' ->
             E.query s nt z z' (fun w ->
               edge w (W.length w) (s', z')
             )
           )
      ) (Lr1.transitions s)

    let estimate _ =
      0

  end) in

  (* Search forward. *)

758
  Printf.fprintf stderr "Forward search:\n%!";
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
  let es = ref 0 in
  let seen = ref Lr1.NodeSet.empty in
  let _, _ = A.search (fun ((s', z), (path : A.path)) ->
    (* Debugging. TEMPORARY *)
    incr es;
    if !es mod 10000 = 0 then
      Printf.fprintf stderr "es = %d\n%!" !es;
    if causes_an_error s' z && not (Lr1.NodeSet.mem s' !seen) then begin
      seen := Lr1.NodeSet.add s' !seen;
      (* An error can be triggered in state [s'] by beginning in the initial
         state [s] and reading the sequence of terminal symbols [w]. *)
      let (s, _), ws = A.reverse path in
      let w = List.fold_right W.append ws (W.singleton z) in
      Printf.fprintf stderr
        "An error can be reached from state %d to state %d:\n%!"
        (Lr1.number s)
        (Lr1.number s');
      Printf.fprintf stderr "%s\n%!" (W.print w);
777
      (*
778 779 780 781 782
      let approx = approximate s'
      and real = W.length w - 1 in
      assert (approx <= real);
      if approx < real then
        Printf.fprintf stderr "Approx = %d, real = %d\n" approx real;
783
      *)
784 785 786
      assert (validate s s' w)
    end
  ) in
787 788 789
  Printf.fprintf stderr "Reachable (forward): %d states\n%!"
    (Lr1.NodeSet.cardinal !seen);
  !seen
790

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
(* ------------------------------------------------------------------------ *)

(* For each state [s'] and for each terminal symbol [z] such that [z] triggers
   an error in [s'], backward search is performed. For each state [s'], we
   stop as soon as one [z] is found, i.e., as soon as one way of causing an
   error in state [s'] is found. *)

let backward s' : W.word option =
  
  (* Debugging. TEMPORARY *)
  Printf.fprintf stderr
    "Attempting to reach an error in state %d:\n%!"
    (Lr1.number s');

  try

    (* This loop stops as soon as we are able to reach one error at [s']. *)
    Terminal.iter (fun z ->
      if not (Terminal.equal z Terminal.error) && causes_an_error s' z then
        backward (s', z)
    );
    (* No error can be triggered in state [s']. *)
    None

  with Success (s, w) ->
    (* An error can be triggered in state [s'] by beginning in the initial
       state [s] and reading the sequence of terminal symbols [w]. *)
    assert (validate s s' w);
    Some w

(* Test. TEMPORARY *)

823 824
let backward () =
  let reachable = ref Lr1.NodeSet.empty in
825 826 827
  Lr1.iter (fun s' ->
    begin match backward s' with
    | None ->
828
        Printf.fprintf stderr "infinity\n%!"
829
    | Some w ->
830 831
        Printf.fprintf stderr "%s\n%!" (W.print w);
        reachable := Lr1.NodeSet.add s' !reachable
832
    end;
833 834 835 836 837 838
    Printf.fprintf stderr "Edges so far: %d\n" !es
  );
  Printf.fprintf stderr "Reachable (backward): %d states\n%!"
    (Lr1.NodeSet.cardinal !reachable);
  !reachable

839 840
(* TEMPORARY what about the pseudo-token [#]? *)
(* TEMPORARY the code in this module should run only if --coverage is set *)
841 842

let () =
843
(*
844 845
  let b = backward() in
  Time.tick "Backward search";
846
*)
847 848
  let f = forward() in
  Time.tick "Forward search";
849 850
  ignore f
(*
851
  assert (Lr1.NodeSet.equal b f)
852
*)