bool.ml 42.9 KB
Newer Older
1 2 3 4
let (<) : int -> int -> bool = (<)
let (>) : int -> int -> bool = (>)
let (=) : int -> int -> bool = (=)

5 6
module type S =
sig
7 8
  type elem
  include Custom.T
9

10
  val get: t -> (elem list * elem list) list
11

12 13 14 15 16 17
  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
18

19
  val iter: (elem-> unit) -> t -> unit
20 21 22

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

25
(*
26
  val print: string -> (Format.formatter -> elem -> unit) -> t ->
27
    (Format.formatter -> unit) list
28
*)
29

30
  val trivially_disjoint: t -> t -> bool
31 32
end

33 34 35
module type MAKE = functor (X : Custom.T) -> S with type elem = X.t

module Make(X : Custom.T) =
36
struct
37 38
  type elem = X.t
  type t =
39 40
    | True
    | False
41
    | Split of int * elem * t * t * t
42

43 44 45 46 47
  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) &&
48 49
	  (equal p1 p2) && (equal i1 i2) &&
	  (equal n1 n2) && (X.equal x1 x2)
50 51
      | _ -> false

52 53 54 55
(* Idea: add a mutable "unique" identifier and set it to
   the minimum of the two when egality ... *)


56 57 58 59 60 61 62 63 64 65 66 67 68
  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
69 70


71 72 73 74 75 76 77 78
  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)

79 80 81 82 83 84 85 86

  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) | _ -> ());
87
	X.check x; check p; check i; check n
88

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

  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) -> 
105 106
	Format.fprintf ppf "%i(@[%a,%a,%a@])" 
	(* X.dump x *) (X.hash x) dump p dump i dump n
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 134 135 136 137
  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) ->
138
	(*OPT: can avoid creating this list cell when pos or neg =False *)
139 140 141 142 143 144 145 146 147 148 149 150 151 152
	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
153
	  and n = diff (aux n) (atom x) in
154 155 156 157 158 159 160 161 162
	  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)

163 164 165 166

    


167 168
  let empty = False
  let full = True
169 170 171 172 173 174

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

175
  let split x pos ign neg =
176 177
    if ign == True then True 
    else if (pos == False) && (neg == False) then ign
178
    else split x pos ign neg
179 180


181 182
(* Invariant:
   - no ``subsumption'
183
*)
184

185
(*
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  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
210 211 212
*)


213
  let rec simplify a l =
214
    if (a == False) then False else simpl_aux1 a [] l
215
  and simpl_aux1 a accu = function
216
    | [] -> 
217
	if accu == [] then a else
218 219 220 221
	  (match a with
	     | True -> True
	     | False -> assert false
	     | Split (_,x,p,i,n) -> simpl_aux2 x p i n [] [] [] accu)
222 223 224
    | False :: l -> simpl_aux1 a accu l
    | True :: l -> False
    | b :: l -> if a == b then False else simpl_aux1 a (b::accu) l
225 226 227 228 229 230 231 232
  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
233
	else
234 235 236 237 238 239 240 241 242 243 244
	  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
245
	else
246
	  simpl_aux2 x p i n (p2 :: i2 :: ap) (i2 :: ai) (n2 :: i2 :: an) l
247 248 249

	  
    
250
  let split x p i n = 
251 252
    split x (simplify p [i]) i (simplify n [i])

253 254

  let rec ( ++ ) a b =
255 256
(*    if equal a b then a *)
    if a == b then a  
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    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 =
280 281
    (*    if equal a b then a *)
    if a == b then a
282 283 284 285 286 287 288 289 290
    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)
291
	      (n1 ** (n2 ++ i2) ++ (n2 ** i1))  *)
292 293 294
	    split x1 
	      ((p1 ++ i1) ** (p2 ++ i2))
	      False
295
	      ((n1 ++ i1) ** (n2 ++ i2)) 
296 297 298 299 300
	  else if c < 0 then
	    split x1 (p1 ** b) (i1 ** b) (n1 ** b)
	  else
	    split x2 (p2 ** a) (i2 ** a) (n2 ** a)

301
  let rec trivially_disjoint a b =
302
    if a == b then a == False
303
    else match (a,b) with
304
      | True, a | a, True -> a == False
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
      | 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

321 322 323 324 325 326 327 328 329
  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 =  
330 331
(*    if equal a b then False  *)
    if a == b then False 
332 333 334 335 336 337 338 339 340 341 342 343
    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
