bool.ml 30.9 KB
Newer Older
1 2
module type S =
sig
3 4
  type elem
  include Custom.T
5

6
  val get: t -> (elem list * elem list) list
7

8 9 10 11 12 13
  val empty : t
  val full  : t
  val cup   : t -> t -> t
  val cap   : t -> t -> t
  val diff  : t -> t -> t
  val atom  : elem -> t
14

15
  val iter: (elem-> unit) -> t -> unit
16 17 18

  val compute: empty:'b -> full:'b -> cup:('b -> 'b -> 'b) 
    -> cap:('b -> 'b -> 'b) -> diff:('b -> 'b -> 'b) ->
19
    atom:(elem -> 'b) -> t -> 'b
20

21
(*
22
  val print: string -> (Format.formatter -> elem -> unit) -> t ->
23
    (Format.formatter -> unit) list
24
*)
25

26
  val trivially_disjoint: t -> t -> bool
27 28
end

29 30 31
module type MAKE = functor (X : Custom.T) -> S with type elem = X.t

module Make(X : Custom.T) =
32
struct
33 34
  type elem = X.t
  type t =
35 36
    | True
    | False
37
    | Split of int * elem * t * t * t
38

39 40 41 42 43
  let rec equal a b =
    (a == b) ||
    match (a,b) with
      | Split (h1,x1, p1,i1,n1), Split (h2,x2, p2,i2,n2) ->
	  (h1 == h2) &&
44 45
	  (equal p1 p2) && (equal i1 i2) &&
	  (equal n1 n2) && (X.equal x1 x2)
46 47
      | _ -> false

48 49 50 51
(* Idea: add a mutable "unique" identifier and set it to
   the minimum of the two when egality ... *)


52 53 54 55 56 57 58 59 60 61 62 63 64
  let rec compare a b =
    if (a == b) then 0 
    else match (a,b) with
      | Split (h1,x1, p1,i1,n1), Split (h2,x2, p2,i2,n2) ->
	  if h1 < h2 then -1 else if h1 > h2 then 1 
	  else let c = X.compare x1 x2 in if c <> 0 then c
	  else let c = compare p1 p2 in if c <> 0 then c
	  else let c = compare i1 i2 in if c <> 0 then c 
	  else compare n1 n2
      | True,_  -> -1
      | _, True -> 1
      | False,_ -> -1
      | _,False -> 1
65 66


67 68 69 70 71 72 73 74
  let rec hash = function
    | True -> 1
    | False -> 0
    | Split(h, _,_,_,_) -> h

  let compute_hash x p i n = 
	(X.hash x) + 17 * (hash p) + 257 * (hash i) + 16637 * (hash n)

75 76 77 78 79 80 81 82

  let rec check = function
    | True | False -> ()
    | Split (h,x,p,i,n) ->
	assert (h = compute_hash x p i n);
	(match p with Split (_,y,_,_,_) -> assert (X.compare x y < 0) | _ -> ());
	(match i with Split (_,y,_,_,_) -> assert (X.compare x y < 0) | _ -> ());
	(match n with Split (_,y,_,_,_) -> assert (X.compare x y < 0) | _ -> ());
83
	X.check x; check p; check i; check n
84

85 86 87
  let atom x =
    let h = X.hash x + 17 in (* partial evaluation of compute_hash... *)
    Split (h, x,True,False,False)
88 89 90 91
 
  let neg_atom x =
    let h = X.hash x + 16637 in (* partial evaluation of compute_hash... *)
    Split (h, x,False,False,True)
92 93 94 95 96 97 98 99 100

  let rec iter f = function
    | Split (_, x, p,i,n) -> f x; iter f p; iter f i; iter f n
    | _ -> ()

  let rec dump ppf = function
    | True -> Format.fprintf ppf "+"
    | False -> Format.fprintf ppf "-"
    | Split (_,x, p,i,n) -> 
101 102
	Format.fprintf ppf "%i(@[%a,%a,%a@])" 
	(* X.dump x *) (X.hash x) dump p dump i dump n
103 104


105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
  let rec print f ppf = function
    | True -> Format.fprintf ppf "Any"
    | False -> Format.fprintf ppf "Empty"
    | Split (_, x, p,i, n) ->
	let flag = ref false in
	let b () = if !flag then Format.fprintf ppf " | " else flag := true in
	(match p with 
	   | True -> b(); Format.fprintf ppf "%a" f x
	   | False -> ()
	   | _ -> b (); Format.fprintf ppf "%a & @[(%a)@]" f x (print f) p );
	(match i with 
	   | True -> assert false;
	   | False -> ()
	   | _ -> b(); print f ppf i);
	(match n with 
	   | True -> b (); Format.fprintf ppf "@[~%a@]" f x
	   | False -> ()
	   | _ -> b (); Format.fprintf ppf "@[~%a@] & @[(%a)@]" f x (print f) n)
	
  let print a f = function
    | True -> [ fun ppf -> Format.fprintf ppf "%s" a ]
    | False -> []
    | c -> [ fun ppf -> print f ppf c ]
	
	
  let rec get accu pos neg = function
    | True -> (pos,neg) :: accu
    | False -> accu
    | Split (_,x, p,i,n) ->
134
	(*OPT: can avoid creating this list cell when pos or neg =False *)
135 136 137 138 139 140 141 142 143 144 145 146 147 148
	let accu = get accu (x::pos) neg p in
	let accu = get accu pos (x::neg) n in
	let accu = get accu pos neg i in
	accu
	  
  let get x = get [] [] [] x
		
  let compute ~empty ~full ~cup ~cap ~diff ~atom b =
    let rec aux = function
      | True -> full
      | False -> empty
      | Split(_,x, p,i,n) ->
	  let p = cap (atom x) (aux p)
	  and i = aux i
149
	  and n = diff (aux n) (atom x) in
150 151 152 153 154 155 156 157 158
	  cup (cup p i) n
    in
    aux b
      
(* Invariant: correct hash value *)

  let split x pos ign neg =
    Split (compute_hash x pos ign neg, x, pos, ign, neg)

159 160 161 162

    


163 164
  let empty = False
  let full = True
165 166 167 168 169 170

(* Invariants:
     Split (x, pos,ign,neg) ==>  (ign <> True);   
     (pos <> False or neg <> False)
*)

171 172 173 174
  let split x pos ign neg =
    if ign = True then True 
    else if (pos = False) && (neg = False) then ign
    else split x pos ign neg
175 176


177 178
(* Invariant:
   - no ``subsumption'
179
*)
180

181
(*
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
  let rec simplify a b =
    if equal a b then False 
    else match (a,b) with
      | False,_ | _, True -> False
      | a, False -> a
      | True, _ -> True
      | Split (_,x1,p1,i1,n1), Split (_,x2,p2,i2,n2) ->
	  let c = X.compare x1 x2 in
	  if c = 0 then
	    let p1' = simplify (simplify p1 i2) p2 
	    and i1' = simplify i1 i2
	    and n1' = simplify (simplify n1 i2) n2 in
	    if (p1 != p1') || (n1 != n1') || (i1 != i1') 
	    then split x1 p1' i1' n1'
	    else a
	  else if c > 0 then
	    simplify a i2
	  else
	    let p1' = simplify p1 b 
	    and i1' = simplify i1 b
	    and n1' = simplify n1 b in
	    if (p1 != p1') || (n1 != n1') || (i1 != i1') 
	    then split x1 p1' i1' n1'
	    else a
206 207 208
*)


209 210 211
  let rec simplify a l =
    if (a = False) then False else simpl_aux1 a [] l
  and simpl_aux1 a accu = function
212 213
    | [] -> 
	if accu = [] then a else
214 215 216 217
	  (match a with
	     | True -> True
	     | False -> assert false
	     | Split (_,x,p,i,n) -> simpl_aux2 x p i n [] [] [] accu)
218 219 220
    | False :: l -> simpl_aux1 a accu l
    | True :: l -> False
    | b :: l -> if a == b then False else simpl_aux1 a (b::accu) l
221 222 223 224 225 226 227 228
  and simpl_aux2 x p i n ap ai an = function
    | [] -> split x (simplify p ap) (simplify i ai) (simplify n an)
    | (Split (_,x2,p2,i2,n2) as b) :: l ->
	let c = X.compare x2 x in
	if c < 0 then 
	  simpl_aux3 x p i n ap ai an l i2
	else if c > 0 then 
	  simpl_aux2 x p i n (b :: ap) (b :: ai) (b :: an) l
229
	else
230 231 232 233 234 235 236 237 238 239 240
	  simpl_aux2 x p i n (p2 :: i2 :: ap) (i2 :: ai) (n2 :: i2 :: an) l
    | _ -> assert false
  and simpl_aux3 x p i n ap ai an l = function
    | False -> simpl_aux2 x p i n ap ai an l
    | True -> assert false
    | Split (_,x2,p2,i2,n2) as b ->
	let c = X.compare x2 x in
	if c < 0 then 
	  simpl_aux3 x p i n ap ai an l i2
	else if c > 0 then 
	  simpl_aux2 x p i n (b :: ap) (b :: ai) (b :: an) l
241
	else
242
	  simpl_aux2 x p i n (p2 :: i2 :: ap) (i2 :: ai) (n2 :: i2 :: an) l
243 244 245

	  
    
246
  let split x p i n = 
247 248
    split x (simplify p [i]) i (simplify n [i])

249 250

  let rec ( ++ ) a b =
251 252
(*    if equal a b then a *)
    if a == b then a  
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    else match (a,b) with
      | True, _ | _, True -> True
      | False, a | a, False -> a
      | Split (_,x1, p1,i1,n1), Split (_,x2, p2,i2,n2) ->
	  let c = X.compare x1 x2 in
	  if c = 0 then
	    split x1 (p1 ++ p2) (i1 ++ i2) (n1 ++ n2)
	  else if c < 0 then
	    split x1 p1 (i1 ++ b) n1
	  else
	    split x2 p2 (i2 ++ a) n2

(* Pseudo-Invariant:
   - pos <> neg
*)

  let split x pos ign neg =
    if equal pos neg then (neg ++ ign) else split x pos ign neg

(* seems better not to make ++ and this split mutually recursive;
   is the invariant still inforced ? *)

  let rec ( ** ) a b =
276 277
    (*    if equal a b then a *)
    if a == b then a
278 279 280 281 282 283 284 285 286
    else match (a,b) with
      | True, a | a, True -> a
      | False, _ | _, False -> False
      | Split (_,x1, p1,i1,n1), Split (_,x2, p2,i2,n2) ->
	  let c = X.compare x1 x2 in
	  if c = 0 then
(*	    split x1 
	      (p1 ** (p2 ++ i2) ++ (p2 ** i1))
	      (i1 ** i2)
287
	      (n1 ** (n2 ++ i2) ++ (n2 ** i1))  *)
288 289 290
	    split x1 
	      ((p1 ++ i1) ** (p2 ++ i2))
	      False
291
	      ((n1 ++ i1) ** (n2 ++ i2)) 
292 293 294 295 296
	  else if c < 0 then
	    split x1 (p1 ** b) (i1 ** b) (n1 ** b)
	  else
	    split x2 (p2 ** a) (i2 ** a) (n2 ** a)

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
  let rec trivially_disjoint a b =
    if a == b then a = False
    else match (a,b) with
      | True, a | a, True -> a = False
      | False, _ | _, False -> true
      | Split (_,x1, p1,i1,n1), Split (_,x2, p2,i2,n2) ->
	  let c = X.compare x1 x2 in
	  if c = 0 then
(* try expanding -> p1 p2; p1 i2; i1 p2; i1 i2 ... *)
	    trivially_disjoint (p1 ++ i1) (p2 ++ i2) &&
	    trivially_disjoint (n1 ++ i1) (n2 ++ i2)
	  else if c < 0 then
	    trivially_disjoint p1 b &&
	    trivially_disjoint i1 b &&
	    trivially_disjoint n1 b
	  else
	    trivially_disjoint p2 a &&
	    trivially_disjoint i2 a &&
	    trivially_disjoint n2 a

317 318 319 320 321 322 323 324 325
  let rec neg = function
    | True -> False
    | False -> True
(*    | Split (_,x, p,i,False) -> split x False (neg (i ++ p)) (neg i)
    | Split (_,x, False,i,n) -> split x (neg i) (neg (i ++ n)) False 
    | Split (_,x, p,False,n) -> split x (neg p) (neg (p ++ n)) (neg n)  *)
    | Split (_,x, p,i,n) -> split x (neg (i ++ p)) False (neg (i ++ n))
	      
  let rec ( // ) a b =  
326 327
(*    if equal a b then False  *)
    if a == b then False 
328 329 330 331 332 333 334 335 336 337 338 339
    else match (a,b) with
      | False,_ | _, True -> False
      | a, False -> a
      | True, b -> neg b
      | Split (_,x1, p1,i1,n1), Split (_,x2, p2,i2,n2) ->
	  let c = X.compare x1 x2 in
	  if c = 0 then
	    split x1
	      ((p1 ++ i1) // (p2 ++ i2))
	      False
	      ((n1 ++ i1) // (n2 ++ i2))
	  else if c < 0 then
340
	    split x1 (p1 // b) (i1 // b) (n1 // b) 
341 342 343 344 345 346 347 348 349
(*	    split x1 ((p1 ++ i1)// b) False ((n1 ++i1) // b)  *)
	  else
	    split x2 (a // (i2 ++ p2)) False (a // (i2 ++ n2))
	      

  let cup = ( ++ )
  let cap = ( ** )
  let diff = ( // )

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
 let rec serialize t = function
    | (True | False) as b -> 
	Serialize.Put.bool t true; Serialize.Put.bool t (b = True)
    | Split (_,x,p,i,n) ->
	Serialize.Put.bool t false;
	X.serialize t x;
	serialize t p;
	serialize t i;
	serialize t n

  let rec cap_atom x pos a = (* Assume that x does not appear in a *)
    match a with
      | False -> False
      | True -> if pos then atom x else neg_atom x
      | Split (_,y,p,i,n) ->
	  let c = X.compare x y in
	  assert (c <> 0);
367
	  if (c < 0) then 
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
	    if pos then split x a False False
	    else split x False False a
	  else split y (cap_atom x pos p) (cap_atom x pos i) (cap_atom x pos n)


    
  let rec deserialize t =
    if Serialize.Get.bool t then
      if Serialize.Get.bool t then True else False
    else
      let x = X.deserialize t in
      let p = deserialize t in
      let i = deserialize t in
      let n = deserialize t in
      (cap_atom x true p) ++ i ++ (cap_atom x false n)
      (* split x p i n is not ok, because order of keys might have changed! *)
  
385
(*
386
  let diff x y =
387
    let d = diff x y in
388
    Format.fprintf Format.std_formatter "X = %a@\nY = %a@\nX\\Z = %a@\n"
389 390 391 392 393 394 395 396 397
      dump x dump y dump d;  
    d

  let cap x y =
    let d = cap x y in
    Format.fprintf Format.std_formatter "X = %a@\nY = %a@\nX**Z = %a@\n"
      dump x dump y dump d;  
    d
*)
398
end
399 400


401 402 403 404 405 406
module type S' = sig
  include S
  type bdd = False | True | Br of elem * t * t
  val br: t -> bdd
end
module MakeBdd(X : Custom.T) =
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
struct
  type elem = X.t
  type t =
    | Zero
    | One
    | Branch of elem * t * t * int * t
  type node = t

  let neg = function
    | Zero -> One | One -> Zero
    | Branch (_,_,_,_,neg) -> neg

  let id = function
    | Zero -> 0
    | One -> 1
    | Branch (_,_,_,id,_) -> id

(* Internalization + detection of useless branching *)
  let max_id = ref 2 (* Must be >= 2 *)
426
  module W = Weak(*Myweak*).Make(
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    struct
      type t = node
	  
      let hash = function
	| Zero | One -> assert false
	| Branch (v,yes,no,_,_) -> 
	    1 + 17*X.hash v + 257*(id yes) + 65537*(id no)

      let equal x y = (x == y) || match x,y with
	| Branch (v1,yes1,no1,id1,_), Branch (v2,yes2,no2,id2,_) ->
	    (id1 == 0 || id2 == 0) && X.equal v1 v2 && 
	      (yes1 == yes2) && (no1 == no2)
	| _ -> assert false
    end)
  let table = W.create 16383
  type branch = 
      { v : X.t; yes : node; no : node; mutable id : int; neg : branch }
  let mk v yes no =
    if yes == no then yes
    else
      let rec pos = Branch (v,yes,no,0,Branch (v,neg yes,neg no,0,pos)) in
      let x = W.merge table pos in
      let pos : branch = Obj.magic x in
      if (pos.id == 0) 
      then (let n = !max_id in
	    max_id := succ n;
	    pos.id <- n;
	    pos.neg.id <- (-n));
      x

  let atom v = mk v One Zero

  let dummy = Obj.magic (ref 0)
  let memo_size = 16383
  let memo_keys = Array.make memo_size (Obj.magic dummy)
  let memo_vals = Array.make memo_size (Obj.magic dummy)
  let memo_occ = Array.make memo_size 0

  let eg2 (x1,y1) (x2,y2) = x1 == x2 && y1 == y2
  let rec cup x1 x2 = if (x1 == x2) then x1 else match x1,x2 with
    | One, x | x, One -> One
    | Zero, x | x, Zero -> x
    | Branch (v1,yes1,no1,id1,neg1), Branch (v2,yes2,no2,id2,neg2) ->
	if (x1 == neg2) then One
	else
	  let k,h = 
	    if id1<id2 then (x1,x2),id1+65537*id2 else (x2,x1),id2+65537*id1 in
	  let h = (h land max_int) mod memo_size in
	  let i = memo_occ.(h) in
	  let k' = memo_keys.(h) in
	  if (k' != dummy) && (eg2 k k') 
	  then (memo_occ.(h) <- succ i; memo_vals.(h))
	  else 
	    let r = 
              let c = X.compare v1 v2 in
	      if (c = 0) then mk v1 (cup yes1 yes2) (cup no1 no2)
	      else if (c < 0) then mk v1 (cup yes1 x2) (cup no1 x2)
	      else mk v2 (cup yes2 x1) (cup no2 x1) in
	    if (i = 0) then (memo_keys.(h) <- k; memo_vals.(h) <- r;
			     memo_occ.(h) <- 1)
	    else memo_occ.(h) <- pred i;
	    r
  
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
  let rec dump ppf = function
    | One -> Format.fprintf ppf "+"
    | Zero -> Format.fprintf ppf "-"
    | Branch (x,p,n,id,_) -> 
	Format.fprintf ppf "%i:%a(@[%a,%a@])" 
	  id
	  X.dump x dump p dump n

(*
  let cup x y =
    let d = cup x y in
    Format.fprintf Format.std_formatter "X = %a@\nY = %a@\nX+Z = %a@\n"
      dump x dump y dump d;  
    d
*)
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
	  

  let cap x1 x2 = neg (cup (neg x1) (neg x2))
  let diff x1 x2 = neg (cup (neg x1) x2)


  let rec iter f = function
    | Branch (x,p,n,_,_) -> f x; iter f p; iter f n
    | _ -> ()



  let rec print f ppf = function
    | One -> Format.fprintf ppf "Any"
    | Zero -> Format.fprintf ppf "Empty"
    | Branch (x,p,n,_,_) ->
	let flag = ref false in
	let b () = if !flag then Format.fprintf ppf " | " else flag := true in
	(match p with 
	   | One -> b(); Format.fprintf ppf "%a" f x
	   | Zero -> ()
	   | _ -> b (); Format.fprintf ppf "%a & @[(%a)@]" f x (print f) p );
	(match n with 
	   | One -> b (); Format.fprintf ppf "@[~%a@]" f x
	   | Zero -> ()
	   | _ -> b (); Format.fprintf ppf "@[~%a@] & @[(%a)@]" f x (print f) n)
	
  let print a f = function
    | One -> [ fun ppf -> Format.fprintf ppf "%s" a ]
    | Zero -> []
    | c -> [ fun ppf -> print f ppf c ]
	
  let rec get accu pos neg = function
    | One -> (pos,neg) :: accu
    | Zero -> accu
    | Branch (x,p,n,_,_) ->
	(*OPT: can avoid creating this list cell when pos or neg =False *)
	let accu = get accu (x::pos) neg p in
	let accu = get accu pos (x::neg) n in
	accu
	  
  let get x = get [] [] [] x
		
  let compute ~empty ~full ~cup ~cap ~diff ~atom b =
    let rec aux = function
      | One -> full
      | Zero -> empty
      | Branch(x,p,n,_,_) ->
	  let p = cap (atom x) (aux p)
	  and n = diff (aux n) (atom x) in
	  cup p n
    in
    aux b
      
  let empty = Zero
  let full = One

  let rec serialize t = function
    | (Zero | One) as b -> 
	Serialize.Put.bool t true; Serialize.Put.bool t (b = One)
    | Branch (x,p,n,_,_) ->
	Serialize.Put.bool t false;
	X.serialize t x;
	serialize t p;
	serialize t n

  let rec deserialize t =
    if Serialize.Get.bool t then
      if Serialize.Get.bool t then One else Zero
    else
      let x = X.deserialize t in
      let p = deserialize t in
      let n = deserialize t in

      let x = atom x in
      cup (cap x p) (cap (neg x) n)

      (* mk x p n is not ok, because order of keys might have changed!
	 OPT TODO: detect when this is ok *)

  let trivially_disjoint x y = neg x == y  
  let compare x y = compare (id x) (id y)
  let equal x y = x == y
  let hash x = id x
  let check x = ()
590 591 592 593 594 595

  type bdd = False | True | Br of elem * t * t 
  let br = function
    | Zero -> False | One -> True | Branch (x,p,n,_,_) -> Br (x,p,n)
end

596
(*
597 598 599 600 601 602
module Simplify(M : MAKE)(X : Custom.T) = struct
  module B = M(X)
  type elem = X.t

  type f = { vars: (X.t * bool) list; (* toplevel vars and their polarity *)
	     subs: f list; (* subformulas *)
603
	     mutable allvars: (X.t * int * int) list; (* # of pos,neg occurences *)
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
	     mutable form: B.t option;
	     mutable id: int  (* unique id for hash consing *)
	   }
  type t = f

  let tmpl = { vars = []; subs = []; allvars = []; form = None; id = 0 }
	
  let print px =
    let allvars ppf f = 
      List.iter (fun (x,p,n) -> Format.fprintf ppf "[%a:%i,%i]" px x p n) 
	f.allvars
    in
    let rec aux ppf f =
(*      Format.fprintf ppf "{%i}" f.id; *)
(*      (match f.form with Some _ ->  Format.fprintf ppf "*" | _ -> ());  *)
(*      allvars ppf f; *)
      let first = ref true in
      let sep () = if !first then first := false else Format.fprintf ppf "|" in
      List.iter (function 
		   | (x,true) -> sep (); Format.fprintf ppf "%a" px x
		   | (x,false) -> sep (); Format.fprintf ppf "~%a" px x) f.vars;
      List.iter (fun f -> sep (); Format.fprintf ppf "~(@[%a@])" aux f) f.subs;
      if !first then Format.fprintf ppf "."
    in
    fun ppf f -> (*allvars ppf f; *) aux ppf f

  let dump = print (*X.dump*)
    (fun ppf i -> Format.fprintf ppf "%i" (X.hash i))

  let rec cup_vars vars1 vars2 = match (vars1,vars2) with
    | ((x1,p1,n1) as z1)::vars1', ((x2,p2,n2) as z2)::vars2' ->
	let c = X.compare x1 x2 in
	if c = 0 then (x1,p1+p2,n1+n2)::(cup_vars vars1' vars2')
	else if c < 0 then z1::(cup_vars vars1' vars2)
	else z2::(cup_vars vars1 vars2')
    | vars, [] | [], vars -> vars

  let occ (x1,x1v) = if x1v then (x1,1,0) else (x1,0,1)

  let rec cup_vars' vars1 vars2 = match (vars1,vars2) with
    | (x1,x1v)::vars1', (x2,p2,n2)::vars2' ->
	let c = X.compare x1 x2 in
	if c = 0 then assert false (* x1::(cup_vars' vars1' vars2') *)
	else if c < 0 then 
	  (if x1v then (x1,1,0) else (x1,0,1))::(cup_vars' vars1' vars2)
	else (x2,n2,p2)::(cup_vars' vars1 vars2')
    | vars, [] -> List.map occ vars
    | [], vars -> List.map (fun (x,p,n) -> (x,n,p)) vars

  let compute_allvars subs vars =
    cup_vars' vars 
      (List.fold_left (fun accu f -> cup_vars accu f.allvars) [] subs)


  let rec cap_vars vars1 vars2 = match (vars1,vars2) with
    | ((x1,xv1) as z1)::vars1', (x2,_,_)::vars2' ->
	let c = X.compare x1 x2 in
	if c = 0 then z1::(cap_vars vars1' vars2')
	else if c < 0 then cap_vars vars1' vars2
	else cap_vars vars1 vars2'
    | _ -> []

  let rec csubs s1 s2 = match s1,s2 with
    | f1::s1', f2::s2' ->
	if f1 == f2 then f1::(csubs s1' s2')
	else if f1.id < f2.id then f1::(csubs s1' s2)
	else f2::(csubs s1 s2')
    | [], [] -> []
    | s, [] | [], s -> s

  let print_vars v = 
    List.iter (fun (x,b) -> Printf.printf "[%i:%b]" (X.hash x) b) v;
    print_newline ()


  module H = struct
    type t = f
    let rec hash_vars accu = function
      | (x,v)::r -> 
	  hash_vars (65537 * accu + 257 * X.hash x + (if v then 1 else 0)) r
      | [] -> accu

    let rec hash_subs accu = function
      | f::r -> hash_subs (257 * accu + f.id) r
      | [] -> accu

    let hash f = hash_vars (hash_subs 1 f.subs) f.vars

(*
    let rec equal_vars vars1 vars2 = vars1 == vars2 || match vars1,vars2 with
      | (x1,xv1)::(x1',xv1')::vars1,(x2,xv2)::(x2',xv2')::vars2 ->
	 xv1 == xv2 && xv1' == xv2' && X.equal x1 x2 && 
	   X.equal x1' x2' && equal_vars vars1 vars2
      | [(x1,xv1)],[(x2,xv2)] ->
	 xv1 == xv2 &&  X.equal x1 x2
      | _ -> false *)

    let rec equal_vars vars1 vars2 = vars1 == vars2 || match vars1,vars2 with
      | (x1,xv1)::vars1,(x2,xv2)::vars2 ->
	 xv1 == xv2 && X.equal x1 x2 && equal_vars vars1 vars2
      | _ -> false

    let rec equal_subs s1 s2 = s1 == s2 || match s1,s2 with
      | f1::s1, f2::s2 -> f1 == f2 && equal_subs s1 s2
      | _ -> false

    let equal f1 f2 =
      (f1 == f2) || ((f1.id = 0 || f2.id = 0) &&
		       equal_vars f1.vars f2.vars &&
		       equal_subs f1.subs f2.subs)
  end
  module W = Myweak.Make(H)

  let mk =
    let tbl = W.create 16387 in
    let id = ref 0 in
720 721 722 723 724 725 726
    fun vars subs ->
      let f = W.merge tbl { tmpl with vars = vars; subs = subs } in
      if (f.id = 0) then (
	f.id <- (incr id; !id);
	f.allvars <- compute_allvars subs vars;
      );
      f
727
      
728 729
  let empty = mk [] []
  let full = mk [] [empty]
730 731 732

  let check f = ()

733 734
  let posvar x = mk [x,true] []
  let negvar x = mk [x,false] []
735 736

  let neg = function
737 738 739
    | { vars = [x,v]; subs = [] } -> mk [x, not v] []
    | { vars = []; subs = [f] } -> f
    | f -> mk [] [f]
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838

  let has_complement f1 f2 = List.memq f2 f1.subs

  let is_complement f1 f2 =
    match f1 with
      | { vars = []; subs = [f] } -> f == f2
      | _ -> match f2 with
	  | { vars = []; subs = [f] } -> f == f1
	  | _ -> false

  exception One

  type memo = { key1 : int array;
		key2 : int array;
		res  : t array }

  let new_memo n = { key1 = Array.create n (-1);
		     key2 = Array.create n (-1);
		     res = Array.create n empty }

  let memo_cup = new_memo 16383
  let memo_cap = new_memo 16383

  let filrat tbl =
    let o = ref 0 in
    Array.iter (fun i -> if i >= 0 then incr o) tbl.key1;
    !o
    
  let memo_bin tbl g f1 f2 =
    let h = ((f1.id + 1027 * f2.id) land max_int) mod (Array.length tbl.res) in
    if (tbl.key1.(h) == f1.id) && (tbl.key2.(h) == f2.id) then
      tbl.res.(h)
    else
      let r = g (f1,f2) in
      tbl.key1.(h) <- f1.id;
      tbl.key2.(h) <- f2.id;
      tbl.res.(h) <- r;
      r


  let rec cvars vars1 vars2 = match (vars1,vars2) with
    | ((x1,xv1) as z1)::vars1', ((x2,xv2) as z2)::vars2' ->
	let c = X.compare x1 x2 in
	if c = 0 then 
	  if xv1 == xv2 then z1::(cvars vars1' vars2') else raise One
	else if c < 0 then z1::(cvars vars1' vars2)
	else z2::(cvars vars1 vars2')
    | vars,[] | [],vars -> vars

  let rec split_vars vars1 vars2 = match vars1,vars2 with
    | ((x1,xv1) as z1)::vars1', ((x2,xv2) as z2)::vars2' ->
	let c = X.compare x1 x2 in
	if c = 0 then
	  let (vars1,common,vars2) = split_vars vars1' vars2' in
	  if xv1 == xv2 then (vars1,z1::common,vars2)
	  else (z1::vars1,common,z2::vars2)
	else if c < 0 then
	  let (vars1,common,vars2) = split_vars vars1' vars2 in
	  z1::vars1,common,vars2
	else
	  let (vars1,common,vars2) = split_vars vars1 vars2' in
	  vars1,common,z2::vars2
    | vars1,vars2 -> vars1,[],vars2
  let rec split_subs s1 s2 = match s1,s2 with
    | f1::s1',f2::s2' ->
	if f1 == f2 then	  
	  let (s1,common,s2) = split_subs s1' s2' in (s1,f1::common,s2)
	else if f1.id < f2.id then
	  let (s1,common,s2) = split_subs s1' s2 in f1::s1,common,s2
	else
	  let (s1,common,s2) = split_subs s1 s2' in s1,common,f2::s2
    | s1,s2 -> s1,[],s2

  let order_subs subs =
    let rec clean = function
      | f1::(f2::_ as z) -> if f1 == f2 then clean z else f1::(clean z)
      | z -> z
    in
    clean (List.sort (fun f1 f2 -> f1.id - f2.id) subs)

  let rec remove_complement f c =
    let rec aux = function
      | c'::r -> if (c == c') then r else c'::(aux r)
      | _ -> assert false
    in
    vars_subs f.vars (aux f.subs)

  and simplify_subs subs =
    (* TODO: avoid quadratic behavior by pre-detecting collisions in one pass *)
    let rec aux f1 = function
      | [] -> [f1]
      | f2::s ->
	  let (vars1,vars,vars2) = split_vars f1.vars f2.vars in
	  let (subs1,subs,subs2) = split_subs f1.subs f2.subs in
	  if vars = [] && subs = [] then 
	    if has_complement f2 f1 then (remove_complement f2 f1)::(aux f1 s)
	    else if has_complement f1 f2 then f2::(aux (remove_complement f1 f2) s)
	    else f2::(aux f1 s)
	  else (
839 840 841
	    let f1' = mk vars1 subs1 in
	    let f2' = mk vars2 subs2 in
	    let f   = mk vars subs in
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
	    let f' = cup f (cap f1' f2') in
(*	    Format.fprintf Format.std_formatter
	      "MERGE %a+%a==>%a@." dump f1 dump f2 dump f'; *)
	    if f' == full then s
	    else aux f' s)
    in
    if subs = [] then [] else
      let subs = List.fold_left (fun accu f -> aux f accu) [] subs in
      order_subs subs

  and vars_subs vars subs =
    let subs = simplify_subs subs in

    let extra = ref [] in
    let rec aux = function
      | [] -> []
      | { vars = [x,v]; subs = [] } :: s -> extra:=(x, not v)::!extra; aux s
      | f :: s -> f :: (aux s) in
    let subs = aux subs in
    let rec aux = function
      | ((x1,v1) as z)::((x2,v2)::_ as r) -> 
	  if X.equal x1 x2 then if v1 == v2 then aux r else raise One
	  else z::(aux r)
      | r -> r in
    let extra = 
      aux (List.sort (fun (x1,_) (x2,_) -> X.compare x1 x2) !extra) in
    let vars = cvars vars extra
    and subs = elim_subs_opt (List.map (fun (x,v) -> (x,not v)) extra) subs 
    in

    let hoist = ref [] in
    let rec aux = function
      | [] -> []
      | { vars = []; subs = [ f ] } :: s -> hoist := f :: !hoist; aux s
      | f :: s -> f :: (aux s) in
    let subs = aux subs in

879
    let f = mk vars subs in
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    List.fold_left cup f !hoist

  and elim_real elv f =
    let vars = cap_vars elv f.allvars in
    if vars = [] then f
    else (
      let el = ref [] in
      let rec evars vars1 vars2 = match (vars1,vars2) with
	| ((x1,xv1) as z1)::vars1', ((x2,xv2) as z2)::vars2' ->
	    let c = X.compare x1 x2 in
	    if c = 0 then 
	      if xv1 == xv2 then raise One else evars vars1' vars2' 
	    else if c < 0 then z1::(evars vars1' vars2)
	    else (el := z2::!el; evars vars1 vars2')
	| vars1, [] -> el := List.rev !el; vars1
	| [], vars2 -> el := List.rev_append !el vars2; []
      in
      try
	let vars = evars f.vars elv in
	let subs = elim_subs_opt !el f.subs in
	vars_subs vars subs
      with One -> full
    )

  and elim elv f =
    let f' = elim_real elv f in
(*    print_string "elim vars="; print_vars elv;
    Format.fprintf Format.std_formatter "<= %a@." dump f;
    Format.fprintf Format.std_formatter "=> %a@." dump f'; *)
    f'

  and elim_subs_opt el subs =
    if el = [] then subs else order_subs (elim_subs el subs)

  and elim_subs vars = function
    | [] -> []
    | f::s ->
	let f = elim vars f in
	if f == empty then raise One
	else if f == full then elim_subs vars s
	else f :: (elim_subs vars s)


  and cup f1 f2 =
    if (f1 == f2) then f1
    else if (f1 == empty) then f2
    else if (f2 == empty) then f1
    else if (f1 == full) || (f2 == full) || (has_complement f1 f2) 
      || (has_complement f2 f1) then full
    else memo_bin memo_cup real_cup f1 f2

  and real_cup (f1,f2) =
    let elim1 = ref [] and elim2 = ref [] in
    let rec cvars vars1 vars2 = match (vars1,vars2) with
      | ((x1,xv1) as z1)::vars1', ((x2,xv2) as z2)::vars2' ->
	  let c = X.compare x1 x2 in
	  if c = 0 then 
	    if xv1 == xv2 then z1::(cvars vars1' vars2') else raise One
	  else if c < 0 then (elim2 := (x1, not xv1)::!elim2; 
			      z1::(cvars vars1' vars2))
	  else (elim1 := (x2,not xv2)::!elim1; z2::(cvars vars1 vars2'))
      | vars, [] -> List.iter (fun (x,v) -> elim2 := (x,not v) :: !elim2) vars; vars
      | [], vars -> List.iter (fun (x,v) -> elim1 := (x,not v) :: !elim1) vars; vars
    in
    try
      let vars = cvars f1.vars f2.vars in
      let elim1 = cap_vars (List.rev !elim1) f1.allvars in
      let subs1 = elim_subs_opt elim1 f1.subs in
      let elim2 = cap_vars (List.rev !elim2) f2.allvars in
      let subs2 = elim_subs_opt elim2 f2.subs in
      let subs = csubs subs1 subs2 in
      vars_subs vars subs
    with One -> full



  and real_cap (f1,f2) = 
    let (vars1,vars,vars2) = split_vars f1.vars f2.vars in
    let (subs1,subs,subs2) = split_subs f1.subs f2.subs in
    if vars = [] && subs = [] then
      neg (cup (neg f1) (neg f2))
    else
962 963 964
      let f1 = mk vars1 subs1 in
      let f2 = mk vars2 subs2 in
      let f  = mk vars subs in
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
(*      print_int (List.length vars); print_char ':';
      print_int (List.length subs); print_char ' '; *)
      cup f (cap f1 f2)

  and cap t1 t2 =     
    if t1 == t2 then t1
    else if t1 == empty || t2 == empty then empty
    else if t1 == full then t2 else if t2 == full then t1 
    else if is_complement t1 t2 then empty
    else memo_bin memo_cap real_cap t1 t2

  let rec diff t1 t2 = 
    if t1 == t2 then empty
    else if t2 == empty then t1 else if t2 == full then empty
    else if is_complement t1 t2 then t1
    else real_diff t1 t2

  and real_diff f1 f2 =
    (* Need only to compute vars1,subs1 *)
    let (vars1,vars,vars2) = split_vars f1.vars f2.vars in
    let (subs1,subs,subs2) = split_subs f1.subs f2.subs in
    if vars = [] && subs = [] then
      neg (cup (neg f1) f2)
    else
989
      let f1 = mk vars1 subs1 in
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
(*      print_int (List.length vars); print_char '!';
      print_int (List.length subs); print_char ' '; *)
      diff f1 f2


  let find_max f l =
    let aux m z = if f m z < 0 then z else m in
    match l with [] -> raise Not_found | m::z -> List.fold_left aux m z

  let simplify f =
    try
      let (x,p,n) = 
	find_max
	  (fun (x1,p1,n1) (x2,p2,n2) ->
	     Pervasives.compare (p1+n1) (p2+n2))
	  f.allvars in
(*      Printf.printf "x=%i;  p=%i,n=%i\n"  (X.hash x) p n;  *)
      if (p + n) > 2 then (
	let g =
	  if (n = 0) then
	    cup (elim [x,false] f) (cap (posvar x) (elim [x,true] f))
	  else if (p = 0) then
	    cup (elim [x,true] f) (cap (negvar x) (elim [x,false] f))
	  else
	    cup (cap (negvar x) (elim [x,false] f)) 
	      (cap (posvar x) (elim [x,true] f))
	in
1017 1018
(*	Format.fprintf Format.std_formatter
	  "Simplify %a ==> %a@." dump f dump g; *)
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
	g
      )
      else
	f
    with Not_found -> f
  let elim_simplify e f =
    simplify (elim e f)

(* TODO: cache neg of form as well ? *)
  let rec form f =
(*    print_char '*'; flush stdout; *)
    match f.form with
      | Some x -> x
      | None -> 
	  (* TODO: simplify before computing ? *)
	  let accu = 
	    List.fold_left
	      (fun accu (x,v) -> 
		 B.cup accu (if v then B.atom x else B.diff B.full (B.atom x)))
	      B.empty
	      f.vars in 
	  let accu =
	    List.fold_left (fun accu s -> B.cup accu (B.diff B.full (form s))) 
	      accu f.subs in
(*	  Format.fprintf Format.std_formatter "FORM: %a ==> %a@." dump f B.dump accu; *)
	  f.form <- Some accu;
	  accu

  let atom x = posvar x
	  
  let trivially_disjoint f1 f2 =
    (f1 == empty) || (f2 == empty) 
    || is_complement f1 f2

(*
  let hash f = f.id (* B.hash (form f) *)
  let equal f1 f2 = (f1 == f2) (* || B.equal (form f1) (form f2) *)
  let compare f1 f2 = f1.id - f2.id (* B.compare (form f1) (form f2) *)
*)
  let hash f = B.hash (form f)
  let equal f1 f2 = (f1 == f2) || B.equal (form f1) (form f2)
  let compare f1 f2 = B.compare (form f1) (form f2)

  let iter g f = B.iter g (form f)

  let compute ~empty ~full ~cup ~cap ~diff ~atom f =
(*
  let rec aux f = 
      let accu = 
	List.fold_left
	  (fun accu (x,v) -> 
	     cup accu (if v then atom x else diff full (atom x)))
	  empty
	  f.vars in 
      let accu =
	List.fold_left (fun accu s -> cup accu (diff full (aux s))) 
	  accu f.subs in
      accu
    in
    aux f
*)
    B.compute ~empty ~full ~cup ~cap ~diff ~atom (form f)

  let get f = 
1083
    B.get (form ((*simplify*) f))
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095


  module V = Custom.List(Custom.Pair(X)(Custom.Bool))
  let rec serialize s f =
    V.serialize s f.vars;
    Serialize.Put.list serialize s f.subs

  let rec deserialize s =
    let vars = V.deserialize s in
    let vars = List.sort (fun (x1,v1) (x2,v2) -> X.compare x1 x2) vars in
    let subs = Serialize.Get.list deserialize s in
    let subs = List.sort (fun f1 f2 -> f1.id - f2.id) subs in
1096
    mk vars subs
1097
   
1098
end
1099
*)