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