Also print the number of states when printing automata.
[tatoo.git] / src / 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 INCLUDE "utils.ml"
17 open Format
18 open Misc
19 type move = [ `First_child
20             | `Next_sibling
21             | `Parent
22             | `Previous_sibling
23             | `Stay ]
24
25 type predicate = Move of move * State.t
26                  | Is_first_child
27                  | Is_next_sibling
28                  | Is of Tree.NodeKind.t
29                  | Has_first_child
30                  | Has_next_sibling
31
32 module Atom =
33 struct
34
35   module Node =
36   struct
37     type t = predicate
38     let equal n1 n2 = n1 = n2
39     let hash n = Hashtbl.hash n
40   end
41
42   include Hcons.Make(Node)
43
44   let print ppf a =
45     match a.node with
46     | Move (m, q) -> begin
47       match m with
48         `First_child -> fprintf ppf "%s" Pretty.down_arrow
49       | `Next_sibling -> fprintf ppf "%s" Pretty.right_arrow
50       | `Parent -> fprintf ppf "%s" Pretty.up_arrow
51       | `Previous_sibling -> fprintf ppf "%s" Pretty.left_arrow
52       | `Stay -> fprintf ppf "%s" Pretty.bullet
53     end;
54         fprintf ppf "%a" State.print q
55     | Is_first_child -> fprintf ppf "%s?" Pretty.up_arrow
56     | Is_next_sibling -> fprintf ppf "%s?" Pretty.left_arrow
57     | Is k -> fprintf ppf "is-%a?" Tree.NodeKind.print k
58     | Has_first_child -> fprintf ppf "%s?" Pretty.down_arrow
59     | Has_next_sibling -> fprintf ppf "%s?" Pretty.right_arrow
60
61 end
62
63
64 module Formula =
65 struct
66   include Boolean.Make(Atom)
67   open Tree.NodeKind
68   let mk_atom a = atom_ (Atom.make a)
69   let is k = mk_atom (Is k)
70
71   let has_first_child = mk_atom Has_first_child
72
73   let has_next_sibling = mk_atom Has_next_sibling
74
75   let is_first_child = mk_atom Is_first_child
76
77   let is_next_sibling = mk_atom Is_next_sibling
78
79   let is_attribute = mk_atom (Is Attribute)
80
81   let is_element = mk_atom (Is Element)
82
83   let is_processing_instruction = mk_atom (Is ProcessingInstruction)
84
85   let is_comment = mk_atom (Is Comment)
86
87   let mk_move m q = mk_atom (Move(m,q))
88   let first_child q =
89     and_
90       (mk_move `First_child q)
91       has_first_child
92
93   let next_sibling q =
94   and_
95     (mk_move `Next_sibling q)
96     has_next_sibling
97
98   let parent q =
99   and_
100     (mk_move `Parent  q)
101     is_first_child
102
103   let previous_sibling q =
104   and_
105     (mk_move `Previous_sibling q)
106     is_next_sibling
107
108   let stay q = mk_move `Stay q
109
110   let get_states phi =
111     fold (fun phi acc ->
112       match expr phi with
113       | Boolean.Atom ({ Atom.node = Move(_,q) ; _ }, _) ->  StateSet.add q acc
114       | _ -> acc
115     ) phi StateSet.empty
116
117 end
118
119 module Transition =
120   struct
121     include Hcons.Make (struct
122   type t = State.t * QNameSet.t * Formula.t
123   let equal (a, b, c) (d, e, f) =
124     a == d && b == e && c == f
125   let hash (a, b, c) =
126     HASHINT4 (PRIME1, a, ((QNameSet.uid b) :> int), ((Formula.uid c) :> int))
127 end)
128     let print ppf t =
129       let q, l, f = t.node in
130       fprintf ppf "%a, %a %s %a"
131         State.print q
132         QNameSet.print l
133         Pretty.double_right_arrow
134         Formula.print f
135   end
136
137
138 module TransList : sig
139   include Hlist.S with type elt = Transition.t
140   val print : Format.formatter -> ?sep:string -> t -> unit
141 end =
142   struct
143     include Hlist.Make(Transition)
144     let print ppf ?(sep="\n") l =
145       iter (fun t ->
146         let q, lab, f = Transition.node t in
147         fprintf ppf "%a, %a -> %a%s" State.print q QNameSet.print lab Formula.print f sep) l
148   end
149
150
151
152 type t = {
153   id : Uid.t;
154   mutable states : StateSet.t;
155   mutable starting_states : StateSet.t;
156   mutable selecting_states: StateSet.t;
157   transitions: (State.t, (QNameSet.t*Formula.t) list) Hashtbl.t;
158 }
159
160 let uid t = t.id
161
162 let get_states a = a.states
163 let get_starting_states a = a.starting_states
164 let get_selecting_states a = a.selecting_states
165
166
167 let _pr_buff = Buffer.create 50
168 let _str_fmt = formatter_of_buffer _pr_buff
169 let _flush_str_fmt () = pp_print_flush _str_fmt ();
170   let s = Buffer.contents _pr_buff in
171   Buffer.clear _pr_buff; s
172
173 let print fmt a =
174   let _ = _flush_str_fmt() in
175   fprintf fmt
176     "Internal UID: %i@\n\
177      States: %a@\n\
178      Number of states: %i@\n\
179      Starting states: %a@\n\
180      Selection states: %a@\n\
181      Alternating transitions:@\n"
182     (a.id :> int)
183     StateSet.print a.states
184     (StateSet.cardinal a.states)
185     StateSet.print a.starting_states
186     StateSet.print a.selecting_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 = Formula.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   fprintf fmt "%s@\n" line;
210   List.iter (fun (q, s1, s2, s3) ->
211     if !prev_q != q && !prev_q != State.dummy then fprintf fmt "%s@\n"  line;
212     prev_q := q;
213     fprintf fmt "%s, %s" s1 s2;
214     fprintf fmt "%s" (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
215     fprintf fmt " %s  %s@\n" Pretty.right_arrow s3;
216   ) strs_strings;
217   fprintf fmt "%s@\n" line
218
219
220 let get_trans a tag states =
221   StateSet.fold (fun q acc0 ->
222     try
223       let trs = Hashtbl.find a.transitions q in
224       List.fold_left (fun acc1 (labs, phi) ->
225         if QNameSet.mem tag labs then
226           TransList.cons (Transition.make (q, labs, phi)) acc1
227         else acc1) acc0 trs
228     with Not_found -> acc0
229   ) states TransList.nil
230
231
232 let get_form a tag q =
233   try
234     let trs = Hashtbl.find a.transitions q in
235     List.fold_left (fun aphi (labs, phi) ->
236       if QNameSet.mem tag labs then Formula.or_ aphi phi else aphi
237     ) Formula.false_ trs
238   with
239     Not_found -> Formula.false_
240
241 (*
242   [complete transitions a] ensures that for each state q
243   and each symbols s in the alphabet, a transition q, s exists.
244   (adding q, s -> F when necessary).
245 *)
246
247 let complete_transitions a =
248   StateSet.iter (fun q ->
249     if StateSet.mem q a.starting_states then ()
250     else
251       let qtrans = Hashtbl.find a.transitions q in
252       let rem =
253         List.fold_left (fun rem (labels, _) ->
254           QNameSet.diff rem labels) QNameSet.any qtrans
255       in
256       let nqtrans =
257         if QNameSet.is_empty rem then qtrans
258         else
259           (rem, Formula.false_) :: qtrans
260       in
261       Hashtbl.replace a.transitions q nqtrans
262   ) a.states
263
264 (* [cleanup_states] remove states that do not lead to a
265    selecting states *)
266
267 let cleanup_states a =
268   let memo = ref StateSet.empty in
269   let rec loop q =
270     if not (StateSet.mem q !memo) then begin
271       memo := StateSet.add q !memo;
272       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
273       List.iter (fun (_, phi) ->
274         StateSet.iter loop (Formula.get_states phi)) trs
275     end
276   in
277   StateSet.iter loop a.selecting_states;
278   let unused = StateSet.diff a.states !memo in
279   StateSet.iter (fun q -> Hashtbl.remove a.transitions q) unused;
280   a.states <- !memo
281
282 (* [normalize_negations a] removes negative atoms in the formula
283    complementing the sub-automaton in the negative states.
284    [TODO check the meaning of negative upward arrows]
285 *)
286
287 let normalize_negations auto =
288   let memo_state = Hashtbl.create 17 in
289   let todo = Queue.create () in
290   let rec flip b f =
291     match Formula.expr f with
292       Boolean.True | Boolean.False -> if b then f else Formula.not_ f
293     | Boolean.Or(f1, f2) -> (if b then Formula.or_ else Formula.and_)(flip b f1) (flip b f2)
294     | Boolean.And(f1, f2) -> (if b then Formula.and_ else Formula.or_)(flip b f1) (flip b f2)
295     | Boolean.Atom(a, b') -> begin
296       match a.Atom.node with
297       | Move (m,  q) ->
298           if b == b' then begin
299           (* a appears positively, either no negation or double negation *)
300             if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
301             Formula.mk_atom (Move(m, q))
302           end else begin
303         (* need to reverse the atom
304            either we have a positive state deep below a negation
305            or we have a negative state in a positive formula
306            b' = sign of the state
307            b = sign of the enclosing formula
308         *)
309             let not_q =
310               try
311             (* does the inverted state of q exist ? *)
312                 Hashtbl.find memo_state (q, false)
313               with
314                 Not_found ->
315               (* create a new state and add it to the todo queue *)
316                   let nq = State.make () in
317                   auto.states <- StateSet.add nq auto.states;
318                   Hashtbl.add memo_state (q, false) nq;
319                   Queue.add (q, false) todo; nq
320             in
321             Formula.mk_atom (Move (m,not_q))
322           end
323       | _ -> if b then f else Formula.not_ f
324     end
325   in
326   (* states that are not reachable from a selection stat are not interesting *)
327   StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selecting_states;
328
329   while not (Queue.is_empty todo) do
330     let (q, b) as key = Queue.pop todo in
331     let q' =
332       try
333         Hashtbl.find memo_state key
334       with
335         Not_found ->
336           let nq = if b then q else
337               let nq = State.make () in
338               auto.states <- StateSet.add nq auto.states;
339               nq
340           in
341           Hashtbl.add memo_state key nq; nq
342     in
343     let trans = try Hashtbl.find auto.transitions q with Not_found -> [] in
344     let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
345     Hashtbl.replace auto.transitions q' trans';
346   done;
347   cleanup_states auto
348
349
350
351
352
353 module Builder =
354   struct
355     type auto = t
356     type t = auto
357     let next = Uid.make_maker ()
358
359     let make () =
360       let auto =
361         {
362           id = next ();
363           states = StateSet.empty;
364           starting_states = StateSet.empty;
365           selecting_states = StateSet.empty;
366           transitions = Hashtbl.create MED_H_SIZE;
367         }
368       in
369       (*
370       at_exit (fun () ->
371         let n4 = ref 0 in
372         let n2 = ref 0 in
373         Cache.N2.iteri (fun _ _ _ b -> if b then incr n2) auto.cache2;
374         Cache.N4.iteri (fun _ _ _ _ _ b -> if b then incr n4) auto.cache4;
375         Logger.msg `STATS "automaton %i, cache2: %i entries, cache6: %i entries"
376           (auto.id :> int) !n2 !n4;
377         let c2l, c2u = Cache.N2.stats auto.cache2 in
378         let c4l, c4u = Cache.N4.stats auto.cache4 in
379         Logger.msg `STATS
380           "cache2: length: %i, used: %i, occupation: %f"
381           c2l c2u (float c2u /. float c2l);
382         Logger.msg `STATS
383           "cache4: length: %i, used: %i, occupation: %f"
384           c4l c4u (float c4u /. float c4l)
385
386       ); *)
387       auto
388
389     let add_state a ?(starting=false) ?(selecting=false) q =
390       a.states <- StateSet.add q a.states;
391       if starting then a.starting_states <- StateSet.add q a.starting_states;
392       if selecting then a.selecting_states <- StateSet.add q a.selecting_states
393
394     let add_trans a q s f =
395       if not (StateSet.mem q a.states) then add_state a q;
396       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
397       let cup, ntrs =
398         List.fold_left (fun (acup, atrs) (labs, phi) ->
399           let lab1 = QNameSet.inter labs s in
400           let lab2 = QNameSet.diff labs s in
401           let tr1 =
402             if QNameSet.is_empty lab1 then []
403             else [ (lab1, Formula.or_ phi f) ]
404           in
405           let tr2 =
406             if QNameSet.is_empty lab2 then []
407             else [ (lab2, Formula.or_ phi f) ]
408           in
409           (QNameSet.union acup labs, tr1@ tr2 @ atrs)
410         ) (QNameSet.empty, []) trs
411       in
412       let rem = QNameSet.diff s cup in
413       let ntrs = if QNameSet.is_empty rem then ntrs
414         else (rem, f) :: ntrs
415       in
416       Hashtbl.replace a.transitions q ntrs
417
418     let finalize a =
419       complete_transitions a;
420       normalize_negations a;
421       a
422   end
423
424
425 let map_set f s =
426   StateSet.fold (fun q a -> StateSet.add (f q) a) s StateSet.empty
427
428 let map_hash fk fv h =
429   let h' = Hashtbl.create (Hashtbl.length h) in
430   let () = Hashtbl.iter (fun k v -> Hashtbl.add h' (fk k) (fv v)) h in
431   h'
432
433 let rec map_form f phi =
434   match Formula.expr phi with
435   | Boolean.Or(phi1, phi2) -> Formula.or_ (map_form f phi1) (map_form f phi2)
436   | Boolean.And(phi1, phi2) -> Formula.and_ (map_form f phi1) (map_form f phi2)
437   | Boolean.Atom({ Atom.node = Move(m,q); _}, b) ->
438       let a = Formula.mk_atom (Move (m,f q)) in
439       if b then a else Formula.not_ a
440   | _ -> phi
441
442 let rename_states mapper a =
443   let rename q = try Hashtbl.find mapper q with Not_found -> q in
444   { Builder.make () with
445     states = map_set rename a.states;
446     starting_states = map_set rename a.starting_states;
447     selecting_states = map_set rename a.selecting_states;
448     transitions =
449       map_hash
450         rename
451         (fun l ->
452           (List.map (fun (labels, form) -> (labels, map_form rename form)) l))
453         a.transitions;
454   }
455
456 let copy a =
457   let mapper = Hashtbl.create MED_H_SIZE in
458   let () =
459     StateSet.iter (fun q -> Hashtbl.add mapper q (State.make())) a.states
460   in
461   rename_states mapper a
462
463
464 let concat a1 a2 =
465   let a1 = copy a1 in
466   let a2 = copy a2 in
467   let link_phi =
468     StateSet.fold
469       (fun q phi -> Formula.(or_ (stay q) phi))
470       a1.selecting_states Formula.false_
471   in
472   Hashtbl.iter (fun q trs -> Hashtbl.add a1.transitions q trs)
473     a2.transitions;
474   StateSet.iter
475     (fun q ->
476       Hashtbl.replace a1.transitions q [(QNameSet.any, link_phi)])
477     a2.starting_states;
478   { a1 with
479     states = StateSet.union a1.states a2.states;
480     selecting_states = a2.selecting_states;
481     transitions = a1.transitions;
482   }
483
484 let merge a1 a2 =
485   let a1 = copy a1 in
486   let a2 = copy a2 in
487   { a1 with
488     states = StateSet.union a1.states a2.states;
489     selecting_states = StateSet.union a1.selecting_states a2.selecting_states;
490     starting_states = StateSet.union a1.starting_states a2.starting_states;
491     transitions =
492       let () =
493         Hashtbl.iter (fun k v -> Hashtbl.add a1.transitions k v) a2.transitions
494       in
495       a1.transitions
496   }
497
498
499 let link a1 a2 q link_phi =
500   { a1 with
501     states = StateSet.union a1.states a2.states;
502     selecting_states = StateSet.singleton q;
503     starting_states = StateSet.union a1.starting_states a2.starting_states;
504     transitions =
505       let () =
506         Hashtbl.iter (fun k v -> Hashtbl.add a1.transitions k v) a2.transitions
507       in
508       Hashtbl.add a1.transitions q [(QNameSet.any, link_phi)];
509       a1.transitions
510   }
511
512 let union a1 a2 =
513   let a1 = copy a1 in
514   let a2 = copy a2 in
515   let q = State.make () in
516   let link_phi =
517     StateSet.fold
518       (fun q phi -> Formula.(or_ (stay q) phi))
519       (StateSet.union a1.selecting_states a2.selecting_states)
520       Formula.false_
521   in
522   link a1 a2 q link_phi
523
524 let inter a1 a2 =
525   let a1 = copy a1 in
526   let a2 = copy a2 in
527   let q = State.make () in
528   let link_phi =
529     StateSet.fold
530       (fun q phi -> Formula.(and_ (stay q) phi))
531       (StateSet.union a1.selecting_states a2.selecting_states)
532       Formula.true_
533   in
534   link a1 a2 q link_phi
535
536 let neg a =
537   let a = copy a in
538   let q = State.make () in
539   let link_phi = 
540     StateSet.fold
541       (fun q phi -> Formula.(and_ (not_(stay q)) phi))
542       a.selecting_states
543       Formula.true_
544   in
545   let () = Hashtbl.add a.transitions q [(QNameSet.any, link_phi)] in
546   let a =
547     { a with
548       selecting_states = StateSet.singleton q;
549     }
550   in
551   normalize_negations a; a
552
553 let diff a1 a2 = inter a1 (neg a2)
554