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