Remove some unneeded code that was slowing down the run function.
[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 INCLUDE "debug.ml"
18
19 open Format
20 open Misc
21
22 type stats = { run : int;
23                tree_size : int;
24                cache2_access : int;
25                cache2_hit : int;
26                cache5_access : int;
27                cache5_hit : int;
28              }
29
30 let cache2_hit = ref 0
31 let cache2_access = ref 0
32 let cache5_hit = ref 0
33 let cache5_access = ref 0
34 let reset_stat_counters () =
35   cache2_hit := 0;
36   cache2_access := 0;
37   cache5_hit := 0;
38   cache5_access := 0
39
40
41 module Make (T : Tree.S) =
42  struct
43
44    module NodeSummary =
45    struct
46      (* Pack into an integer the result of the is_* and has_ predicates
47         for a given node *)
48      type t = int
49      let dummy = -1
50     (*
51       4444444444443210
52       4 -> kind
53       3 -> is_left
54       2 -> is_right
55       1 -> has_left
56       0 -> has_right
57     *)
58
59      let has_right (s : t) : bool =
60        Obj.magic (s land 1)
61
62      let has_left (s : t) : bool =
63        Obj.magic ((s lsr 1) land 1)
64
65      let is_right (s : t) : bool =
66        Obj.magic ((s lsr 2) land 1)
67
68      let is_left (s : t) : bool =
69        Obj.magic ((s lsr 3) land 1)
70
71      let kind (s : t) : Tree.NodeKind.t =
72        Obj.magic (s lsr 4)
73
74      let make is_left is_right has_left has_right kind =
75        ((Obj.magic kind) lsl 4) lor
76          ((int_of_bool is_left) lsl 3) lor
77          ((int_of_bool is_right) lsl 2) lor
78          ((int_of_bool has_left) lsl 1) lor
79          (int_of_bool has_right)
80
81    end
82
83    type node_status = {
84      rank : int;
85      sat : StateSet.t;  (* States that are satisfied at the current node *)
86      todo : StateSet.t; (* States that remain to be proven *)
87         (* For every node_status and automaton a,
88            a.states - (sat U todo) = unsat *)
89      summary : NodeSummary.t; (* Summary of the shape of the node *)
90    }
91 (* Describe what is kept at each node for a run *)
92
93    module NodeStatus =
94      struct
95        include Hcons.Make(struct
96          type t = node_status
97          let equal c d =
98            c == d ||
99              c.rank == d.rank &&
100              c.sat == d.sat &&
101              c.todo == d.todo &&
102              c.summary == d.summary
103
104          let hash c =
105            HASHINT4(c.rank,
106                     (c.sat.StateSet.id :> int),
107                     (c.todo.StateSet.id :> int),
108                     c.summary)
109        end
110        )
111        let print ppf s =
112          fprintf ppf
113            "{ rank: %i; sat: %a; todo: %a; summary: _ }"
114            s.node.rank
115            StateSet.print s.node.sat
116            StateSet.print s.node.todo
117      end
118
119    let dummy_status =
120      NodeStatus.make {
121        rank = -1;
122        sat = StateSet.empty;
123        todo = StateSet.empty;
124        summary = NodeSummary.dummy;
125      }
126
127
128    type run = {
129      tree : T.t ;
130      (* The argument of the run *)
131      auto : Ata.t;
132      (* The automaton to be run *)
133      status : NodeStatus.t array;
134      (* A mapping from node preorders to NodeStatus *)
135      mutable redo : bool;
136      (* A boolean indicating whether the run is incomplete *)
137      mutable pass : int;
138      (* The number of times this run was updated *)
139      mutable cache2 : Ata.Formula.t Cache.N2.t;
140      (* A cache from states * label to list of transitions *)
141      mutable cache5 : NodeStatus.t Cache.N5.t;
142    }
143
144    let pass r = r.pass
145    let stable r = not r.redo
146    let auto r = r.auto
147    let tree r = r.tree
148
149
150    let dummy_form = Ata.Formula.stay State.dummy
151
152    let make auto tree =
153      let len = T.size tree in
154      {
155        tree = tree;
156        auto = auto;
157        status = Array.create len dummy_status;
158        redo = true;
159        pass = 0;
160        cache2 = Cache.N2.create dummy_form;
161        cache5 = Cache.N5.create dummy_status;
162      }
163
164    let get_status a i =
165      if i < 0 then dummy_status else Array.get a i
166
167    let unsafe_get_status a i =
168      if i < 0 then dummy_status else Array.unsafe_get a i
169
170 IFDEF HTMLTRACE
171   THEN
172 DEFINE IFTRACE(e) = (e)
173   ELSE
174 DEFINE IFTRACE(e) = ()
175 END
176
177    let html tree node i config msg =
178      let config = config.NodeStatus.node in
179      Html.trace ~msg:msg
180        (T.preorder tree node) i
181        config.todo
182        config.sat
183
184
185
186    let debug msg tree node i config =
187      let config = config.NodeStatus.node in
188      eprintf
189        "DEBUG:%s node: %i\nsat: %a\ntodo: %a\nround: %i\n"
190        msg
191        (T.preorder tree node)
192        StateSet.print config.sat
193        StateSet.print config.todo
194        i
195
196    let get_form cache2 auto tag q =
197      let phi =
198        incr cache2_access;
199        Cache.N2.find cache2 (tag.QName.id :> int) (q :> int)
200      in
201      if phi == dummy_form then
202        let phi = Ata.get_form auto tag q in
203        let () =
204          Cache.N2.add
205            cache2
206            (tag.QName.id :> int)
207            (q :> int) phi
208        in phi
209      else begin
210        incr cache2_hit;
211        phi
212      end
213
214    type trivalent = False | True | Unknown
215    let of_bool = function false -> False | true -> True
216    let or_ t1 t2 =
217      match t1 with
218        False -> t2
219      | True -> True
220      | Unknown -> if t2 == True then True else Unknown
221
222    let and_ t1 t2 =
223      match t1 with
224        False -> False
225      | True -> t2
226      | Unknown -> if t2 == False then False else Unknown
227
228  (* Define as macros to get lazyness *)
229 DEFINE OR_(t1,t2) =
230      match t1 with
231        False -> (t2)
232      | True -> True
233      | Unknown -> if (t2) == True then True else Unknown
234
235 DEFINE AND_(t1,t2) =
236      match t1 with
237        False -> False
238      | True -> (t2)
239      | Unknown -> if (t2) == False then False else Unknown
240
241
242    let eval_form phi fcs nss ps ss summary =
243      let open Ata in
244          let rec loop phi =
245            begin match Formula.expr phi with
246            | Boolean.False -> False
247            | Boolean.True -> True
248            | Boolean.Atom (a, b) ->
249                begin
250                  let open NodeSummary in
251                      match a.Atom.node with
252                      | Move (m, q) ->
253                          let down, ({ NodeStatus.node = n_sum; _ } as sum) =
254                            match m with
255                              `First_child -> true, fcs
256                            | `Next_sibling -> true, nss
257                            | `Parent | `Previous_sibling -> false, ps
258                            | `Stay -> false, ss
259                          in
260                          if sum == dummy_status
261                            || (down && n_sum.rank < ss.NodeStatus.node.rank)
262                            || StateSet.mem q n_sum.todo then
263                            Unknown
264                          else
265                            of_bool (b == StateSet.mem q n_sum.sat)
266                      | Is_first_child -> of_bool (b == is_left summary)
267                      | Is_next_sibling -> of_bool (b == is_right summary)
268                      | Is k -> of_bool (b == (k == kind summary))
269                      | Has_first_child -> of_bool (b == has_left summary)
270                      | Has_next_sibling -> of_bool (b == has_right summary)
271                end
272            | Boolean.And(phi1, phi2) -> AND_ (loop phi1, loop phi2)
273            | Boolean.Or (phi1, phi2) -> OR_ (loop phi1, loop phi2)
274            end
275          in
276          loop phi
277
278
279    let eval_trans_aux auto cache2 tag fcs nss ps old_status =
280      let { sat = old_sat;
281            todo = old_todo;
282            summary = old_summary } as os_node = old_status.NodeStatus.node
283      in
284      let sat, todo =
285        StateSet.fold (fun q ((a_sat, a_todo) as acc) ->
286          let phi =
287            get_form cache2 auto tag q
288          in
289
290          let v = eval_form phi fcs nss ps old_status old_summary in
291          match v with
292            True -> StateSet.add q a_sat, a_todo
293          | False -> acc
294          | Unknown -> a_sat, StateSet.add q a_todo
295        ) old_todo (old_sat, StateSet.empty)
296      in
297      if old_sat != sat || old_todo != todo then
298        NodeStatus.make { os_node with sat; todo }
299      else old_status
300
301
302    let eval_trans auto cache2 cache5 tag fcs nss ps ss =
303      let rec loop old_status =
304        let new_status =
305          eval_trans_aux auto cache2 tag fcs nss ps old_status
306        in
307        if new_status == old_status then old_status else loop new_status
308      in
309      let fcsid = (fcs.NodeStatus.id :> int) in
310      let nssid = (nss.NodeStatus.id :> int) in
311      let psid = (ps.NodeStatus.id :> int) in
312      let ssid = (ss.NodeStatus.id :> int) in
313      let tagid = (tag.QName.id :> int) in
314      let res = Cache.N5.find cache5 tagid ssid fcsid nssid psid in
315      incr cache5_access;
316      if res != dummy_status then begin incr cache5_hit; res end
317      else let new_status = loop ss in
318           Cache.N5.add cache5 tagid ssid fcsid nssid psid new_status;
319           new_status
320
321
322
323   let top_down run =
324     let i = run.pass in
325     let tree = run.tree in
326     let auto = run.auto in
327     let status = run.status in
328     let cache2 = run.cache2 in
329     let cache5 = run.cache5 in
330     let states_by_rank = Ata.get_states_by_rank auto in
331     let td_todo = states_by_rank.(i) in
332     let bu_todo = if i + 1 = Array.length states_by_rank then StateSet.empty
333       else
334         states_by_rank.(i+1)
335     in
336     let rec loop node =
337       let node_id = T.preorder tree node in
338       if node != T.nil then begin
339         let parent = T.parent tree node in
340         let fc = T.first_child tree node in
341         let fc_id = T.preorder tree fc in
342         let ns = T.next_sibling tree node in
343         let ns_id = T.preorder tree ns in
344         let tag = T.tag tree node in
345         (* We enter the node from its parent *)
346         let status0 =
347           let c = unsafe_get_status status node_id in
348           if c.NodeStatus.node.rank < i then
349             (* first time we visit the node during this run *)
350             NodeStatus.make
351               { rank = i;
352                 sat = c.NodeStatus.node.sat;
353                 todo = td_todo;
354                 summary = let summary = c.NodeStatus.node.summary
355                           in
356                           if summary != NodeSummary.dummy then summary
357                           else
358                             NodeSummary.make
359                               (node == T.first_child tree parent) (* is_left *)
360                               (node == T.next_sibling tree parent) (* is_right *)
361                               (fc != T.nil) (* has_left *)
362                               (ns != T.nil) (* has_right *)
363                               (T.kind tree node) (* kind *)
364               }
365           else c
366         in
367         (* get the node_statuses for the first child, next sibling and parent *)
368         let ps = unsafe_get_status status (T.preorder tree parent) in
369         let fcs = unsafe_get_status status fc_id in
370         let nss = unsafe_get_status status ns_id in
371         (* evaluate the transitions with all this statuses *)
372         let status1 =
373           if status0.NodeStatus.node.todo == StateSet.empty then status0
374           else begin
375             let status1 = eval_trans auto cache2 cache5 tag fcs nss ps status0 in
376           (* update the cache if the status of the node changed *)
377             if status1 != status0 then status.(node_id) <- status1;
378             status1
379           end
380         in
381         (* recursively traverse the first child *)
382         let () = loop fc in
383         (* here we re-enter the node from its first child,
384            get the new status of the first child *)
385         let fcs1 = unsafe_get_status status fc_id in
386         (* update the status *)
387         let status1 = if status1.NodeStatus.node.rank < i then
388             NodeStatus.make { status1.NodeStatus.node with
389               rank = i;
390               todo = bu_todo }
391           else
392             status1
393         in
394         let status2 =
395           if status1.NodeStatus.node.todo == StateSet.empty then status1
396           else begin
397             let status2 = eval_trans auto cache2 cache5 tag fcs1 nss ps status1 in
398             if status2 != status1 then status.(node_id) <- status2;
399             status2
400           end
401         in
402         let () = loop ns in
403         let nss1 = unsafe_get_status status ns_id in
404         if status2.NodeStatus.node.todo != StateSet.empty then
405           let status3 = eval_trans auto cache2 cache5 tag fcs1 nss1 ps status2 in
406           if status3 != status2 then status.(node_id) <- status3
407       end
408     in
409     loop (T.root tree)
410
411
412   let get_results run =
413     let cache = run.status in
414     let auto = run.auto in
415     let tree = run.tree in
416     let sel_states = Ata.get_selecting_states auto in
417     let rec loop node acc =
418       if node == T.nil then acc
419       else
420         let acc0 = loop (T.next_sibling tree node) acc in
421         let acc1 = loop (T.first_child tree node) acc0 in
422
423         if StateSet.intersect
424           cache.(T.preorder tree node).NodeStatus.node.sat
425           sel_states then node::acc1
426         else acc1
427     in
428     loop (T.root tree) []
429
430
431   let get_full_results run =
432     let cache = run.status in
433     let auto = run.auto in
434     let tree = run.tree in
435     let res_mapper = Hashtbl.create MED_H_SIZE in
436     let () =
437       StateSet.iter
438         (fun q -> Hashtbl.add res_mapper q [])
439         (Ata.get_selecting_states auto)
440     in
441     let dummy = [ T.nil ] in
442     let res_mapper = Cache.N1.create dummy in
443     let () =
444       StateSet.iter
445         (fun q -> Cache.N1.add res_mapper (q :> int) [])
446         (Ata.get_selecting_states auto)
447     in
448     let rec loop node =
449       if node != T.nil then
450         let () = loop (T.next_sibling tree node) in
451         let () = loop (T.first_child tree node) in
452         StateSet.iter
453           (fun q ->
454             let res = Cache.N1.find res_mapper (q :> int) in
455             if res != dummy then
456               Cache.N1.add res_mapper (q :> int) (node::res)
457           )
458           cache.(T.preorder tree node).NodeStatus.node.sat
459     in
460     loop (T.root tree);
461     (StateSet.fold_right
462        (fun q acc -> (q, Cache.N1.find res_mapper (q :> int))::acc)
463        (Ata.get_selecting_states auto) [])
464
465
466   let prepare_run run list =
467     let tree = run.tree in
468     let auto = run.auto in
469     let status = run.status in
470     List.iter (fun node ->
471       let parent = T.parent tree node in
472       let fc = T.first_child tree node in
473       let ns = T.next_sibling tree node in
474       let status0 =
475         NodeStatus.make
476           { rank = 0;
477             sat = Ata.get_starting_states auto;
478             todo =
479               StateSet.diff (Ata.get_states auto) (Ata.get_starting_states auto);
480             summary = NodeSummary.make
481               (node == T.first_child tree parent) (* is_left *)
482               (node == T.next_sibling tree parent) (* is_right *)
483               (fc != T.nil) (* has_left *)
484               (ns != T.nil) (* has_right *)
485               (T.kind tree node) (* kind *)
486           }
487       in
488       let node_id = T.preorder tree node in
489       status.(node_id) <- status0) list
490
491   let tree_size = ref 0
492   let pass = ref 0
493   let compute_run auto tree nodes =
494     pass := 0;
495     tree_size := T.size tree;
496     let run = make auto tree in
497     prepare_run run nodes;
498     for i = 0 to Ata.get_max_rank auto do
499       top_down run;
500       run.pass <- run.pass + 1
501     done;
502     pass := Ata.get_max_rank auto + 1;
503     IFTRACE(Html.gen_trace auto (module T : Tree.S with type t = T.t) tree);
504
505     run
506
507   let full_eval auto tree nodes =
508     let r = compute_run auto tree nodes in
509     get_full_results r
510
511   let eval auto tree nodes =
512     let r = compute_run auto tree nodes in
513     get_results r
514
515   let stats () = {
516     tree_size = !tree_size;
517     run = !pass;
518     cache2_access = !cache2_access;
519     cache2_hit = !cache2_hit;
520     cache5_access = !cache5_access;
521     cache5_hit = !cache5_hit;
522   }
523
524 end