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