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