Working for element only document (with arbitrary paths & negation).
[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-05 18:25:03 CET by Kim Nguyen>
18 *)
19
20 INCLUDE "utils.ml"
21 open Format
22 open Utils
23
24 type move = [ `Left | `Right | `Up1 | `Up2 | `Epsilon |`Is1 |`Is2 ]
25 type state_ctx = { mutable left : StateSet.t;
26              mutable right : StateSet.t;
27              mutable up1 : StateSet.t;
28              mutable up2 : StateSet.t;
29              mutable epsilon : StateSet.t;
30              mutable is_left : bool;
31              mutable is_root : bool}
32
33 type pred_ = move * bool * State.t
34 let make_ctx a b c d e f g =
35   { left = a; right = b; up1 = c; up2 = d; epsilon = e; is_left = f; is_root = g }
36
37 let print_ctx fmt c = fprintf fmt "{ left : %a; right : %a; up1: %a ; up2 : %a; epsilon : %a ; is_left : %b; is_root : %b }"
38   StateSet.print c.left StateSet.print c.right StateSet.print c.up1 StateSet.print c.up2
39   StateSet.print c.epsilon
40   c.is_left c.is_root
41
42 module Move : (Formula.PREDICATE with type data = pred_ and type ctx = state_ctx ) =
43 struct
44
45   module Node =
46   struct
47     type t = move * bool * State.t
48     let equal n1 n2 = n1 = n2
49     let hash n = Hashtbl.hash n
50   end
51
52   type ctx = state_ctx
53
54
55   include Hcons.Make(Node)
56   let _pr_buff = Buffer.create 10
57   let _str_fmt = formatter_of_buffer _pr_buff
58   let _flush_str_fmt () = pp_print_flush _str_fmt ();
59     let s = Buffer.contents _pr_buff in
60     Buffer.clear _pr_buff; s
61
62   let print ppf a =
63     let _ = _flush_str_fmt () in
64
65     let m, b, s = a.node in
66     let dir,num =
67       match  m with
68       | `Left ->  Pretty.down_arrow, Pretty.subscript 1
69       | `Right -> Pretty.down_arrow, Pretty.subscript 2
70       | `Epsilon -> Pretty.epsilon, ""
71       | `Up1 -> Pretty.up_arrow, Pretty.subscript 1
72       | `Up2 -> Pretty.up_arrow, Pretty.subscript 2
73       | `Is1 -> "?", Pretty.subscript 1
74       | `Is2 -> "?", Pretty.subscript 2
75     in
76     fprintf _str_fmt "%s%s" dir num;
77     if s != State.dummy then State.print _str_fmt s;
78     let str = _flush_str_fmt () in
79     fprintf ppf "%s%s" (if b then "" else Pretty.lnot) str
80   let neg p =
81     let l, b, s = p.node in
82     make (l, not b, s)
83
84   exception NegativeAtom of (move*State.t)
85
86   let eval ctx p =
87     let l, b, s = p.node in
88     if s == State.dummy then
89       let dir =
90         match l with
91           | `Is1 -> ctx.is_left
92           | _ -> not ctx.is_left
93       in
94       let res = dir && not ctx.is_root in
95       res && b || (not (b || res))
96     else begin
97       if not b then raise (NegativeAtom(l,s));
98       StateSet.mem s begin
99         match l with
100             `Left -> ctx.left
101           | `Right -> ctx.right
102           | `Up1 -> ctx.up1
103           | `Up2 -> ctx.up2
104           | `Epsilon -> ctx.epsilon
105           | _ -> StateSet.empty
106       end
107     end
108 end
109
110 module SFormula = Formula.Make(Move)
111 type t = {
112   id : Uid.t;
113   mutable states : StateSet.t;
114   mutable top_states : StateSet.t;
115   mutable bottom_states: StateSet.t;
116   mutable selection_states: StateSet.t;
117   transitions: (State.t, (QNameSet.t*SFormula.t) list) Hashtbl.t;
118 }
119
120 let next = Uid.make_maker ()
121
122 let create () = { id = next ();
123                   states = StateSet.empty;
124                   top_states = StateSet.empty;
125                   bottom_states = StateSet.empty;
126                   selection_states = StateSet.empty;
127                   transitions = Hashtbl.create 17;
128  }
129
130
131 let get_trans a states tag =
132   StateSet.fold (fun q acc0 ->
133     try
134       let trs = Hashtbl.find a.transitions q in
135       List.fold_left (fun acc1 (labs, phi) ->
136         if QNameSet.mem tag labs then (q,phi)::acc1 else acc1) acc0 trs
137     with Not_found -> acc0
138   ) states []
139
140 (*
141   [add_trans a q labels f] adds a transition [(q,labels) -> f] to the
142   automaton [a] but ensures that transitions remains pairwise disjoint
143 *)
144
145 let add_trans a q s f =
146   let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
147   let cup, ntrs =
148     List.fold_left (fun (acup, atrs) (labs, phi) ->
149       let lab1 = QNameSet.inter labs s in
150       let lab2 = QNameSet.diff labs s in
151       let tr1 =
152         if QNameSet.is_empty lab1 then []
153         else [ (lab1, SFormula.or_ phi f) ]
154       in
155       let tr2 =
156         if QNameSet.is_empty lab2 then []
157         else [ (lab2, SFormula.or_ phi f) ]
158       in
159       (QNameSet.union acup labs, tr1@ tr2 @ atrs)
160     ) (QNameSet.empty, []) trs
161   in
162   let rem = QNameSet.diff s cup in
163   let ntrs = if QNameSet.is_empty rem then ntrs
164     else (rem, f) :: ntrs
165   in
166   Hashtbl.replace a.transitions q ntrs
167
168 let _pr_buff = Buffer.create 50
169 let _str_fmt = formatter_of_buffer _pr_buff
170 let _flush_str_fmt () = pp_print_flush _str_fmt ();
171   let s = Buffer.contents _pr_buff in
172   Buffer.clear _pr_buff; s
173
174 let print fmt a =
175   fprintf fmt
176     "\nInternal UID: %i@\n\
177      States: %a@\n\
178      Top states: %a@\n\
179      Bottom 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.top_states
185     StateSet.print a.bottom_states
186     StateSet.print a.selection_states;
187   let trs =
188     Hashtbl.fold
189       (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
190       a.transitions
191       []
192   in
193   let sorted_trs = List.stable_sort (fun (q1, s1, _) (q2, s2, _) ->
194     let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
195     trs
196   in
197   let _ = _flush_str_fmt () in
198   let strs_strings, max_pre, max_all = List.fold_left (fun (accl, accp, acca) (q, s, f) ->
199     let s1 = State.print _str_fmt q; _flush_str_fmt () in
200     let s2 = QNameSet.print _str_fmt s;  _flush_str_fmt () in
201     let s3 = SFormula.print _str_fmt f;  _flush_str_fmt () in
202     let pre = Pretty.length s1 + Pretty.length s2 in
203     let all = Pretty.length s3 in
204     ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
205   ) ([], 0, 0) sorted_trs
206   in
207   let line = Pretty.line (max_all + max_pre + 6) in
208   let prev_q = ref State.dummy in
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     let qtrans = Hashtbl.find a.transitions q in
227     let rem =
228       List.fold_left (fun rem (labels, _) ->
229         QNameSet.diff rem labels) QNameSet.any qtrans
230     in
231     let nqtrans =
232       if QNameSet.is_empty rem then qtrans
233       else
234         (rem, SFormula.false_) :: qtrans
235     in
236     Hashtbl.replace a.transitions q nqtrans
237   ) a.states
238
239 (* [normalize_negations a] removes negative atoms in the formula
240    complementing the sub-automaton in the negative states.
241    [TODO check the meaning of negative upward arrows]
242 *)
243 let normalize_negations auto =
244   let memo_state = Hashtbl.create 17 in
245   let todo = Queue.create () in
246   let rec flip b f =
247     match SFormula.expr f with
248       Formula.True | Formula.False -> if b then f else SFormula.not_ f
249     | Formula.Or(f1, f2) -> (if b then SFormula.or_ else SFormula.and_)(flip b f1) (flip b f2)
250     | Formula.And(f1, f2) -> (if b then SFormula.and_ else SFormula.or_)(flip b f1) (flip b f2)
251     | Formula.Atom(a) -> begin
252       let l, b', q = Move.node a in
253       if q == State.dummy then if b then f else SFormula.not_ f
254       else
255         if b == b' then begin
256         (* a appears positively, either no negation or double negation *)
257           if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
258           SFormula.atom_ (Move.make (l, true, q))
259         end else begin
260         (* need to reverse the atom
261            either we have a positive state deep below a negation
262            or we have a negative state in a positive formula
263            b' = sign of the state
264            b = sign of the enclosing formula
265         *)
266         let not_q =
267           try
268             (* does the inverted state of q exist ? *)
269             Hashtbl.find memo_state (q, false)
270           with
271             Not_found ->
272               (* create a new state and add it to the todo queue *)
273               let nq = State.make () in
274               auto.states <- StateSet.add nq auto.states;
275 (*              if not (StateSet.mem q auto.bottom_states) then
276                 auto.bottom_states <- StateSet.add nq auto.bottom_states;
277               if not (StateSet.mem q auto.top_states) then
278                 auto.top_states <- StateSet.add nq auto.top_states; *)
279               Hashtbl.add memo_state (q, false) nq;
280               Queue.add (q, false) todo; nq
281         in
282         SFormula.atom_ (Move.make (l, true, not_q))
283       end
284     end
285   in
286   (* states that are not reachable from a selection stat are not interesting *)
287   StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selection_states;
288
289   while not (Queue.is_empty todo) do
290     let (q, b) as key = Queue.pop todo in
291     let q' =
292       try
293         Hashtbl.find memo_state key
294       with
295         Not_found ->
296           let nq = if b then q else
297               let nq = State.make () in
298               auto.states <- StateSet.add nq auto.states;
299 (*              if not (StateSet.mem q auto.bottom_states) then
300                 auto.bottom_states <- StateSet.add nq auto.bottom_states;
301               if not (StateSet.mem q auto.top_states) then
302                 auto.top_states <- StateSet.add nq auto.top_states; *)
303               nq
304           in
305           Hashtbl.add memo_state key nq; nq
306     in
307     let trans = Hashtbl.find auto.transitions q in
308     let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
309     Hashtbl.replace auto.transitions q' trans'
310   done