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