LRijkstra.ml 11.9 KB
Newer Older
1 2
open Grammar

3 4 5 6 7 8 9 10
  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)

11 12 13 14 15 16 17 18 19 20 21 22
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

23 24 25
module MyMap (X : Map.OrderedType) = struct
  include Map.Make(X)
  let update none some key m f =
26
    update add find none some key m f
27 28
end

29 30 31 32 33 34 35 36
module W : sig

  type word
  val epsilon: word
  val singleton: Terminal.t -> word
  val append: word -> word -> word
  val length: word -> int
  val first: word -> Terminal.t (* word must be nonempty *)
37
  val print: word -> string
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

end = struct

  type word = {
    data: Terminal.t Seq.seq;
    length: int;
  }

  let epsilon = {
    data = Seq.empty;
    length = 0;
  }

  (* TEMPORARY tabulate? *)
  let singleton t = {
    data = Seq.singleton t;
    length = 1;
  }

  let append w1 w2 =
    if w1.length = 0 then
      w2
    else if w2.length = 0 then
      w1
    else {
      data = Seq.append w1.data w2.data;
      length = w1.length + w2.length;
    }

  let length w =
    w.length

  let first w =
    Seq.first w.data

73 74 75 76
  let print w =
    string_of_int w.length ^ " " ^
    String.concat " " (List.map Terminal.print (Seq.elements w.data))

77 78 79 80
end

module Q = LowIntegerPriorityQueue

81 82 83 84 85
module Trie = struct

  let c = ref 0

  type trie =
86
    | Trie of int * Production.index list * trie SymbolMap.t
87

88
  let mktrie prods children =
89
    let stamp = Misc.postincrement c in
90
    Trie (stamp, prods, children)
91 92

  let empty =
93
    mktrie [] SymbolMap.empty
94

95 96
  let is_empty (Trie (_, prods, children)) =
    prods = [] && SymbolMap.is_empty children
97

98 99
  let accepts prod (Trie (_, prods, _)) =
    List.mem prod prods
100 101 102 103

  let update : Symbol.t -> trie SymbolMap.t -> (trie -> trie) -> trie SymbolMap.t =
    update SymbolMap.add SymbolMap.find empty id

104
  let rec insert w prod (Trie (_, prods, children)) =
105 106
    match w with
    | [] ->
107
        mktrie (prod :: prods) children
108
    | a :: w ->
109
        mktrie prods (update a children (insert w prod))
110 111 112 113 114 115 116 117 118 119 120 121

  let derivative a (Trie (_, _, children)) =
    try
      SymbolMap.find a children
    with Not_found ->
      empty

  let compare (Trie (stamp1, _, _)) (Trie (stamp2, _, _)) =
    Pervasives.compare stamp1 stamp2

end

122 123 124
type fact = {
  source: Lr1.node;
  target: Lr1.node;
125
  future: Trie.trie;
126
  word: W.word;
127
  lookahead: Terminal.t
128 129
}

130 131
let print_fact fact =
  Printf.fprintf stderr
132
    "from state %d to state %d via %s . %s\n%!"
133 134 135 136 137
    (Lr1.number fact.source)
    (Lr1.number fact.target)
    (W.print fact.word)
    (Terminal.print fact.lookahead)

138 139
let extensible fact sym =
  not (Trie.is_empty (Trie.derivative sym fact.future))
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
let foreach_terminal f =
  Terminal.iter (fun t ->
    if not (Terminal.equal t Terminal.error) then
      f t
  )

exception Found

let has_nonterminal_transition s =
  try
    SymbolMap.iter (fun sym _ ->
      match sym with
      | Symbol.T _ ->
          ()
      | Symbol.N _ ->
          raise Found
    ) (Lr1.transitions s);
    false
  with Found ->
    true

162 163 164 165 166 167 168 169
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
170
          Trie.insert w prod accu
171 172 173
        )
  ) (Lr1.transitions s) Trie.empty

