c7bb1720e855130e8884e47db29e8a6d115585ad
[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-09 18:06:46 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_attribute
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_attribute -> fprintf ppf "%s" "@?"
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   let mk_atom a b c = atom_ (Atom.make (a,b,c))
81   let has_first_child =
82     (mk_atom Has_first_child true State.dummy)
83
84   let has_next_sibling =
85     (mk_atom Has_next_sibling true State.dummy)
86
87   let is_first_child =
88     (mk_atom Is_first_child true State.dummy)
89
90   let is_next_sibling =
91     (mk_atom Is_next_sibling true State.dummy)
92
93   let is_attribute =
94     (mk_atom Is_attribute true State.dummy)
95
96   let first_child q =
97   and_
98     (mk_atom First_child true q)
99     has_first_child
100
101   let next_sibling q =
102   and_
103     (mk_atom Next_sibling true q)
104     has_next_sibling
105
106   let parent q =
107   and_
108     (mk_atom Parent true q)
109     is_first_child
110
111   let previous_sibling q =
112   and_
113     (mk_atom Previous_sibling true q)
114     is_next_sibling
115
116   let stay q =
117     (mk_atom Stay true q)
118
119   let get_states phi =
120     fold (fun phi acc ->
121       match expr phi with
122       | Formula.Atom a -> let _, _, q = Atom.node a in
123                           if q != State.dummy then StateSet.add q acc else acc
124       | _ -> acc
125     ) phi StateSet.empty
126
127 end
128
129 type t = {
130   id : Uid.t;
131   mutable states : StateSet.t;
132   mutable selection_states: StateSet.t;
133   transitions: (State.t, (QNameSet.t*SFormula.t) list) Hashtbl.t;
134 }
135
136 let next = Uid.make_maker ()
137
138 let create () = { id = next ();
139                   states = StateSet.empty;
140                   selection_states = StateSet.empty;
141                   transitions = Hashtbl.create 17;
142  }
143
144
145 let get_trans a states tag =
146   StateSet.fold (fun q acc0 ->
147     try
148       let trs = Hashtbl.find a.transitions q in
149       List.fold_left (fun acc1 (labs, phi) ->
150         if QNameSet.mem tag labs then (q,phi)::acc1 else acc1) acc0 trs
151     with Not_found -> acc0
152   ) states []
153
154 (*
155   [add_trans a q labels f] adds a transition [(q,labels) -> f] to the
156   automaton [a] but ensures that transitions remains pairwise disjoint
157 *)
158
159 let add_trans a q s f =
160   let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
161   let cup, ntrs =
162     List.fold_left (fun (acup, atrs) (labs, phi) ->
163       let lab1 = QNameSet.inter labs s in
164       let lab2 = QNameSet.diff labs s in
165       let tr1 =
166         if QNameSet.is_empty lab1 then []
167         else [ (lab1, SFormula.or_ phi f) ]
168       in
169       let tr2 =
170         if QNameSet.is_empty lab2 then []
171         else [ (lab2, SFormula.or_ phi f) ]
172       in
173       (QNameSet.union acup labs, tr1@ tr2 @ atrs)
174     ) (QNameSet.empty, []) trs
175   in
176   let rem = QNameSet.diff s cup in
177   let ntrs = if QNameSet.is_empty rem then ntrs
178     else (rem, f) :: ntrs
179   in
180   Hashtbl.replace a.transitions q ntrs
181
182 let _pr_buff = Buffer.create 50
183 let _str_fmt = formatter_of_buffer _pr_buff
184 let _flush_str_fmt () = pp_print_flush _str_fmt ();
185   let s = Buffer.contents _pr_buff in
186   Buffer.clear _pr_buff; s
187
188 let print fmt a =
189   fprintf fmt
190     "\nInternal UID: %i@\n\
191      States: %a@\n\
192      Selection states: %a@\n\
193      Alternating transitions:@\n"
194     (a.id :> int)
195     StateSet.print a.states
196     StateSet.print a.selection_states;
197   let trs =
198     Hashtbl.fold
199       (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
200       a.transitions
201       []
202   in
203   let sorted_trs = List.stable_sort (fun (q1, s1, _) (q2, s2, _) ->
204     let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
205     trs
206   in
207   let _ = _flush_str_fmt () in
208   let strs_strings, max_pre, max_all = List.fold_left (fun (accl, accp, acca) (q, s, f) ->
209     let s1 = State.print _str_fmt q; _flush_str_fmt () in
210     let s2 = QNameSet.print _str_fmt s;  _flush_str_fmt () in
211     let s3 = SFormula.print _str_fmt f;  _flush_str_fmt () in
212     let pre = Pretty.length s1 + Pretty.length s2 in
213     let all = Pretty.length s3 in
214     ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
215   ) ([], 0, 0) sorted_trs
216   in
217   let line = Pretty.line (max_all + max_pre + 6) in
218   let prev_q = ref State.dummy in
219   List.iter (fun (q, s1, s2, s3) ->
220     if !prev_q != q && !prev_q != State.dummy then fprintf fmt " %s\n%!"  line;
221     prev_q := q;
222     fprintf fmt " %s, %s" s1 s2;
223     fprintf fmt "%s" (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
224     fprintf fmt " %s  %s@\n%!" Pretty.right_arrow s3;
225   ) strs_strings;
226   fprintf fmt " %s\n%!" line
227
228 (*
229   [complete transitions a] ensures that for each state q
230   and each symbols s in the alphabet, a transition q, s exists.
231   (adding q, s -> F when necessary).
232 *)
233
234 let complete_transitions a =
235   StateSet.iter (fun q ->
236     let qtrans = Hashtbl.find a.transitions q in
237     let rem =
238       List.fold_left (fun rem (labels, _) ->
239         QNameSet.diff rem labels) QNameSet.any qtrans
240     in
241     let nqtrans =
242       if QNameSet.is_empty rem then qtrans
243       else
244         (rem, SFormula.false_) :: qtrans
245     in
246     Hashtbl.replace a.transitions q nqtrans
247   ) a.states
248
249 let cleanup_states a =
250   let memo = ref StateSet.empty in
251   let rec loop q =
252     if not (StateSet.mem q !memo) then begin
253       memo := StateSet.add q !memo;
254       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
255       List.iter (fun (_, phi) ->
256         StateSet.iter loop (SFormula.get_states phi)) trs
257     end
258   in
259   StateSet.iter loop a.selection_states;
260   let unused = StateSet.diff a.states !memo in
261   eprintf "Unused states %a\n%!" StateSet.print unused;
262   StateSet.iter (fun q -> Hashtbl.remove a.transitions q) unused;
263   a.states <- !memo
264
265 (* [normalize_negations a] removes negative atoms in the formula
266    complementing the sub-automaton in the negative states.
267    [TODO check the meaning of negative upward arrows]
268 *)
269
270 let normalize_negations auto =
271   eprintf "Automaton before normalize_trans:\n";
272   print err_formatter auto;
273   eprintf "--------------------\n%!";
274
275   let memo_state = Hashtbl.create 17 in
276   let todo = Queue.create () in
277   let rec flip b f =
278     match SFormula.expr f with
279       Formula.True | Formula.False -> if b then f else SFormula.not_ f
280     | Formula.Or(f1, f2) -> (if b then SFormula.or_ else SFormula.and_)(flip b f1) (flip b f2)
281     | Formula.And(f1, f2) -> (if b then SFormula.and_ else SFormula.or_)(flip b f1) (flip b f2)
282     | Formula.Atom(a) -> begin
283       let l, b', q = Atom.node a in
284       if q == State.dummy then if b then f else SFormula.not_ f
285       else
286         if b == b' then begin
287         (* a appears positively, either no negation or double negation *)
288           if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
289           SFormula.atom_ (Atom.make (l, true, q))
290         end else begin
291         (* need to reverse the atom
292            either we have a positive state deep below a negation
293            or we have a negative state in a positive formula
294            b' = sign of the state
295            b = sign of the enclosing formula
296         *)
297         let not_q =
298           try
299             (* does the inverted state of q exist ? *)
300             Hashtbl.find memo_state (q, false)
301           with
302             Not_found ->
303               (* create a new state and add it to the todo queue *)
304               let nq = State.make () in
305               auto.states <- StateSet.add nq auto.states;
306               Hashtbl.add memo_state (q, false) nq;
307               Queue.add (q, false) todo; nq
308         in
309         SFormula.atom_ (Atom.make (l, true, not_q))
310       end
311     end
312   in
313   (* states that are not reachable from a selection stat are not interesting *)
314   StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selection_states;
315
316   while not (Queue.is_empty todo) do
317     let (q, b) as key = Queue.pop todo in
318     let q' =
319       try
320         Hashtbl.find memo_state key
321       with
322         Not_found ->
323           let nq = if b then q else
324               let nq = State.make () in
325               auto.states <- StateSet.add nq auto.states;
326               nq
327           in
328           Hashtbl.add memo_state key nq; nq
329     in
330     let trans = Hashtbl.find auto.transitions q in
331     let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
332     Hashtbl.replace auto.transitions q' trans';
333   done;
334   cleanup_states auto
335
336