Remove the 'round' counter from the hashconsed configurations.
[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-25 16:20:41 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
163 type node_summary = int
164 let dummy_summary = -1
165 (*
166 4444444444443210
167 4 -> kind
168 3 -> is_left
169 2 -> is_right
170 1 -> has_left
171 0 -> has_right
172 *)
173
174 let has_right (s : node_summary) : bool =
175   Obj.magic (s land 1)
176 let has_left (s : node_summary) : bool =
177   Obj.magic ((s lsr 1) land 1)
178
179 let is_right (s : node_summary) : bool =
180   Obj.magic ((s lsr 2) land 1)
181
182 let is_left (s : node_summary) : bool =
183   Obj.magic ((s lsr 3) land 1)
184
185 let kind (s : node_summary ) : Tree.NodeKind.t =
186   Obj.magic (s lsr 4)
187
188 let node_summary is_left is_right has_left has_right kind =
189   ((Obj.magic kind) lsl 4) lor
190     ((Obj.magic is_left) lsl 3) lor
191     ((Obj.magic is_right) lsl 2) lor
192     ((Obj.magic has_left) lsl 1) lor
193     (Obj.magic has_right)
194
195
196
197 type config = {
198   sat : StateSet.t;
199   unsat : StateSet.t;
200   todo : TransList.t;
201   summary : node_summary;
202 }
203
204 module Config = Hcons.Make(struct
205   type t = config
206   let equal c d =
207     c == d ||
208       c.sat == d.sat &&
209       c.unsat == d.unsat &&
210       c.todo == d.todo &&
211       c.summary == d.summary
212
213   let hash c =
214     HASHINT4((c.sat.StateSet.id :> int),
215              (c.unsat.StateSet.id :> int),
216              (c.todo.TransList.id :> int),
217              c.summary)
218 end
219 )
220
221 type t = {
222   id : Uid.t;
223   mutable states : StateSet.t;
224   mutable selection_states: StateSet.t;
225   transitions: (State.t, (QNameSet.t*SFormula.t) list) Hashtbl.t;
226   mutable cache2 : TransList.t Cache.N2.t;
227   mutable cache4 : Config.t Cache.N4.t;
228 }
229
230 let next = Uid.make_maker ()
231
232 let dummy2 = TransList.cons
233   (Transition.make (State.dummy,QNameSet.empty, SFormula.false_))
234   TransList.nil
235
236
237
238 let dummy_config =
239   Config.make { sat = StateSet.empty;
240                 unsat = StateSet.empty;
241                 todo = TransList.nil;
242                 summary = dummy_summary
243               }
244
245
246 let create s ss =
247   let auto = { id = next ();
248                states = s;
249                selection_states = ss;
250                transitions = Hashtbl.create 17;
251                cache2 = Cache.N2.create dummy2;
252                cache4 = Cache.N4.create dummy_config;
253              }
254   in
255   at_exit (fun () ->
256     let n4 = ref 0 in
257     let n2 = ref 0 in
258     Cache.N2.iteri (fun _ _ _ b -> if b then incr n2) auto.cache2;
259     Cache.N4.iteri (fun _ _ _ _ _ b -> if b then incr n4) auto.cache4;
260     Logger.msg `STATS "automaton %i, cache2: %i entries, cache6: %i entries"
261       (auto.id :> int) !n2 !n4;
262     let c2l, c2u = Cache.N2.stats auto.cache2 in
263     let c4l, c4u = Cache.N4.stats auto.cache4 in
264     Logger.msg `STATS
265       "cache2: length: %i, used: %i, occupation: %f"
266       c2l c2u (float c2u /. float c2l);
267     Logger.msg `STATS
268       "cache4: length: %i, used: %i, occupation: %f"
269       c4l c4u (float c4u /. float c4l)
270
271   );
272   auto
273
274 let reset a =
275   a.cache4 <- Cache.N4.create (Cache.N4.dummy a.cache4)
276
277 let full_reset a =
278   reset a;
279   a.cache2 <- Cache.N2.create (Cache.N2.dummy a.cache2)
280
281
282 let get_trans_aux a tag states =
283   StateSet.fold (fun q acc0 ->
284     try
285       let trs = Hashtbl.find a.transitions q in
286       List.fold_left (fun acc1 (labs, phi) ->
287         if QNameSet.mem tag labs then TransList.cons (Transition.make (q, labs, phi)) acc1 else acc1) acc0 trs
288     with Not_found -> acc0
289   ) states TransList.nil
290
291
292 let get_trans a tag states =
293   let trs =
294     Cache.N2.find a.cache2
295       (tag.QName.id :> int) (states.StateSet.id :> int)
296   in
297   if trs == dummy2 then
298     let trs = get_trans_aux a tag states in
299     (Cache.N2.add
300        a.cache2
301        (tag.QName.id :> int)
302        (states.StateSet.id :> int) trs; trs)
303   else trs
304
305 let simplify_atom atom pos q { Config.node=config; _ } =
306   if (pos && StateSet.mem q config.sat)
307     || ((not pos) && StateSet.mem q config.unsat) then SFormula.true_
308   else if (pos && StateSet.mem q config.unsat)
309       || ((not pos) && StateSet.mem q config.sat) then SFormula.false_
310   else atom
311
312 let eval_form phi fcs nss ps ss summary =
313   let rec loop phi =
314     begin match SFormula.expr phi with
315       Formula.True | Formula.False -> phi
316     | Formula.Atom a ->
317         let p, b, q = Atom.node a in begin
318           match p with
319           | First_child -> simplify_atom phi b q fcs
320           | Next_sibling -> simplify_atom phi b q nss
321           | Parent | Previous_sibling -> simplify_atom phi b q ps
322           | Stay -> simplify_atom phi b q ss
323           | Is_first_child -> SFormula.of_bool (b == (is_left summary))
324           | Is_next_sibling -> SFormula.of_bool (b == (is_right summary))
325           | Is k -> SFormula.of_bool (b == (k == (kind summary)))
326           | Has_first_child -> SFormula.of_bool (b == (has_left summary))
327           | Has_next_sibling -> SFormula.of_bool (b == (has_right summary))
328         end
329     | Formula.And(phi1, phi2) -> SFormula.and_ (loop phi1) (loop phi2)
330     | Formula.Or (phi1, phi2) -> SFormula.or_  (loop phi1) (loop phi2)
331     end
332   in
333   loop phi
334
335
336
337 let eval_trans auto fcs nss ps ss =
338   let fcsid = (fcs.Config.id :> int) in
339   let nssid = (nss.Config.id :> int) in
340   let psid = (ps.Config.id :> int) in
341   let rec loop old_config =
342     let oid = (old_config.Config.id :> int) in
343     let res =
344       let res = Cache.N4.find auto.cache4 oid fcsid nssid psid in
345       if res != dummy_config then res
346       else
347         let { sat = old_sat;
348               unsat = old_unsat;
349               todo = old_todo;
350               summary = old_summary } = old_config.Config.node
351         in
352         let sat, unsat, removed, kept, todo =
353           TransList.fold
354             (fun trs acc ->
355               let q, lab, phi = Transition.node trs in
356               let a_sat, a_unsat, a_rem, a_kept, a_todo = acc in
357               if StateSet.mem q a_sat || StateSet.mem q a_unsat then acc else
358                 let new_phi =
359                   eval_form phi fcs nss ps old_config old_summary
360                 in
361                 if SFormula.is_true new_phi then
362                   StateSet.add q a_sat, a_unsat, StateSet.add q a_rem, a_kept, a_todo
363                 else if SFormula.is_false new_phi then
364                   a_sat, StateSet.add q a_unsat, StateSet.add q a_rem, a_kept, a_todo
365                 else
366                   let new_tr = Transition.make (q, lab, new_phi) in
367                   (a_sat, a_unsat, a_rem, StateSet.add q a_kept, (TransList.cons new_tr a_todo))
368             ) old_todo (old_sat, old_unsat, StateSet.empty, StateSet.empty, TransList.nil)
369         in
370         (* States that have been removed from the todo list and not kept are now
371            unsatisfiable *)
372         let unsat = StateSet.union unsat (StateSet.diff removed kept) in
373         (* States that were found once to be satisfiable remain so *)
374         let unsat = StateSet.diff unsat sat in
375         let new_config = Config.make { old_config.Config.node with sat; unsat; todo; } in
376         Cache.N4.add auto.cache4 oid fcsid nssid psid new_config;
377         new_config
378     in
379     if res == old_config then res else loop res
380   in
381   loop ss
382
383 (*
384   [add_trans a q labels f] adds a transition [(q,labels) -> f] to the
385   automaton [a] but ensures that transitions remains pairwise disjoint
386 *)
387
388 let add_trans a q s f =
389   let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
390   let cup, ntrs =
391     List.fold_left (fun (acup, atrs) (labs, phi) ->
392       let lab1 = QNameSet.inter labs s in
393       let lab2 = QNameSet.diff labs s in
394       let tr1 =
395         if QNameSet.is_empty lab1 then []
396         else [ (lab1, SFormula.or_ phi f) ]
397       in
398       let tr2 =
399         if QNameSet.is_empty lab2 then []
400         else [ (lab2, SFormula.or_ phi f) ]
401       in
402       (QNameSet.union acup labs, tr1@ tr2 @ atrs)
403     ) (QNameSet.empty, []) trs
404   in
405   let rem = QNameSet.diff s cup in
406   let ntrs = if QNameSet.is_empty rem then ntrs
407     else (rem, f) :: ntrs
408   in
409   Hashtbl.replace a.transitions q ntrs
410
411 let _pr_buff = Buffer.create 50
412 let _str_fmt = formatter_of_buffer _pr_buff
413 let _flush_str_fmt () = pp_print_flush _str_fmt ();
414   let s = Buffer.contents _pr_buff in
415   Buffer.clear _pr_buff; s
416
417 let print fmt a =
418   fprintf fmt
419     "Internal UID: %i@\n\
420      States: %a@\n\
421      Selection states: %a@\n\
422      Alternating transitions:@\n"
423     (a.id :> int)
424     StateSet.print a.states
425     StateSet.print a.selection_states;
426   let trs =
427     Hashtbl.fold
428       (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
429       a.transitions
430       []
431   in
432   let sorted_trs = List.stable_sort (fun (q1, s1, _) (q2, s2, _) ->
433     let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
434     trs
435   in
436   let _ = _flush_str_fmt () in
437   let strs_strings, max_pre, max_all = List.fold_left (fun (accl, accp, acca) (q, s, f) ->
438     let s1 = State.print _str_fmt q; _flush_str_fmt () in
439     let s2 = QNameSet.print _str_fmt s;  _flush_str_fmt () in
440     let s3 = SFormula.print _str_fmt f;  _flush_str_fmt () in
441     let pre = Pretty.length s1 + Pretty.length s2 in
442     let all = Pretty.length s3 in
443     ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
444   ) ([], 0, 0) sorted_trs
445   in
446   let line = Pretty.line (max_all + max_pre + 6) in
447   let prev_q = ref State.dummy in
448   fprintf fmt "%s@\n" line;
449   List.iter (fun (q, s1, s2, s3) ->
450     if !prev_q != q && !prev_q != State.dummy then fprintf fmt "%s@\n"  line;
451     prev_q := q;
452     fprintf fmt "%s, %s" s1 s2;
453     fprintf fmt "%s" (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
454     fprintf fmt " %s  %s@\n" Pretty.right_arrow s3;
455   ) strs_strings;
456   fprintf fmt "%s@\n" line
457
458 (*
459   [complete transitions a] ensures that for each state q
460   and each symbols s in the alphabet, a transition q, s exists.
461   (adding q, s -> F when necessary).
462 *)
463
464 let complete_transitions a =
465   StateSet.iter (fun q ->
466     let qtrans = Hashtbl.find a.transitions q in
467     let rem =
468       List.fold_left (fun rem (labels, _) ->
469         QNameSet.diff rem labels) QNameSet.any qtrans
470     in
471     let nqtrans =
472       if QNameSet.is_empty rem then qtrans
473       else
474         (rem, SFormula.false_) :: qtrans
475     in
476     Hashtbl.replace a.transitions q nqtrans
477   ) a.states
478
479 let cleanup_states a =
480   let memo = ref StateSet.empty in
481   let rec loop q =
482     if not (StateSet.mem q !memo) then begin
483       memo := StateSet.add q !memo;
484       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
485       List.iter (fun (_, phi) ->
486         StateSet.iter loop (SFormula.get_states phi)) trs
487     end
488   in
489   StateSet.iter loop a.selection_states;
490   let unused = StateSet.diff a.states !memo in
491   StateSet.iter (fun q -> Hashtbl.remove a.transitions q) unused;
492   a.states <- !memo
493
494 (* [normalize_negations a] removes negative atoms in the formula
495    complementing the sub-automaton in the negative states.
496    [TODO check the meaning of negative upward arrows]
497 *)
498
499 let normalize_negations auto =
500   let memo_state = Hashtbl.create 17 in
501   let todo = Queue.create () in
502   let rec flip b f =
503     match SFormula.expr f with
504       Formula.True | Formula.False -> if b then f else SFormula.not_ f
505     | Formula.Or(f1, f2) -> (if b then SFormula.or_ else SFormula.and_)(flip b f1) (flip b f2)
506     | Formula.And(f1, f2) -> (if b then SFormula.and_ else SFormula.or_)(flip b f1) (flip b f2)
507     | Formula.Atom(a) -> begin
508       let l, b', q = Atom.node a in
509       if q == State.dummy then if b then f else SFormula.not_ f
510       else
511         if b == b' then begin
512         (* a appears positively, either no negation or double negation *)
513           if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
514           SFormula.atom_ (Atom.make (l, true, q))
515         end else begin
516         (* need to reverse the atom
517            either we have a positive state deep below a negation
518            or we have a negative state in a positive formula
519            b' = sign of the state
520            b = sign of the enclosing formula
521         *)
522         let not_q =
523           try
524             (* does the inverted state of q exist ? *)
525             Hashtbl.find memo_state (q, false)
526           with
527             Not_found ->
528               (* create a new state and add it to the todo queue *)
529               let nq = State.make () in
530               auto.states <- StateSet.add nq auto.states;
531               Hashtbl.add memo_state (q, false) nq;
532               Queue.add (q, false) todo; nq
533         in
534         SFormula.atom_ (Atom.make (l, true, not_q))
535       end
536     end
537   in
538   (* states that are not reachable from a selection stat are not interesting *)
539   StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selection_states;
540
541   while not (Queue.is_empty todo) do
542     let (q, b) as key = Queue.pop todo in
543     let q' =
544       try
545         Hashtbl.find memo_state key
546       with
547         Not_found ->
548           let nq = if b then q else
549               let nq = State.make () in
550               auto.states <- StateSet.add nq auto.states;
551               nq
552           in
553           Hashtbl.add memo_state key nq; nq
554     in
555     let trans = Hashtbl.find auto.transitions q in
556     let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
557     Hashtbl.replace auto.transitions q' trans';
558   done;
559   cleanup_states auto
560
561