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