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