Refactor the Ata module:
[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 selecting_states: StateSet.t;
146   transitions: (State.t, (QNameSet.t*Formula.t) list) Hashtbl.t;
147 }
148
149
150
151 let get_states a = a.states
152 let get_selecting_states a = a.selecting_states
153
154 let get_trans a tag states =
155   StateSet.fold (fun q acc0 ->
156     try
157       let trs = Hashtbl.find a.transitions q in
158       List.fold_left (fun acc1 (labs, phi) ->
159            if QNameSet.mem tag labs then
160              TransList.cons (Transition.make (q, labs, phi)) acc1
161            else acc1) acc0 trs
162     with Not_found -> acc0
163   ) states TransList.nil
164
165
166
167 let _pr_buff = Buffer.create 50
168 let _str_fmt = formatter_of_buffer _pr_buff
169 let _flush_str_fmt () = pp_print_flush _str_fmt ();
170   let s = Buffer.contents _pr_buff in
171   Buffer.clear _pr_buff; s
172
173 let print fmt a =
174   fprintf fmt
175     "Internal UID: %i@\n\
176      States: %a@\n\
177      Selection states: %a@\n\
178      Alternating transitions:@\n"
179     (a.id :> int)
180     StateSet.print a.states
181     StateSet.print a.selecting_states;
182   let trs =
183     Hashtbl.fold
184       (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
185       a.transitions
186       []
187   in
188   let sorted_trs = List.stable_sort (fun (q1, s1, _) (q2, s2, _) ->
189     let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
190     trs
191   in
192   let _ = _flush_str_fmt () in
193   let strs_strings, max_pre, max_all = List.fold_left (fun (accl, accp, acca) (q, s, f) ->
194     let s1 = State.print _str_fmt q; _flush_str_fmt () in
195     let s2 = QNameSet.print _str_fmt s;  _flush_str_fmt () in
196     let s3 = Formula.print _str_fmt f;  _flush_str_fmt () in
197     let pre = Pretty.length s1 + Pretty.length s2 in
198     let all = Pretty.length s3 in
199     ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
200   ) ([], 0, 0) sorted_trs
201   in
202   let line = Pretty.line (max_all + max_pre + 6) in
203   let prev_q = ref State.dummy in
204   fprintf fmt "%s@\n" line;
205   List.iter (fun (q, s1, s2, s3) ->
206     if !prev_q != q && !prev_q != State.dummy then fprintf fmt "%s@\n"  line;
207     prev_q := q;
208     fprintf fmt "%s, %s" s1 s2;
209     fprintf fmt "%s" (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
210     fprintf fmt " %s  %s@\n" Pretty.right_arrow s3;
211   ) strs_strings;
212   fprintf fmt "%s@\n" line
213
214 (*
215   [complete transitions a] ensures that for each state q
216   and each symbols s in the alphabet, a transition q, s exists.
217   (adding q, s -> F when necessary).
218 *)
219
220 let complete_transitions a =
221   StateSet.iter (fun q ->
222     let qtrans = Hashtbl.find a.transitions q in
223     let rem =
224       List.fold_left (fun rem (labels, _) ->
225         QNameSet.diff rem labels) QNameSet.any qtrans
226     in
227     let nqtrans =
228       if QNameSet.is_empty rem then qtrans
229       else
230         (rem, Formula.false_) :: qtrans
231     in
232     Hashtbl.replace a.transitions q nqtrans
233   ) a.states
234
235 let cleanup_states a =
236   let memo = ref StateSet.empty in
237   let rec loop q =
238     if not (StateSet.mem q !memo) then begin
239       memo := StateSet.add q !memo;
240       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
241       List.iter (fun (_, phi) ->
242         StateSet.iter loop (Formula.get_states phi)) trs
243     end
244   in
245   StateSet.iter loop a.selecting_states;
246   let unused = StateSet.diff a.states !memo in
247   StateSet.iter (fun q -> Hashtbl.remove a.transitions q) unused;
248   a.states <- !memo
249
250 (* [normalize_negations a] removes negative atoms in the formula
251    complementing the sub-automaton in the negative states.
252    [TODO check the meaning of negative upward arrows]
253 *)
254
255 let normalize_negations auto =
256   let memo_state = Hashtbl.create 17 in
257   let todo = Queue.create () in
258   let rec flip b f =
259     match Formula.expr f with
260       Boolean.True | Boolean.False -> if b then f else Formula.not_ f
261     | Boolean.Or(f1, f2) -> (if b then Formula.or_ else Formula.and_)(flip b f1) (flip b f2)
262     | Boolean.And(f1, f2) -> (if b then Formula.and_ else Formula.or_)(flip b f1) (flip b f2)
263     | Boolean.Atom(a, b') -> begin
264       match a.Atom.node with
265       | Move (m,  q) ->
266           if b == b' then begin
267           (* a appears positively, either no negation or double negation *)
268             if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
269             Formula.mk_atom (Move(m, q))
270           end else begin
271         (* need to reverse the atom
272            either we have a positive state deep below a negation
273            or we have a negative state in a positive formula
274            b' = sign of the state
275            b = sign of the enclosing formula
276         *)
277             let not_q =
278               try
279             (* does the inverted state of q exist ? *)
280                 Hashtbl.find memo_state (q, false)
281               with
282                 Not_found ->
283               (* create a new state and add it to the todo queue *)
284                   let nq = State.make () in
285                   auto.states <- StateSet.add nq auto.states;
286                   Hashtbl.add memo_state (q, false) nq;
287                   Queue.add (q, false) todo; nq
288             in
289             Formula.mk_atom (Move (m,not_q))
290           end
291       | _ -> if b then f else Formula.not_ f
292     end
293   in
294   (* states that are not reachable from a selection stat are not interesting *)
295   StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selecting_states;
296
297   while not (Queue.is_empty todo) do
298     let (q, b) as key = Queue.pop todo in
299     let q' =
300       try
301         Hashtbl.find memo_state key
302       with
303         Not_found ->
304           let nq = if b then q else
305               let nq = State.make () in
306               auto.states <- StateSet.add nq auto.states;
307               nq
308           in
309           Hashtbl.add memo_state key nq; nq
310     in
311     let trans = Hashtbl.find auto.transitions q in
312     let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
313     Hashtbl.replace auto.transitions q' trans';
314   done;
315   cleanup_states auto
316
317
318 module Builder =
319   struct
320     type auto = t
321     type t = auto
322     let next = Uid.make_maker ()
323
324     let make () =
325       let auto =
326         {
327           id = next ();
328           states = StateSet.empty;
329           selecting_states = StateSet.empty;
330           transitions = Hashtbl.create MED_H_SIZE;
331         }
332       in
333       (*
334       at_exit (fun () ->
335         let n4 = ref 0 in
336         let n2 = ref 0 in
337         Cache.N2.iteri (fun _ _ _ b -> if b then incr n2) auto.cache2;
338         Cache.N4.iteri (fun _ _ _ _ _ b -> if b then incr n4) auto.cache4;
339         Logger.msg `STATS "automaton %i, cache2: %i entries, cache6: %i entries"
340           (auto.id :> int) !n2 !n4;
341         let c2l, c2u = Cache.N2.stats auto.cache2 in
342         let c4l, c4u = Cache.N4.stats auto.cache4 in
343         Logger.msg `STATS
344           "cache2: length: %i, used: %i, occupation: %f"
345           c2l c2u (float c2u /. float c2l);
346         Logger.msg `STATS
347           "cache4: length: %i, used: %i, occupation: %f"
348           c4l c4u (float c4u /. float c4l)
349
350       ); *)
351       auto
352
353     let add_state a ?(selecting=false) q =
354       a.states <- StateSet.add q a.states;
355       if selecting then a.selecting_states <- StateSet.add q a.selecting_states
356
357     let add_trans a q s f =
358       if not (StateSet.mem q a.states) then add_state a q;
359       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
360       let cup, ntrs =
361         List.fold_left (fun (acup, atrs) (labs, phi) ->
362           let lab1 = QNameSet.inter labs s in
363           let lab2 = QNameSet.diff labs s in
364           let tr1 =
365             if QNameSet.is_empty lab1 then []
366             else [ (lab1, Formula.or_ phi f) ]
367           in
368           let tr2 =
369             if QNameSet.is_empty lab2 then []
370             else [ (lab2, Formula.or_ phi f) ]
371           in
372           (QNameSet.union acup labs, tr1@ tr2 @ atrs)
373         ) (QNameSet.empty, []) trs
374       in
375       let rem = QNameSet.diff s cup in
376       let ntrs = if QNameSet.is_empty rem then ntrs
377         else (rem, f) :: ntrs
378       in
379       Hashtbl.replace a.transitions q ntrs
380
381     let finalize a =
382       complete_transitions a;
383       normalize_negations a;
384       a
385   end