344
	    split x1 (p1 // b) (i1 // b) (n1 // b) 
345 346 347 348 349 350 351 352 353
(*	    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 = ( // )

354 355
 let rec serialize t = function
    | (True | False) as b -> 
356
	Serialize.Put.bool t true; Serialize.Put.bool t (b == True)
357 358 359 360 361 362 363 364 365 366 367 368 369 370
    | 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);
371
	  if (c < 0) then 
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
	    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! *)
  
389
(*
390
  let diff x y =
391
    let d = diff x y in
392
    Format.fprintf Format.std_formatter "X = %a@\nY = %a@\nX\\Z = %a@\n"
393 394 395 396 397 398 399 400 401
      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
*)
402
end
403 404


405 406 407 408 409 410
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) =
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
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 *)
430
  module W = Weak(*Myweak*).Make(
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 490 491 492 493
    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
  
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
  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
*)
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
	  

  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 -> 
568
	Serialize.Put.bool t true; Serialize.Put.bool t (b == One)
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    | 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 = ()
594 595 596 597 598 599

  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

600
(*
601
module Simplify(X : Custom.T) = struct
602 603
  type elem = X.t

604 605
  module V = SortedList.Make(X)

606
  type tree = Split of elem list * elem list * tree list option
607 608 609 610
  type f = {
    pos: V.t;
    neg: V.t;
    subs: fset;
611 612 613
    mutable id: int;  (* unique id for hash consing *)
    mutable dnf: (V.t * V.t) list option;
    mutable dnf_neg: (V.t * V.t) list option;
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
  }
  and fset =
    | Empty
    | Leaf of f
    | Branch of int * int * fset * fset

  type t = PosF of f | NegF of f | PosV of X.t | NegV of X.t | Zero | One

  let id k = k.id

  module F = struct
    let empty = Empty
    let is_empty = function Empty -> true | _ -> false
    let singleton k = Leaf k
    let zero_bit k m = (k land m) == 0
    let rec mem k = function
      | Empty -> false
      | Leaf j -> k == j
      | Branch (_, m, l, r) -> mem k (if zero_bit (id k) m then l else r)
    let lowest_bit x = x land (-x)
    let branching_bit p0 p1 = lowest_bit (p0 lxor p1)
    let mask p m = p land (m-1)
    let join (p0,t0,p1,t1) = 
      let m = branching_bit p0 p1 in
      if zero_bit p0 m then Branch (mask p0 m, m, t0, t1)
      else Branch (mask p0 m, m, t1, t0)
    let match_prefix k p m = (mask k m) == p
    let add k t =
      let rec ins = function
	| Empty -> Leaf k
644
	| Leaf j as t -> if j == k then t else join (id k, Leaf k, id j, t)
645 646 647 648 649 650 651
	| Branch (p,m,t0,t1) as t ->
            if match_prefix (id k) p m then
              if zero_bit (id k) m then Branch (p, m, ins t0, t1)
              else Branch (p, m, t0, ins t1)
            else join (id k, Leaf k, p, t)
      in
      ins t
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 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
    let rec union s t = match s,t with
      | Empty, t  -> t
      | t, Empty  -> t
      | Leaf k, t -> add k t
      | t, Leaf k -> add k t
      | (Branch (p,m,s0,s1) as s), (Branch (q,n,t0,t1) as t) ->
	  if m == n && match_prefix q p m then 
	    Branch (p, m, union s0 t0, union s1 t1)
	  else if m < n && match_prefix q p m then
            if zero_bit q m then Branch (p, m, union s0 t, s1)
            else Branch (p, m, s0, union s1 t)
	  else if m > n && match_prefix p q n then
            if zero_bit p n then Branch (q, n, union s t0, t1)
            else Branch (q, n, t0, union s t1)
	  else join (p, s, q, t)
	    
    let rec subset s1 s2 = match s1,s2 with
      | Empty, _ -> true
      | _, Empty -> false
      | Leaf k1, _ -> mem k1 s2
      | Branch _, Leaf _ -> false
      | Branch (p1,m1,l1,r1), Branch (p2,m2,l2,r2) ->
	  if m1 == m2 && p1 == p2 then subset l1 l2 && subset r1 r2
	  else if m1 > m2 && match_prefix p1 p2 m2 then
            if zero_bit p1 m2 then subset l1 l2 && subset r1 l2
            else subset l1 r2 && subset r1 r2
	  else
            false
	      
    let branch = function
      | (_,_,Empty,t) -> t
      | (_,_,t,Empty) -> t
      | (p,m,t0,t1)   -> Branch (p,m,t0,t1)
	  
    let rec remove k = function
      | Empty -> Empty
      | Leaf j as t -> if k == j then Empty else t
      | Branch (p,m,t0,t1) as t ->
          if match_prefix (id k) p m then 
	    if zero_bit (id k) m then branch (p, m, remove k t0, t1)
            else branch (p, m, t0, remove k t1)
          else t
	    
    let rec inter s1 s2 = match s1,s2 with
      | Empty, _ -> Empty
      | _, Empty -> Empty
      | Leaf k1, _ -> if mem k1 s2 then s1 else Empty
      | _, Leaf k2 -> if mem k2 s1 then s2 else Empty
      | Branch (p1,m1,l1,r1), Branch (p2,m2,l2,r2) ->
	  if m1 == m2 && p1 == p2 then union (inter l1 l2) (inter r1 r2)
	  else if m1 < m2 && match_prefix p2 p1 m1 then
            inter (if zero_bit p2 m1 then l1 else r1) s2
	  else if m1 > m2 && match_prefix p1 p2 m2 then
            inter s1 (if zero_bit p1 m2 then l2 else r2)
	  else Empty
	    
    let rec split s1 s2 = match s1,s2 with
      | Empty, _ -> Empty,Empty,s2
      | _, Empty -> s1,Empty,Empty
      | Leaf k1, _ -> if mem k1 s2 then Empty,s1,(remove k1 s2) else s1,Empty,s2
      | _, Leaf k2 -> if mem k2 s1 then (remove k2 s1),s2,Empty else s1,Empty,s2
      | Branch (p1,m1,l1,r1), Branch (p2,m2,l2,r2) ->
	  if m1 == m2 && p1 == p2 then 
	    let x1,x12,x2 = split l1 l2
	    and y1,y12,y2 = split r1 r2 in
	    union x1 y1, union x12 y12, union x2 y2
	  else if m1 < m2 && match_prefix p2 p1 m1 then
	    if zero_bit p2 m1 
	    then let x1,x12,x2 = split l1 s2 in union x1 r1, x12, x2
	    else let x1,x12,x2 = split r1 s2 in union l1 x1, x12, x2
	  else if m2 < m1 && match_prefix p1 p2 m1 then
	    if zero_bit p1 m2 
	    then let x1,x12,x2 = split l2 s1 in x1, x12, union x2 r2
	    else let x1,x12,x2 = split r1 s2 in x1, x12, union l2 x2
	  else (s1,Empty,s2)

    let rec diff s1 s2 = match s1,s2 with
      | Empty, _ -> Empty
      | _, Empty -> s1
      | Leaf k1, _ -> if mem k1 s2 then Empty else s1
      | _, Leaf k2 -> remove k2 s1
      | Branch (p1,m1,l1,r1), Branch (p2,m2,l2,r2) ->
	  if m1 == m2 && p1 == p2 then union (diff l1 l2) (diff r1 r2)
	  else if m1 < m2 && match_prefix p2 p1 m1 then
            if zero_bit p2 m1 then union (diff l1 s2) r1
            else union l1 (diff r1 s2)
	  else if m1 > m2 && match_prefix p1 p2 m2 then
            if zero_bit p1 m2 then diff s1 l2 else diff s1 r2
	  else s1

    let rec intersect s1 s2 = match s1,s2 with
      | Empty, _ -> false
      | _, Empty -> false
      | Leaf k1, _ -> mem k1 s2
      | _, Leaf k2 -> mem k2 s1
      | Branch (p1,m1,l1,r1), Branch (p2,m2,l2,r2) ->
	  if m1 == m2 && p1 == p2 then intersect l1 l2 || intersect r1 r2
	  else if m1 < m2 && match_prefix p2 p1 m1 then
            intersect (if zero_bit p2 m1 then l1 else r1) s2
	  else if m1 > m2 && match_prefix p1 p2 m2 then
            intersect s1 (if zero_bit p1 m2 then l2 else r2)
	  else false

    let disjoint s1 s2 = not (intersect s1 s2)

    let rec equal x y = x == y || match x,y with
      | Leaf k1, Leaf k2 -> k1 == k2
      | Branch (p1,m1,l1,r1), Branch (p2,m2,l2,r2) ->
          p1 == p2 && m1 == m2 && (equal l1 l2) && (equal r1 r2)
      | _ -> false

764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
    let rec compare x y = match x,y with
      | Empty, Empty -> 0
      | Leaf k1, Leaf k2 -> id k1 - id k2
      | Branch (p1,m1,l1,r1), Branch (p2,m2,l2,r2) ->
	  if (p1 < p2) then (-1) else if (p1 > p2) then 1
	  else if (m1 < m2) then (-1) else if (m1 > m2) then 1
	  else let c =  compare l1 l2 in if c != 0 then c
	  else compare r1 r2
      | Empty, _ -> -1 | _, Empty -> 1
      | Leaf _, _ -> -1 | _, Leaf _ -> 1
      
(* 3,19,65599,1048577 *)
    let z1 = 3 (* int_of_string (Sys.getenv "Z1") *)
    let z2 = 19 (* int_of_string (Sys.getenv "Z2") *)
    let z3 = 65599 (* int_of_string (Sys.getenv "Z3") *)
    let z4 = 1048577 (* int_of_string (Sys.getenv "Z4") *)

781 782
    let rec hash = function
      | Empty -> 0
783
      | Leaf k -> 1 + z1 * (id k)
784
      | Branch (p,m,l,r) -> 
785
	  2 + z1 * p + z2 * m + z3 * (hash l) + z4 * (hash r)
786 787 788 789 790 791

    let rec iter f = function
      | Empty -> ()
      | Leaf k -> f k
      | Branch (_,_,t0,t1) -> iter f t0; iter f t1

792 793 794 795 796
    let rec exists f = function
      | Empty -> false
      | Leaf k -> f k
      | Branch (_,_,t0,t1) -> exists f t0 || exists f t1

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    let rec fold f s accu = match s with
      | Empty -> accu
      | Leaf k -> f k accu
      | Branch (_,_,t0,t1) -> fold f t0 (fold f t1 accu)

    let rec card f s accu = match s with
      | Empty -> accu
      | Leaf k -> f k accu
      | Branch (_,_,t0,t1) -> fold f t0 (fold f t1 accu)

    let rec cardinal = function
      | Empty -> 0
      | Leaf _ -> 1
      | Branch (_,_,t0,t1) -> cardinal t0 + cardinal t1

812 813 814 815
    let rec elements accu = function
      | Empty -> accu
      | Leaf k -> k :: accu
      | Branch (_,_,t0,t1) -> elements (elements accu t0) t1
816 817 818 819 820
  end



  let print_f px =
821 822
    let rec aux ppf f =
      let first = ref true in
823
      let sep () = if !first then first := false else Format.fprintf ppf "." in
824 825 826
      V.iter (fun x -> sep (); Format.fprintf ppf "%a" px x) f.pos;
      V.iter (fun x -> sep (); Format.fprintf ppf "~%a" px x) f.neg;
      F.iter (fun f -> sep (); Format.fprintf ppf "~(@[%a@])" aux f) f.subs;
827 828 829 830
      if !first then Format.fprintf ppf "."
    in
    fun ppf f -> (*allvars ppf f; *) aux ppf f

831 832 833 834 835 836 837 838
  let print_t px ppf = function
    | PosV f -> Format.fprintf ppf "%a" px f
    | NegV f -> Format.fprintf ppf "~%a" px f
    | PosF f -> Format.fprintf ppf "%a" (print_f px) f
    | NegF f -> Format.fprintf ppf "~(%a)" (print_f px) f
    | Zero -> Format.fprintf ppf "0"
    | One -> Format.fprintf ppf "1"

839
  let dump = print_t
840 841
    (fun ppf i -> Format.fprintf ppf "%i" (X.hash i))

842
(*
843 844 845 846 847 848 849 850 851
  let dump_vars ppf v =
    let first = ref true in
    let sep () = if !first then first := false else Format.fprintf ppf "|" in
    V.iter (fun x -> sep (); Format.fprintf ppf "%i" (X.hash x)) v
    
  let dump_subs ppf v =
    let first = ref true in
    let sep () = if !first then first := false else Format.fprintf ppf "|" in
    F.iter (fun f -> sep (); Format.fprintf ppf "#%i:%a" f.id dump f) v
852
*)    
853 854

(*
855 856 857 858 859 860 861 862 863
  let rec form f =
    let rec aux1 accu = function
      | x::l -> aux1 (B.cup accu (B.atom x)) l
      | [] -> accu in
    let rec aux2 accu = function
      | x::l -> aux2 (B.cup accu (B.diff B.full (B.atom x))) l
      | [] -> accu in
    let accu = aux2 (aux1 B.empty f.pos) f.neg in
    F.fold (fun f accu -> B.cup accu (B.diff B.full (form f))) f.subs accu
864
      
865 866 867 868 869
  let get f = match f.get with Some x -> x | None ->
    let r = B.get (form f) in
    f.get <- Some r;
    r
*)
870

871
  (* Hash-consing *)
872 873 874 875 876 877 878 879 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 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 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 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
  module H = struct
    type t = f

    let compare f g =
      let c = V.compare f.pos g.pos in if c != 0 then c 
      else let c = V.compare f.neg g.neg in if c != 0 then c 
      else F.compare f.subs g.subs

    let equal0 f pos neg subs =
      V.equal f.pos pos 
      && V.equal f.neg neg 
      && F.equal f.subs subs

   let hash f = 
     (V.hash f.pos) 
     + 257 * (V.hash f.neg) 
     + 65537 * (F.hash f.subs)

   let hash0 pos neg subs =
     (V.hash pos) 
     + 257 * (V.hash neg) 
     + 65537 * (F.hash subs)

   let equal f1 f2 =
     V.equal f1.pos f2.pos 
     && V.equal f1.neg f2.neg 
     && F.equal f1.subs f2.subs
  end

(*  module W = Weak.Make(H) *)

(*
  module W = struct
    type table = {
      mutable table : H.t Weak.t array;
      mutable totsize : int;
      mutable limit : int;
    }

    let create sz =
      let sz = if sz < 7 then 7 else sz in
      let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in
      let emptybucket = Weak.create 0 in
      { table = Array.create sz emptybucket;
	totsize = 0;
	limit = 3; }

    let next_sz n = min (3*n/2 + 3) (Sys.max_array_length - 1)

    let rec copy t t' =
      let rec aux b =
	for i = 0 to Weak.length b - 1 do
	  match Weak.get b i with
            | Some v -> add t' v 
		(((H.hash0 v.pos v.neg v.subs) land max_int)
		 mod (Array.length t'.table))
            | None -> ()
	done
      in
      Array.iter aux t.table

   and resize t =
      let oldlen = Array.length t.table in
      let newlen = next_sz oldlen in
      if newlen > oldlen then begin
	let newt = create newlen in
	newt.limit <- t.limit + 100;          (* prevent resizing of newt *)
	copy t newt;
	t.table <- newt.table;
	t.limit <- t.limit + 2;
      end

   and add t v index =
      let bucket = t.table.(index) in
      let sz = Weak.length bucket in
      let rec loop i =
	if i >= sz then begin
	  let newsz = min (sz + 3) (Sys.max_array_length - 1) in
	  if newsz <= sz then 
            failwith "Hashcons.Make: hash bucket cannot grow more";
	  let newbucket = Weak.create newsz in
	  Weak.blit bucket 0 newbucket 0 sz;
	  Weak.set newbucket i (Some v);
	  t.table.(index) <- newbucket;
	  t.totsize <- t.totsize + (newsz - sz);
	  if t.totsize > t.limit * Array.length t.table then resize t;
	end else begin
	  if Weak.check bucket i
	  then loop (i+1)
	  else Weak.set bucket i (Some v)
	end
      in
      loop 0

    let count t =
      let rec count_bucket i b accu =
	if i >= Weak.length b then accu else
	  count_bucket (i+1) b (accu + (if Weak.check b i then 1 else 0))
      in
      Array.fold_right (count_bucket 0) t.table 0

    let stats t =
      let len = Array.length t.table in
      let lens = Array.map Weak.length t.table in
      Array.sort compare lens;
      let totlen = Array.fold_left ( + ) 0 lens in
      (len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1))

    let cur_id = ref 0
    let merge t pos neg subs =
      let index = H.hash0 pos neg subs in
      let index = (index land max_int) mod (Array.length t.table) in
      let bucket = t.table.(index) in
      let sz = Weak.length bucket in
      let rec loop i =
	if i >= sz then begin
	  let hnode = { id = (incr cur_id; !cur_id); pos = pos; neg = neg;
			subs = subs; dnf = None; dnf_neg = None } in
	  add t hnode index;
(*
	  if (!cur_id mod 1000 = 0) then
	    (let (len, count, totlen, min, med, max) = stats t in
	    Format.fprintf Format.std_formatter
	      "id=%i len=%i count=%i totlen=%i min=%i med=%i max=%i  ratio=%f@." 
	      !cur_id len count totlen min med max
	      (float_of_int count /. float_of_int len)
	    ); 
*)
	  hnode
	end else begin
	  match Weak.get_copy bucket i with
            | Some v when H.equal0 v pos neg subs -> 
		begin match Weak.get bucket i with
		  | Some v -> v
		  | None -> loop (i+1)
		end
            | _ -> loop (i+1)
	end
      in
      loop 0

  end
*)

  module W = struct
    module H = Hashset.MakeTable(H)
    let cur_id = ref 0
    let create = H.create
    let merge h pos neg subs =
      let x = { pos = pos; neg = neg; subs = subs; dnf = None; dnf_neg = None;
		id = 0 } in
      try H.find h x
      with Not_found -> 
	x.id <- (incr cur_id; !cur_id);
	H.add h x x;
	x
  end

  let s = 157 (* int_of_string (Sys.getenv "MEMO") *)

  let mk_f = W.merge (W.create s) 
(*
  let mk_f = let id = ref 0 and tbl = W.create s in 

1036
  fun pos neg subs ->
1037 1038 1039 1040 1041 1042
(*    assert (V.length pos + V.length neg + F.cardinal subs >= 2);
    assert (V.disjoint pos neg);  *)
    let f = W.merge tbl { pos = pos; neg = neg; subs = subs; id = 0; 
			  dnf = None; dnf_neg = None } in
    if f.id = 0 then (f.id <- (incr id; !id)(*; print_char '0'*))
    (*else print_char '1'*);
1043
    f
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 1083 1084 1085
(*
  let rec check_f f =
    assert (V.length f.pos + V.length f.neg + F.cardinal f.subs >= 2);
    assert (V.disjoint f.pos f.neg);
    F.iter check_f f.subs

  let check = function
    | PosF f | NegF f -> check_f f
    | _ -> ()
*)
  let check _ = ()

  let hash = function
    | Zero -> 0
    | One -> 1
    | PosV x -> 2 + 7 * (X.hash x)
    | NegV x -> 3 + 7 * (X.hash x)
    | PosF f -> 4 + 7 * f.id
    | NegF f -> 5 + 7 * f.id

  let equal t1 t2 = t1 == t2 || match t1,t2 with
    | PosV x, PosV y | NegV x, NegV y -> X.equal x y
    | PosF f, PosF g | NegF f, NegF g -> f == g
    | _ -> false

  let compare t1 t2 = match t1,t2 with
    | Zero, Zero | One, One -> 0
    | PosV x, PosV y | NegV x, NegV y -> X.compare x y
    | PosF f, PosF g | NegF f, NegF g -> f.id - g.id
    | Zero, _ -> -1 | _, Zero -> 1
    | One, _ -> -1 | _, One -> 1
    | PosV _, _ -> -1 | _, PosV _ -> 1
    | NegV _, _ -> -1 | _, NegV _ -> 1
    | PosF _, _ -> -1 | _, PosF _ -> 1

  let atom x = PosV x

  let empty = Zero
  let full = One

1086
  let neg = function
1087 1088 1089 1090 1091 1092 1093 1094
    | PosF x -> NegF x
    | NegF x -> PosF x
    | PosV x -> NegV x
    | NegV x -> PosV x
    | Zero -> One
    | One -> Zero

  let mk pos neg subs = match pos,neg,subs with
1095
    | [],[],Empty  -> One
1096 1097 1098 1099 1100
    | [x],[],Empty -> PosV x
    | [],[x],Empty -> NegV x
    | [],[],Leaf f -> NegF f
    | _ -> PosF (mk_f pos neg subs)

1101 1102 1103 1104
  let trivially_subset f g =
    V.subset g.pos f.pos && V.subset g.neg f.neg &&
      F.subset g.subs f.subs

1105
  let trivially_disjoint f g =
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
(*    F.mem f g.subs || F.mem g f.subs || *)
      not (V.disjoint f.pos g.neg) || not (V.disjoint f.neg g.pos) (*||
      (F.exists (trivially_subset g) f.subs) ||
      (F.exists (trivially_subset f) g.subs) *)


  (* Memoization *)
  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 Zero }

1118 1119 1120 1121
  let s = 16383 (* int_of_string (Sys.getenv "H") *)
  let memo_cap = new_memo s
  let memo_diff = new_memo s
  let memo_nor = new_memo s
1122 1123

  let memo_bin tbl g f1 f2 =
1124
    let h = ((f1.id + 65599 * f2.id) land max_int) mod (Array.length tbl.res) in
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    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 overlap f g =
    not ((V.disjoint f.pos g.pos) && (V.disjoint f.neg g.neg) &&
	   (F.disjoint f.subs g.subs))

  let remove_overlap f g =
    mk (V.diff f.pos g.pos) (V.diff f.neg g.neg) (F.diff f.subs g.subs)
1140 1141

  let cap_f f g =
1142 1143
    if f == g then PosF f
    else if trivially_disjoint f g then Zero
1144 1145 1146 1147
    else
      PosF 
	(mk_f (V.cup f.pos g.pos) (V.cup f.neg g.neg) (F.union f.subs g.subs))

1148 1149 1150
  let rec diff_f f g =
    if f == g then Zero
    else if trivially_disjoint f g then PosF f
1151
    else
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
      if overlap f g then
	let g' = remove_overlap g f in
	let r =  cap (PosF f) (neg g') in
(*	Format.fprintf Format.std_formatter 
	  "diff opt: %a DIFF %a == %a DIFF %a ==> %a@."
	  dump (PosF f) dump (PosF g)
	  dump (PosF f) dump g'
	  dump r; *)
	r
      else
	PosF (mk_f f.pos f.neg (F.union (Leaf g) f.subs))
    
1164

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
  and nor_f f g =
    (* TODO: factorize common part of f and g ?? *)
    if f == g then NegF f 
    else if trivially_subset f g then NegF g
    else if trivially_subset g f then NegF f
    else (* here  f != g *)
      if F.mem f g.subs then
	cap (NegF f) (neg (mk g.pos g.neg (F.remove f g.subs))) (* OPT *)
      else if F.mem g f.subs then 
	cap (NegF g) (neg (mk f.pos f.neg (F.remove g f.subs))) (* OPT *)
1175
      else 
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
(*	if overlap f g then
	  let pos1,posc,pos2 = V.split f.pos g.pos 
	  and neg1,negc,neg2 = V.split f.neg g.neg
	  and sub1,subc,sub2 = F.split f.subs g.subs in
	  let f1 = mk pos1 neg1 sub1
	  and f2 = mk pos2 neg2 sub2
	  and fc = mk posc negc subc in
	  neg (cap fc (neg (cap (neg f1) (neg f2))))
	else *)
	  PosF (mk_f [] [] (F.union (Leaf f) (Leaf g)))

  and cap t1 t2 = match t1,t2 with 
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    | Zero, t | t, Zero -> Zero
    | One, t | t, One -> t
    | PosV x, PosV y -> 
	let c = X.compare x y in
	if c = 0 then t1 
	else PosF (mk_f (if c <0 then [x;y] else [y;x]) [] Empty)
    | NegV x, NegV y ->
	let c = X.compare x y in
	if c = 0 then t1 
	else PosF (mk_f [] (if c <0 then [x;y] else [y;x]) Empty)
    | PosV x, NegV y 
    | NegV y, PosV x -> if X.equal x y then Zero else PosF (mk_f [x] [y] Empty)
1200 1201 1202 1203
    | PosF f, PosF g -> 
	if f.id < g.id then memo_bin memo_cap cap_f f g
	else if f.id > g.id then memo_bin memo_cap cap_f g f
	else t1
1204
    | PosF f, NegF g
1205
    | NegF g, PosF f -> memo_bin memo_diff diff_f f g
1206 1207 1208 1209
    | NegF f, NegF g -> 
	if f.id < g.id then memo_bin memo_nor nor_f f g
	else if f.id > g.id then memo_bin memo_nor nor_f g f
	else t1
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    | (PosF f as t), PosV x | PosV x, (PosF f as t) -> 
	if V.mem f.pos x then t
	else if V.mem f.neg x then Zero
	else PosF (mk_f (V.add x f.pos) f.neg f.subs)
    | (PosF f as t), NegV x | NegV x, (PosF f as t) -> 
	if V.mem f.neg x then t
	else if V.mem f.pos x then Zero
	else PosF (mk_f f.pos (V.add x f.neg) f.subs)
    | (PosV x as t), NegF f | NegF f, (PosV x as t) ->
	if V.mem f.pos x then 
	  match mk (V.remove x f.pos) f.neg f.subs with
1221 1222
	    | PosF f -> PosF (mk_f [x] [] (Leaf f))
	    | NegF f -> PosF (mk_f (V.add x f.pos) f.neg f.subs)
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
	    | PosV y -> if X.equal x y then Zero else PosF (mk_f [x] [y] Empty)
	    | NegV y -> 	
		let c = X.compare x y in
		if c = 0 then t
		else PosF (mk_f (if c <0 then [x;y] else [y;x]) [] Empty)
	    | Zero | One -> assert false
	else if V.mem f.neg x then t
	else PosF (mk_f [x] [] (Leaf f))
    | (NegV x as t), NegF f | NegF f, (NegV x as t) ->
	if V.mem f.neg x then 
	  match mk f.pos (V.remove x f.neg) f.subs with
1234 1235
	    | PosF f -> PosF (mk_f [] [x] (Leaf f))
	    | NegF f -> PosF (mk_f f.pos (V.add x f.neg) f.subs)
1236 1237 1238 1239 1240 1241 1242 1243 1244
	    | NegV y -> if X.equal x y then Zero else PosF (mk_f [y] [x] Empty)
	    | PosV y -> 	
		let c = X.compare x y in
		if c = 0 then t
		else PosF (mk_f [] (if c <0 then [x;y] else [y;x]) Empty)
	    | Zero | One -> assert false
	else if V.mem f.pos x then t
	else PosF (mk_f [] [x] (Leaf f))

1245

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288

  let rec mk_clean pos neg negf f =
    if not (V.disjoint pos f.neg) || not (V.disjoint neg f.pos) then Zero
    else
      let pos' = V.diff f.pos pos
      and neg' = V.diff f.neg neg
      and subs' = F.diff f.subs negf in
      let pos = V.cup pos pos' and neg = V.cup neg neg' and negf = 
	F.union negf subs' in
      let rec aux pos' neg' subs' = function
	| g::r ->
	    (match mk_clean pos neg negf g with
	       | NegF g -> 
		   if not (V.disjoint pos' g.neg) ||
		     not (V.disjoint neg' g.pos) then raise Exit;
		   aux 
		     (V.cup pos' g.pos) 
		     (V.cup neg' g.neg)
		     (F.union subs' g.subs) 
		     r
	       | PosF g -> aux pos' neg' (F.add g subs') r
	       | NegV x -> 
		   if V.mem neg' x then raise Exit;
		   aux (V.add x pos') neg' subs' r
	       | PosV x -> 
		   if V.mem pos' x then raise Exit;
		   aux pos' (V.add x neg') subs' r
	       | One -> raise Exit
	       | Zero -> aux pos' neg' subs' r)
	| [] -> mk pos' neg' subs'
      in
      try aux pos' neg' F.empty (F.elements [] subs') with Exit -> Zero

  let clean = function
    | PosF f as t when F.cardinal f.subs >= 1 -> 
	let t' = mk_clean [] [] F.empty f in
	if equal t t' then t else t'
    | NegF f as t when F.cardinal f.subs >= 1 -> 
	let t' = neg (mk_clean [] [] F.empty f) in
	if equal t t' then t else t'
    | x -> x


1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
  let get_f pos neg subs =
    let all = ref [] in
    let reg pos neg = all := (pos,neg) :: !all in
    let rec aux pos neg = function
      | [] -> reg pos neg
      | f::r ->
	  if (V.exists (fun x -> V.mem pos x) f.neg
	      || V.exists (fun x -> V.mem neg x) f.pos)
	  then aux pos neg r
	  else (
	    V.iter (fun x ->
		      if V.mem neg x then ()
		      else aux (V.add x pos) neg r) f.neg;
	    V.iter (fun x ->
		      if V.mem pos x then ()
		      else aux pos (V.add x neg) r) f.pos;
	    F.iter (fun f -> 
		      if not (V.disjoint f.pos neg && V.disjoint f.neg pos)
		      then ()
		      else
			aux (V.cup f.pos pos) (V.cup f.neg neg)
			  (F.elements r f.subs)) f.subs
	  )
1312
    in
1313 1314
    aux pos neg subs;
    !all
1315

1316 1317 1318 1319 1320 1321 1322 1323
  let get = function
    | Zero -> []
    | One -> [ [],[] ]
    | PosF f ->
	(match f.dnf with
	   | Some r -> r
	   | None ->
	       let r = get_f f.pos f.neg (F.elements [] f.subs) in
1324
	       f.dnf <- Some r; 
1325 1326 1327 1328 1329 1330
	       r)
    | NegF f -> 
	(match f.dnf_neg with
	   | Some r -> r
	   | None ->
	       let r = get_f [] [] [f] in
1331
	       f.dnf_neg <- Some r; 
1332 1333 1334 1335
	       r)
    | PosV x -> [ [x],[] ]
    | NegV x -> [ [],[x] ]

1336 1337
  let get t = get (clean t)

1338 1339 1340
  let non_triv = function
    | PosF f | NegF f -> F.cardinal f.subs >= 1
    | _ -> false
1341 1342

(*
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
  let get t =
    let r = get t in
    if non_triv t then (
      let ppf = Format.std_formatter in
      Format.fprintf ppf "GET %a -->" dump t;
      List.iter (fun (pos,neg) ->
		   List.iter (fun x -> Format.fprintf ppf "%i." (X.hash x)) pos;
		   List.iter (fun x -> Format.fprintf ppf "~%i." (X.hash x)) neg;
		   Format.fprintf ppf "|"
		) r;
      Format.fprintf ppf "@.");
    r
1355
*)
1356

1357 1358 1359
(*
  let cap f1 f2 =
    let r = cap f1 f2 in
1360
    if (non_triv f1) || (non_triv f2) then
1361 1362 1363 1364 1365
      Format.fprintf Format.std_formatter
	"%a AND %a ===>%a@." dump f1 dump f2 dump r;
    check r;
    r
*)
1366

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
  let rec compute_f full cap diff atom f =
    let accu = full in
    let accu = List.fold_left (fun accu x -> cap accu (atom x)) accu f.pos in
    let accu = List.fold_left (fun accu x -> diff accu (atom x)) accu f.neg in
    let accu = F.fold (fun f accu -> diff accu (compute_f full cap diff atom f)) f.subs accu in
    accu

  let compute ~empty ~full ~cup ~cap ~diff ~atom = function
    | Zero -> empty
    | One -> full
    | PosF f -> compute_f full cap diff atom f
    | NegF f -> diff full (compute_f full cap diff atom f)
    | PosV x -> atom x
    | NegV x -> diff full (atom x)

  let cup t1 t2 = neg (cap (neg t1) (neg t2))
  let diff t1 t2 = cap t1 (neg t2)

  let trivially_disjoint t1 t2 = (*cap t1 t2 == Zero*)
(* cap t1 t2 == Zero ?? *)
    match t1,t2 with
      | Zero, _ | _, Zero -> true
      | PosV x, NegV y | NegV x, PosV y -> X.equal x y
      | PosF f, PosF g -> trivially_disjoint f g
      | PosF f, NegF g | NegF g, PosF f -> trivially_subset f g
      | PosV x, PosF f -> V.mem f.neg x
      | NegV x, PosF f -> V.mem f.pos x
      | _ -> false
1395

1396 1397 1398 1399 1400 1401 1402
  let trivially_disjoint t1 t2 =
    let r = trivially_disjoint t1 t2 in
    if r && (t1 != Zero) && (t2 != Zero) then
      if trivially_disjoint t1 t2 then
	Format.fprintf Format.std_formatter
	  "DISJOINT: %a AND %a@." dump t1 dump t2;
    r
1403

1404

1405
  let rec serialize_f s f =
1406 1407
    V.serialize s f.pos;
    V.serialize s f.neg;
1408
    Serialize.Put.list serialize_f s (F.elements [] f.subs)
1409

1410
  let rec deserialize_f s =
1411 1412
    let pos = V.deserialize s in
    let neg = V.deserialize s in
1413 1414 1415 1416 1417 1418 1419