LRijkstra.ml 8.36 KB
Newer Older
1 2 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
open Grammar

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

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

end

module Q = LowIntegerPriorityQueue

type fact = {
  source: Lr1.node;
  height: int;
  target: Lr1.node;
  word: W.word;
55
  lookahead: Terminal.t
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
}

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

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

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 =
  if has_nonterminal_transition s then
98 99 100 101 102 103 104 105 106
    foreach_terminal (fun z ->
      add {
        source = s;
        height = 0;
        target = s;
        word = W.epsilon;
        lookahead = z
      }
    )
107

108 109 110
let first w z =
  if W.length w > 0 then W.first w else z

111
module T : sig
112
  val register: fact -> bool (* true if fact is new *)
113
  (* target/z *)
114
  val query: Lr1.node -> Terminal.t -> (fact -> unit) -> unit
115
end = struct
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 141 142 143 144 145 146

  (* For now, we implement a mapping of [source, height, target, a, z] to [w]. *)

  module M =
    Map.Make(struct
      type t = Lr1.node * int * Lr1.node * Terminal.t * Terminal.t
      let compare (source1, height1, target1, a1, z1) (source2, height2, target2, a2, z2) =
        let c = Lr1.Node.compare source1 source2 in
        if c <> 0 then c else
        let c = Pervasives.compare height1 height2 in
        if c <> 0 then c else
        let c = Lr1.Node.compare target1 target2 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

  let add key w' =
    match M.find key !m with
    | w ->
        assert (W.length w <= W.length w');
          (* no need to add again *)
        false
    | exception Not_found ->
        m := M.add key w' !m;
        true

147 148 149 150
  let register fact =
    let z = fact.lookahead in
    let a = first fact.word z in
    add (fact.source, fact.height, fact.target, a, z) fact.word
151

152
  let query _ = assert false
153

154 155 156 157 158 159 160 161 162
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
163 164 165
     [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
166 167 168 169

  (* [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
170 171
     [w.z] is [a]. *)
  val query: Lr1.node -> Nonterminal.t -> Terminal.t -> Terminal.t -> (W.word -> unit) -> unit
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

end = struct

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

  module M =
    Map.Make(struct
      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

193 194 195 196 197 198 199 200 201 202
  let add key w' =
    match M.find key !m with
    | w ->
        assert (W.length w <= W.length w')
          (* no need to add again *);
        false
    | exception Not_found ->
        m := M.add key w' !m;
        true

203 204 205
  let register s nt w z =
    let a = first w z in
    add (s, nt, a, z) w
206

207 208 209 210
  let query s nt a z f =
    match M.find (s, nt, a, z) !m with
    | w -> f w
    | exception Not_found -> ()
211 212 213

end

214 215
let extend fact target w z =
  assert (Terminal.equal fact.lookahead (first w z));
216 217 218 219 220
  {
    source = fact.source;
    height = fact.height + 1;
    target = target;
    word = W.append fact.word w;
221
    lookahead = z
222 223
  }

224 225 226 227
let new_edge s nt w z =
  if E.register s nt w z then
    T.query s (first w z) (fun fact ->
      add (extend fact s w z)
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

(* [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]. *)
  
  SymbolMap.iter (fun sym s ->
    match sym with
    | Symbol.T t ->

        (* 1a. There is a transition labeled [t] out of [fact.target]. If the
           lookahead assumption [fact.lookahead] accepts [t], then we derive a
           new fact, where one more edge has been taken. We enqueue this new
           fact for later examination. *)
        (**)

261 262 263 264
        if Terminal.equal fact.lookahead t then
          foreach_terminal (fun z ->
            add (extend fact s (W.singleton t) z)
          )
265 266 267 268 269 270 271 272 273 274 275 276 277 278

    | 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. *)
        (**)
      
        foreach_terminal (fun z ->
          E.query fact.target nt fact.lookahead z (fun w ->
279
            add (extend fact s w z)
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
          )
        )
    
  ) (Lr1.transitions fact.target);

  (* 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
     [fact.height] equals the length of [prod]. 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. *)
  (**)

  match Invariant.has_default_reduction fact.target with
  | Some (prod, _) ->
      if Production.length prod = fact.height then
        new_edge fact.source (Production.nt prod) fact.word fact.lookahead
  | None ->
300 301 302 303 304
      let z = fact.lookahead in
      let prods = reductions fact.target z in
      let prod = Misc.single prods in
      if Production.length prod = fact.height then
        new_edge fact.source (Production.nt prod) fact.word z
305 306

let discover fact =
307
  if T.register fact then
308 309 310 311 312
    consequences fact

let main () =
  Lr1.iter init;
  Q.repeat q discover