LRijkstra.ml 27.2 KB
Newer Older
1
open Grammar
2
module W = Terminal.Word(struct end) (* TEMPORARY wrap side effect in functor *)
3

4 5 6 7
(* Throughout, we ignore the [error] pseudo-token completely. We consider that
   it never appears on the input stream. Hence, any state whose incoming
   symbol is [error] is considered unreachable. *)

8 9
(* ------------------------------------------------------------------------ *)

10 11 12 13 14 15 16 17
(* We begin with a number of auxiliary functions that provide information
   about the LR(1) automaton. These functions could perhaps be moved to a
   separate module. We keep them here, for the moment, because they are not
   used anywhere else. *)

(* [reductions s z] is the list of reductions permitted in state [s] when the
   lookahead symbol is [z]. This is a list of zero or one elements. This does
   not take default reductions into account. *)
18

19
let reductions s z : Production.index list =
20 21 22 23 24
  try
    TerminalMap.find z (Lr1.reductions s)
  with Not_found ->
    []

25 26 27
(* [has_reduction s z] tells whether state [s] is willing to reduce some
   production (and if so, which one) when the lookahead symbol is [z]. It
   takes a possible default reduction into account. *)
28 29 30 31 32 33 34 35 36 37 38 39 40

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

41 42 43 44 45 46 47 48 49 50 51 52 53
(* [can_reduce s prod] indicates whether state [s] is able to reduce
   production [prod] (either as a default reduction, or as a normal
   reduction). *)

