Refactor the Ata module:
[tatoo.git] / src / run.ml
1 (***********************************************************************)
2 (*                                                                     *)
3 (*                               TAToo                                 *)
4 (*                                                                     *)
5 (*                     Kim Nguyen, LRI UMR8623                         *)
6 (*                   Université Paris-Sud & CNRS                       *)
7 (*                                                                     *)
8 (*  Copyright 2010-2013 Université Paris-Sud and Centre National de la *)
9 (*  Recherche Scientifique. All rights reserved.  This file is         *)
10 (*  distributed under the terms of the GNU Lesser General Public       *)
11 (*  License, with the special exception on linking described in file   *)
12 (*  ../LICENSE.                                                        *)
13 (*                                                                     *)
14 (***********************************************************************)
15
16 INCLUDE "utils.ml"
17 open Format
18 open Misc
19
20 module Make (T : Tree.S) =
21  struct
22
23    module NodeSummary =
24    struct
25      (* Pack into an integer the result of the is_* and has_ predicates
26         for a given node *)
27      type t = int
28      let dummy = -1
29     (*
30       4444444444443210
31       4 -> kind
32       3 -> is_left
33       2 -> is_right
34       1 -> has_left
35       0 -> has_right
36     *)
37
38      let has_right (s : t) : bool =
39        Obj.magic (s land 1)
40
41      let has_left (s : t) : bool =
42        Obj.magic ((s lsr 1) land 1)
43
44      let is_right (s : t) : bool =
45        Obj.magic ((s lsr 2) land 1)
46
47      let is_left (s : t) : bool =
48        Obj.magic ((s lsr 3) land 1)
49
50      let kind (s : t) : Tree.NodeKind.t =
51        Obj.magic (s lsr 4)
52
53      let make is_left is_right has_left has_right kind =
54        ((Obj.magic kind) lsl 4) lor
55          ((int_of_bool is_left) lsl 3) lor
56          ((int_of_bool is_right) lsl 2) lor
57          ((int_of_bool has_left) lsl 1) lor
58          (int_of_bool has_right)
59
60    end
61
62    type node_status = {
63      sat : StateSet.t;
64      unsat : StateSet.t;
65      todo : Ata.TransList.t;
66      summary : NodeSummary.t;
67    }
68 (* Describe what is kept at each node for a run *)
69
70    module NodeStatus = Hcons.Make(struct
71      type t = node_status
72      let equal c d =
73        c == d ||
74          c.sat == d.sat &&
75          c.unsat == d.unsat &&
76          c.todo == d.todo &&
77          c.summary == d.summary
78
79      let hash c =
80        HASHINT4((c.sat.StateSet.id :> int),
81                 (c.unsat.StateSet.id :> int),
82                 (c.todo.Ata.TransList.id :> int),
83                 c.summary)
84    end
85    )
86
87    let dummy_status =
88      NodeStatus.make { sat = StateSet.empty;
89                        unsat = StateSet.empty;
90                        todo = Ata.TransList.nil;
91                        summary = NodeSummary.dummy;
92                      }
93
94
95    type run = {
96      tree : T.t ;
97      (* The argument of the run *)
98      auto : Ata.t;
99      (* The automaton to be run *)
100      status : NodeStatus.t array;
101      (* A mapping from node preorders to NodeStatus *)
102      unstable : Bitvector.t;
103      (* A bitvector remembering whether a subtree is stable *)
104      mutable redo : bool;
105      (* A boolean indicating whether the run is incomplete *)
106      mutable pass : int;
107      (* The number of times this run was updated *)
108      mutable cache2 : Ata.TransList.t Cache.N2.t;
109      (* A cache from states * label to list of transitions *)
110      mutable cache4 : NodeStatus.t Cache.N4.t;
111    }
112
113    let pass r = r.pass
114    let stable r = not r.redo
115    let auto r = r.auto
116    let tree r = r.tree
117
118
119    let dummy_trl =
120      Ata.(TransList.cons
121             (Transition.make
122                (State.dummy,QNameSet.empty, Formula.false_))
123             TransList.nil)
124
125    let make auto tree =
126      let len = T.size tree in
127      {
128        tree = tree;
129        auto = auto;
130        status = Array.create len dummy_status;
131        unstable = Bitvector.create ~init:true len;
132        redo = true;
133        pass = 0;
134        cache2 = Cache.N2.create dummy_trl;
135        cache4 = Cache.N4.create dummy_status;
136      }
137
138    let get_status a i =
139      if i < 0 then dummy_status else Array.get a i
140
141    let unsafe_get_status a i =
142      if i < 0 then dummy_status else Array.unsafe_get a i
143
144 IFDEF HTMLTRACE
145   THEN
146 DEFINE TRACE(e) = (e)
147   ELSE
148 DEFINE TRACE(e) = ()
149 END
150
151    let html tree node i config msg =
152      let config = config.NodeStatus.node in
153      Html.trace (T.preorder tree node) i
154        "node: %i<br/>%s<br/>sat: %a<br/>unsat: %a<br/>todo: %around: %i<br/>"
155        (T.preorder tree node)
156        msg
157        StateSet.print config.sat
158        StateSet.print config.unsat
159        (Ata.TransList.print ~sep:"<br/>") config.todo i
160
161
162
163    let get_trans cache2 auto tag states =
164      let trs =
165        Cache.N2.find cache2
166          (tag.QName.id :> int) (states.StateSet.id :> int)
167      in
168      if trs == dummy_trl then
169        let trs = Ata.get_trans auto tag states in
170        (Cache.N2.add
171           cache2
172           (tag.QName.id :> int)
173           (states.StateSet.id :> int) trs; trs)
174      else trs
175
176
177
178    let simplify_atom atom pos q { NodeStatus.node = status; _ } =
179      if (pos && StateSet.mem q status.sat)
180        || ((not pos) && StateSet.mem q status.unsat) then Ata.Formula.true_
181      else if (pos && StateSet.mem q status.unsat)
182          || ((not pos) && StateSet.mem q status.sat) then Ata.Formula.false_
183      else atom
184
185
186    let eval_form phi fcs nss ps ss summary =
187      let open Ata in
188          let rec loop phi =
189            begin match Formula.expr phi with
190              Boolean.True | Boolean.False -> phi
191            | Boolean.Atom (a, b) ->
192                begin
193                  let open NodeSummary in
194                      match a.Atom.node with
195                      | Move (m, q) ->
196                          let states = match m with
197                            `First_child -> fcs
198                          | `Next_sibling -> nss
199                          | `Parent | `Previous_sibling -> ps
200                          | `Stay -> ss
201                          in simplify_atom phi b q states
202                      | Is_first_child -> Formula.of_bool (b == is_left summary)
203                      | Is_next_sibling -> Formula.of_bool (b == is_right summary)
204                      | Is k -> Formula.of_bool (b == (k == kind summary))
205                      | Has_first_child -> Formula.of_bool (b == has_left summary)
206                      | Has_next_sibling -> Formula.of_bool (b == has_right summary)
207                end
208            | Boolean.And(phi1, phi2) -> Formula.and_ (loop phi1) (loop phi2)
209            | Boolean.Or (phi1, phi2) -> Formula.or_  (loop phi1) (loop phi2)
210            end
211          in
212          loop phi
213
214
215
216    let eval_trans cache4 fcs nss ps ss =
217      let fcsid = (fcs.NodeStatus.id :> int) in
218      let nssid = (nss.NodeStatus.id :> int) in
219      let psid = (ps.NodeStatus.id :> int) in
220      let rec loop old_config =
221        let oid = (old_config.NodeStatus.id :> int) in
222        let res =
223          let res = Cache.N4.find cache4 oid fcsid nssid psid in
224          if res != dummy_status then res
225          else
226            let { sat = old_sat;
227                  unsat = old_unsat;
228                  todo = old_todo;
229                  summary = old_summary } = old_config.NodeStatus.node
230            in
231            let sat, unsat, removed, kept, todo =
232              Ata.TransList.fold
233                (fun trs acc ->
234                  let q, lab, phi = Ata.Transition.node trs in
235                  let a_sat, a_unsat, a_rem, a_kept, a_todo = acc in
236                  if StateSet.mem q a_sat || StateSet.mem q a_unsat then acc else
237                    let new_phi =
238                      eval_form phi fcs nss ps old_config old_summary
239                    in
240                    if Ata.Formula.is_true new_phi then
241                      StateSet.add q a_sat, a_unsat, StateSet.add q a_rem, a_kept, a_todo
242                    else if Ata.Formula.is_false new_phi then
243                      a_sat, StateSet.add q a_unsat, StateSet.add q a_rem, a_kept, a_todo
244                    else
245                      let new_tr = Ata.Transition.make (q, lab, new_phi) in
246                      (a_sat, a_unsat, a_rem, StateSet.add q a_kept, (Ata.TransList.cons new_tr a_todo))
247                ) old_todo (old_sat, old_unsat, StateSet.empty, StateSet.empty, Ata.TransList.nil)
248            in
249         (* States that have been removed from the todo list and not kept are now
250            unsatisfiable *)
251            let unsat = StateSet.union unsat (StateSet.diff removed kept) in
252         (* States that were found once to be satisfiable remain so *)
253            let unsat = StateSet.diff unsat sat in
254            let new_config = NodeStatus.make { old_config.NodeStatus.node with sat; unsat; todo; } in
255            Cache.N4.add cache4 oid fcsid nssid psid new_config;
256            new_config
257        in
258        if res == old_config then res else loop res
259      in
260      loop ss
261
262
263
264
265   let top_down node run =
266     let tree = run.tree in
267     let auto = run.auto in
268     let status = run.status in
269     let cache2 = run.cache2 in
270     let cache4 = run.cache4 in
271     let unstable = run.unstable in
272     let rec loop node =
273       let node_id = T.preorder tree node in
274       if node == T.nil || not (Bitvector.get unstable node_id) then false else begin
275         let parent = T.parent tree node in
276         let fc = T.first_child tree node in
277         let fc_id = T.preorder tree fc in
278         let ns = T.next_sibling tree node in
279         let ns_id = T.preorder tree ns in
280         let tag = T.tag tree node in
281         (* We enter the node from its parent *)
282
283         let status0 =
284           let c = unsafe_get_status status node_id in
285           if c == dummy_status then
286             (* first time we visit the node *)
287             NodeStatus.make
288               { c.NodeStatus.node with
289                 todo = get_trans cache2 auto tag (Ata.get_states auto);
290                 summary = NodeSummary.make
291                   (node == T.first_child tree parent) (* is_left *)
292                   (node == T.next_sibling tree parent) (* is_right *)
293                   (fc != T.nil) (* has_left *)
294                   (ns != T.nil) (* has_right *)
295                   (T.kind tree node) (* kind *)
296               }
297           else c
298         in
299
300         TRACE(html tree node _i config0 "Entering node");
301
302         (* get the node_statuses for the first child, next sibling and parent *)
303         let ps = unsafe_get_status status (T.preorder tree parent) in
304         let fcs = unsafe_get_status status fc_id in
305         let nss = unsafe_get_status status ns_id in
306         (* evaluate the transitions with all this statuses *)
307         let status1 = eval_trans cache4 fcs nss ps status0 in
308
309         TRACE(html tree node _i config1 "Updating transitions");
310
311         (* update the cache if the status of the node changed *)
312
313         if status1 != status0 then status.(node_id) <- status1;
314         (* recursively traverse the first child *)
315         let unstable_left = loop fc in
316         (* here we re-enter the node from its first child,
317            get the new status of the first child *)
318         let fcs1 = unsafe_get_status status fc_id in
319         (* update the status *)
320         let status2 = eval_trans cache4 fcs1 nss ps status1 in
321
322         TRACE(html tree node _i config2 "Updating transitions (after first-child)");
323
324         if status2 != status1 then status.(node_id) <- status2;
325         let unstable_right = loop ns in
326         let nss1 = unsafe_get_status status ns_id in
327         let status3 = eval_trans cache4 fcs1 nss1 ps status2 in
328
329         TRACE(html tree node _i config3 "Updating transitions (after next-sibling)");
330
331         if status3 != status2 then status.(node_id) <- status3;
332
333         let unstable_self =
334           (* if either our left or right child is unstable or if we still have transitions
335              pending, the current node is unstable *)
336           unstable_left
337           || unstable_right
338           || Ata.TransList.nil != status3.NodeStatus.node.todo
339         in
340         Bitvector.unsafe_set unstable node_id unstable_self;
341         TRACE((if not unstable_self then
342             Html.finalize_node
343               node_id
344               _i
345               Ata.(StateSet.intersect config3.Config.node.sat auto.selection_states)));
346         unstable_self
347       end
348     in
349     run.redo <- loop node;
350     run.pass <- run.pass + 1
351
352 (*
353   let stats run =
354     let count = ref 0 in
355     let len = Bitvector.length run.unstable in
356     for i = 0 to len - 1 do
357       if not (Bitvector.unsafe_get run.unstable i) then
358         incr count
359     done;
360     Logger.msg `STATS
361       "%i nodes over %i were skipped in iteration %i (%.2f %%), redo is: %b"
362       !count len run.pass (100. *. (float !count /. float len))
363       run.redo
364
365
366   let eval auto tree node =
367     let len = T.size tree in
368     let run = { config = Array.create len Ata.dummy_config;
369                 unstable = Bitvector.create ~init:true len;
370                 redo = true;
371                 pass = 0
372               }
373     in
374     while run.redo do
375       run.redo <- false;
376       Ata.reset auto; (* prevents the .cache2 and .cache4 memoization tables from growing too much *)
377       run.redo <- top_down_run auto tree node run;
378       stats run;
379       run.pass <- run.pass + 1;
380     done;
381     at_exit (fun () -> Logger.msg `STATS "%i iterations" run.pass);
382     at_exit (fun () -> stats run);
383     let r = get_results auto tree node run.config in
384
385     TRACE(Html.gen_trace (module T : Tree.S with type t = T.t) (tree));
386
387     r
388 *)
389
390   let get_results run =
391     let cache = run.status in
392     let auto = run.auto in
393     let tree = run.tree in
394     let rec loop node acc =
395       if node == T.nil then acc
396       else
397         let acc0 = loop (T.next_sibling tree node) acc in
398         let acc1 = loop (T.first_child tree node) acc0 in
399
400         if Ata.(
401           StateSet.intersect
402             cache.(T.preorder tree node).NodeStatus.node.sat
403             (get_selecting_states auto)) then node::acc1
404         else acc1
405     in
406     loop (T.root tree) []
407
408
409   let eval auto tree node =
410     let run = make auto tree in
411     while run.redo do top_down node run done;
412     get_results run
413 end