Flatten the sources, only leave the XPath module packed.
[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-04 18:46:50 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 = { id = next ();
181                   states = s;
182                   selection_states = ss;
183                   transitions = Hashtbl.create 17;
184                   cache2 = Cache.N2.create dummy2;
185                   cache6 = Cache.N6.create dummy6;
186  }
187
188 let reset a =
189   a.cache2 <- Cache.N2.create dummy2;
190   a.cache6 <- Cache.N6.create dummy6
191
192
193 let get_trans_aux a tag states =
194   StateSet.fold (fun q acc0 ->
195     try
196       let trs = Hashtbl.find a.transitions q in
197       List.fold_left (fun acc1 (labs, phi) ->
198         if QNameSet.mem tag labs then TransList.cons (Transition.make (q, labs, phi)) acc1 else acc1) acc0 trs
199     with Not_found -> acc0
200   ) states TransList.nil
201
202
203 let get_trans a tag states =
204   let trs =
205     Cache.N2.find a.cache2
206       (tag.QName.id :> int) (states.StateSet.id :> int)
207   in
208   if trs == dummy2 then
209     let trs = get_trans_aux a tag states in
210     (Cache.N2.add
211        a.cache2
212        (tag.QName.id :> int)
213        (states.StateSet.id :> int) trs; trs)
214   else trs
215
216
217
218 let eval_form phi fcs nss ps ss is_left is_right has_left has_right kind =
219   let rec loop phi =
220     begin match SFormula.expr phi with
221       Formula.True -> true
222     | Formula.False -> false
223     | Formula.Atom a ->
224         let p, b, q = Atom.node a in
225         let pos =
226           match p with
227           | First_child -> StateSet.mem q fcs
228           | Next_sibling ->  StateSet.mem q nss
229           | Parent | Previous_sibling -> StateSet.mem q ps
230           | Stay -> StateSet.mem q ss
231           | Is_first_child -> is_left
232           | Is_next_sibling -> is_right
233           | Is k -> k == kind
234           | Has_first_child -> has_left
235           | Has_next_sibling -> has_right
236         in
237         if is_move p && (not b) then
238           eprintf "Warning: Invalid negative atom %a" Atom.print a;
239         b == pos
240     | Formula.And(phi1, phi2) -> loop phi1 && loop phi2
241     | Formula.Or (phi1, phi2) -> loop phi1 || loop phi2
242     end
243   in
244   loop phi
245
246 let int_of_conf is_left is_right has_left has_right kind =
247   ((Obj.magic kind) lsl 4) lor
248     ((Obj.magic is_left) lsl 3) lor
249     ((Obj.magic is_right) lsl 2) lor
250     ((Obj.magic has_left) lsl 1) lor
251     (Obj.magic has_right)
252
253 let eval_trans auto ltrs fcs nss ps ss is_left is_right has_left has_right kind =
254   let i = int_of_conf is_left is_right has_left has_right kind
255   and k = (fcs.StateSet.id :> int)
256   and l = (nss.StateSet.id :> int)
257   and m = (ps.StateSet.id :> int)
258   in
259
260   let rec loop ltrs ss =
261     let j = (ltrs.TransList.id :> int)
262     and n = (ss.StateSet.id :> int) in
263     let (new_ltrs, new_ss) as res =
264       let res = Cache.N6.find auto.cache6 i j k l m n in
265       if res == dummy6 then
266         let res =
267           TransList.fold (fun trs (acct, accs) ->
268             let q, _, phi = Transition.node trs in
269             if StateSet.mem q accs then (acct, accs) else
270               if eval_form
271                 phi fcs nss ps accs
272                 is_left is_right has_left has_right kind
273               then
274                 (acct, StateSet.add q accs)
275               else
276                 (TransList.cons trs acct, accs)
277           ) ltrs (TransList.nil, ss)
278         in
279         Cache.N6.add auto.cache6 i j k l m n res; res
280       else
281         res
282     in
283     if new_ss == ss then res else
284       loop new_ltrs new_ss
285   in
286   loop ltrs ss
287
288
289
290
291
292 (*
293   [add_trans a q labels f] adds a transition [(q,labels) -> f] to the
294   automaton [a] but ensures that transitions remains pairwise disjoint
295 *)
296
297 let add_trans a q s f =
298   let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
299   let cup, ntrs =
300     List.fold_left (fun (acup, atrs) (labs, phi) ->
301       let lab1 = QNameSet.inter labs s in
302       let lab2 = QNameSet.diff labs s in
303       let tr1 =
304         if QNameSet.is_empty lab1 then []
305         else [ (lab1, SFormula.or_ phi f) ]
306       in
307       let tr2 =
308         if QNameSet.is_empty lab2 then []
309         else [ (lab2, SFormula.or_ phi f) ]
310       in
311       (QNameSet.union acup labs, tr1@ tr2 @ atrs)
312     ) (QNameSet.empty, []) trs
313   in
314   let rem = QNameSet.diff s cup in
315   let ntrs = if QNameSet.is_empty rem then ntrs
316     else (rem, f) :: ntrs
317   in
318   Hashtbl.replace a.transitions q ntrs
319
320 let _pr_buff = Buffer.create 50
321 let _str_fmt = formatter_of_buffer _pr_buff
322 let _flush_str_fmt () = pp_print_flush _str_fmt ();
323   let s = Buffer.contents _pr_buff in
324   Buffer.clear _pr_buff; s
325
326 let print fmt a =
327   fprintf fmt
328     "\nInternal UID: %i@\n\
329      States: %a@\n\
330      Selection states: %a@\n\
331      Alternating transitions:@\n"
332     (a.id :> int)
333     StateSet.print a.states
334     StateSet.print a.selection_states;
335   let trs =
336     Hashtbl.fold
337       (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
338       a.transitions
339       []
340   in
341   let sorted_trs = List.stable_sort (fun (q1, s1, _) (q2, s2, _) ->
342     let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
343     trs
344   in
345   let _ = _flush_str_fmt () in
346   let strs_strings, max_pre, max_all = List.fold_left (fun (accl, accp, acca) (q, s, f) ->
347     let s1 = State.print _str_fmt q; _flush_str_fmt () in
348     let s2 = QNameSet.print _str_fmt s;  _flush_str_fmt () in
349     let s3 = SFormula.print _str_fmt f;  _flush_str_fmt () in
350     let pre = Pretty.length s1 + Pretty.length s2 in
351     let all = Pretty.length s3 in
352     ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
353   ) ([], 0, 0) sorted_trs
354   in
355   let line = Pretty.line (max_all + max_pre + 6) in
356   let prev_q = ref State.dummy in
357   List.iter (fun (q, s1, s2, s3) ->
358     if !prev_q != q && !prev_q != State.dummy then fprintf fmt " %s\n%!"  line;
359     prev_q := q;
360     fprintf fmt " %s, %s" s1 s2;
361     fprintf fmt "%s" (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
362     fprintf fmt " %s  %s@\n%!" Pretty.right_arrow s3;
363   ) strs_strings;
364   fprintf fmt " %s\n%!" line
365
366 (*
367   [complete transitions a] ensures that for each state q
368   and each symbols s in the alphabet, a transition q, s exists.
369   (adding q, s -> F when necessary).
370 *)
371
372 let complete_transitions a =
373   StateSet.iter (fun q ->
374     let qtrans = Hashtbl.find a.transitions q in
375     let rem =
376       List.fold_left (fun rem (labels, _) ->
377         QNameSet.diff rem labels) QNameSet.any qtrans
378     in
379     let nqtrans =
380       if QNameSet.is_empty rem then qtrans
381       else
382         (rem, SFormula.false_) :: qtrans
383     in
384     Hashtbl.replace a.transitions q nqtrans
385   ) a.states
386
387 let cleanup_states a =
388   let memo = ref StateSet.empty in
389   let rec loop q =
390     if not (StateSet.mem q !memo) then begin
391       memo := StateSet.add q !memo;
392       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
393       List.iter (fun (_, phi) ->
394         StateSet.iter loop (SFormula.get_states phi)) trs
395     end
396   in
397   StateSet.iter loop a.selection_states;
398   let unused = StateSet.diff a.states !memo in
399   eprintf "Unused states %a\n%!" StateSet.print unused;
400   StateSet.iter (fun q -> Hashtbl.remove a.transitions q) unused;
401   a.states <- !memo
402
403 (* [normalize_negations a] removes negative atoms in the formula
404    complementing the sub-automaton in the negative states.
405    [TODO check the meaning of negative upward arrows]
406 *)
407
408 let normalize_negations auto =
409   eprintf "Automaton before normalize_trans:\n";
410   print err_formatter auto;
411   eprintf "--------------------\n%!";
412
413   let memo_state = Hashtbl.create 17 in
414   let todo = Queue.create () in
415   let rec flip b f =
416     match SFormula.expr f with
417       Formula.True | Formula.False -> if b then f else SFormula.not_ f
418     | Formula.Or(f1, f2) -> (if b then SFormula.or_ else SFormula.and_)(flip b f1) (flip b f2)
419     | Formula.And(f1, f2) -> (if b then SFormula.and_ else SFormula.or_)(flip b f1) (flip b f2)
420     | Formula.Atom(a) -> begin
421       let l, b', q = Atom.node a in
422       if q == State.dummy then if b then f else SFormula.not_ f
423       else
424         if b == b' then begin
425         (* a appears positively, either no negation or double negation *)
426           if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
427           SFormula.atom_ (Atom.make (l, true, q))
428         end else begin
429         (* need to reverse the atom
430            either we have a positive state deep below a negation
431            or we have a negative state in a positive formula
432            b' = sign of the state
433            b = sign of the enclosing formula
434         *)
435         let not_q =
436           try
437             (* does the inverted state of q exist ? *)
438             Hashtbl.find memo_state (q, false)
439           with
440             Not_found ->
441               (* create a new state and add it to the todo queue *)
442               let nq = State.make () in
443               auto.states <- StateSet.add nq auto.states;
444               Hashtbl.add memo_state (q, false) nq;
445               Queue.add (q, false) todo; nq
446         in
447         SFormula.atom_ (Atom.make (l, true, not_q))
448       end
449     end
450   in
451   (* states that are not reachable from a selection stat are not interesting *)
452   StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selection_states;
453
454   while not (Queue.is_empty todo) do
455     let (q, b) as key = Queue.pop todo in
456     let q' =
457       try
458         Hashtbl.find memo_state key
459       with
460         Not_found ->
461           let nq = if b then q else
462               let nq = State.make () in
463               auto.states <- StateSet.add nq auto.states;
464               nq
465           in
466           Hashtbl.add memo_state key nq; nq
467     in
468     let trans = Hashtbl.find auto.transitions q in
469     let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
470     Hashtbl.replace auto.transitions q' trans';
471   done;
472   cleanup_states auto
473
474