let can_reduce s prod =
  match Invariant.has_default_reduction s with
  | Some (prod', _) when prod = prod' ->
      true
  | _ ->
      TerminalMap.fold (fun _ prods accu ->
        accu || List.mem prod prods
      ) (Lr1.reductions s) false

54 55
(* [causes_an_error s z] tells whether state [s] will initiate an error on the
   lookahead symbol [z]. *)
56

57
let causes_an_error s z : bool =
58 59 60 61 62 63 64
  match Invariant.has_default_reduction s with
  | Some _ ->
      false
  | None ->
      reductions s z = [] &&
      not (SymbolMap.mem (Symbol.T z) (Lr1.transitions s))

65 66 67
(* [foreach_terminal f] applies the function [f] to every terminal symbol in
   turn, except [error]. *)

68 69 70 71 72 73
let foreach_terminal f =
  Terminal.iter (fun t ->
    if not (Terminal.equal t Terminal.error) then
      f t
  )

74 75 76 77 78
(* [foreach_terminal_not_causing_an_error s f] applies the function [f] to
   every terminal symbol [z] such that [causes_an_error s z] is false. This
   could be implemented in a naive manner using [foreach_terminal] and
   [causes_an_error]. This implementation is slightly more efficient. *)

79 80 81
let foreach_terminal_not_causing_an_error s f =
  match Invariant.has_default_reduction s with
  | Some _ ->
82
      (* There is a default reduction. No symbol causes an error. *)
83 84
      foreach_terminal f
  | None ->
85 86 87 88 89
      (* Enumerate every terminal symbol [z] for which there is a
         reduction. *)
      TerminalMap.iter (fun z _ ->
        if not (Terminal.equal z Terminal.error) then
          f z
90
      ) (Lr1.reductions s);
91 92
      (* Enumerate every terminal symbol [z] for which there is a
         transition. *)
93 94
      SymbolMap.iter (fun sym _ ->
        match sym with
95 96 97
        | Symbol.T z ->
            if not (Terminal.equal z Terminal.error) then
              f z
98 99 100 101
        | Symbol.N _ ->
            ()
      ) (Lr1.transitions s)

102 103
(* ------------------------------------------------------------------------ *)

POTTIER Francois's avatar
POTTIER Francois committed
104 105 106 107 108 109 110 111 112 113 114 115
(* Suppose [s] is a state that carries an outgoing edge labeled with a
   non-terminal symbol [nt]. We are interested in finding out how this edge
   can be taken. In order to do that, we must determine how, by starting in
   [s], one can follow a path that corresponds to (the right-hand side of) a
   production [prod] associated with [nt]. There are in general several such
   productions. The paths that they determine in the automaton form a "star".
   We represent the star rooted at [s] as a trie. For every state [s], the
   star rooted at [s] is constructed in advance, before the algorithm runs.
   While the algorithm runs, a point in the trie (that is, a sub-trie) tells
   us where we come form, where we are, and which production(s) we are hoping
   to reduce in the future. *)

116 117 118
module Trie : sig

  type trie
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

  (* [star s] creates a (new) trie whose source is [s], populated with its
     branches. (There is one branch for every production [prod] associated
     with every non-terminal symbol [nt] for which [s] carries an outgoing
     edge.) If the star turns out to be trivial (i.e., without any branches)
     then [None] is returned. *)
  val star: Lr1.node -> trie option

  (* Every (sub-)trie has a unique identity. (One can think of it as its
     address.) [compare] compares the identity of two tries. This can be
     used, e.g., to set up a map whose keys are tries. *)
  val compare: trie -> trie -> int

  (* [source t] returns the source state of the (sub-)trie [t]. This is
     the root of the star of which [t] is a sub-trie. In other words, this
     tells us "where we come from". *)
135
  val source: trie -> Lr1.node
POTTIER Francois's avatar
POTTIER Francois committed
136 137

  (* [current t] returns the current state of the (sub-)trie [t]. This is
138 139
     the root of the sub-trie [t]. In other words, this tells us "where
     we are". *)
POTTIER Francois's avatar
POTTIER Francois committed
140
  val current: trie -> Lr1.node
141

142 143 144 145 146
  (* [accepts prod t] tells whether the current state of the trie [t] is
     the end of a branch associated with production [prod]. If so, this
     means that we have successfully followed a path that corresponds to
     the right-hand side of production [prod]. *)
  val accepts: Production.index -> trie -> bool
147

148 149 150 151 152 153 154 155
  (* [step sym t] is the immediate sub-trie of [t] along the symbol [sym].
     This function raises [Not_found] if [t] has no child labeled [sym]. *)
  val step: Symbol.t -> trie -> trie

  (* [verbose()] outputs debugging & performance information. *)
  val verbose: unit -> unit

end = struct
156

157 158
  (* A trie has the following structure. *)

159
  type trie = {
160 161 162
    (* A unique identity, used by [compare]. The trie construction code
       ensures that these numbers are indeed unique: see [fresh], [insert],
       [star]. *)
163
    identity: int;
164
    (* The root state of this star: "where we come from". *)
165
    source: Lr1.node;
166
    (* The current state, i.e., the root of this sub-trie: "where we are". *)
POTTIER Francois's avatar
POTTIER Francois committed
167
    current: Lr1.node;
168 169 170
    (* The productions that we can reduce in the current state. In other
       words, if this list is nonempty, then the current state is the end
       of one (or several) branches. It can nonetheless have children. *)
171
    productions: Production.index list;
172 173
    (* The children, or sub-tries. *)
    transitions: trie SymbolMap.t
174
  }
175

176
  (* This counter is used by [mktrie] to produce unique identities. *)
177 178
  let c = ref 0

179
  (* This smart constructor creates a new trie with a unique identity. *)
POTTIER Francois's avatar
POTTIER Francois committed
180
  let mktrie source current productions transitions =
181
    let identity = Misc.postincrement c in
POTTIER Francois's avatar
POTTIER Francois committed
182
    { identity; source; current; productions; transitions }
183

184 185
  exception DeadBranch

186
  let rec insert w prod t =
187 188
    match w with
    | [] ->
POTTIER Francois's avatar
POTTIER Francois committed
189
        (* We check whether the current state [t.current] is able to reduce
190 191 192 193 194
           production [prod]. (If [prod] cannot be reduced, the reduction
           action must have been suppressed by conflict resolution.) If not,
           then this branch is dead. This test is superfluous (i.e., it would
           be OK to conservatively assume that [prod] can be reduced) but
           allows us to build a slightly smaller star in some cases. *)
POTTIER Francois's avatar
POTTIER Francois committed
195
        if can_reduce t.current prod then
196 197 198 199 200 201
          (* We consume (update) the trie [t], so there is no need to allocate
             a new stamp. (Of course we could allocate a new stamp, but I prefer
             to be precise.) *)
          { t with productions = prod :: t.productions }
        else
          raise DeadBranch
202
    | a :: w ->
POTTIER Francois's avatar
POTTIER Francois committed
203
        (* Check if there is a transition labeled [a] out of [t.current]. If
204 205
           there is, we add a child to the trie [t]. If there isn't, then it
           must have been removed by conflict resolution. (Indeed, it must be
206 207 208
           present in a canonical automaton.) We could in this case return an
           unchanged sub-trie. We can do slightly better: we abort the whole
           insertion, so as to return an unchanged toplevel trie. *)
POTTIER Francois's avatar
POTTIER Francois committed
209
        match SymbolMap.find a (Lr1.transitions t.current) with
210
        | successor ->
211 212 213 214 215 216 217 218
            (* Find our child at [a], or create it. *)
            let t' =
              try
                SymbolMap.find a t.transitions
              with Not_found ->
                mktrie t.source successor [] SymbolMap.empty
            in
            (* Update the child [t']. *)
219
            let t' = insert w prod t' in
220 221
            (* Update [t]. Again, no need to allocate a new stamp. *)
            { t with transitions = SymbolMap.add a t' t.transitions }
222
        | exception Not_found ->
223
            raise DeadBranch
224

225 226 227 228 229
  (* [insert prod t] inserts a new branch, corresponding to production
     [prod], into the trie [t]. This function consumes its argument,
     which should no longer be used afterwards. *)
  let insert prod t =
    let w = Array.to_list (Production.rhs prod) in
230 231 232 233 234 235
    let save = !c in
    try
      insert w prod t
    with DeadBranch ->
      c := save;
      t
236

237 238 239 240 241 242 243 244 245 246 247 248 249
  (* [fresh s] creates a new empty trie whose source is [s]. *)
  let fresh source =
    mktrie source source [] SymbolMap.empty

  let star s =
    SymbolMap.fold (fun sym _ accu ->
      match sym with
      | Symbol.T _ ->
          accu
      | Symbol.N nt ->
          Production.foldnt nt accu insert
    ) (Lr1.transitions s) (fresh s)

250 251
  (* [nontrivial t] tests whether the trie [t] has any branches, i.e.,
     contains at least one sub-trie whose [productions] field is nonempty. *)
252 253 254
  let nontrivial t =
    not (t.productions = [] && SymbolMap.is_empty t.transitions)

255
  (* Redefine [star] to include a [nontrivial] test. *)
256 257 258 259 260 261 262
  let star s =
    let t = star s in
    if nontrivial t then
      Some t
    else
      None

POTTIER Francois's avatar
POTTIER Francois committed
263 264
  let compare t1 t2 =
    Pervasives.compare (t1.identity : int) t2.identity
265

266 267 268
  let source t =
    t.source

POTTIER Francois's avatar
POTTIER Francois committed
269 270
  let current t =
    t.current
271

272 273 274
  let accepts prod t =
    List.mem prod t.productions

275
  let step a t =
276
    SymbolMap.find a t.transitions (* careful: may raise [Not_found] *)
277

278
  let verbose () =
279
    Printf.fprintf stderr "Cumulated star size: %d\n%!" !c
280

281 282
end

POTTIER Francois's avatar
POTTIER Francois committed
283 284
(* ------------------------------------------------------------------------ *)

POTTIER Francois's avatar
POTTIER Francois committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
(* The main algorithm, [LRijkstra], accumulates facts. A fact is a triple of a
   position (that is, a sub-trie), a word, and a lookahead assumption. Such a
   fact means that this position can be reached, from the source state
   [Trie.source fact.position], by consuming [fact.word], under the assumption
   that the next input symbol is [fact.lookahead]. *)

(* The first symbol of the input, [first fact.word fact.lookahead], plays a
   special role. Indeed, for every position, for every first symbol, and for
   every lookahead symbol, we keep track of at most one fact. Thus, the total
   number of facts accumulated by the algorithm is at most [T.n^2], where [T]
   is the total size of the tries that we have constructed, and [n] is the
   number of terminal symbols. (This number can be quite large. [T] can be in
   the tens of thousands, and [n] can be over one hundred. These figures lead
   to a theoretical upper bound of 100M. In practice, for T=25K and n=108, we
   observe that the algorithm gathers about 7M facts.) *)

301
type fact = {
302
  position: Trie.trie;
303
  word: W.word;
304
  lookahead: Terminal.t
305 306
}

307
let source fact =
308
  Trie.source fact.position
309

POTTIER Francois's avatar
POTTIER Francois committed
310
let current fact =
311
  Trie.current fact.position
312

POTTIER Francois's avatar
POTTIER Francois committed
313
(* ------------------------------------------------------------------------ *)
314 315

module T : sig
316 317

  (* [register fact] registers the fact [fact]. It returns [true] if this fact
POTTIER Francois's avatar
POTTIER Francois committed
318 319
     is new, i.e., no fact concerning the same triple of [position], [a], and
     [z] was previously known. *)
320 321
  val register: fact -> bool

POTTIER Francois's avatar
POTTIER Francois committed
322 323
  (* [query current z f] enumerates all known facts whose current state is
     [current] and whose lookahead assumption is [z]. *)
324
  val query: Lr1.node -> Terminal.t -> (fact -> unit) -> unit
325

326
  val verbose: unit -> unit
327

328
end = struct
329

330
  (* This module implements a set of facts. Two facts are considered equal
331
     (for the purposes of this set) if they have the same [position], [a], and
332 333 334 335 336 337
     [z] fields. The [word] is not considered. Indeed, we are not interested
     in keeping track of several words that produce the same effect. Only the
     shortest such word is of interest. *)

  (* We need to query the set of facts in two ways. In [register], we need to
     test whether a fact is in the set. In [query], we need to find all facts
POTTIER Francois's avatar
POTTIER Francois committed
338 339
     that match a pair [current, z]. For this reason, we use a two-level table.
     The first level is a matrix indexed by [current] and [z]. At the second
340
     level, we find sets of facts. *)
341 342 343
(**)

  module M =
344
    MySet.Make(struct
345 346
      type t = fact
      let compare fact1 fact2 =
347
        let c = Trie.compare fact1.position fact2.position in
348
        if c <> 0 then c else
349 350
        let a1 = W.first fact1.word fact1.lookahead
        and a2 = W.first fact2.word fact2.lookahead in
351 352
        Terminal.compare a1 a2
    end)
353

354 355 356
  let table = (* a pretty large table... *)
    Array.make (Lr1.n * Terminal.n) M.empty

POTTIER Francois's avatar
POTTIER Francois committed
357 358
  let index current z =
    Terminal.n * (Lr1.number current) + Terminal.t2i z
359

360 361
  let count = ref 0

362
  let register fact =
POTTIER Francois's avatar
POTTIER Francois committed
363
    let current = current fact in
364
    let z = fact.lookahead in
POTTIER Francois's avatar
POTTIER Francois committed
365
    let i = index current z in
366 367 368 369 370 371 372 373 374 375 376 377
    let m = table.(i) in
    (* We crucially rely on the fact that [M.add] guarantees not to
       change the set if an ``equal'' fact already exists. Thus, a
       later, longer path is ignored in favor of an earlier, shorter
       path. *)
    let m' = M.add fact m in
    m != m' && begin
      incr count;
      table.(i) <- m';
      true
    end

POTTIER Francois's avatar
POTTIER Francois committed
378 379
  let query current z f =
    let i = index current z in
380 381
    let m = table.(i) in
    M.iter f m
382

383
  let verbose () =
384 385
    Printf.fprintf stderr "T stores %d facts.\n%!" !count

386 387
end

POTTIER Francois's avatar
POTTIER Francois committed
388 389
(* ------------------------------------------------------------------------ *)

390 391 392 393 394 395 396
(* 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
397 398 399
     [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
400 401 402 403

  (* [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
404 405
     [w.z] is [a]. *)
  val query: Lr1.node -> Nonterminal.t -> Terminal.t -> Terminal.t -> (W.word -> unit) -> unit
406

407
  val verbose: unit -> unit
408

409 410 411 412
end = struct

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

413 414 415 416 417 418 419 420 421
  module H = Hashtbl
(*
    Hashtbl.Make(struct
      type t = Nonterminal.t * Terminal.t * Terminal.t
      let equal = (=)
      let hash = Hashtbl.hash
    end)
*)
(*
422
  module M =
423
    MySet.Make(struct
424 425
      type t = Nonterminal.t * Terminal.t * W.word
      let compare (nt1, a1, _w1) (nt2, a2, _w2) =
426 427
        let c = Nonterminal.compare nt1 nt2 in
        if c <> 0 then c else
428
        Terminal.compare a1 a2
429
    end)
430
*)
431
  let table = (* a pretty large table... *)
432 433 434 435
    Array.init (Lr1.n) (fun _ -> H.create 6311)

  let index s =
    Lr1.number s
436

437 438 439 440
  let pack nt a z : int =
    (Nonterminal.n2i nt lsl 16) lor
    (Terminal.t2i a lsl 8) lor
    (Terminal.t2i z)
441

442 443
  let count = ref 0

444
  let register s nt w z =
445
    let i = index s in
446
    let m = table.(i) in
447
    let a = W.first w z in
448 449 450 451
    let key = pack nt a z in
    if H.mem m key then
      false
    else begin
452
      incr count;
453
      H.add m key w;
454 455
      true
    end
456

457
  let query s nt a z f =
458
    let i = index s in
459
    let m = table.(i) in
460 461 462
    let key = pack nt a z in
    match H.find m key with
    | w -> f w
463
    | exception Not_found -> ()
464

465
  let verbose () =
466 467
    Printf.fprintf stderr "E stores %d facts.\n%!" !count

468 469
end

POTTIER Francois's avatar
POTTIER Francois committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
(* ------------------------------------------------------------------------ *)

(* As in Dijkstra's algorithm, a priority queue contains the facts that await
   examination. The length of [fact.word] serves as the priority of a fact.
   This guarantees that we discover shortest paths. (We never insert into the
   queue a fact whose priority is less than the priority of the last fact
   extracted out of the queue.) *)

(* [LowIntegerPriorityQueue] offers very efficient operations (essentially
   constant time, for a small constant). It exploits the fact that priorities
   are low nonnegative integers. *)

module Q = LowIntegerPriorityQueue

let q =
  Q.create()

(* We never insert into the queue a fact that immediately causes an error,
   i.e., a fact such that [causes_an_error (current fact) fact.lookahead]
   holds. In practice, this convention allows reducing the number of facts
   that go through the queue by a factor of two. *)

(* In principle, there is no need to insert the fact into the queue if [T]
   already stores a comparable fact. We could perform this test in [add].
   However, a quick experiment suggests that this is not worthwhile. The run
   time augments (because membership in [T] is tested twice, upon inserting
   and upon extracting) and the memory consumption does not seem to go down
   significantly. *)

let add fact =
  (* assert (not (causes_an_error (current fact) fact.lookahead)); *)
  (* The length of [fact.word] serves as the priority of this fact. *)
  Q.add q fact (W.length fact.word)

let init s =
  match Trie.star s with
  | Some trie ->
      foreach_terminal_not_causing_an_error s (fun z ->
        add {
          position = trie;
          word = W.epsilon;
          lookahead = z
        }
      )
  | None ->
      ()

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

519
let new_edge s nt w z =
POTTIER Francois's avatar
POTTIER Francois committed
520 521 522 523
  (*
  Printf.fprintf stderr "Considering reduction on %s in state %d\n"
    (Terminal.print z) (Lr1.number s);
  *)
524
  if E.register s nt w z then
525
    let sym = Symbol.N nt in
526
    T.query s (W.first w z) (fun fact ->
527
      assert (Terminal.equal fact.lookahead (W.first w z));
528 529 530
      match Trie.step sym fact.position with
      | position ->
          if not (causes_an_error (Trie.current position) z) then
531
            add {
532
              position;
533 534 535 536 537
              word = W.append fact.word w;
              lookahead = z
            }
      | exception Not_found ->
          ()
538
    )
539 540 541 542 543 544 545 546 547 548

(* [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.
POTTIER Francois's avatar
POTTIER Francois committed
549 550
   This is the case when the word from [fact.source] to [fact.current]
   represents a production of the grammar and [fact.current] is willing
551 552 553 554 555 556 557 558
   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 =

POTTIER Francois's avatar
POTTIER Francois committed
559
  let current = current fact in
560

POTTIER Francois's avatar
POTTIER Francois committed
561
  (* 1. View [fact] as a vertex. Examine the transitions out of [current]. *)
562
  
563
  SymbolMap.iter (fun sym s' ->
564
    match Trie.step sym fact.position, sym with
565
    | exception Not_found -> ()
566
    | position, Symbol.T t ->
567

POTTIER Francois's avatar
POTTIER Francois committed
568
        (* 1a. There is a transition labeled [t] out of [current]. If
569 570 571 572 573 574 575
           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. *)
        (**)

        if Terminal.equal fact.lookahead t then
          let word = W.append fact.word (W.singleton t) in
576
          (* assert (Lr1.Node.compare position.Trie.current s' = 0); *)
577
          foreach_terminal_not_causing_an_error s' (fun z ->
578
            add { position; word; lookahead = z }
579
          )
580

581
    | position, Symbol.N nt ->
582

POTTIER Francois's avatar
POTTIER Francois committed
583
        (* 1b. There is a transition labeled [nt] out of [current]. We
584 585 586 587 588 589 590 591 592
           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. *)
        (**)

        foreach_terminal_not_causing_an_error s' (fun z ->
POTTIER Francois's avatar
POTTIER Francois committed
593
          E.query current nt fact.lookahead z (fun w ->
594 595
            assert (Terminal.equal fact.lookahead (W.first w z));
            add {
596
              position;
597 598 599 600 601
              word = W.append fact.word w;
              lookahead = z
            }
          )
        )
602

POTTIER Francois's avatar
POTTIER Francois committed
603
  ) (Lr1.transitions current);
604 605

  (* 2. View [fact] as a possible edge. This is possible if the path from
POTTIER Francois's avatar
POTTIER Francois committed
606 607
     [fact.source] to [current] represents a production [prod] and
     [current] is willing to reduce this production. We check that
608
     [fact.position] accepts [epsilon]. This guarantees that reducing [prod]
609 610 611 612
     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. *)
613 614
  (**)

POTTIER Francois's avatar
POTTIER Francois committed
615
  match has_reduction current fact.lookahead with
616
  | Some prod when Trie.accepts prod fact.position ->
617
      new_edge (source fact) (Production.nt prod) fact.word fact.lookahead
618 619 620
  | _ ->
      ()

621
let level = ref 0
622

POTTIER Francois's avatar
POTTIER Francois committed
623 624
let done_with_level () =
  Printf.fprintf stderr "Done with level %d.\n" !level;
625
  W.verbose();
626 627
  T.verbose();
  E.verbose();
POTTIER Francois's avatar
POTTIER Francois committed
628 629
  Printf.fprintf stderr "Q stores %d facts.\n%!" (Q.cardinal q)

630
let discover fact =
631
  if T.register fact then begin
632
    if W.length fact.word > ! level then begin
POTTIER Francois's avatar
POTTIER Francois committed
633
      done_with_level();
634 635
      level := W.length fact.word;
    end;
636
    consequences fact
637
  end
638

POTTIER Francois's avatar
POTTIER Francois committed
639
let () =
640
  Lr1.iter init;
641
  Trie.verbose();
642
  Q.repeat q discover;
643
  Time.tick "Running LRijkstra";
POTTIER Francois's avatar
POTTIER Francois committed
644
  done_with_level()
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
(* 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')
      )

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

678 679 680 681 682 683 684
(* 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
685
   module [E] above. *)
686

687
let forward () =
688

689
  let module A = Astar.Make(struct
690

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
    (* 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
712 713
      )

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    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. *)

739
  Printf.fprintf stderr "Forward search:\n%!";
740
  let seen = ref Lr1.NodeSet.empty in
741
  let _, _ = A.search (fun ((s', z), path) ->
742 743 744 745 746 747 748 749 750 751 752 753 754 755
    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);
      assert (validate s s' w)
    end
  ) in
756 757 758
  Printf.fprintf stderr "Reachable (forward): %d states\n%!"
    (Lr1.NodeSet.cardinal !seen);
  !seen
759

760
(* TEMPORARY the code in this module should run only if --coverage is set *)
761 762

let () =
763 764
  let f = forward() in
  Time.tick "Forward search";
POTTIER Francois's avatar
POTTIER Francois committed
765 766 767 768
  let stat = Gc.quick_stat() in
  Printf.fprintf stderr
    "Maximum size reached by the major heap: %dM\n"
    (stat.Gc.top_heap_words * (Sys.word_size / 8) / 1024 / 1024);
769
  ignore f
770 771

(* TODO:
POTTIER Francois's avatar
POTTIER Francois committed
772
  in E, try a larger array and/or combine nt/a/z in just one word
773 774
  subject to --coverage
  write to .coverage file
POTTIER Francois's avatar
POTTIER Francois committed
775
  remove Coverage, remove CompletedNatWitness?, revert Fix
776
  collect performance data, correlated with star size and alphabet size; draw a graph
POTTIER Francois's avatar
POTTIER Francois committed
777
  count the unreachable states and see if they are numerous in practice
POTTIER Francois's avatar
POTTIER Francois committed
778 779
  search github for .mly files (batch search? unique files?)
    extension:mly in:path size:>10000 mly
780
*)
POTTIER Francois's avatar
POTTIER Francois committed
781 782 783 784 785 786 787 788 789 790 791

(* One could approach the problem just by exploring the (infinite) graph whose
   vertices are configurations of the LR automaton (i.e., stacks, or perhaps
   pairs of a stack and a lookahead symbol) and transitions are determined by
   feeding one symbol to the automaton. A small-step version of the reference
   interpreter would allow us to set this up easily. One could then run a
   breadth-first exploration of this graph and stop when desired, e.g., as
   soon as all automaton states have been reached. However, this process does
   not necessarily terminate, and could be very costly -- e.g. enumerating all
   sentences of length 10 when the alphabet has size 100 costs 10^20. Also,
   this approach cannot prove that a state is unreachable. *)