WIP
[tatoo.git] / src / ata.ml
index 6a3570c..8a13705 100644 (file)
 (*                                                                     *)
 (***********************************************************************)
 
-(*
-  Time-stamp: <Last modified on 2013-04-22 17:22:38 CEST by Kim Nguyen>
-*)
-
 INCLUDE "utils.ml"
 open Format
+open Misc
+type move = [ `First_child
+            | `Next_sibling
+            | `Parent
+            | `Previous_sibling
+            | `Stay ]
+
+module Move =
+  struct
+    type t = move
+    type 'a table = 'a array
+    let idx = function
+      | `First_child -> 0
+      | `Next_sibling -> 1
+      | `Parent -> 2
+      | `Previous_sibling -> 3
+      | `Stay -> 4
+    let ridx = function
+      | 0 -> `First_child
+      | 1 -> `Next_sibling
+      | 2 -> `Parent
+      | 3 -> `Previous_sibling
+      | 4 -> `Stay
+      | _ -> assert false
+
+    let create_table a = Array.make 5 a
+    let get m k = m.(idx k)
+    let set m k v = m.(idx k) <- v
+    let iter f m = Array.iteri (fun i v -> f (ridx i) v) m
+    let fold f m acc =
+      let acc = ref acc in
+      iter (fun i v -> acc := f i v !acc) m;
+      !acc
+    let for_all p m =
+      try
+        iter (fun i v -> if not (p i v) then raise Exit) m;
+        true
+      with
+        Exit -> false
+    let for_all2 p m1 m2 =
+      try
+        for i = 0 to 4 do
+          let v1 = m1.(i)
+          and v2 = m2.(i) in
+          if not (p (ridx i) v1 v2) then raise Exit
+        done;
+        true
+      with
+        Exit -> false
 
-type predicate = | First_child
-                 | Next_sibling
-                 | Parent
-                 | Previous_sibling
-                 | Stay
+    let exists p m =
+      try
+        iter (fun i v -> if p i v then raise Exit) m;
+        false
+      with
+        Exit -> true
+    let print ppf m =
+      match m with
+        `First_child -> fprintf ppf "%s" Pretty.down_arrow
+      | `Next_sibling -> fprintf ppf "%s" Pretty.right_arrow
+      | `Parent -> fprintf ppf "%s" Pretty.up_arrow
+      | `Previous_sibling -> fprintf ppf "%s" Pretty.left_arrow
+      | `Stay -> fprintf ppf "%s" Pretty.bullet
+
+    let print_table pr_e ppf m =
+      iter (fun i v -> fprintf ppf "%a: %a" print i pr_e v;
+        if (idx i) < 4 then fprintf ppf ", ") m
+  end
+
+type predicate = Move of move * State.t
                  | Is_first_child
                  | Is_next_sibling
-                 | Is of (Tree.NodeKind.t)
+                 | Is of Tree.NodeKind.t
                  | Has_first_child
                  | Has_next_sibling
 
-let is_move p = match p with
-| First_child | Next_sibling
-| Parent | Previous_sibling | Stay -> true
-| _ -> false
-
-
-type atom = predicate * bool * State.t
-
-module Atom : (Formula.ATOM with type data = atom) =
+module Atom =
 struct
 
   module Node =
   struct
-    type t = atom
+    type t = predicate
     let equal n1 n2 = n1 = n2
     let hash n = Hashtbl.hash n
   end
@@ -52,98 +104,97 @@ struct
   include Hcons.Make(Node)
 
   let print ppf a =
-    let p, b, q = a.node in
-    if not b then fprintf ppf "%s" Pretty.lnot;
-    match p with
-    | First_child -> fprintf ppf "FC(%a)" State.print q
-    | Next_sibling -> fprintf ppf "NS(%a)" State.print q
-    | Parent -> fprintf ppf "FC%s(%a)" Pretty.inverse State.print q
-    | Previous_sibling -> fprintf ppf "NS%s(%a)" Pretty.inverse State.print q
-    | Stay -> fprintf ppf "%s(%a)" Pretty.epsilon State.print q
-    | Is_first_child -> fprintf ppf "FC%s?" Pretty.inverse
-    | Is_next_sibling -> fprintf ppf "NS%s?" Pretty.inverse
+    match a.node with
+    | Move (m, q) ->
+      fprintf ppf "%a%a" Move.print m State.print q
+    | Is_first_child -> fprintf ppf "%s?" Pretty.up_arrow
+    | Is_next_sibling -> fprintf ppf "%s?" Pretty.left_arrow
     | Is k -> fprintf ppf "is-%a?" Tree.NodeKind.print k
-    | Has_first_child -> fprintf ppf "FC?"
-    | Has_next_sibling -> fprintf ppf "NS?"
-
-  let neg a =
-    let p, b, q = a.node in
-    make (p, not b, q)
-
+    | Has_first_child -> fprintf ppf "%s?" Pretty.down_arrow
+    | Has_next_sibling -> fprintf ppf "%s?" Pretty.right_arrow
 
 end
 
-module SFormula =
+
+module Formula =
 struct
-  include Formula.Make(Atom)
+  include Boolean.Make(Atom)
   open Tree.NodeKind
-  let mk_atom a b c = atom_ (Atom.make (a,b,c))
-  let mk_kind k = mk_atom (Is k) true State.dummy
-  let has_first_child =
-    (mk_atom Has_first_child true State.dummy)
+  let mk_atom a = atom_ (Atom.make a)
+  let is k = mk_atom (Is k)
+
+  let has_first_child = mk_atom Has_first_child
 
-  let has_next_sibling =
-    (mk_atom Has_next_sibling true State.dummy)
+  let has_next_sibling = mk_atom Has_next_sibling
 
-  let is_first_child =
-    (mk_atom Is_first_child true State.dummy)
+  let is_first_child = mk_atom Is_first_child
 
-  let is_next_sibling =
-    (mk_atom Is_next_sibling true State.dummy)
+  let is_next_sibling = mk_atom Is_next_sibling
 
-  let is_attribute =
-    (mk_atom (Is Attribute) true State.dummy)
+  let is_attribute = mk_atom (Is Attribute)
 
-  let is_element =
-    (mk_atom (Is Element) true State.dummy)
+  let is_element = mk_atom (Is Element)
 
-  let is_processing_instruction =
-    (mk_atom (Is ProcessingInstruction) true State.dummy)
+  let is_processing_instruction = mk_atom (Is ProcessingInstruction)
 
-  let is_comment =
-    (mk_atom (Is Comment) true State.dummy)
+  let is_comment = mk_atom (Is Comment)
 
+  let mk_move m q = mk_atom (Move(m,q))
   let first_child q =
-  and_
-    (mk_atom First_child true q)
-    has_first_child
+    and_
+      (mk_move `First_child q)
+      has_first_child
 
   let next_sibling q =
   and_
-    (mk_atom Next_sibling true q)
+    (mk_move `Next_sibling q)
     has_next_sibling
 
   let parent q =
   and_
-    (mk_atom Parent true q)
+    (mk_move `Parent  q)
     is_first_child
 
   let previous_sibling q =
   and_
-    (mk_atom Previous_sibling true q)
+    (mk_move `Previous_sibling q)
     is_next_sibling
 
-  let stay q =
-    (mk_atom Stay true q)
+  let stay q = mk_move `Stay q
 
-  let get_states phi =
-    fold (fun phi acc ->
+  let get_states_by_move phi =
+    let table = Move.create_table StateSet.empty in
+    iter (fun phi ->
       match expr phi with
-      | Formula.Atom a -> let _, _, q = Atom.node a in
-                          if q != State.dummy then StateSet.add q acc else acc
-      | _ -> acc
-    ) phi StateSet.empty
+      | Boolean.Atom ({ Atom.node = Move(v,q) ; _ }, _) ->
+        let s = Move.get table v in
+        Move.set table v (StateSet.add q s)
+      | _ -> ()
+    ) phi;
+    table
+  let get_states phi =
+    let table = get_states_by_move phi in
+    Move.fold (fun _ s acc -> StateSet.union s acc) table StateSet.empty
 
 end
 
-
-module Transition = Hcons.Make (struct
-  type t = State.t * QNameSet.t * SFormula.t
+module Transition =
+  struct
+    include Hcons.Make (struct
+  type t = State.t * QNameSet.t * Formula.t
   let equal (a, b, c) (d, e, f) =
     a == d && b == e && c == f
   let hash (a, b, c) =
-    HASHINT4 (PRIME1, a, ((QNameSet.uid b) :> int), ((SFormula.uid c) :> int))
+    HASHINT4 (PRIME1, a, ((QNameSet.uid b) :> int), ((Formula.uid c) :> int))
 end)
+    let print ppf t =
+      let q, l, f = t.node in
+      fprintf ppf "%a, %a %s %a"
+        State.print q
+        QNameSet.print l
+        Pretty.double_right_arrow
+        Formula.print f
+  end
 
 
 module TransList : sig
@@ -155,327 +206,30 @@ end =
     let print ppf ?(sep="\n") l =
       iter (fun t ->
         let q, lab, f = Transition.node t in
-        fprintf ppf "%a, %a -> %a%s" State.print q QNameSet.print lab SFormula.print f sep) l
+        fprintf ppf "%a, %a → %a%s"
+          State.print q
+          QNameSet.print lab
+          Formula.print f sep) l
   end
 
 
 
-type node_summary = int
-let dummy_summary = -1
-(*
-4444444444443210
-4 -> kind
-3 -> is_left
-2 -> is_right
-1 -> has_left
-0 -> has_right
-*)
-
-let has_right (s : node_summary) : bool =
-  Obj.magic (s land 1)
-let has_left (s : node_summary) : bool =
-  Obj.magic ((s lsr 1) land 1)
-
-let is_right (s : node_summary) : bool =
-  Obj.magic ((s lsr 2) land 1)
-
-let is_left (s : node_summary) : bool =
-  Obj.magic ((s lsr 3) land 1)
-
-let kind (s : node_summary ) : Tree.NodeKind.t =
-  Obj.magic (s lsr 4)
-
-let node_summary is_left is_right has_left has_right kind =
-  ((Obj.magic kind) lsl 4) lor
-    ((Obj.magic is_left) lsl 3) lor
-    ((Obj.magic is_right) lsl 2) lor
-    ((Obj.magic has_left) lsl 1) lor
-    (Obj.magic has_right)
-
-
-
-type config = {
-  sat : StateSet.t;
-  unsat : StateSet.t;
-  todo : TransList.t;
-  summary : node_summary;
-}
-
-module Config = Hcons.Make(struct
-  type t = config
-  let equal c d =
-    c == d ||
-      c.sat == d.sat &&
-      c.unsat == d.unsat &&
-      c.todo == d.todo &&
-      c.summary == d.summary
-
-  let hash c =
-    HASHINT4((c.sat.StateSet.id :> int),
-             (c.unsat.StateSet.id :> int),
-             (c.todo.TransList.id :> int),
-             c.summary)
-end
-)
-
 type t = {
   id : Uid.t;
   mutable states : StateSet.t;
-  mutable selection_states: StateSet.t;
-  transitions: (State.t, (QNameSet.t*SFormula.t) list) Hashtbl.t;
-  mutable cache2 : TransList.t Cache.N2.t;
-  mutable cache4 : Config.t Cache.N4.t;
+  mutable starting_states : StateSet.t;
+  mutable selecting_states: StateSet.t;
+  transitions: (State.t, (QNameSet.t*Formula.t) list) Hashtbl.t;
+  mutable ranked_states : StateSet.t array
 }
 
-let next = Uid.make_maker ()
-
-let dummy2 = TransList.cons
-  (Transition.make (State.dummy,QNameSet.empty, SFormula.false_))
-  TransList.nil
-
-
-
-let dummy_config = Config.make { sat = StateSet.empty;
-                                 unsat = StateSet.empty;
-                                 todo = TransList.nil;
-                                 summary = dummy_summary
-                               }
-
-
-let create s ss =
-  let auto = { id = next ();
-               states = s;
-               selection_states = ss;
-               transitions = Hashtbl.create 17;
-               cache2 = Cache.N2.create dummy2;
-               cache4 = Cache.N4.create dummy_config;
-             }
-  in
-  at_exit (fun () ->
-    let n4 = ref 0 in
-    let n2 = ref 0 in
-    Cache.N2.iteri (fun _ _ _ b -> if b then incr n2) auto.cache2;
-    Cache.N4.iteri (fun _ _ _ _ _ b -> if b then incr n4) auto.cache4;
-    Format.eprintf "STATS: automaton %i, cache2: %i entries, cache6: %i entries\n%!"
-      (auto.id :> int) !n2 !n4;
-    let c2l, c2u = Cache.N2.stats auto.cache2 in
-    let c4l, c4u = Cache.N4.stats auto.cache4 in
-    Format.eprintf "STATS: cache2: length: %i, used: %i, occupation: %f\n%!" c2l c2u (float c2u /. float c2l);
-    Format.eprintf "STATS: cache4: length: %i, used: %i, occupation: %f\n%!" c4l c4u (float c4u /. float c4l)
-
-  );
-  auto
-
-let reset a =
-  a.cache2 <- Cache.N2.create (Cache.N2.dummy a.cache2);
-  a.cache4 <- Cache.N4.create (Cache.N4.dummy a.cache4)
-
-
-let get_trans_aux a tag states =
-  StateSet.fold (fun q acc0 ->
-    try
-      let trs = Hashtbl.find a.transitions q in
-      List.fold_left (fun acc1 (labs, phi) ->
-        if QNameSet.mem tag labs then TransList.cons (Transition.make (q, labs, phi)) acc1 else acc1) acc0 trs
-    with Not_found -> acc0
-  ) states TransList.nil
-
-
-let get_trans a tag states =
-  let trs =
-    Cache.N2.find a.cache2
-      (tag.QName.id :> int) (states.StateSet.id :> int)
-  in
-  if trs == dummy2 then
-    let trs = get_trans_aux a tag states in
-    (Cache.N2.add
-       a.cache2
-       (tag.QName.id :> int)
-       (states.StateSet.id :> int) trs; trs)
-  else trs
-
-
-(*
-let eval_form phi fcs nss ps ss is_left is_right has_left has_right kind =
-  let rec loop phi =
-    begin match SFormula.expr phi with
-      Formula.True | Formula.False -> phi
-    | Formula.Atom a ->
-        let p, b, q = Atom.node a in begin
-          match p with
-          | First_child ->
-              if b == StateSet.mem q fcs then SFormula.true_ else phi
-          | Next_sibling ->
-              if b == StateSet.mem q nss then SFormula.true_ else phi
-          | Parent | Previous_sibling ->
-              if b == StateSet.mem q ps then SFormula.true_ else phi
-          | Stay ->
-              if b == StateSet.mem q ss then SFormula.true_ else phi
-          | Is_first_child -> SFormula.of_bool (b == is_left)
-          | Is_next_sibling -> SFormula.of_bool (b == is_right)
-          | Is k -> SFormula.of_bool (b == (k == kind))
-          | Has_first_child -> SFormula.of_bool (b == has_left)
-          | Has_next_sibling -> SFormula.of_bool (b == has_right)
-        end
-    | Formula.And(phi1, phi2) -> SFormula.and_ (loop phi1) (loop phi2)
-    | Formula.Or (phi1, phi2) -> SFormula.or_  (loop phi1) (loop phi2)
-    end
-  in
-  loop phi
-
-let int_of_conf is_left is_right has_left has_right kind =
-  ((Obj.magic kind) lsl 4) lor
-    ((Obj.magic is_left) lsl 3) lor
-    ((Obj.magic is_right) lsl 2) lor
-    ((Obj.magic has_left) lsl 1) lor
-    (Obj.magic has_right)
-
-let eval_trans auto ltrs fcs nss ps ss is_left is_right has_left has_right kind =
-  let n = int_of_conf is_left is_right has_left has_right kind
-  and k = (fcs.StateSet.id :> int)
-  and l = (nss.StateSet.id :> int)
-  and m = (ps.StateSet.id :> int) in
-  let rec loop ltrs ss =
-    let i = (ltrs.TransList.id :> int)
-    and j = (ss.StateSet.id :> int) in
-    let (new_ltrs, new_ss) as res =
-      let res = Cache.N6.find auto.cache6 i j k l m n in
-      if res == dummy6 then
-        let res =
-          TransList.fold (fun trs (acct, accs) ->
-            let q, lab, phi = Transition.node trs in
-            if StateSet.mem q accs then (acct, accs) else
-              let new_phi =
-                eval_form
-                  phi fcs nss ps accs
-                  is_left is_right has_left has_right kind
-              in
-              if SFormula.is_true new_phi then
-                (acct, StateSet.add q accs)
-              else if SFormula.is_false new_phi then
-                (acct, accs)
-              else
-                 let new_tr = Transition.make (q, lab, new_phi) in
-                (TransList.cons new_tr acct, accs)
-          ) ltrs (TransList.nil, ss)
-        in
-        Cache.N6.add auto.cache6 i j k l m n res; res
-      else
-        res
-    in
-    if new_ss == ss then res else
-      loop new_ltrs new_ss
-  in
-  loop ltrs ss
-
-*)
-
-let simplify_atom atom pos q { Config.node=config; _ } =
-  if (pos && StateSet.mem q config.sat)
-    || ((not pos) && StateSet.mem q config.unsat) then SFormula.true_
-  else if (pos && StateSet.mem q config.unsat)
-      || ((not pos) && StateSet.mem q config.sat) then SFormula.false_
-  else atom
-
-
-let eval_form phi fcs nss ps ss summary =
-  let rec loop phi =
-    begin match SFormula.expr phi with
-      Formula.True | Formula.False -> phi
-    | Formula.Atom a ->
-        let p, b, q = Atom.node a in begin
-          match p with
-          | First_child -> simplify_atom phi b q fcs
-          | Next_sibling -> simplify_atom phi b q nss
-          | Parent | Previous_sibling -> simplify_atom phi b q ps
-          | Stay -> simplify_atom phi b q ss
-          | Is_first_child -> SFormula.of_bool (b == (is_left summary))
-          | Is_next_sibling -> SFormula.of_bool (b == (is_right summary))
-          | Is k -> SFormula.of_bool (b == (k == (kind summary)))
-          | Has_first_child -> SFormula.of_bool (b == (has_left summary))
-          | Has_next_sibling -> SFormula.of_bool (b == (has_right summary))
-        end
-    | Formula.And(phi1, phi2) -> SFormula.and_ (loop phi1) (loop phi2)
-    | Formula.Or (phi1, phi2) -> SFormula.or_  (loop phi1) (loop phi2)
-    end
-  in
-  loop phi
-
-
-
-let eval_trans auto fcs nss ps ss =
-  let fcsid = (fcs.Config.id :> int) in
-  let nssid = (nss.Config.id :> int) in
-  let psid = (ps.Config.id :> int) in
-  let rec loop old_config =
-    let oid = (old_config.Config.id :> int) in
-    let res =
-      let res = Cache.N4.find auto.cache4 oid fcsid nssid psid in
-      if res != dummy_config then res
-      else
-        let { sat = old_sat;
-              unsat = old_unsat;
-              todo = old_todo;
-              summary = old_summary } = old_config.Config.node
-        in
-        let sat, unsat, removed, kept, todo =
-          TransList.fold
-            (fun trs acc ->
-              let q, lab, phi = Transition.node trs in
-              let a_sat, a_unsat, a_rem, a_kept, a_todo = acc in
-              if StateSet.mem q a_sat || StateSet.mem q a_unsat then acc else
-                let new_phi =
-                  eval_form phi fcs nss ps old_config old_summary
-                in
-                if SFormula.is_true new_phi then
-                  StateSet.add q a_sat, a_unsat, StateSet.add q a_rem, a_kept, a_todo
-                else if SFormula.is_false new_phi then
-                  a_sat, StateSet.add q a_unsat, StateSet.add q a_rem, a_kept, a_todo
-                else
-                  let new_tr = Transition.make (q, lab, new_phi) in
-                  (a_sat, a_unsat, a_rem, StateSet.add q a_kept, (TransList.cons new_tr a_todo))
-            ) old_todo (old_sat, old_unsat, StateSet.empty, StateSet.empty, TransList.nil)
-        in
-        (* States that have been removed from the todo list and not kept are now
-           unsatisfiable *)
-        let unsat = StateSet.union unsat (StateSet.diff removed kept) in
-        (* States that were found once to be satisfiable remain so *)
-        let unsat = StateSet.diff unsat sat in
-        let new_config = Config.make { sat; unsat; todo ; summary = old_summary } in
-        Cache.N4.add auto.cache4 oid fcsid nssid psid new_config;
-        new_config
-    in
-    if res == old_config then res else loop res
-  in
-  loop ss
+let uid t = t.id
 
-(*
-  [add_trans a q labels f] adds a transition [(q,labels) -> f] to the
-  automaton [a] but ensures that transitions remains pairwise disjoint
-*)
-
-let add_trans a q s f =
-  let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
-  let cup, ntrs =
-    List.fold_left (fun (acup, atrs) (labs, phi) ->
-      let lab1 = QNameSet.inter labs s in
-      let lab2 = QNameSet.diff labs s in
-      let tr1 =
-        if QNameSet.is_empty lab1 then []
-        else [ (lab1, SFormula.or_ phi f) ]
-      in
-      let tr2 =
-        if QNameSet.is_empty lab2 then []
-        else [ (lab2, SFormula.or_ phi f) ]
-      in
-      (QNameSet.union acup labs, tr1@ tr2 @ atrs)
-    ) (QNameSet.empty, []) trs
-  in
-  let rem = QNameSet.diff s cup in
-  let ntrs = if QNameSet.is_empty rem then ntrs
-    else (rem, f) :: ntrs
-  in
-  Hashtbl.replace a.transitions q ntrs
+let get_states a = a.states
+let get_starting_states a = a.starting_states
+let get_selecting_states a = a.selecting_states
+let get_states_by_rank a = a.ranked_states
+let get_max_rank a = Array.length a.ranked_states - 1
 
 let _pr_buff = Buffer.create 50
 let _str_fmt = formatter_of_buffer _pr_buff
@@ -484,14 +238,22 @@ let _flush_str_fmt () = pp_print_flush _str_fmt ();
   Buffer.clear _pr_buff; s
 
 let print fmt a =
+  let _ = _flush_str_fmt() in
   fprintf fmt
     "Internal UID: %i@\n\
      States: %a@\n\
+     Number of states: %i@\n\
+     Starting states: %a@\n\
      Selection states: %a@\n\
+     Ranked states: %a@\n\
      Alternating transitions:@\n"
     (a.id :> int)
     StateSet.print a.states
-    StateSet.print a.selection_states;
+    (StateSet.cardinal a.states)
+    StateSet.print a.starting_states
+    StateSet.print a.selecting_states
+    (let r = ref 0 in Pretty.print_array ~sep:", " (fun ppf s ->
+      fprintf ppf "%i:%a" !r StateSet.print s; incr r)) a.ranked_states;
   let trs =
     Hashtbl.fold
       (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
@@ -499,18 +261,19 @@ let print fmt a =
       []
   in
   let sorted_trs = List.stable_sort (fun (q1, s1, _) (q2, s2, _) ->
-    let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
+    let c = State.compare q2 q1 in if c == 0 then QNameSet.compare s2 s1 else c)
     trs
   in
   let _ = _flush_str_fmt () in
-  let strs_strings, max_pre, max_all = List.fold_left (fun (accl, accp, acca) (q, s, f) ->
-    let s1 = State.print _str_fmt q; _flush_str_fmt () in
-    let s2 = QNameSet.print _str_fmt s;  _flush_str_fmt () in
-    let s3 = SFormula.print _str_fmt f;  _flush_str_fmt () in
-    let pre = Pretty.length s1 + Pretty.length s2 in
-    let all = Pretty.length s3 in
-    ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
-  ) ([], 0, 0) sorted_trs
+  let strs_strings, max_pre, max_all =
+    List.fold_left (fun (accl, accp, acca) (q, s, f) ->
+      let s1 = State.print _str_fmt q; _flush_str_fmt () in
+      let s2 = QNameSet.print _str_fmt s;  _flush_str_fmt () in
+      let s3 = Formula.print _str_fmt f;  _flush_str_fmt () in
+      let pre = Pretty.length s1 + Pretty.length s2 in
+      let all = Pretty.length s3 in
+      ( (q, s1, s2, s3) :: accl, max accp pre, max acca all)
+    ) ([], 0, 0) sorted_trs
   in
   let line = Pretty.line (max_all + max_pre + 6) in
   let prev_q = ref State.dummy in
@@ -519,11 +282,34 @@ let print fmt a =
     if !prev_q != q && !prev_q != State.dummy then fprintf fmt "%s@\n"  line;
     prev_q := q;
     fprintf fmt "%s, %s" s1 s2;
-    fprintf fmt "%s" (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
+    fprintf fmt "%s"
+      (Pretty.padding (max_pre - Pretty.length s1 - Pretty.length s2));
     fprintf fmt " %s  %s@\n" Pretty.right_arrow s3;
   ) strs_strings;
   fprintf fmt "%s@\n" line
 
+
+let get_trans a tag states =
+  StateSet.fold (fun q acc0 ->
+    try
+      let trs = Hashtbl.find a.transitions q in
+      List.fold_left (fun acc1 (labs, phi) ->
+        if QNameSet.mem tag labs then
+          TransList.cons (Transition.make (q, labs, phi)) acc1
+        else acc1) acc0 trs
+    with Not_found -> acc0
+  ) states TransList.nil
+
+
+let get_form a tag q =
+  try
+    let trs = Hashtbl.find a.transitions q in
+    List.fold_left (fun aphi (labs, phi) ->
+      if QNameSet.mem tag labs then Formula.or_ aphi phi else aphi
+    ) Formula.false_ trs
+  with
+    Not_found -> Formula.false_
+
 (*
   [complete transitions a] ensures that for each state q
   and each symbols s in the alphabet, a transition q, s exists.
@@ -532,19 +318,24 @@ let print fmt a =
 
 let complete_transitions a =
   StateSet.iter (fun q ->
-    let qtrans = Hashtbl.find a.transitions q in
-    let rem =
-      List.fold_left (fun rem (labels, _) ->
-        QNameSet.diff rem labels) QNameSet.any qtrans
-    in
-    let nqtrans =
-      if QNameSet.is_empty rem then qtrans
-      else
-        (rem, SFormula.false_) :: qtrans
-    in
-    Hashtbl.replace a.transitions q nqtrans
+    if StateSet.mem q a.starting_states then ()
+    else
+      let qtrans = Hashtbl.find a.transitions q in
+      let rem =
+        List.fold_left (fun rem (labels, _) ->
+          QNameSet.diff rem labels) QNameSet.any qtrans
+      in
+      let nqtrans =
+        if QNameSet.is_empty rem then qtrans
+        else
+          (rem, Formula.false_) :: qtrans
+      in
+      Hashtbl.replace a.transitions q nqtrans
   ) a.states
 
+(* [cleanup_states] remove states that do not lead to a
+   selecting states *)
+
 let cleanup_states a =
   let memo = ref StateSet.empty in
   let rec loop q =
@@ -552,10 +343,10 @@ let cleanup_states a =
       memo := StateSet.add q !memo;
       let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
       List.iter (fun (_, phi) ->
-        StateSet.iter loop (SFormula.get_states phi)) trs
+        StateSet.iter loop (Formula.get_states phi)) trs
     end
   in
-  StateSet.iter loop a.selection_states;
+  StateSet.iter loop a.selecting_states;
   let unused = StateSet.diff a.states !memo in
   StateSet.iter (fun q -> Hashtbl.remove a.transitions q) unused;
   a.states <- !memo
@@ -569,62 +360,332 @@ let normalize_negations auto =
   let memo_state = Hashtbl.create 17 in
   let todo = Queue.create () in
   let rec flip b f =
-    match SFormula.expr f with
-      Formula.True | Formula.False -> if b then f else SFormula.not_ f
-    | Formula.Or(f1, f2) -> (if b then SFormula.or_ else SFormula.and_)(flip b f1) (flip b f2)
-    | Formula.And(f1, f2) -> (if b then SFormula.and_ else SFormula.or_)(flip b f1) (flip b f2)
-    | Formula.Atom(a) -> begin
-      let l, b', q = Atom.node a in
-      if q == State.dummy then if b then f else SFormula.not_ f
-      else
-        if b == b' then begin
-        (* a appears positively, either no negation or double negation *)
-          if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
-          SFormula.atom_ (Atom.make (l, true, q))
-        end else begin
+    match Formula.expr f with
+      Boolean.True | Boolean.False -> if b then f else Formula.not_ f
+    | Boolean.Or(f1, f2) ->
+      (if b then Formula.or_ else Formula.and_)(flip b f1) (flip b f2)
+    | Boolean.And(f1, f2) ->
+      (if b then Formula.and_ else Formula.or_)(flip b f1) (flip b f2)
+    | Boolean.Atom(a, b') -> begin
+      match a.Atom.node with
+      | Move (m,  q) ->
+          if b == b' then begin
+          (* a appears positively, either no negation or double negation *)
+            if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
+            Formula.mk_atom (Move(m, q))
+          end else begin
         (* need to reverse the atom
            either we have a positive state deep below a negation
            or we have a negative state in a positive formula
            b' = sign of the state
            b = sign of the enclosing formula
         *)
-        let not_q =
-          try
+            let not_q =
+              try
             (* does the inverted state of q exist ? *)
-            Hashtbl.find memo_state (q, false)
-          with
-            Not_found ->
+                Hashtbl.find memo_state (q, false)
+              with
+                Not_found ->
               (* create a new state and add it to the todo queue *)
-              let nq = State.make () in
-              auto.states <- StateSet.add nq auto.states;
-              Hashtbl.add memo_state (q, false) nq;
-              Queue.add (q, false) todo; nq
-        in
-        SFormula.atom_ (Atom.make (l, true, not_q))
-      end
+                  let nq = State.make () in
+                  auto.states <- StateSet.add nq auto.states;
+                  Hashtbl.add memo_state (q, false) nq;
+                  Queue.add (q, false) todo; nq
+            in
+            Formula.mk_atom (Move (m,not_q))
+          end
+      | _ -> if b then f else Formula.not_ f
     end
   in
   (* states that are not reachable from a selection stat are not interesting *)
-  StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selection_states;
+  StateSet.iter (fun q -> Queue.add (q, true) todo) auto.selecting_states;
 
   while not (Queue.is_empty todo) do
     let (q, b) as key = Queue.pop todo in
-    let q' =
-      try
-        Hashtbl.find memo_state key
-      with
-        Not_found ->
-          let nq = if b then q else
-              let nq = State.make () in
-              auto.states <- StateSet.add nq auto.states;
-              nq
-          in
-          Hashtbl.add memo_state key nq; nq
-    in
-    let trans = Hashtbl.find auto.transitions q in
-    let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
-    Hashtbl.replace auto.transitions q' trans';
+    if not (StateSet.mem q auto.starting_states) then
+      let q' =
+        try
+          Hashtbl.find memo_state key
+        with
+          Not_found ->
+            let nq = if b then q else
+                let nq = State.make () in
+                auto.states <- StateSet.add nq auto.states;
+                nq
+            in
+            Hashtbl.add memo_state key nq; nq
+      in
+      let trans = try Hashtbl.find auto.transitions q with Not_found -> [] in
+      let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
+      Hashtbl.replace auto.transitions q' trans';
   done;
   cleanup_states auto
 
+(* [compute_dependencies auto] returns a hash table storing for each
+   states [q] a Move.table containing the set of states on which [q]
+   depends (loosely). [q] depends on [q'] if there is a transition
+   [q, {...} -> phi], where [q'] occurs in [phi].
+*)
+let compute_dependencies auto =
+  let edges = Hashtbl.create 17 in
+  StateSet.iter
+    (fun q -> Hashtbl.add edges q (Move.create_table StateSet.empty))
+    auto.starting_states;
+  Hashtbl.iter (fun q trans ->
+    let moves = try Hashtbl.find edges q with Not_found ->
+      let m = Move.create_table StateSet.empty in
+      Hashtbl.add edges q m;
+      m
+    in
+    List.iter (fun (_, phi) ->
+      let m_phi = Formula.get_states_by_move phi in
+      Move.iter (fun m set ->
+        Move.set moves m (StateSet.union set (Move.get moves m)))
+        m_phi) trans) auto.transitions;
+
+  edges
+
+
+let compute_rank auto =
+  let dependencies = compute_dependencies auto in
+  let upward = [ `Stay ; `Parent ; `Previous_sibling ] in
+  let downward = [ `Stay; `First_child; `Next_sibling ] in
+  let swap dir = if dir == upward then downward else upward in
+  let is_satisfied dir q t =
+    Move.for_all (fun d set ->
+      if List.mem d dir then
+        StateSet.(is_empty (remove q set))
+      else StateSet.is_empty set) t
+  in
+  let update_dependencies dir initacc =
+    let rec loop acc =
+      let new_acc =
+        Hashtbl.fold (fun q deps acc ->
+          let to_remove = StateSet.union acc initacc in
+          List.iter
+            (fun m ->
+              Move.set deps m (StateSet.diff (Move.get deps m) to_remove)
+            )
+            dir;
+          if is_satisfied dir q deps then StateSet.add q acc else acc
+        ) dependencies acc
+      in
+      if acc == new_acc then new_acc else loop new_acc
+    in
+    let satisfied = loop StateSet.empty in
+    StateSet.iter (fun q ->
+      Hashtbl.remove dependencies q) satisfied;
+    satisfied
+  in
+  let current_states = ref StateSet.empty in
+  let rank_list = ref [] in
+  let rank = ref 0 in
+  let current_dir = ref upward in
+  let detect_cycle = ref 0 in
+  while Hashtbl.length dependencies != 0 do
+    let new_sat = update_dependencies !current_dir !current_states in
+    if StateSet.is_empty new_sat then incr detect_cycle;
+    if !detect_cycle > 2 then assert false;
+    rank_list := (!rank, new_sat) :: !rank_list;
+    rank := !rank + 1;
+    current_dir := swap !current_dir;
+    current_states := StateSet.union new_sat !current_states;
+  done;
+  let by_rank = Hashtbl.create 17 in
+  List.iter (fun (r,s) ->
+    let set = try Hashtbl.find by_rank r with Not_found -> StateSet.empty in
+    Hashtbl.replace by_rank r (StateSet.union s set)) !rank_list;
+  auto.ranked_states <-
+    Array.init (Hashtbl.length by_rank) (fun i -> Hashtbl.find by_rank i)
+
+
+module Builder =
+  struct
+    type auto = t
+    type t = auto
+    let next = Uid.make_maker ()
+
+    let make () =
+      let auto =
+        {
+          id = next ();
+          states = StateSet.empty;
+          starting_states = StateSet.empty;
+          selecting_states = StateSet.empty;
+          transitions = Hashtbl.create MED_H_SIZE;
+          ranked_states = [| |]
+        }
+      in
+      auto
+
+    let add_state a ?(starting=false) ?(selecting=false) q =
+      a.states <- StateSet.add q a.states;
+      if starting then a.starting_states <- StateSet.add q a.starting_states;
+      if selecting then a.selecting_states <- StateSet.add q a.selecting_states
+
+    let add_trans a q s f =
+      if not (StateSet.mem q a.states) then add_state a q;
+      let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
+      let cup, ntrs =
+        List.fold_left (fun (acup, atrs) (labs, phi) ->
+          let lab1 = QNameSet.inter labs s in
+          let lab2 = QNameSet.diff labs s in
+          let tr1 =
+            if QNameSet.is_empty lab1 then []
+            else [ (lab1, Formula.or_ phi f) ]
+          in
+          let tr2 =
+            if QNameSet.is_empty lab2 then []
+            else [ (lab2, Formula.or_ phi f) ]
+          in
+          (QNameSet.union acup labs, tr1@ tr2 @ atrs)
+        ) (QNameSet.empty, []) trs
+      in
+      let rem = QNameSet.diff s cup in
+      let ntrs = if QNameSet.is_empty rem then ntrs
+        else (rem, f) :: ntrs
+      in
+      Hashtbl.replace a.transitions q ntrs
+
+    let finalize a =
+      complete_transitions a;
+      normalize_negations a;
+      compute_rank a;
+      a
+  end
+
+
+let map_set f s =
+  StateSet.fold (fun q a -> StateSet.add (f q) a) s StateSet.empty
+
+let map_hash fk fv h =
+  let h' = Hashtbl.create (Hashtbl.length h) in
+  let () = Hashtbl.iter (fun k v -> Hashtbl.add h' (fk k) (fv v)) h in
+  h'
+
+let rec map_form f phi =
+  match Formula.expr phi with
+  | Boolean.Or(phi1, phi2) -> Formula.or_ (map_form f phi1) (map_form f phi2)
+  | Boolean.And(phi1, phi2) -> Formula.and_ (map_form f phi1) (map_form f phi2)
+  | Boolean.Atom({ Atom.node = Move(m,q); _}, b) ->
+      let a = Formula.mk_atom (Move (m,f q)) in
+      if b then a else Formula.not_ a
+  | _ -> phi
+
+let rename_states mapper a =
+  let rename q = try Hashtbl.find mapper q with Not_found -> q in
+  { Builder.make () with
+    states = map_set rename a.states;
+    starting_states = map_set rename a.starting_states;
+    selecting_states = map_set rename a.selecting_states;
+    transitions =
+      map_hash
+        rename
+        (fun l ->
+          (List.map (fun (labels, form) -> (labels, map_form rename form)) l))
+        a.transitions;
+    ranked_states = Array.map (map_set rename) a.ranked_states
+  }
+
+let copy a =
+  let mapper = Hashtbl.create MED_H_SIZE in
+  let () =
+    StateSet.iter (fun q -> Hashtbl.add mapper q (State.make())) a.states
+  in
+  rename_states mapper a
+
+
+let concat a1 a2 =
+  let a1 = copy a1 in
+  let a2 = copy a2 in
+  let link_phi =
+    StateSet.fold
+      (fun q phi -> Formula.(or_ (stay q) phi))
+      a1.selecting_states Formula.false_
+  in
+  Hashtbl.iter (fun q trs -> Hashtbl.add a1.transitions q trs)
+    a2.transitions;
+  StateSet.iter
+    (fun q ->
+      Hashtbl.replace a1.transitions q [(QNameSet.any, link_phi)])
+    a2.starting_states;
+  let a = { a1 with
+    states = StateSet.union a1.states a2.states;
+    selecting_states = a2.selecting_states;
+    transitions = a1.transitions;
+  }
+  in compute_rank a; a
+
+let merge a1 a2 =
+  let a1 = copy a1 in
+  let a2 = copy a2 in
+  let a = { a1 with
+    states = StateSet.union a1.states a2.states;
+    selecting_states = StateSet.union a1.selecting_states a2.selecting_states;
+    starting_states = StateSet.union a1.starting_states a2.starting_states;
+    transitions =
+      let () =
+        Hashtbl.iter (fun k v -> Hashtbl.add a1.transitions k v) a2.transitions
+      in
+      a1.transitions
+  } in
+  compute_rank a ; a
+
+
+let link a1 a2 q link_phi =
+  let a = { a1 with
+    states = StateSet.union a1.states a2.states;
+    selecting_states = StateSet.singleton q;
+    starting_states = StateSet.union a1.starting_states a2.starting_states;
+    transitions =
+      let () =
+        Hashtbl.iter (fun k v -> Hashtbl.add a1.transitions k v) a2.transitions
+      in
+      Hashtbl.add a1.transitions q [(QNameSet.any, link_phi)];
+      a1.transitions
+  }
+  in
+  compute_rank a; a
+
+let union a1 a2 =
+  let a1 = copy a1 in
+  let a2 = copy a2 in
+  let q = State.make () in
+  let link_phi =
+    StateSet.fold
+      (fun q phi -> Formula.(or_ (stay q) phi))
+      (StateSet.union a1.selecting_states a2.selecting_states)
+      Formula.false_
+  in
+  link a1 a2 q link_phi
+
+let inter a1 a2 =
+  let a1 = copy a1 in
+  let a2 = copy a2 in
+  let q = State.make () in
+  let link_phi =
+    StateSet.fold
+      (fun q phi -> Formula.(and_ (stay q) phi))
+      (StateSet.union a1.selecting_states a2.selecting_states)
+      Formula.true_
+  in
+  link a1 a2 q link_phi
+
+let neg a =
+  let a = copy a in
+  let q = State.make () in
+  let link_phi =
+    StateSet.fold
+      (fun q phi -> Formula.(and_ (not_(stay q)) phi))
+      a.selecting_states
+      Formula.true_
+  in
+  let () = Hashtbl.add a.transitions q [(QNameSet.any, link_phi)] in
+  let a =
+    { a with
+      selecting_states = StateSet.singleton q;
+    }
+  in
+  normalize_negations a; compute_rank a; a
 
+let diff a1 a2 = inter a1 (neg a2)