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