1 (***********************************************************************)
5 (* Kim Nguyen, LRI UMR8623 *)
6 (* Université Paris-Sud & CNRS *)
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 *)
14 (***********************************************************************)
19 type move = [ `First_child
28 type 'a table = 'a array
33 | `Previous_sibling -> 3
39 | 3 -> `Previous_sibling
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
49 iter (fun i v -> acc := f i v !acc) m;
53 iter (fun i v -> if not (p i v) then raise Exit) m;
57 let for_all2 p m1 m2 =
62 if not (p (ridx i) v1 v2) then raise Exit
70 iter (fun i v -> if p i v then raise Exit) m;
76 `First_child -> fprintf ppf "%s" Pretty.down_arrow
77 | `Next_sibling -> fprintf ppf "%s" Pretty.right_arrow
78 | `Parent -> fprintf ppf "%s" Pretty.up_arrow
79 | `Previous_sibling -> fprintf ppf "%s" Pretty.left_arrow
80 | `Stay -> fprintf ppf "%s" Pretty.bullet
82 let print_table pr_e ppf m =
83 iter (fun i v -> fprintf ppf "%a: %a" print i pr_e v;
84 if (idx i) < 4 then fprintf ppf ", ") m
87 type predicate = Move of move * State.t
90 | Is of Tree.NodeKind.t
100 let equal n1 n2 = n1 = n2
101 let hash n = Hashtbl.hash n
104 include Hcons.Make(Node)
109 fprintf ppf "%a%a" Move.print m State.print q
110 | Is_first_child -> fprintf ppf "%s?" Pretty.up_arrow
111 | Is_next_sibling -> fprintf ppf "%s?" Pretty.left_arrow
112 | Is k -> fprintf ppf "is-%a?" Tree.NodeKind.print k
113 | Has_first_child -> fprintf ppf "%s?" Pretty.down_arrow
114 | Has_next_sibling -> fprintf ppf "%s?" Pretty.right_arrow
121 include Boolean.Make(Atom)
123 let mk_atom a = atom_ (Atom.make a)
124 let is k = mk_atom (Is k)
126 let has_first_child = mk_atom Has_first_child
128 let has_next_sibling = mk_atom Has_next_sibling
130 let is_first_child = mk_atom Is_first_child
132 let is_next_sibling = mk_atom Is_next_sibling
134 let is_attribute = mk_atom (Is Attribute)
136 let is_element = mk_atom (Is Element)
138 let is_processing_instruction = mk_atom (Is ProcessingInstruction)
140 let is_comment = mk_atom (Is Comment)
142 let mk_move m q = mk_atom (Move(m,q))
145 (mk_move `First_child q)
150 (mk_move `Next_sibling q)
158 let previous_sibling q =
160 (mk_move `Previous_sibling q)
163 let stay q = mk_move `Stay q
165 let get_states_by_move phi =
166 let table = Move.create_table StateSet.empty in
169 | Boolean.Atom ({ Atom.node = Move(v,q) ; _ }, _) ->
170 let s = Move.get table v in
171 Move.set table v (StateSet.add q s)
176 let table = get_states_by_move phi in
177 Move.fold (fun _ s acc -> StateSet.union s acc) table StateSet.empty
183 include Hcons.Make (struct
184 type t = State.t * QNameSet.t * Formula.t
185 let equal (a, b, c) (d, e, f) =
186 a == d && b == e && c == f
188 HASHINT4 (PRIME1, a, ((QNameSet.uid b) :> int), ((Formula.uid c) :> int))
191 let q, l, f = t.node in
192 fprintf ppf "%a, %a %s %a"
195 Pretty.double_right_arrow
200 module TransList : sig
201 include Hlist.S with type elt = Transition.t
202 val print : Format.formatter -> ?sep:string -> t -> unit
205 include Hlist.Make(Transition)
206 let print ppf ?(sep="\n") l =
208 let q, lab, f = Transition.node t in
209 fprintf ppf "%a, %a -> %a%s" State.print q QNameSet.print lab Formula.print f sep) l
216 mutable states : StateSet.t;
217 mutable starting_states : StateSet.t;
218 mutable selecting_states: StateSet.t;
219 transitions: (State.t, (QNameSet.t*Formula.t) list) Hashtbl.t;
220 mutable ranked_states : StateSet.t array
225 let get_states a = a.states
226 let get_starting_states a = a.starting_states
227 let get_selecting_states a = a.selecting_states
228 let get_states_by_rank a = a.ranked_states
229 let get_max_rank a = Array.length a.ranked_states - 1
231 let _pr_buff = Buffer.create 50
232 let _str_fmt = formatter_of_buffer _pr_buff
233 let _flush_str_fmt () = pp_print_flush _str_fmt ();
234 let s = Buffer.contents _pr_buff in
235 Buffer.clear _pr_buff; s
238 let _ = _flush_str_fmt() in
240 "Internal UID: %i@\n\
242 Number of states: %i@\n\
243 Starting states: %a@\n\
244 Selection states: %a@\n\
245 Ranked states: %a@\n\
246 Alternating transitions:@\n"
248 StateSet.print a.states
249 (StateSet.cardinal a.states)
250 StateSet.print a.starting_states
251 StateSet.print a.selecting_states
252 (let r = ref 0 in Pretty.print_array ~sep:", " (fun ppf s ->
253 fprintf ppf "%i:%a" !r StateSet.print s; incr r)) a.ranked_states;
256 (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
260 let sorted_trs = List.stable_sort (fun (q1, s1, _) (q2, s2, _) ->
261 let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
264 let _ = _flush_str_fmt () in
265 let strs_strings, max_pre, max_all = List.fold_left (fun (accl, accp, acca) (q, s, f) ->
266 let s1 = State.print _str_fmt q; _flush_str_fmt () in
267 let s2 = QNameSet.print _str_fmt s; _flush_str_fmt () in
268 let s3 = Formula.print _str_fmt f; _flush_str_fmt () in
269 let pre = Pretty.length s1 + Pretty.length s2 in
270 let all = Pretty.length s3 in
271 ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
272 ) ([], 0, 0) sorted_trs
274 let line = Pretty.line (max_all + max_pre + 6) in
275 let prev_q = ref State.dummy in
276 fprintf fmt "%s@\n" line;
277 List.iter (fun (q, s1, s2, s3) ->
278 if !prev_q != q && !prev_q != State.dummy then fprintf fmt "%s@\n" line;
280 fprintf fmt "%s, %s" s1 s2;
281 fprintf fmt "%s" (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
282 fprintf fmt " %s %s@\n" Pretty.right_arrow s3;
284 fprintf fmt "%s@\n" line
287 let get_trans a tag states =
288 StateSet.fold (fun q acc0 ->
290 let trs = Hashtbl.find a.transitions q in
291 List.fold_left (fun acc1 (labs, phi) ->
292 if QNameSet.mem tag labs then
293 TransList.cons (Transition.make (q, labs, phi)) acc1
295 with Not_found -> acc0
296 ) states TransList.nil
299 let get_form a tag q =
301 let trs = Hashtbl.find a.transitions q in
302 List.fold_left (fun aphi (labs, phi) ->
303 if QNameSet.mem tag labs then Formula.or_ aphi phi else aphi
306 Not_found -> Formula.false_
309 [complete transitions a] ensures that for each state q
310 and each symbols s in the alphabet, a transition q, s exists.
311 (adding q, s -> F when necessary).
314 let complete_transitions a =
315 StateSet.iter (fun q ->
316 if StateSet.mem q a.starting_states then ()
318 let qtrans = Hashtbl.find a.transitions q in
320 List.fold_left (fun rem (labels, _) ->
321 QNameSet.diff rem labels) QNameSet.any qtrans
324 if QNameSet.is_empty rem then qtrans
326 (rem, Formula.false_) :: qtrans
328 Hashtbl.replace a.transitions q nqtrans
331 (* [cleanup_states] remove states that do not lead to a
334 let cleanup_states a =
335 let memo = ref StateSet.empty in
337 if not (StateSet.mem q !memo) then begin
338 memo := StateSet.add q !memo;
339 let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
340 List.iter (fun (_, phi) ->
341 StateSet.iter loop (Formula.get_states phi)) trs
344 StateSet.iter loop a.selecting_states;
345 let unused = StateSet.diff a.states !memo in
346 StateSet.iter (fun q -> Hashtbl.remove a.transitions q) unused;
349 (* [normalize_negations a] removes negative atoms in the formula
350 complementing the sub-automaton in the negative states.
351 [TODO check the meaning of negative upward arrows]
354 let normalize_negations auto =
355 let memo_state = Hashtbl.create 17 in
356 let todo = Queue.create () in
358 match Formula.expr f with
359 Boolean.True | Boolean.False -> if b then f else Formula.not_ f
360 | Boolean.Or(f1, f2) -> (if b then Formula.or_ else Formula.and_)(flip b f1) (flip b f2)
361 | Boolean.And(f1, f2) -> (if b then Formula.and_ else Formula.or_)(flip b f1) (flip b f2)
362 | Boolean.Atom(a, b') -> begin
363 match a.Atom.node with
365 if b == b' then begin
366 (* a appears positively, either no negation or double negation *)
367 if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
368 Formula.mk_atom (Move(m, q))
370 (* need to reverse the atom
371 either we have a positive state deep below a negation
372 or we have a negative state in a positive formula
373 b' = sign of the state
374 b = sign of the enclosing formula
378 (* does the inverted state of q exist ? *)
379 Hashtbl.find memo_state (q, false)
382 (* create a new state and add it to the todo queue *)
383 let nq = State.make () in
384 auto.states <- StateSet.add nq auto.states;
385 Hashtbl.add memo_state (q, false) nq;
386 Queue.add (q, false) todo; nq
388 Formula.mk_atom (Move (m,not_q))
390 | _ -> if b then f else Formula.not_ f
393 (* states that are not reachable from a selection stat are not interesting *)
394 StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selecting_states;
396 while not (Queue.is_empty todo) do
397 let (q, b) as key = Queue.pop todo in
398 if not (StateSet.mem q auto.starting_states) then
401 Hashtbl.find memo_state key
404 let nq = if b then q else
405 let nq = State.make () in
406 auto.states <- StateSet.add nq auto.states;
409 Hashtbl.add memo_state key nq; nq
411 let trans = try Hashtbl.find auto.transitions q with Not_found -> [] in
412 let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
413 Hashtbl.replace auto.transitions q' trans';
417 (* [compute_dependencies auto] returns a hash table storing for each
418 states [q] a Move.table containing the set of states on which [q]
419 depends (loosely). [q] depends on [q'] if there is a transition
420 [q, {...} -> phi], where [q'] occurs in [phi].
422 let compute_dependencies auto =
423 let edges = Hashtbl.create 17 in
425 (fun q -> Hashtbl.add edges q (Move.create_table StateSet.empty))
426 auto.starting_states;
427 Hashtbl.iter (fun q trans ->
428 let moves = try Hashtbl.find edges q with Not_found ->
429 let m = Move.create_table StateSet.empty in
430 Hashtbl.add edges q m;
433 List.iter (fun (_, phi) ->
434 let m_phi = Formula.get_states_by_move phi in
435 Move.iter (fun m set ->
436 Move.set moves m (StateSet.union set (Move.get moves m)))
437 m_phi) trans) auto.transitions;
442 let compute_rank auto =
443 let dependencies = compute_dependencies auto in
444 let upward = [ `Stay ; `Parent ; `Previous_sibling ] in
445 let downward = [ `Stay; `First_child; `Next_sibling ] in
446 let swap dir = if dir == upward then downward else upward in
447 let is_satisfied q t =
448 Move.for_all (fun _ set -> StateSet.(is_empty (remove q set))) t
450 let update_dependencies dir initacc =
453 Hashtbl.fold (fun q deps acc ->
454 let to_remove = StateSet.union acc initacc in
457 Move.set deps m (StateSet.diff (Move.get deps m) to_remove)
460 if is_satisfied q deps then StateSet.add q acc else acc
463 if acc == new_acc then new_acc else loop new_acc
465 let satisfied = loop StateSet.empty in
466 StateSet.iter (fun q ->
467 Hashtbl.remove dependencies q) satisfied;
470 let current_states = ref StateSet.empty in
471 let rank_list = ref [] in
473 let current_dir = ref upward in
474 let detect_cycle = ref 0 in
475 while Hashtbl.length dependencies != 0 do
476 let new_sat = update_dependencies !current_dir !current_states in
477 if StateSet.is_empty new_sat then incr detect_cycle;
478 if !detect_cycle > 2 then assert false;
479 rank_list := (!rank, new_sat) :: !rank_list;
481 current_dir := swap !current_dir;
482 current_states := StateSet.union new_sat !current_states;
484 let by_rank = Hashtbl.create 17 in
485 List.iter (fun (r,s) ->
487 let set = try Hashtbl.find by_rank r with Not_found -> StateSet.empty in
488 Hashtbl.replace by_rank r (StateSet.union s set)) !rank_list;
489 auto.ranked_states <-
490 Array.init (Hashtbl.length by_rank) (fun i -> Hashtbl.find by_rank i)
497 let next = Uid.make_maker ()
503 states = StateSet.empty;
504 starting_states = StateSet.empty;
505 selecting_states = StateSet.empty;
506 transitions = Hashtbl.create MED_H_SIZE;
507 ranked_states = [| |]
512 let add_state a ?(starting=false) ?(selecting=false) q =
513 a.states <- StateSet.add q a.states;
514 if starting then a.starting_states <- StateSet.add q a.starting_states;
515 if selecting then a.selecting_states <- StateSet.add q a.selecting_states
517 let add_trans a q s f =
518 if not (StateSet.mem q a.states) then add_state a q;
519 let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
521 List.fold_left (fun (acup, atrs) (labs, phi) ->
522 let lab1 = QNameSet.inter labs s in
523 let lab2 = QNameSet.diff labs s in
525 if QNameSet.is_empty lab1 then []
526 else [ (lab1, Formula.or_ phi f) ]
529 if QNameSet.is_empty lab2 then []
530 else [ (lab2, Formula.or_ phi f) ]
532 (QNameSet.union acup labs, tr1@ tr2 @ atrs)
533 ) (QNameSet.empty, []) trs
535 let rem = QNameSet.diff s cup in
536 let ntrs = if QNameSet.is_empty rem then ntrs
537 else (rem, f) :: ntrs
539 Hashtbl.replace a.transitions q ntrs
542 complete_transitions a;
543 normalize_negations a;
550 StateSet.fold (fun q a -> StateSet.add (f q) a) s StateSet.empty
552 let map_hash fk fv h =
553 let h' = Hashtbl.create (Hashtbl.length h) in
554 let () = Hashtbl.iter (fun k v -> Hashtbl.add h' (fk k) (fv v)) h in
557 let rec map_form f phi =
558 match Formula.expr phi with
559 | Boolean.Or(phi1, phi2) -> Formula.or_ (map_form f phi1) (map_form f phi2)
560 | Boolean.And(phi1, phi2) -> Formula.and_ (map_form f phi1) (map_form f phi2)
561 | Boolean.Atom({ Atom.node = Move(m,q); _}, b) ->
562 let a = Formula.mk_atom (Move (m,f q)) in
563 if b then a else Formula.not_ a
566 let rename_states mapper a =
567 let rename q = try Hashtbl.find mapper q with Not_found -> q in
568 { Builder.make () with
569 states = map_set rename a.states;
570 starting_states = map_set rename a.starting_states;
571 selecting_states = map_set rename a.selecting_states;
576 (List.map (fun (labels, form) -> (labels, map_form rename form)) l))
578 ranked_states = Array.map (map_set rename) a.ranked_states
582 let mapper = Hashtbl.create MED_H_SIZE in
584 StateSet.iter (fun q -> Hashtbl.add mapper q (State.make())) a.states
586 rename_states mapper a
594 (fun q phi -> Formula.(or_ (stay q) phi))
595 a1.selecting_states Formula.false_
597 Hashtbl.iter (fun q trs -> Hashtbl.add a1.transitions q trs)
601 Hashtbl.replace a1.transitions q [(QNameSet.any, link_phi)])
604 states = StateSet.union a1.states a2.states;
605 selecting_states = a2.selecting_states;
606 transitions = a1.transitions;
614 states = StateSet.union a1.states a2.states;
615 selecting_states = StateSet.union a1.selecting_states a2.selecting_states;
616 starting_states = StateSet.union a1.starting_states a2.starting_states;
619 Hashtbl.iter (fun k v -> Hashtbl.add a1.transitions k v) a2.transitions
626 let link a1 a2 q link_phi =
628 states = StateSet.union a1.states a2.states;
629 selecting_states = StateSet.singleton q;
630 starting_states = StateSet.union a1.starting_states a2.starting_states;
633 Hashtbl.iter (fun k v -> Hashtbl.add a1.transitions k v) a2.transitions
635 Hashtbl.add a1.transitions q [(QNameSet.any, link_phi)];
644 let q = State.make () in
647 (fun q phi -> Formula.(or_ (stay q) phi))
648 (StateSet.union a1.selecting_states a2.selecting_states)
651 link a1 a2 q link_phi
656 let q = State.make () in
659 (fun q phi -> Formula.(and_ (stay q) phi))
660 (StateSet.union a1.selecting_states a2.selecting_states)
663 link a1 a2 q link_phi
667 let q = State.make () in
670 (fun q phi -> Formula.(and_ (not_(stay q)) phi))
674 let () = Hashtbl.add a.transitions q [(QNameSet.any, link_phi)] in
677 selecting_states = StateSet.singleton q;
680 normalize_negations a; compute_rank a; a
682 let diff a1 a2 = inter a1 (neg a2)