0ae25f9cf5693c6136ac07fe7a12859e75228743
[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 open Bigarray
22
23 type stats = { mutable pass : int;
24                tree_size : int;
25                mutable fetch_trans_cache_access : int;
26                mutable fetch_trans_cache_hit : int;
27                mutable eval_trans_cache_access : int;
28                mutable eval_trans_cache_hit : int;
29                mutable nodes_per_run : int list;
30              }
31
32 module NodeSummary =
33 struct
34   (* Pack into an integer the result of the is_* and has_ predicates
35      for a given node *)
36   type t = int
37   let dummy = -1
38   (*
39     ...44443210
40     ...4444 -> kind
41     3 -> has_right
42     2 -> has_left
43     1 -> is_right
44     0 -> is_left
45   *)
46   let is_left (s : t) : bool =
47     s land 1 != 0
48
49   let is_right (s : t) : bool =
50     s land 0b10 != 0
51
52   let has_left (s : t) : bool =
53     s land 0b100 != 0
54
55   let has_right (s : t) : bool =
56     s land 0b1000 != 0
57
58   let kind (s : t) : Tree.NodeKind.t =
59     Obj.magic (s lsr 4)
60
61   let make is_left is_right has_left has_right kind =
62     (int_of_bool is_left) lor
63       ((int_of_bool is_right) lsl 1) lor
64       ((int_of_bool has_left) lsl 2) lor
65       ((int_of_bool has_right) lsl 3) lor
66       ((Obj.magic kind) lsl 4)
67 end
68
69 let dummy_set = StateSet.singleton State.dummy_state
70
71
72
73   IFDEF HTMLTRACE
74   THEN
75 type sat_array = StateSet.t array list
76   DEFINE IFHTML(a,b) = (a)
77   ELSE
78 type sat_array = StateSet.t array
79   DEFINE IFHTML(a,b) = (b)
80   END
81
82 let unsafe_get a i =
83   if i < 0 then StateSet.empty else
84     Array.unsafe_get (IFHTML(List.hd a, a)) i
85
86 let unsafe_set a i v old_v =
87   if v != old_v then
88     Array.unsafe_set (IFHTML(List.hd a, a)) i v
89
90 type 'a run = {
91   tree : 'a ;
92      (* The argument of the run *)
93   auto : Ata.t;
94      (* The automaton to be run *)
95   mutable sat: sat_array;
96      (* A mapping from node preorders to states satisfied at that node *)
97   mutable pass : int;
98      (* Number of run we have performed *)
99   mutable fetch_trans_cache : Ata.Formula.t Cache.N2.t;
100      (* A cache from states * label to list of transitions *)
101   mutable td_cache : StateSet.t Cache.N6.t;
102   mutable bu_cache : StateSet.t Cache.N6.t;
103      (* Two 6-way caches used during the top-down and bottom-up phase
104         label * self-set * fc-set * ns-set * parent-set * node-shape -> self-set
105      *)
106   node_summaries: (int, int16_unsigned_elt, c_layout) Array1.t;
107   stats : stats;
108 }
109
110 let dummy_form = Ata.Formula.stay State.dummy_state
111
112 let get_form run tag (q : State.t) =
113   let auto = run.auto in
114   let fetch_trans_cache = run.fetch_trans_cache in
115   let stats = run.stats in
116   let phi =
117     stats.fetch_trans_cache_access <- stats.fetch_trans_cache_access + 1;
118     Cache.N2.find fetch_trans_cache (tag.QName.id :> int) (q :> int)
119   in
120   if phi == dummy_form then
121     let phi = Ata.get_form auto tag q in
122     let () =
123       Cache.N2.add
124         fetch_trans_cache
125         (tag.QName.id :> int)
126         (q :> int) phi
127     in phi
128   else begin
129     stats.fetch_trans_cache_hit <- stats.fetch_trans_cache_hit + 1;
130     phi
131   end
132
133
134 let eval_form phi fcs nss ps ss summary =
135   let open Ata in
136   let rec loop phi =
137     begin match Formula.expr phi with
138     | Boolean.False -> false
139     | Boolean.True -> true
140     | Boolean.Atom (a, b) ->
141       begin
142         let open NodeSummary in
143         match a.Atom.node with
144         | Move (m, q) ->
145           b && StateSet.mem q (
146             match m with
147               `First_child -> fcs
148             | `Next_sibling -> nss
149             | `Parent | `Previous_sibling -> ps
150             | `Stay -> ss
151           )
152         | Is_first_child -> b == is_left summary
153         | Is_next_sibling -> b == is_right summary
154         | Is k -> b == (k == kind summary)
155         | Has_first_child -> b == has_left summary
156         | Has_next_sibling -> b == has_right summary
157       end
158     | Boolean.And(phi1, phi2) -> loop phi1 && loop phi2
159     | Boolean.Or (phi1, phi2) -> loop phi1 || loop phi2
160     end
161   in
162   loop phi
163
164
165 let eval_trans_aux run tag summary fcs nss ps sat todo  =
166   StateSet.fold (fun q (a_sat) ->
167     let phi =
168       get_form run tag q
169     in
170     if eval_form phi fcs nss ps a_sat summary then
171       StateSet.add q a_sat
172     else a_sat
173   ) todo sat
174
175
176 let rec eval_trans_fix run tag summary fcs nss ps sat todo  =
177   let new_sat =
178     eval_trans_aux run tag summary fcs nss ps sat todo
179   in
180   if new_sat == sat then sat else
181     eval_trans_fix run tag summary fcs nss ps new_sat todo
182
183
184 let eval_trans run trans_cache tag summary fcs nss ps ss todo =
185   let stats = run.stats in
186   let fcsid = (fcs.StateSet.id :> int) in
187   let nssid = (nss.StateSet.id :> int) in
188   let psid = (ps.StateSet.id :> int) in
189   let ssid = (ss.StateSet.id :> int) in
190   let tagid = (tag.QName.id :> int) in
191
192   let res = Cache.N6.find trans_cache tagid summary ssid fcsid nssid psid in
193   stats.eval_trans_cache_access <- 1 + stats.eval_trans_cache_access;
194   if res != dummy_set then begin
195     stats.eval_trans_cache_hit <- 1 + stats.eval_trans_cache_hit;
196     res
197   end else let new_sat =
198              eval_trans_fix run tag summary fcs nss ps ss todo
199            in
200            Cache.N6.add trans_cache tagid summary ssid fcsid nssid psid new_sat;
201            new_sat
202
203
204 module Make (T : Tree.S) (L : Node_list.S with type node = T.node) =
205 struct
206
207   let make auto tree =
208     let len = T.size tree in
209     let ba = Array1.create int16_unsigned c_layout len in
210     Array1.fill ba 0;
211     {
212       tree = tree;
213       auto = auto;
214       sat = (let a = Array.make len StateSet.empty in
215              IFHTML([a], a));
216       pass = 0;
217       fetch_trans_cache = Cache.N2.create dummy_form;
218       td_cache = Cache.N6.create dummy_set;
219       bu_cache = Cache.N6.create dummy_set;
220       node_summaries = ba;
221       stats = {
222         pass = 0;
223         tree_size = len;
224         fetch_trans_cache_access = 0;
225         fetch_trans_cache_hit = 0;
226         eval_trans_cache_access = 0;
227         eval_trans_cache_hit = 0;
228         nodes_per_run = [];
229       }
230     }
231
232
233   let top_down run update_res =
234     let num_visited = ref 0 in
235     let i = run.pass in
236     let tree = run.tree in
237     let auto = run.auto in
238     let states_by_rank = Ata.get_states_by_rank auto in
239     let td_todo = states_by_rank.(i) in
240     let bu_todo =
241       if i == Array.length states_by_rank - 1 then StateSet.empty
242       else
243         states_by_rank.(i+1)
244     in
245     let last_run = i >= Array.length states_by_rank - 2 in
246     let rec loop_td_and_bu node parent parent_sat =
247       if node == T.nil then StateSet.empty
248       else begin
249         incr num_visited;
250         let tag = T.tag tree node in
251         let node_id = T.preorder tree node in
252         let fc = T.first_child tree node in
253         let ns = T.next_sibling tree node in
254          (* We enter the node from its parent *)
255         let summary =
256           let s = Array1.unsafe_get run.node_summaries node_id in
257           if  s != 0 then s else
258             let s =
259               NodeSummary.make
260                 (node == (T.first_child tree parent)) (*is_left *)
261                 (node == (T.next_sibling tree parent)) (*is_right *)
262                 (fc != T.nil) (* has_left *)
263                 (ns != T.nil) (* has_right *)
264                 (T.kind tree node) (* kind *)
265             in
266             run.node_summaries.{node_id} <- s; s
267         in
268         let status0 = unsafe_get run.sat node_id in
269         (* get the node_statuses for the first child, next sibling and parent *)
270         (* evaluate the transitions with all this statuses *)
271         let status1 =
272           eval_trans run
273             run.td_cache tag
274             summary
275             (unsafe_get run.sat (T.preorder tree fc))
276             (unsafe_get run.sat (T.preorder tree ns))
277             parent_sat
278             status0 td_todo
279         in
280           (* update the cache if the status of the node changed
281              unsafe_set run.sat node_id status1 status0;*)
282         if bu_todo == StateSet.empty then begin
283           unsafe_set run.sat node_id status1 status0; (* write the td_states *)
284           update_res false status1 node;
285           let _ = loop_td_and_bu fc node status1 in
286           loop_td_and_bu ns node status1 (* tail call *)
287         end else
288           let fcs1, nss1 =
289             if last_run then
290               let nss1 = loop_td_and_bu ns node status1 in
291               let fcs1 = loop_td_and_bu fc node status1 in
292               fcs1, nss1
293             else
294               let fcs1 = loop_td_and_bu fc node status1 in
295               let nss1 = loop_td_and_bu ns node status1 in
296               fcs1, nss1
297           in
298           let status2 =
299             eval_trans run run.bu_cache tag
300               summary fcs1
301               nss1
302               parent_sat
303               status1 bu_todo
304           in
305           unsafe_set run.sat node_id status2 status0;
306           if last_run && status2 != StateSet.empty then update_res true status2 node;
307           status2
308       end
309     in
310     let _ = loop_td_and_bu (T.root tree) T.nil dummy_set in
311     run.pass <- run.pass + 2;
312     run.stats.pass <- run.stats.pass + 1;
313     run.stats.nodes_per_run <- !num_visited :: run.stats.nodes_per_run
314
315
316
317   let mk_update_result auto =
318     let sel_states = Ata.get_selecting_states auto in
319     let res = L.create () in
320     (fun prepend sat node ->
321       if StateSet.intersect sel_states sat then begin
322         if prepend then L.push_front node res else
323           L.push_back node res
324       end),
325     (fun () -> res)
326
327
328   let mk_update_full_result auto =
329     let dummy = L.create () in
330     let res_mapper = Cache.N1.create dummy in
331     let () =
332       StateSet.iter
333         (fun q -> Cache.N1.add res_mapper (q :> int) (L.create()))
334         (Ata.get_selecting_states auto)
335     in
336     (fun prepend sat node ->
337       StateSet.iter
338         (fun q ->
339           let res = Cache.N1.find res_mapper (q :> int) in
340           if res != dummy then begin
341             if prepend then L.push_front node res
342             else L.push_back node res
343           end
344         ) sat),
345     (fun () ->
346       StateSet.fold_right
347         (fun q acc -> (q, Cache.N1.find res_mapper (q :> int))::acc)
348         (Ata.get_selecting_states auto) [])
349
350   let prepare_run run list =
351     let tree = run.tree in
352     let auto = run.auto in
353     let sat = IFHTML((List.hd run.sat), run.sat) in
354     let sat0 = Ata.get_starting_states auto in
355     L.iter (fun node ->
356       let node_id = T.preorder tree node in
357       sat.(node_id) <- sat0) list
358
359
360   let compute_run auto tree nodes update_res =
361     let run = make auto tree in
362     prepare_run run nodes;
363     let rank = Ata.get_max_rank auto in
364     while run.pass <= rank do
365       top_down run update_res;
366       IFHTML((run.sat <- (Array.copy (List.hd run.sat)) :: run.sat), ());
367       run.td_cache <- Cache.N6.create dummy_set;
368       run.bu_cache <- Cache.N6.create dummy_set;
369     done;
370     IFHTML((run.sat <- List.tl run.sat), ());
371     IFHTML(Html_trace.gen_trace auto run.sat (module T : Tree.S with type t = T.t) tree ,());
372     run
373
374
375   let last_stats = ref None
376
377   let full_eval auto tree nodes =
378     let update_full,get_full = mk_update_full_result auto in
379     let run = compute_run auto tree nodes update_full in
380     last_stats := Some run.stats;
381     get_full ()
382
383   let eval auto tree nodes =
384     let update_res,get_res = mk_update_result auto in
385     let run = compute_run auto tree nodes update_res in
386     last_stats := Some run.stats;
387     get_res ()
388
389   let stats () = match !last_stats with
390       Some s -> s.nodes_per_run <- List.rev s.nodes_per_run;s
391     | None -> failwith "Missing stats"
392
393 end