174 175 176 177 178 179 180 181 182 183
(* 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 ->
    []

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
(* 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

201 202 203 204 205 206 207 208
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)

let init s =
209 210
  let trie = star s in
  assert (Trie.is_empty trie = not (has_nonterminal_transition s));
211
  if has_nonterminal_transition s then
212 213 214 215
    foreach_terminal (fun z ->
      add {
        source = s;
        target = s;
216
        future = trie;
217 218 219 220
        word = W.epsilon;
        lookahead = z
      }
    )
221

222 223 224
let first w z =
  if W.length w > 0 then W.first w else z

225
module T : sig
226 227 228 229 230 231 232 233

  (* [register fact] registers the fact [fact]. It returns [true] if this fact
     is new, i.e., no fact concerning the same quintuple of [source], [height],
     [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]. *)
234
  val query: Lr1.node -> Terminal.t -> (fact -> unit) -> unit
235

236
end = struct
237

238
  (* We use a map of [target, z] to a map of [source, height, a] to facts. *)
239

240 241 242 243
  module M1 =
    MyMap(struct
      type t = Lr1.node * Terminal.t
      let compare (target1, z1) (target2, z2) =
244 245 246 247 248
        let c = Lr1.Node.compare target1 target2 in
        if c <> 0 then c else
        Terminal.compare z1 z2
    end)

249 250
  module M2 =
    MyMap(struct
251
      type t = Lr1.node * Trie.trie * Terminal.t
252 253 254
      let compare (source1, height1, a1) (source2, height2, a2) =
        let c = Lr1.Node.compare source1 source2 in
        if c <> 0 then c else
255
        let c = Trie.compare height1 height2 in
256 257 258
        if c <> 0 then c else
        Terminal.compare a1 a2
    end)
259

260 261
  let m : fact M2.t M1.t ref =
    ref M1.empty
262

263 264 265
  let register fact =
    let z = fact.lookahead in
    let a = first fact.word z in
266 267
    update_ref m (fun m1 ->
      M1.update M2.empty id (fact.target, z) m1 (fun m2 ->
268
        M2.update None some (fact.source, fact.future, a) m2 (function
269 270 271 272 273 274 275 276
          | None ->
              fact
          | Some earlier_fact ->
              assert (W.length earlier_fact.word <= W.length fact.word);
              earlier_fact
        )
      )
    )
277

278 279 280 281 282 283 284 285
  let query target z f =
    match M1.find (target, z) !m with
    | m2 ->
        M2.iter (fun _ fact ->
          f fact
        ) m2
    | exception Not_found ->
        ()
286

287 288 289 290 291 292 293 294 295
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
296 297 298
     [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
299 300 301 302

  (* [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
303 304
     [w.z] is [a]. *)
  val query: Lr1.node -> Nonterminal.t -> Terminal.t -> Terminal.t -> (W.word -> unit) -> unit
305 306 307 308 309 310

end = struct

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

  module M =
311
    MyMap(struct
312 313 314 315 316 317 318 319 320 321 322 323 324 325
      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

326 327
  let register s nt w z =
    let a = first w z in
328 329 330 331 332 333 334 335 336
    update_ref m (fun m ->
      M.update None some (s, nt, a, z) m (function
      | None ->
          w
      | Some earlier_w ->
          assert (W.length earlier_w <= W.length w);
          earlier_w
      )
    )
337

338 339 340 341
  let query s nt a z f =
    match M.find (s, nt, a, z) !m with
    | w -> f w
    | exception Not_found -> ()
342 343 344

end

345
let extend fact target sym w z =
346
  assert (Terminal.equal fact.lookahead (first w z));
347 348
  let future = Trie.derivative sym fact.future in
  assert (not (Trie.is_empty future));
349 350 351
  {
    source = fact.source;
    target = target;
352
    future = future;
353
    word = W.append fact.word w;
354
    lookahead = z
355 356
  }

357 358
let new_edge s nt w z =
  if E.register s nt w z then
359
    let sym = (Symbol.N nt) in
360
    T.query s (first w z) (fun fact ->
361 362
      if extensible fact sym then
        add (extend fact s sym w z)
363
    )
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

(* [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]. *)
  
386 387
  SymbolMap.iter (fun sym s ->
    if extensible fact sym then
388 389 390
      match sym with
      | Symbol.T t ->

391 392 393 394
          (* 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. *)
395 396 397 398
          (**)

          if Terminal.equal fact.lookahead t then
            foreach_terminal (fun z ->
399
              add (extend fact s sym (W.singleton t) z)
400 401 402 403 404 405 406 407 408 409 410 411
            )

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

413
          foreach_terminal (fun z ->
414
            E.query fact.target nt fact.lookahead z (fun w ->
415
              add (extend fact s sym w z)
416
            )
417
          )
418

419
  ) (Lr1.transitions fact.target);
420 421 422 423

  (* 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
424 425 426 427 428
     [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. *)
429 430
  (**)

431
  match has_reduction fact.target fact.lookahead with
432
  | Some prod when Trie.accepts prod fact.future ->
433 434 435 436 437
      new_edge fact.source (Production.nt prod) fact.word fact.lookahead
  | _ ->
      ()

let facts = ref 0
438 439

let discover fact =
440 441 442
  if T.register fact then begin

    incr facts;
443
    Printf.fprintf stderr "Facts = %d, current length = %d\n%!"
444
      !facts (W.length fact.word);
445
    Printf.fprintf stderr "New fact:\n";
446 447
    print_fact fact;

448
    consequences fact
449
  end
450

451
let main =
452 453
  Lr1.iter init;
  Q.repeat q discover
454