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