type_tallying.ml 26 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
open Types

let cap_t d t = cap d (descr t)

let cap_product any_left any_right l =
  List.fold_left
    (fun (d1,d2) (t1,t2) -> (cap_t d1 t1, cap_t d2 t2))
    (any_left,any_right)
    l
type constr =
  |Pos of (Var.var * Types.t) (** alpha <= t | alpha \in P *)
  |Neg of (Types.t * Var.var) (** t <= alpha | alpha \in N *)

exception UnSatConstr of string

module CS = struct

  let semantic_compare t1 t2 =
19 20 21 22 23 24 25
    let inf12 = Types.subtype t1 t2 in
    let inf21 = Types.subtype t2 t1 in
    if inf12 && inf21 then 0
    else if inf12 then -1 else if inf21 then 1 else
	let c = Types.compare t1 t2 in
	assert (c <> 0);
	c
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 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 590 591 592 593 594 595 596 597 598 599 600 601 602 603 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 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

    (* constraint set : map to store constraints of the form (s <= alpha <= t) *)
  module M = struct

    module Key = struct
      type t = Var.var
      let compare v1 v2 = Var.compare v1 v2
    end
    type key = Key.t
    module VarMap =  Map.Make(Key)
    type t = (Types.t * Types.t) VarMap.t
    let singleton = VarMap.singleton
    let cardinal = VarMap.cardinal

      (* a set of constraints m1 subsumes a set of constraints m2,
         that is the solutions for m1 contains all the solutions for
         m2 if:
         forall i1 <= v <= s1 in m1,
         there exists i2 <= v <= s2 in m2 such that i1 <= i2 <= v <= s2 <= s1
      *)
    let subsumes map1 map2 =
      VarMap.for_all (fun v (i1, s1) ->
        try let i2, s2 = VarMap.find v map2 in
            subtype i1 i2 && subtype s2 s1
        with Not_found -> false
      ) map1

    let pp ppf map =
      Utils.pp_list ~delim:("{","}") (fun ppf (v, (i,s)) ->
        Format.fprintf ppf "%a <= %a <= %a" Print.pp_type i Var.pp v Print.pp_type s
      ) ppf (VarMap.bindings map)

    let compare map1 map2 =
      VarMap.compare (fun (i1,s1) (i2,s2) ->
        let c = semantic_compare i1 i2 in
        if c == 0 then semantic_compare s1 s2
        else c) map1 map2

    let add delta v (inf, sup) map =
      let new_i, new_s =
        try
          let old_i, old_s = VarMap.find v map in
          cup old_i inf,
          cap old_s sup
        with
          Not_found -> inf, sup
      in
      if Var.Set.mem delta v then map
      else VarMap.add v (new_i, new_s) map

    let inter delta map1 map2 = VarMap.fold (add delta) map1 map2
    let fold = VarMap.fold
    let empty = VarMap.empty
    let for_all = VarMap.for_all
  end

    (* equation set : (s < alpha < t) stored as
       { alpha -> ((s v beta) ^ t) } with beta fresh *)
  module E = struct
    include Map.Make(struct
      type t = Var.var
      let compare = Var.compare
    end)

    let pp ppf e =
      Utils.pp_list ~delim:("{","}") (fun ppf -> fun (v,t) ->
        Format.fprintf ppf "%a = %a@," Var.pp v Print.pp_type t
      ) ppf (bindings e)

  end

    (* Set of equation sets *)
  module ES = struct
    include Set.Make(struct
      type t = Types.t E.t
      let compare = E.compare semantic_compare
    end)

    let pp ppf s = Utils.pp_list ~delim:("{","}") E.pp ppf (elements s)
  end

    (* Set of constraint sets *)
  module S = struct
      (* A set of constraint-sets is just a list of constraint-sets,
         that are pairwise "non-subsumable"
      *)

    type t = M.t list

    let elements t = t

    let empty = []

    let add m l =
      let rec loop m l acc =
        match l with
          [] -> m :: acc
        | mm :: ll ->
           if M.subsumes m mm then List.rev_append ll (m::acc)
           else if M.subsumes mm m then List.rev_append ll (mm::acc)
           else loop m ll (mm::acc)
      in
      loop m l []

    let singleton m = add m empty

    let pp ppf s = Utils.pp_list ~delim:("{","}") M.pp ppf s

    let fold f l a = List.fold_left (fun e a -> f a e) a l

    let is_empty l = l == []

      (* Square union : *)
    let union s1 s2 =
      match s1, s2 with
        [], _ -> s2
      | _, [] -> s1
      | _ ->
          (* Invariant: all elements of s1 (resp s2) are pairwise
             incomparable (they don't subsume one another)
             let e1 be an element of s1:
             - if e1 subsumes no element of s2, add e1 to the result
             - if e1 subsumes an element e2 of s2, add e1 to the
             result and remove e2 from s2

             - if an element e2 of s2 subsumes e1, add e2 to the
             result and remove e2 from s2 (and discard e1)

             once we are done for all e1, add the remaining elements from
             s2 to the result.
          *)

         let append e1 s2 result =
           let rec loop s2 accs2 =
             match s2 with
               [] -> accs2, e1::result
             | e2 :: ss2 ->
                if M.subsumes e1 e2 then List.rev_append ss2 accs2, e1::result
                else if M.subsumes e2 e1 then List.rev_append ss2 accs2, e2::result
                else loop ss2 (e2::accs2)
           in
           loop s2 []
         in
         let rec loop s1 s2 result =
           match s1 with
             [] -> List.rev_append s2 result
           | e1 :: ss1 ->
              let new_s2, new_result = append e1 s2 result in
              loop ss1 new_s2 new_result
         in
         loop s1 s2 []

      (* Square intersection *)
    let inter delta s1 s2 =
      match s1,s2 with
        [], _ | _, [] -> []
      | _ ->
          (* Perform the cartesian product. For each constraint m1 in s1,
             m2 in s2, we add M.inter m1 m2 to the result.
             Optimisations:
             - we use add to ensure that we do not add something that subsumes
             a constraint set that is already in the result
             - if m1 subsumes m2, it means that whenever m2 holds, so does m1, so
             we only add m2 (note that the condition is reversed w.r.t. union).
          *)
         fold (fun m1 acc1 ->
           fold (fun m2 acc2 ->
             let merged = if M.subsumes m1 m2 then m2
               else if M.subsumes m2 m1 then m1
               else M.inter delta m1 m2
             in
             add merged acc2
           )
             s2 acc1) s1 []
    let filter = List.filter
  end

  type s = S.t
  type m = M.t
  type es = ES.t
  type sigma = Types.t E.t
  module SUB = SortedList.FiniteCofinite(struct
    type t = Types.t E.t
    let compare = E.compare compare
    let equal = E.equal equal
    let hash = Hashtbl.hash
    let dump = E.pp
    let check _ = ()
  end)

  type sl = sigma list

  let singleton c =
    let constr =
      match c with
      |Pos (v,s) -> M.singleton v (empty,s)
      |Neg (s,v) -> M.singleton v (s,any)
    in
    S.singleton constr

  let pp_s = S.pp
  let pp_m = M.pp
  let pp_e = E.pp
  let pp_sl ppf ll = Utils.pp_list ~delim:("{","}") E.pp ppf ll

  let sat = S.singleton M.empty
  let unsat = S.empty

  let union = S.union
  let prod delta = S.inter delta
  let merge delta = M.inter delta
end

let normatoms (t,_,_) = if Atoms.is_empty t then CS.sat else CS.unsat
let normchars (t,_,_) = if Chars.is_empty t then CS.sat else CS.unsat
let normints (t,_,_) = if Intervals.is_empty t then CS.sat else CS.unsat
let normabstract (t,_,_) = if Abstracts.is_empty t then CS.sat else CS.unsat

let single_aux constr (b,v,p,n) =
  let aux f constr l =
    List.fold_left (fun acc ->
      function
      |`Var a -> cap acc (f(var a))
      |`Atm a -> cap acc (f(constr a))
    ) any l
  in
  let id = (fun x -> x) in
  let t = cap (aux id constr p) (aux neg constr n) in
    (* t = bigdisj ... alpha \in P --> alpha <= neg t *)
    (* t = bigdisj ... alpha \in N --> t <= alpha *)
  if b then (neg t) else t

let single_atoms = single_aux atom

let single_abstract = single_aux abstract

let single_chars = single_aux char

let single_ints = single_aux interval

let single_times = single_aux (fun p -> VarTimes.(inj (atom (`Atm p))))

let single_xml = single_aux (fun p -> VarXml.(inj (atom (`Atm p))))

let single_record = single_aux (fun p -> VarRec.(inj (atom (`Atm p))))

let single_arrow = single_aux (fun p -> VarArrow.(inj (atom (`Atm p))))

  (* check if there exists a toplevel variable : fun (pos,neg) *)
let toplevel delta single norm_rec mem p n =
  let _compare delta v1 v2 =
    let monov1 = Var.Set.mem delta v1 in
    let monov2 = Var.Set.mem delta v2 in
    if monov1 == monov2 then
      Var.compare v1 v2
    else
      if monov1 then 1 else -1
  in
  match (p,n) with
  |([], (`Var x)::neg) ->
     let t = single (false,x,[],neg) in
     CS.singleton (Neg (t, x))

  |((`Var x)::pos,[]) ->
     let t = single (true,x,pos,[]) in
     CS.singleton (Pos (x,t))

  |((`Var x)::pos, (`Var y)::neg) ->
     if _compare delta x y < 0 then
       let t = single (true,x,pos,n) in
       CS.singleton (Pos (x,t))
     else
       let t = single (false,y,p,neg) in
       CS.singleton (Neg (t, y))

  |([`Atm a], (`Var x)::neg) ->
     let t = single (false,x,p,neg) in
     CS.singleton (Neg (t,x))

  |([`Atm t], []) -> norm_rec (t,delta,mem)
  |_,_ -> assert false

let big_prod delta f acc l =
  List.fold_left (fun acc (pos,neg) ->
	(* if CS.S.is_empty acc then acc else *)
    CS.prod delta acc (f pos neg)
  ) acc l

  (* norm generates a constraint set for the costraint t <= 0 *)


module NormMemoHash = Hashtbl.Make(Custom.Pair(Descr)(Var.Set))

let memo_norm = NormMemoHash.create 17
let () = Format.pp_set_margin Format.err_formatter 100


let rec norm (t,delta,mem) =
  DEBUG normrec (
    Format.eprintf
      " @[Entering norm rec(%a):@\n" Print.pp_type t);
  let res =
    try
        (* If we find it in the global hashtable, we are finished *)
      let res = NormMemoHash.find memo_norm (t, delta) in
      DEBUG normrec (Format.eprintf
                       "@[ - Result found in global table @]@\n");
      res
    with
      Not_found ->
        try
          let finished, cst = NormMemoHash.find mem (t, delta) in
          DEBUG normrec (Format.eprintf
                           "@[ - Result found in local table, finished = %b @]@\n" finished);
          if finished then cst else CS.sat
        with
          Not_found ->
            begin
              let res =
                  (* base cases *)
                if is_empty t then begin
                  DEBUG normrec (Format.eprintf "@[ - Empty type case @]@\n");
                  CS.sat
                end else if no_var t then begin
                  DEBUG normrec (Format.eprintf "@[ - No var case @]@\n");
                  CS.unsat
                end else if is_var t then begin
                  let (v,p) = Variable.extract t in
                  if Var.Set.mem delta v then begin
                    DEBUG normrec (Format.eprintf "@[ - Monomorphic var case @]@\n");
                    CS.unsat (* if it is monomorphic, unsat *)
                  end else begin
                    DEBUG normrec (Format.eprintf "@[ - Polymorphic var case @]@\n");
                      (* otherwise, create a single constraint according to its polarity *)
                    let s = if p then (Pos (v,empty)) else (Neg (any,v)) in
                    CS.singleton s
                  end
                end else begin (* type is not empty and is not a variable *)
                  DEBUG normrec (Format.eprintf "@[ - Inductive case:@\n");
                  let mem = NormMemoHash.add mem (t,delta) (false, CS.sat); mem in
                  let t = Iter.simplify t in
                  let aux single norm_aux acc l =
                    big_prod delta (toplevel delta single norm_aux mem) acc l
                  in
                  let acc = aux single_atoms normatoms CS.sat VarAtoms.(get (proj t)) in
                  DEBUG normrec (Format.eprintf "@[ - After Atoms constraints: %a @]@\n" CS.pp_s acc);
                  let acc = aux single_chars normchars acc VarChars.(get (proj t)) in
                  DEBUG normrec (Format.eprintf "@[ - After Chars constraints: %a @]@\n" CS.pp_s acc);
                  let acc = aux single_ints normints acc VarIntervals.(get (proj t)) in
                  DEBUG normrec (Format.eprintf "@[ - After Ints constraints: %a @]@\n" CS.pp_s acc);
                  let acc = aux single_times normpair acc VarTimes.(get (proj t)) in
                  DEBUG normrec (Format.eprintf "@[ - After Times constraints: %a @]@\n" CS.pp_s acc);
                  let acc = aux single_xml normpair acc VarXml.(get (proj t)) in
                  DEBUG normrec (Format.eprintf "@[ - After Xml constraints: %a @]@\n" CS.pp_s acc);
                  let acc = aux single_arrow normarrow acc VarArrow.(get (proj t)) in
                  DEBUG normrec (Format.eprintf "@[ - After Arrow constraints: %a @]@\n" CS.pp_s acc);
                  let acc = aux single_abstract normabstract acc VarAbstracts.(get (proj t)) in
                  DEBUG normrec (Format.eprintf "@[ - After Abstract constraints: %a @]@\n" CS.pp_s acc);
                    (* XXX normrec is not tested at all !!! *)
                  let acc = aux single_record normrec acc VarRec.(get (proj t)) in
                  DEBUG normrec (Format.eprintf "@[ - After Record constraints: %a @]@\n" CS.pp_s acc);
                  let acc = (* Simplify the constraints on that type *)
                    CS.S.filter
                      (fun m -> CS.M.for_all (fun v (s, t) ->
                        if Var.Set.mem delta v then
                            (* constraint on a monomorphic variables must be trivial *)
                          let x = var v in subtype s x && subtype x t
                        else true (*
                                    subtype s t || (non_empty (cap s t)) *)
                       ) m)
                      acc
                  in
                  DEBUG normrec (Format.eprintf "@[ - After Filtering constraints: %a @]@\n" CS.pp_s acc);
                  DEBUG normrec (Format.eprintf "@]@\n");
                  acc
                end
              in
              NormMemoHash.replace mem (t, delta) (true,res); res
            end
  in
  DEBUG normrec (Format.eprintf
                   "Leaving norm rec(%a) = %a@]@\n%!"
                   Print.pp_type t
                   CS.pp_s res
  );
  res

  (* (t1,t2) = intersection of all (fst pos,snd pos) \in P
   * (s1,s2) \in N
   * [t1] v [t2] v ( [t1 \ s1] ^ [t2 \ s2] ^
   * [t1 \ s1 \ s1_1] ^ [t2 \ s2 \ s2_1 ] ^
   * [t1 \ s1 \ s1_1 \ s1_2] ^ [t2 \ s2 \ s2_1 \ s2_2 ] ^ ... )
   *
   * prod(p,n) = [t1] v [t2] v prod'(t1,t2,n)
   * prod'(t1,t2,{s1,s2} v n) = ([t1\s1] v prod'(t1\s1,t2,n)) ^
   *                            ([t2\s2] v prod'(t1,t2\s2,n))
   * *)
and normpair (t,delta,mem) =
  let norm_prod pos neg =
    let rec aux t1 t2 = function
      |[] -> CS.unsat
      |(s1,s2) :: rest -> begin
        let z1 = diff t1 (descr s1) in
        let z2 = diff t2 (descr s2) in
        let con1 = norm (z1, delta, mem) in
        let con2 = norm (z2, delta, mem) in
        let con10 = aux z1 t2 rest in
        let con20 = aux t1 z2 rest in
        let con11 = CS.union con1 con10 in
        let con22 = CS.union con2 con20 in
        CS.prod delta con11 con22
      end
    in
      (* cap_product return the intersection of all (fst pos,snd pos) *)
    let (t1,t2) = cap_product any any pos in
    let con1 = norm (t1, delta, mem) in
    let con2 = norm (t2, delta, mem) in
    let con0 = aux t1 t2 neg in
    CS.union (CS.union con1 con2) con0
  in
  big_prod delta norm_prod CS.sat (Pair.get t)

and normrec (t,delta,mem) =
  let norm_rec ((oleft,left),rights) =
    let rec aux accus seen = function
      |[] -> CS.sat
      |(false,_) :: rest when oleft -> aux accus seen rest
      |(b,field) :: rest ->
         let right = seen @ rest in
         snd (Array.fold_left (fun (i,acc) t ->
           let di = diff accus.(i) t in
           let accus' = Array.copy accus in accus'.(i) <- di ;
           (i+1,CS.prod delta acc (CS.prod delta (norm (di,delta,mem)) (aux accus' [] right)))
         ) (0,CS.sat) field
         )
    in
    let c = Array.fold_left (fun acc t -> CS.union (norm (t,delta,mem)) acc) CS.sat left in
    CS.prod delta (aux left [] rights) c
  in
  List.fold_left (fun acc (_,p,n) ->
    if CS.S.is_empty acc then acc else CS.prod delta acc (norm_rec (p,n))
  ) CS.sat (get_record t)

  (* arrow(p,{t1 -> t2}) = [t1] v arrow'(t1,any \ t2,p)
   * arrow'(t1,acc,{s1 -> s2} v p) =
   * ([t1\s1] v arrow'(t1\s1,acc,p)) ^
   * ([acc ^ {s2}] v arrow'(t1,acc ^ {s2},p))

   * t1 -> t2 \ s1 -> s2 =
   * [t1] v (([t1\s1] v {[]}) ^ ([t2\s2] v {[]}))

   * Bool -> Bool \ Int -> A =
   * [Bool] v (([Bool\Int] v {[]}) ^ ([Bool\A] v {[]})

   * P(Q v {a}) = {a} v P(Q) v {X v {a} | X \in P(Q) }
   *)
and normarrow (t,delta,mem) =
  let rec norm_arrow pos neg =
    match neg with
    |[] -> CS.unsat
    |(t1,t2) :: n ->
       let con1 = norm (descr t1, delta, mem) in (* [t1] *)
       let con2 = aux (descr t1) (diff any (descr t2)) pos in
       let con0 = norm_arrow pos n in
       CS.union (CS.union con1 con2) con0
  and aux t1 acc = function
    |[] -> CS.unsat
    |(s1,s2) :: p ->
       let t1s1 = diff t1 (descr s1) in
       let acc1 = cap acc (descr s2) in
       let con1 = norm (t1s1, delta, mem) in (* [t1 \ s1] *)
       let con2 = norm (acc1, delta, mem) in (* [(Any \ t2) ^ s2] *)
       let con10 = aux t1s1 acc p in
       let con20 = aux t1 acc1 p in
       let con11 = CS.union con1 con10 in
       let con22 = CS.union con2 con20 in
       CS.prod delta con11 con22
  in
  big_prod delta norm_arrow CS.sat (Pair.get t)



let norm delta t =
  try NormMemoHash.find memo_norm (t,delta)
  with Not_found -> begin
    let res = norm (t,delta,NormMemoHash.create 17) in
    NormMemoHash.add memo_norm (t,delta) res; res
  end

  (* merge needs delta because it calls norm recursively *)
let rec merge m delta cache =
  let res =
    CS.M.fold (fun v (inf, sup) acc ->
        (* no need to add new constraints *)
      if subtype inf sup  then acc
      else
        let x = diff inf sup in
        if Cache.lookup x cache != None then acc
        else
          let cache, _ = Cache.find ignore x cache in
          let n = norm delta x in
          if CS.S.is_empty n then
            raise (UnSatConstr "merge2");
          let c1 = CS.prod delta (CS.S.singleton m) n
          in
          let c2 =
            CS.S.fold
              (fun m1 acc ->
                CS.union acc (merge m1 delta cache))
              c1 CS.S.empty
          in
          CS.union c2 acc
    ) m CS.S.empty
  in
  if CS.S.is_empty res then CS.S.singleton m else res

let merge delta m = merge m delta Cache.emp

  (* Add constraints of the form { alpha = ( s v fresh ) ^ t } *)

let solve delta s =

  let aux alpha (s,t) acc =
      (* we cannot solve twice the same variable *)
    assert(not(CS.E.mem alpha acc));
    let v = Var.mk (Printf.sprintf "#fr_%s" (Var.id alpha)) in
    let b = var v in
      (* s <= alpha <= t --> alpha = ( s v fresh ) ^ t *)
    CS.E.add alpha (cap (cup s b) t) acc
  in
  let aux1 m =
    let cache = Hashtbl.create 17 in
    CS.M.fold (fun alpha (s,t) acc ->
      if Hashtbl.mem cache alpha then acc else begin
        Hashtbl.add cache alpha ();
          (* if t containts only a toplevel variable and nothing else
           * means that the constraint is of the form (alpha,beta). *)
        if is_var t then begin
          let (beta,_) = Variable.extract t in
          if Var.Set.mem delta beta then aux alpha (s, t) acc
          else
            let acc1 = aux beta (empty,any) acc in
              (* alpha <= beta --> { empty <= alpha <= beta ; empty <= beta <= any } *)
            aux alpha (s,t) acc1
        end else
            (* alpha = ( s v fresh) ^ t *)
          aux alpha (s,t) acc;
      end
    ) m CS.E.empty
  in
  CS.S.fold (fun m acc -> CS.ES.add (aux1 m) acc) s CS.ES.empty

let unify e =
  let rec aux sol e =
      (* Format.printf "e = %a\n" CS.print_e e; *)
    if CS.E.is_empty e then sol
    else begin
      let (alpha,t) = CS.E.min_binding e in
        (* Format.printf "Unify -> %a = %a\n" Var.pp alpha Print.pp_type t; *)
      let e1 = CS.E.remove alpha e in
        (* Format.printf "e1 = %a\n" CS.print_e e1; *)
        (* remove from E \ { (alpha,t) } every occurrences of alpha
         * by mu X . (t{X/alpha}) with X fresh . X is a recursion variale *)
        (* solve_rectype remove also all previously introduced fresh variables *)
      let x = Substitution.solve_rectype t alpha in
        (* Format.printf "X = %a %a %a\n" Var.pp alpha Print.print x dump t; *)
      let es =
        CS.E.fold (fun beta s acc ->
          CS.E.add beta (Substitution.single s (alpha,x)) acc
        ) e1 CS.E.empty
      in
        (* Format.printf "es = %a\n" CS.print_e es; *)
      let sigma = aux ((CS.E.add alpha x sol)) es in
      let talpha = CS.E.fold (fun v sub acc -> Substitution.single acc (v,sub)) sigma x in
      CS.E.add alpha talpha sigma
    end
  in
    (* Format.printf "Begin e = %a\n" CS.print_e e; *)
  let r = aux CS.E.empty e in
    (* Format.printf "r = %a\n" CS.print_e r; *)
  r

exception Step1Fail
exception Step2Fail

let tallying delta l =
  let n =
    List.fold_left (fun acc (s,t) ->
      let d = diff s t in
      if is_empty d then CS.sat
      else if no_var d then CS.unsat
      else CS.prod delta acc (norm delta d)
    ) CS.sat l
  in
  if Pervasives.(n = CS.unsat) then raise Step1Fail else
    let m =
      CS.S.fold (fun c acc ->
        try CS.ES.union (solve delta (merge delta c)) acc
        with UnSatConstr _ -> acc
      ) n CS.ES.empty
    in
    if CS.ES.is_empty m then raise Step2Fail else
      let el =
	CS.ES.fold (fun e acc -> CS.ES.add (unify e) acc ) m CS.ES.empty
      in
      (CS.ES.elements el)

  (* apply sigma to t *)
let (>>) t si = CS.E.fold (fun v sub acc -> Substitution.single acc (v,sub)) si t

type symsubst = I | S of CS.sigma | A of (symsubst * symsubst)

let rec dom = function
  |I -> Var.Set.empty
  |S si -> CS.E.fold (fun v _ acc -> Var.Set.add v acc) si Var.Set.empty
  |A (si,sj) -> Var.Set.cup (dom si) (dom sj)

  (* composition of two symbolic substitution sets sigmaI, sigmaJ .
     Cartesian product *)
let (++) sI sJ =
  let bind m f = List.flatten(List.map f m) in
  bind sI (fun si ->
    bind sJ (fun sj ->
      [A(si,sj)]
    )
  )

  (* apply a symbolic substitution si to a type t *)
let (@@) t si =
  let vst = ref Var.Set.empty in
  let vsi = ref Var.Set.empty in
  let get e = CS.E.fold (fun v _ acc -> Var.Set.add v acc) e Var.Set.empty in
  let filter t si =
    vsi := get si;
    vst := all_vars t;
    not(Var.Set.is_empty (Var.Set.cap !vst !vsi))
  in
  let filterdiff t si sj =
    let vsj = get sj in
    not(Var.Set.is_empty (Var.Set.cap !vst (Var.Set.diff !vsi vsj)))
  in
  let rec aux t = function
    |I -> t
    |S si -> t >> si
    |A (S si,_) when filter t si -> t >> si
    |A (S si,S sj) when filterdiff t si sj -> (t >> sj) >> si
    |A (si,sj) -> aux (aux t sj) si
  in
  aux t si

let domain sl =
  List.fold_left (fun acc si ->
    CS.E.fold (fun v _ acc ->
      Var.Set.add v acc
    ) si acc
  ) Var.Set.empty sl

let codomain ll =
  List.fold_left (fun acc e ->
    CS.E.fold (fun _ v acc ->
      Var.Set.cup (all_vars v) acc
    ) e acc
  ) Var.Set.empty ll

let is_identity = List.for_all (CS.E.is_empty)
let identity = [CS.E.empty]

let filter f sl =
  if is_identity sl then sl else
    List.fold_left (fun acc si ->
      let e = CS.E.filter (fun v _ -> f v) si in
      if CS.E.is_empty e then acc else e::acc
    ) [] sl



let set a i v =
  let len = Array.length !a in
  if i <  len then (!a).(i) <- v
  else begin
    let b = Array.make (2*len+1) empty in
    Array.blit !a 0 b 0 len;
    b.(i) <- v;
    a := b
  end
let get a i = if i < 0 then any else (!a).(i)

exception FoundSquareSub of CS.sl

let squaresubtype delta s t =
  NormMemoHash.clear memo_norm;
  let ai = ref [| |] in
  let tallying i =
    try
      let s = get ai i in
      let sl = tallying delta [ (s,t) ] in
      raise (FoundSquareSub sl)
    with
      Step1Fail -> (assert (i == 0); raise (UnSatConstr "apply_raw step1"))
    | Step2Fail -> () (* continue *)
  in
  let rec loop i =
    try
      let ss =
        if i = 0 then s
        else (cap (Substitution.freshen delta s) (get ai (i-1)))
      in
      set ai i ss;
      tallying i;
      loop (i+1)
    with FoundSquareSub sl -> sl
  in
  loop 0

let is_squaresubtype delta s t =
  try ignore(squaresubtype delta s t);true with UnSatConstr _ -> false

exception FoundApply of t * int * int * CS.sl

(** find two sets of type substitutions I,J such that
    s @@ sigma_i < t @@ sigma_j for all i \in I, j \in J *)

let apply_raw delta s t =
  DEBUG apply_raw (Format.eprintf " @[Entering apply_raw (delta:@[%a@], @[%a@], @[%a@])@\n%!"
                     Var.Set.pp delta
                     Print.pp_type s
                     Print.pp_type t
  );

  NormMemoHash.clear memo_norm;
  let s = Substitution.kind delta Var.function_kind s in
757
  let t = Substitution.kind delta Var.argument_kind t in 
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
  let vgamma = Var.mk "Gamma" in
  let gamma = var vgamma in
  let cgamma = cons gamma in
  (* cell i of ai contains /\k<=i s_k, cell j of aj contains /\k<=j t_k *)
  let ai = ref [| |]
  and aj = ref [| |] in
  let tallying i j  =
    try
      let s = get ai i in
      let t = arrow (cons (get aj j)) cgamma in
      let sl = tallying delta [ (s,t) ] in
      let new_res =
        Substitution.clean_type delta (
          List.fold_left (fun tacc si ->
            cap tacc ((gamma >> si))
          ) any sl
        )
      in
      raise (FoundApply(new_res,i,j,sl))
    with
      Step1Fail -> (assert (i == 0 &&  j == 0); raise (UnSatConstr "apply_raw step1"))
    | Step2Fail -> () (* continue *)
  in
  let rec loop i =
    try
      (* Format.printf "Starting expansion %i @\n@." i; *)
      let (ss,tt) =
        if i = 0 then (s,t) else
          ((cap (Substitution.freshen delta s) (get ai (i-1))),
           (cap (Substitution.freshen delta t) (get aj (i-1))))
      in
      set ai i ss;
      set aj i tt;
      for j = 0 to i-1 do
        tallying j i;
        tallying i j;
      done;
      tallying i i;
      loop (i+1)
    with FoundApply (res, i, j, sl) ->
      DEBUG apply_raw (Format.eprintf " Leaving apply_raw (delta:@[%a@], @[%a@], @[%a@]) = @[%a@], @[%a@] @]@\n%!"
                         Var.Set.pp delta
                         Print.pp_type s
                         Print.pp_type t
                         Print.pp_type res
                         CS.pp_sl sl
      );
      (sl, get ai i, get aj j, res)
  in
  loop 0

let apply_full delta s t =
  let _,_,_,res = apply_raw delta s t in
  res

let squareapply delta s t = let s,_,_,res = apply_raw delta s t in (s,res)