Maintain the set of unsatisfiable states.
[tatoo.git] / src / ata.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 (*
17   Time-stamp: <Last modified on 2013-04-18 17:05:32 CEST by Kim Nguyen>
18 *)
19
20 INCLUDE "utils.ml"
21 open Format
22
23 type predicate = | First_child
24                  | Next_sibling
25                  | Parent
26                  | Previous_sibling
27                  | Stay
28                  | Is_first_child
29                  | Is_next_sibling
30                  | Is of (Tree.NodeKind.t)
31                  | Has_first_child
32                  | Has_next_sibling
33
34 let is_move p = match p with
35 | First_child | Next_sibling
36 | Parent | Previous_sibling | Stay -> true
37 | _ -> false
38
39
40 type atom = predicate * bool * State.t
41
42 module Atom : (Formula.ATOM with type data = atom) =
43 struct
44
45   module Node =
46   struct
47     type t = atom
48     let equal n1 n2 = n1 = n2
49     let hash n = Hashtbl.hash n
50   end
51
52   include Hcons.Make(Node)
53
54   let print ppf a =
55     let p, b, q = a.node in
56     if not b then fprintf ppf "%s" Pretty.lnot;
57     match p with
58     | First_child -> fprintf ppf "FC(%a)" State.print q
59     | Next_sibling -> fprintf ppf "NS(%a)" State.print q
60     | Parent -> fprintf ppf "FC%s(%a)" Pretty.inverse State.print q
61     | Previous_sibling -> fprintf ppf "NS%s(%a)" Pretty.inverse State.print q
62     | Stay -> fprintf ppf "%s(%a)" Pretty.epsilon State.print q
63     | Is_first_child -> fprintf ppf "FC%s?" Pretty.inverse
64     | Is_next_sibling -> fprintf ppf "NS%s?" Pretty.inverse
65     | Is k -> fprintf ppf "is-%a?" Tree.NodeKind.print k
66     | Has_first_child -> fprintf ppf "FC?"
67     | Has_next_sibling -> fprintf ppf "NS?"
68
69   let neg a =
70     let p, b, q = a.node in
71     make (p, not b, q)
72
73
74 end
75
76 module SFormula =
77 struct
78   include Formula.Make(Atom)
79   open Tree.NodeKind
80   let mk_atom a b c = atom_ (Atom.make (a,b,c))
81   let mk_kind k = mk_atom (Is k) true State.dummy
82   let has_first_child =
83     (mk_atom Has_first_child true State.dummy)
84
85   let has_next_sibling =
86     (mk_atom Has_next_sibling true State.dummy)
87
88   let is_first_child =
89     (mk_atom Is_first_child true State.dummy)
90
91   let is_next_sibling =
92     (mk_atom Is_next_sibling true State.dummy)
93
94   let is_attribute =
95     (mk_atom (Is Attribute) true State.dummy)
96
97   let is_element =
98     (mk_atom (Is Element) true State.dummy)
99
100   let is_processing_instruction =
101     (mk_atom (Is ProcessingInstruction) true State.dummy)
102
103   let is_comment =
104     (mk_atom (Is Comment) true State.dummy)
105
106   let first_child q =
107   and_
108     (mk_atom First_child true q)
109     has_first_child
110
111   let next_sibling q =
112   and_
113     (mk_atom Next_sibling true q)
114     has_next_sibling
115
116   let parent q =
117   and_
118     (mk_atom Parent true q)
119     is_first_child
120
121   let previous_sibling q =
122   and_
123     (mk_atom Previous_sibling true q)
124     is_next_sibling
125
126   let stay q =
127     (mk_atom Stay true q)
128
129   let get_states phi =
130     fold (fun phi acc ->
131       match expr phi with
132       | Formula.Atom a -> let _, _, q = Atom.node a in
133                           if q != State.dummy then StateSet.add q acc else acc
134       | _ -> acc
135     ) phi StateSet.empty
136
137 end
138
139
140 module Transition = Hcons.Make (struct
141   type t = State.t * QNameSet.t * SFormula.t
142   let equal (a, b, c) (d, e, f) =
143     a == d && b == e && c == f
144   let hash (a, b, c) =
145     HASHINT4 (PRIME1, a, ((QNameSet.uid b) :> int), ((SFormula.uid c) :> int))
146 end)
147
148
149 module TransList : sig
150   include Hlist.S with type elt = Transition.t
151   val print : Format.formatter -> ?sep:string -> t -> unit
152 end =
153   struct
154     include Hlist.Make(Transition)
155     let print ppf ?(sep="\n") l =
156       iter (fun t ->
157         let q, lab, f = Transition.node t in
158         fprintf ppf "%a, %a -> %a%s" State.print q QNameSet.print lab SFormula.print f sep) l
159   end
160
161
162 type t = {
163   id : Uid.t;
164   mutable states : StateSet.t;
165   mutable selection_states: StateSet.t;
166   transitions: (State.t, (QNameSet.t*SFormula.t) list) Hashtbl.t;
167   mutable cache2 : TransList.t Cache.N2.t;
168   mutable cache6 : (TransList.t*StateSet.t) Cache.N6.t;
169 }
170
171 let next = Uid.make_maker ()
172
173 let dummy2 = TransList.cons
174   (Transition.make (State.dummy,QNameSet.empty, SFormula.false_))
175   TransList.nil
176
177 let dummy6 = (dummy2, StateSet.empty)
178
179
180 let create s ss =
181   let auto = { id = next ();
182                states = s;
183                selection_states = ss;
184                transitions = Hashtbl.create 17;
185                cache2 = Cache.N2.create dummy2;
186                cache6 = Cache.N6.create dummy6;
187              }
188   in
189   at_exit (fun () ->
190     let n6 = ref 0 in
191     let n2 = ref 0 in
192     Cache.N2.iteri (fun _ _ _ b -> if b then incr n2) auto.cache2;
193     Cache.N6.iteri (fun _ _ _ _ _ _ _ b -> if b then incr n6) auto.cache6;
194     Format.eprintf "INFO: automaton %i, cache2: %i entries, cache6: %i entries\n%!"
195       (auto.id :> int) !n2 !n6;
196     let c2l, c2u = Cache.N2.stats auto.cache2 in
197     let c6l, c6u = Cache.N6.stats auto.cache6 in
198     Format.eprintf "INFO: cache2: length: %i, used: %i, occupation: %f\n%!" c2l c2u (float c2u /. float c2l);
199     Format.eprintf "INFO: cache6: length: %i, used: %i, occupation: %f\n%!" c6l c6u (float c6u /. float c6l)
200
201   );
202   auto
203
204 let reset a =
205   a.cache2 <- Cache.N2.create dummy2;
206   a.cache6 <- Cache.N6.create dummy6
207
208
209 let get_trans_aux a tag states =
210   StateSet.fold (fun q acc0 ->
211     try
212       let trs = Hashtbl.find a.transitions q in
213       List.fold_left (fun acc1 (labs, phi) ->
214         if QNameSet.mem tag labs then TransList.cons (Transition.make (q, labs, phi)) acc1 else acc1) acc0 trs
215     with Not_found -> acc0
216   ) states TransList.nil
217
218
219 let get_trans a tag states =
220   let trs =
221     Cache.N2.find a.cache2
222       (tag.QName.id :> int) (states.StateSet.id :> int)
223   in
224   if trs == dummy2 then
225     let trs = get_trans_aux a tag states in
226     (Cache.N2.add
227        a.cache2
228        (tag.QName.id :> int)
229        (states.StateSet.id :> int) trs; trs)
230   else trs
231
232
233
234 let eval_form phi fcs nss ps ss is_left is_right has_left has_right kind =
235   let rec loop phi =
236     begin match SFormula.expr phi with
237       Formula.True | Formula.False -> phi
238     | Formula.Atom a ->
239         let p, b, q = Atom.node a in begin
240           match p with
241           | First_child ->
242               if b == StateSet.mem q fcs then SFormula.true_ else phi
243           | Next_sibling ->
244               if b == StateSet.mem q nss then SFormula.true_ else phi
245           | Parent | Previous_sibling ->
246               if b == StateSet.mem q ps then SFormula.true_ else phi
247           | Stay ->
248               if b == StateSet.mem q ss then SFormula.true_ else phi
249           | Is_first_child -> SFormula.of_bool (b == is_left)
250           | Is_next_sibling -> SFormula.of_bool (b == is_right)
251           | Is k -> SFormula.of_bool (b == (k == kind))
252           | Has_first_child -> SFormula.of_bool (b == has_left)
253           | Has_next_sibling -> SFormula.of_bool (b == has_right)
254         end
255     | Formula.And(phi1, phi2) -> SFormula.and_ (loop phi1) (loop phi2)
256     | Formula.Or (phi1, phi2) -> SFormula.or_  (loop phi1) (loop phi2)
257     end
258   in
259   loop phi
260
261 let int_of_conf is_left is_right has_left has_right kind =
262   ((Obj.magic kind) lsl 4) lor
263     ((Obj.magic is_left) lsl 3) lor
264     ((Obj.magic is_right) lsl 2) lor
265     ((Obj.magic has_left) lsl 1) lor
266     (Obj.magic has_right)
267
268 let eval_trans auto ltrs fcs nss ps ss is_left is_right has_left has_right kind =
269   let n = int_of_conf is_left is_right has_left has_right kind
270   and k = (fcs.StateSet.id :> int)
271   and l = (nss.StateSet.id :> int)
272   and m = (ps.StateSet.id :> int) in
273   let rec loop ltrs ss =
274     let i = (ltrs.TransList.id :> int)
275     and j = (ss.StateSet.id :> int) in
276     let (new_ltrs, new_ss) as res =
277       let res = Cache.N6.find auto.cache6 i j k l m n in
278       if res == dummy6 then
279         let res =
280           TransList.fold (fun trs (acct, accs) ->
281             let q, lab, phi = Transition.node trs in
282             if StateSet.mem q accs then (acct, accs) else
283               let new_phi =
284                 eval_form
285                   phi fcs nss ps accs
286                   is_left is_right has_left has_right kind
287               in
288               if SFormula.is_true new_phi then
289                 (acct, StateSet.add q accs)
290               else if SFormula.is_false new_phi then
291                 (acct, accs)
292               else
293                 let new_tr = Transition.make (q, lab, new_phi) in
294                 (TransList.cons new_tr acct, accs)
295           ) ltrs (TransList.nil, ss)
296         in
297         Cache.N6.add auto.cache6 i j k l m n res; res
298       else
299         res
300     in
301     if new_ss == ss then res else
302       loop new_ltrs new_ss
303   in
304   loop ltrs ss
305
306
307
308
309 type config = {
310   sat : StateSet.t;
311   unsat : StateSet.t;
312   todo : TransList.t;
313 }
314
315 let eq_config c1 c2 =
316   c1.sat == c2.sat && c1.unsat == c2.unsat && c1.todo == c2.todo
317
318 let simplify_atom atom pos q config =
319   if (pos && StateSet.mem q config.sat)
320     || ((not pos) && StateSet.mem q config.unsat) then SFormula.true_
321   else if (pos && StateSet.mem q config.unsat)
322       || ((not pos) && StateSet.mem q config.sat) then SFormula.false_
323   else atom
324
325
326 let eval_form2 phi fcs nss ps ss is_left is_right has_left has_right kind =
327   let rec loop phi =
328     begin match SFormula.expr phi with
329       Formula.True | Formula.False -> phi
330     | Formula.Atom a ->
331         let p, b, q = Atom.node a in begin
332           match p with
333           | First_child -> simplify_atom phi b q fcs
334           | Next_sibling -> simplify_atom phi b q nss
335           | Parent | Previous_sibling -> simplify_atom phi b q ps
336           | Stay -> simplify_atom phi b q ss
337           | Is_first_child -> SFormula.of_bool (b == is_left)
338           | Is_next_sibling -> SFormula.of_bool (b == is_right)
339           | Is k -> SFormula.of_bool (b == (k == kind))
340           | Has_first_child -> SFormula.of_bool (b == has_left)
341           | Has_next_sibling -> SFormula.of_bool (b == has_right)
342         end
343     | Formula.And(phi1, phi2) -> SFormula.and_ (loop phi1) (loop phi2)
344     | Formula.Or (phi1, phi2) -> SFormula.or_  (loop phi1) (loop phi2)
345     end
346   in
347   loop phi
348
349
350
351 let eval_trans2 auto fcs nss ps ss is_left is_right has_left has_right kind =
352   let rec loop old_config =
353     let { sat = old_sat; unsat = old_unsat; todo = old_todo } = old_config in
354     let sat, unsat, removed, kept, todo =
355       TransList.fold
356         (fun trs acc ->
357           let q, lab, phi = Transition.node trs in
358           let a_sat, a_unsat, a_rem, a_kept, a_todo = acc in
359           if StateSet.mem q a_sat || StateSet.mem q a_unsat then acc else
360             let new_phi =
361             eval_form2
362               phi fcs nss ps old_config
363               is_left is_right has_left has_right kind
364             in
365             if SFormula.is_true new_phi then
366               StateSet.add q a_sat, a_unsat, StateSet.add q a_rem, a_kept, a_todo
367             else if SFormula.is_false new_phi then
368               a_sat, StateSet.add q a_unsat, StateSet.add q a_rem, a_kept, a_todo
369             else
370               let new_tr = Transition.make (q, lab, new_phi) in
371               (a_sat, a_unsat, a_rem, StateSet.add q a_kept, (TransList.cons new_tr a_todo))
372         ) old_todo (old_sat, old_unsat, StateSet.empty, StateSet.empty, TransList.nil)
373     in
374   (* States that have been removed from the todo list and not kept are now
375      unsatisfiable *)
376     let unsat = StateSet.union unsat (StateSet.diff removed kept) in
377   (* States that were found once to be satisfiable remain so *)
378     let unsat = StateSet.diff unsat sat in
379     let new_config = { sat; unsat; todo } in
380     if sat == old_sat && unsat == old_unsat && todo == old_todo then new_config
381     else loop new_config
382   in
383   loop ss
384
385 (*
386   [add_trans a q labels f] adds a transition [(q,labels) -> f] to the
387   automaton [a] but ensures that transitions remains pairwise disjoint
388 *)
389
390 let add_trans a q s f =
391   let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
392   let cup, ntrs =
393     List.fold_left (fun (acup, atrs) (labs, phi) ->
394       let lab1 = QNameSet.inter labs s in
395       let lab2 = QNameSet.diff labs s in
396       let tr1 =
397         if QNameSet.is_empty lab1 then []
398         else [ (lab1, SFormula.or_ phi f) ]
399       in
400       let tr2 =
401         if QNameSet.is_empty lab2 then []
402         else [ (lab2, SFormula.or_ phi f) ]
403       in
404       (QNameSet.union acup labs, tr1@ tr2 @ atrs)
405     ) (QNameSet.empty, []) trs
406   in
407   let rem = QNameSet.diff s cup in
408   let ntrs = if QNameSet.is_empty rem then ntrs
409     else (rem, f) :: ntrs
410   in
411   Hashtbl.replace a.transitions q ntrs
412
413 let _pr_buff = Buffer.create 50
414 let _str_fmt = formatter_of_buffer _pr_buff
415 let _flush_str_fmt () = pp_print_flush _str_fmt ();
416   let s = Buffer.contents _pr_buff in
417   Buffer.clear _pr_buff; s
418
419 let print fmt a =
420   fprintf fmt
421     "\nInternal UID: %i@\n\
422      States: %a@\n\
423      Selection states: %a@\n\
424      Alternating transitions:@\n"
425     (a.id :> int)
426     StateSet.print a.states
427     StateSet.print a.selection_states;
428   let trs =
429     Hashtbl.fold
430       (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
431       a.transitions
432       []
433   in
434   let sorted_trs = List.stable_sort (fun (q1, s1, _) (q2, s2, _) ->
435     let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
436     trs
437   in
438   let _ = _flush_str_fmt () in
439   let strs_strings, max_pre, max_all = List.fold_left (fun (accl, accp, acca) (q, s, f) ->
440     let s1 = State.print _str_fmt q; _flush_str_fmt () in
441     let s2 = QNameSet.print _str_fmt s;  _flush_str_fmt () in
442     let s3 = SFormula.print _str_fmt f;  _flush_str_fmt () in
443     let pre = Pretty.length s1 + Pretty.length s2 in
444     let all = Pretty.length s3 in
445     ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
446   ) ([], 0, 0) sorted_trs
447   in
448   let line = Pretty.line (max_all + max_pre + 6) in
449   let prev_q = ref State.dummy in
450   List.iter (fun (q, s1, s2, s3) ->
451     if !prev_q != q && !prev_q != State.dummy then fprintf fmt " %s\n%!"  line;
452     prev_q := q;
453     fprintf fmt " %s, %s" s1 s2;
454     fprintf fmt "%s" (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
455     fprintf fmt " %s  %s@\n%!" Pretty.right_arrow s3;
456   ) strs_strings;
457   fprintf fmt " %s\n%!" line
458
459 (*
460   [complete transitions a] ensures that for each state q
461   and each symbols s in the alphabet, a transition q, s exists.
462   (adding q, s -> F when necessary).
463 *)
464
465 let complete_transitions a =
466   StateSet.iter (fun q ->
467     let qtrans = Hashtbl.find a.transitions q in
468     let rem =
469       List.fold_left (fun rem (labels, _) ->
470         QNameSet.diff rem labels) QNameSet.any qtrans
471     in
472     let nqtrans =
473       if QNameSet.is_empty rem then qtrans
474       else
475         (rem, SFormula.false_) :: qtrans
476     in
477     Hashtbl.replace a.transitions q nqtrans
478   ) a.states
479
480 let cleanup_states a =
481   let memo = ref StateSet.empty in
482   let rec loop q =
483     if not (StateSet.mem q !memo) then begin
484       memo := StateSet.add q !memo;
485       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
486       List.iter (fun (_, phi) ->
487         StateSet.iter loop (SFormula.get_states phi)) trs
488     end
489   in
490   StateSet.iter loop a.selection_states;
491   let unused = StateSet.diff a.states !memo in
492   eprintf "Unused states %a\n%!" StateSet.print unused;
493   StateSet.iter (fun q -> Hashtbl.remove a.transitions q) unused;
494   a.states <- !memo
495
496 (* [normalize_negations a] removes negative atoms in the formula
497    complementing the sub-automaton in the negative states.
498    [TODO check the meaning of negative upward arrows]
499 *)
500
501 let normalize_negations auto =
502   eprintf "Automaton before normalize_trans:\n";
503   print err_formatter auto;
504   eprintf "--------------------\n%!";
505
506   let memo_state = Hashtbl.create 17 in
507   let todo = Queue.create () in
508   let rec flip b f =
509     match SFormula.expr f with
510       Formula.True | Formula.False -> if b then f else SFormula.not_ f
511     | Formula.Or(f1, f2) -> (if b then SFormula.or_ else SFormula.and_)(flip b f1) (flip b f2)
512     | Formula.And(f1, f2) -> (if b then SFormula.and_ else SFormula.or_)(flip b f1) (flip b f2)
513     | Formula.Atom(a) -> begin
514       let l, b', q = Atom.node a in
515       if q == State.dummy then if b then f else SFormula.not_ f
516       else
517         if b == b' then begin
518         (* a appears positively, either no negation or double negation *)
519           if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
520           SFormula.atom_ (Atom.make (l, true, q))
521         end else begin
522         (* need to reverse the atom
523            either we have a positive state deep below a negation
524            or we have a negative state in a positive formula
525            b' = sign of the state
526            b = sign of the enclosing formula
527         *)
528         let not_q =
529           try
530             (* does the inverted state of q exist ? *)
531             Hashtbl.find memo_state (q, false)
532           with
533             Not_found ->
534               (* create a new state and add it to the todo queue *)
535               let nq = State.make () in
536               auto.states <- StateSet.add nq auto.states;
537               Hashtbl.add memo_state (q, false) nq;
538               Queue.add (q, false) todo; nq
539         in
540         SFormula.atom_ (Atom.make (l, true, not_q))
541       end
542     end
543   in
544   (* states that are not reachable from a selection stat are not interesting *)
545   StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selection_states;
546
547   while not (Queue.is_empty todo) do
548     let (q, b) as key = Queue.pop todo in
549     let q' =
550       try
551         Hashtbl.find memo_state key
552       with
553         Not_found ->
554           let nq = if b then q else
555               let nq = State.make () in
556               auto.states <- StateSet.add nq auto.states;
557               nq
558           in
559           Hashtbl.add memo_state key nq; nq
560     in
561     let trans = Hashtbl.find auto.transitions q in
562     let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
563     Hashtbl.replace auto.transitions q' trans';
564   done;
565   cleanup_states auto
566
567