types.ml 26.7 KB
Newer Older
1 2 3 4
open Recursive
open Printf


5 6
let map_sort f l =
  SortedList.from_list (List.map f l)
7

8 9 10 11 12 13
module HashedString = 
struct 
  type t = string 
  let hash = Hashtbl.hash
  let equal = (=)
end
14

15 16
module LabelPool = Pool.Make(HashedString)
module AtomPool  = Pool.Make(HashedString)
17

18 19
type label = LabelPool.t
type atom  = AtomPool.t
20

21
type const = Integer of Big_int.big_int | Atom of atom | Char of Chars.Unichar.t
22 23 24 25 26 27 28 29

module I = struct
  type 'a t = {
    ints  : Intervals.t;
    atoms : atom Atoms.t;
    times : ('a * 'a) Boolean.t;
    arrow : ('a * 'a) Boolean.t;
    record: (label * bool * 'a) Boolean.t;
30
    chars : Chars.t;
31
  }
32

33 34 35 36 37 38
  let empty = { 
    times = Boolean.empty; 
    arrow = Boolean.empty; 
    record= Boolean.empty;
    ints  = Intervals.empty;
    atoms = Atoms.empty;
39
    chars = Chars.empty;
40
  }
41

42 43 44 45
  let any =  {
    times = Boolean.full; 
    arrow = Boolean.full; 
    record= Boolean.full; 
46
    ints  = Intervals.any;
47 48
    atoms = Atoms.any;
    chars = Chars.any;
49 50
  }
	       
51
  let interval i = { empty with ints = i }
52 53 54
  let times x y = { empty with times = Boolean.atom (x,y) }
  let arrow x y = { empty with arrow = Boolean.atom (x,y) }
  let record label opt t = { empty with record = Boolean.atom (label,opt,t) }
55 56
  let atom a = { empty with atoms = a }
  let char c = { empty with chars = c }
57
  let constant = function
58
    | Integer i -> interval (Intervals.atom i)
59 60
    | Atom a -> atom (Atoms.atom a)
    | Char c -> char (Chars.atom c)
61 62 63 64

		   
  let any_record = { empty with record = any.record }

65
  let cup x y = 
66
    if x = y then x else { 
67 68 69 70 71
      times = Boolean.cup x.times y.times;
      arrow = Boolean.cup x.arrow y.arrow;
      record= Boolean.cup x.record y.record;
      ints  = Intervals.cup x.ints  y.ints;
      atoms = Atoms.cup x.atoms y.atoms;
72
      chars = Chars.cup x.chars y.chars;
73 74 75
    }
      
  let cap x y = 
76
    if x = y then x else {
77 78 79 80 81
      times = Boolean.cap x.times y.times;
      record= Boolean.cap x.record y.record;
      arrow = Boolean.cap x.arrow y.arrow;
      ints  = Intervals.cap x.ints  y.ints;
      atoms = Atoms.cap x.atoms y.atoms;
82
      chars = Chars.cap x.chars y.chars;
83 84 85
    }
      
  let diff x y = 
86
    if x = y then empty else { 
87 88 89 90 91
      times = Boolean.diff x.times y.times;
      arrow = Boolean.diff x.arrow y.arrow;
      record= Boolean.diff x.record y.record;
      ints  = Intervals.diff x.ints  y.ints;
      atoms = Atoms.diff x.atoms y.atoms;
92
      chars = Chars.diff x.chars y.chars;
93 94
    }

95 96 97 98
  let neg x = diff any x
		   
  let equal e a b =
    if a.atoms <> b.atoms then raise NotEqual;
99
    if a.chars <> b.chars then raise NotEqual;
100
    if a.ints <> b.ints then raise NotEqual;
101 102 103 104 105 106 107 108 109 110 111 112
    Boolean.equal (fun (x1,x2) (y1,y2) -> e x1 y1; e x2 y2) a.times b.times;
    Boolean.equal (fun (x1,x2) (y1,y2) -> e x1 y1; e x2 y2) a.arrow b.arrow;
    Boolean.equal (fun (l1,o1,x1) (l2,o2,x2) -> 
		     if (l1 <> l2) || (o1 <> o2) then raise NotEqual;
		     e x1 x2) a.record b.record
      
  let map f a =
    { times = Boolean.map (fun (x1,x2) -> (f x1, f x2)) a.times;
      arrow = Boolean.map (fun (x1,x2) -> (f x1, f x2)) a.arrow;
      record= Boolean.map (fun (l,o,x) -> (l,o, f x)) a.record;
      ints  = a.ints;
      atoms = a.atoms;
113
      chars = a.chars;
114 115 116
    }
    
  let hash h a =
117 118
    Hashtbl.hash (map h a)
(*
119
    (Hashtbl.hash { (map h a) with ints = Intervals.empty })
120
    + (Intervals.hash a.ints)
121
*)
122 123 124
      
  let iter f a =
    ignore (map f a)
125
     
126 127 128 129
  let deep = 4
end

	     
130
module Algebra = Recursive_noshare.Make(I)
131 132
include I
include Algebra
133 134 135 136 137 138 139 140 141 142
module DescrHash = 
  Hashtbl.Make(
    struct 
      type t = descr
      let hash = hash_descr
      let equal = equal_descr
    end
  )

module DescrMap = Map.Make(struct type t = descr let compare = compare end)
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

let check d =
  Boolean.check d.times;
  Boolean.check d.arrow;
  Boolean.check d.record;
  ()

(*
let define n d = check d; define n d
*)

let cons d =
  let n = make () in
  define n d;
  internalize n


160 161
module Print = 
struct
162 163
  let print_atom ppf a = 
    Format.fprintf ppf "`%s" (AtomPool.value a)
164 165 166 167 168 169

  let print_const ppf = function
    | Integer i -> Format.fprintf ppf "%s" (Big_int.string_of_big_int i)
    | Atom a -> print_atom ppf a
    | Char c -> Chars.Unichar.print ppf c

170 171 172
  let named = State.ref "Types.Printf.named" DescrMap.empty
  let register_global name d = 
    named := DescrMap.add d name !named
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

  let marks = DescrHash.create 63
  let wh = ref []
  let count_name = ref 0
  let name () =
    incr count_name;
    "X" ^ (string_of_int !count_name)
(* TODO: 
   check that these generated names does not conflict with declared types *)

  let bool_iter f b =
    List.iter (fun (p,n) -> List.iter f p; List.iter f n) b

  let trivial b = b = Boolean.empty || b = Boolean.full

  let worth_abbrev d = 
    not (trivial d.times && trivial d.arrow && trivial d.record) 

  let rec mark n = mark_descr (descr n)
  and mark_descr d =
193
    if not (DescrMap.mem d !named) then
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
      try 
	let r = DescrHash.find marks d in
	if (!r = None) && (worth_abbrev d) then 
	  let na = name () in 
	  r := Some na;
	  wh := (na,d) :: !wh
      with Not_found -> 
	DescrHash.add marks d (ref None);
    	bool_iter (fun (n1,n2) -> mark n1; mark n2) d.times;
    	bool_iter (fun (n1,n2) -> mark n1; mark n2) d.arrow;
    	bool_iter (fun (l,o,n) -> mark n) d.record

    
  let rec print_union ppf = function
    | [] -> Format.fprintf ppf "Empty"
    | [h] -> h ppf
    | h::t -> Format.fprintf ppf "@[%t |@ %a@]" h print_union t


  let rec print ppf n = print_descr ppf (descr n)
  and print_descr ppf d = 
    try 
216
      let name = DescrMap.find d !named in
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
      Format.fprintf ppf "%s" name
    with Not_found ->
      try
      	match !(DescrHash.find marks d) with
      	  | Some n -> Format.fprintf ppf "%s" n
      	  | None -> real_print_descr ppf d
      with
	  Not_found -> Format.fprintf ppf "XXX"
  and real_print_descr ppf d = 
    if d = any then Format.fprintf ppf "Any" else
      print_union ppf 
	(Intervals.print d.ints @
	 Chars.print d.chars @
	 Atoms.print "Atom" print_atom d.atoms @
	 Boolean.print "Pair" print_times d.times @
	 Boolean.print "Arrow" print_arrow d.arrow @
	 Boolean.print "Record" print_record d.record
	)
  and print_times ppf (t1,t2) =
    Format.fprintf ppf "@[(%a,%a)@]" print t1 print t2
  and print_arrow ppf (t1,t2) =
    Format.fprintf ppf "@[(%a -> %a)@]" print t1 print t2
  and print_record ppf (l,o,t) =
    Format.fprintf ppf "@[{ %s =%s %a }@]" 
241
      (LabelPool.value l) (if o then "?" else "") print t
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

	  
  let end_print ppf =
    (match List.rev !wh with
       | [] -> ()
       | (na,d)::t ->
	   Format.fprintf ppf " where@ @[%s = %a" na real_print_descr d;
	   List.iter 
	     (fun (na,d) -> 
		Format.fprintf ppf " and@ %s = %a" na real_print_descr d)
	     t;
	   Format.fprintf ppf "@]"
    );
    Format.fprintf ppf "@]";
    count_name := 0;
    wh := [];
    DescrHash.clear marks

  let print_descr ppf d =
    mark_descr d;
    Format.fprintf ppf "@[%a" print_descr d;
    end_print ppf

   let print ppf n = print_descr ppf (descr n)

end



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
module Positive =
struct
  type rhs = [ `Type of descr | `Cup of v list | `Times of v * v ]
  and v = { mutable def : rhs; mutable node : node option }


  let rec make_descr seen v =
    if List.memq v seen then empty
    else
      let seen = v :: seen in
      match v.def with
	| `Type d -> d
	| `Cup vl -> 
	    List.fold_left (fun acc v -> cup acc (make_descr seen v)) empty vl
	| `Times (v1,v2) -> times (make_node v1) (make_node v2)

  and make_node v =
    match v.node with
      | Some n -> n
      | None ->
	  let n = make () in
	  v.node <- Some n;
	  let d = make_descr [] v in
	  define n d;
	  n

  let forward () = { def = `Cup []; node = None }
  let def v d = v.def <- d
  let cons d = let v = forward () in def v d; v
  let ty d = cons (`Type d)
  let cup vl = cons (`Cup vl)
  let times d1 d2 = cons (`Times (d1,d2))
  let define v1 v2 = def v1 (`Cup [v2]) 

  let solve v = internalize (make_node v)
end


let get_record r =
  let add = SortedMap.add (fun (o1,t1) (o2,t2) -> (o1&&o2, cap t1 t2)) in
  let line (p,n) =
    let accu = List.fold_left 
		 (fun accu (l,o,t) -> add l (o,descr t) accu) [] p in
    List.fold_left 
      (fun accu (l,o,t) -> add l (not o,neg (descr t)) accu) accu n in
  List.map line r
    


(* Subtyping algorithm *)

let diff_t d t = diff d (descr t)
let cap_t d t = cap d (descr t)
324
let cup_t d t = cup d (descr t)
325 326 327 328 329
let cap_product l = 
  List.fold_left 
    (fun (d1,d2) (t1,t2) -> (cap_t d1 t1, cap_t d2 t2))
    (any,any)
    l
330 331 332 333 334
let cup_product l = 
  List.fold_left 
    (fun (d1,d2) (t1,t2) -> (cup_t d1 t1, cup_t d2 t2))
    (empty,empty)
    l
335 336 337 338 339 340 341 342 343 344 345 346 347 348


module Assumptions = Set.Make(struct type t = descr let compare = compare end)

let memo = ref Assumptions.empty
let cache_false = ref Assumptions.empty

exception NotEmpty

let rec empty_rec d =
  if Assumptions.mem d !cache_false then false 
  else if Assumptions.mem d !memo then true
  else if not (Intervals.is_empty d.ints) then false
  else if not (Atoms.is_empty d.atoms) then false
349
  else if not (Chars.is_empty d.chars) then false
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
  else (
    let backup = !memo in
    memo := Assumptions.add d backup;
    if 
      (empty_rec_times d.times) &&
      (empty_rec_arrow d.arrow) &&
      (empty_rec_record d.record) 
    then true
    else (
      memo := backup;
      cache_false := Assumptions.add d !cache_false;
      false
    )
  )

and empty_rec_times c =
  List.for_all empty_rec_times_aux c

and empty_rec_times_aux (left,right) =
  let rec aux accu1 accu2 = function
    | (t1,t2)::right ->
        let accu1' = diff_t accu1 t1 in
        if not (empty_rec accu1') then aux accu1' accu2 right;
        let accu2' = diff_t accu2 t2 in
        if not (empty_rec accu2') then aux accu1 accu2' right
    | [] -> raise NotEmpty
  in
  let (accu1,accu2) = cap_product left in
  (empty_rec accu1) || (empty_rec accu2) ||
379 380 381 382 383 384 385 386 387 388
(* OPT? It does'nt seem so ...  The hope was to return false quickly
   for large right hand-side *)
  (
    ((*if (List length right > 2) then
       let (cup1,cup2) = cup_product right in
       (empty_rec (diff accu1 cup1)) && (empty_rec (diff accu2 cup2))
     else*) true)
    && 
    (try aux accu1 accu2 right; true with NotEmpty -> false)
  )
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

and empty_rec_arrow c =
  List.for_all empty_rec_arrow_aux c

and empty_rec_arrow_aux (left,right) =
  let single_right (s1,s2) =
    let rec aux accu1 accu2 = function
      | (t1,t2)::left ->
          let accu1' = diff_t accu1 t1 in
          if not (empty_rec accu1') then aux accu1 accu2 left;
          let accu2' = cap_t accu2 t2 in
          if not (empty_rec accu2') then aux accu1 accu2 left
      | [] -> raise NotEmpty
    in
    let accu1 = descr s1 in
    (empty_rec accu1) ||
    (try aux accu1 (diff any (descr s2)) left; true with NotEmpty -> false)
  in
  List.exists single_right right

and empty_rec_record c =
  let aux = List.exists (fun (_,(opt,t)) -> (not opt) && (empty_rec t)) in
  List.for_all aux (get_record c)

let is_empty d =
414
  let old = !memo in
415
  let r = empty_rec d in
416
  if not r then memo := old; 
417
(*  cache_false := Assumptions.empty;  *)
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  r

let non_empty d = 
  not (is_empty d)

let subtype d1 d2 =
  is_empty (diff d1 d2)

(* Sample value *)
module Sample =
struct

let rec find f = function
  | [] -> raise Not_found
  | x::r -> try f x with Not_found -> find f r

type t =
435
  | Int of Big_int.big_int
436
  | Atom of atom
437
  | Char of Chars.Unichar.t
438 439 440 441 442 443 444 445
  | Pair of t * t
  | Record of (label * t) list
  | Fun of (node * node) list

let rec sample_rec memo d =
  if (Assumptions.mem d memo) || (is_empty d) then raise Not_found 
  else 
    try Int (Intervals.sample d.ints) with Not_found ->
446 447 448
    try Atom (Atoms.sample (fun _ -> AtomPool.dummy_min) d.atoms) with 
	Not_found ->
(* Here: could create a fresh atom ... *)
449
    try Char (Chars.sample d.chars) with Not_found ->
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
    try sample_rec_arrow d.arrow with Not_found ->

    let memo = Assumptions.add d memo in
    try sample_rec_times memo d.times with Not_found ->
    try sample_rec_record memo d.record with Not_found -> 
    raise Not_found


and sample_rec_times memo c = 
  find (sample_rec_times_aux memo) c

and sample_rec_times_aux memo (left,right) =
  let rec aux accu1 accu2 = function
    | (t1,t2)::right ->
        let accu1' = diff_t accu1 t1 in
        if non_empty accu1' then aux accu1' accu2 right else
          let accu2' = diff_t accu2 t2 in
          if non_empty accu2' then aux accu1 accu2' right else
	    raise Not_found
    | [] -> Pair (sample_rec memo accu1, sample_rec memo accu2)
  in
  let (accu1,accu2) = cap_product left in
  if (is_empty accu1) || (is_empty accu2) then raise Not_found;
  aux accu1 accu2 right

and sample_rec_arrow c =
  find sample_rec_arrow_aux c

478 479 480 481 482 483 484 485
and check_empty_simple_arrow_line left (s1,s2) = 
  let rec aux accu1 accu2 = function
    | (t1,t2)::left ->
        let accu1' = diff_t accu1 t1 in
        if non_empty accu1' then aux accu1 accu2 left;
        let accu2' = cap_t accu2 t2 in
        if non_empty accu2' then aux accu1 accu2 left
    | [] -> raise NotEmpty
486
  in
487 488 489 490 491 492 493 494 495
  let accu1 = descr s1 in
  (is_empty accu1) ||
  (try aux accu1 (diff any (descr s2)) left; true with NotEmpty -> false)

and check_empty_arrow_line left right = 
  List.exists (check_empty_simple_arrow_line left) right

and sample_rec_arrow_aux (left,right) =
  if (check_empty_arrow_line left right) then raise Not_found
496 497 498 499 500 501 502 503 504 505 506
  else Fun left


and sample_rec_record memo c =
  Record (find (sample_rec_record_aux memo) (get_record c))

and sample_rec_record_aux memo fields =
  let aux acc (l,(o,t)) = if o then acc else (l, sample_rec memo t) :: acc in
  List.fold_left aux [] fields

let get x = sample_rec Assumptions.empty x
507

508 509 510 511 512 513 514 515
  let rec print_sep f sep ppf = function
    | [] -> ()
    | [x] -> f ppf x
    | x::rem -> f ppf x; Format.fprintf ppf "%s" sep; print_sep f sep ppf rem


  let rec print ppf = function
    | Int i -> Format.fprintf ppf "%s" (Big_int.string_of_big_int i)
516 517 518 519 520
    | Atom a ->    
	if a = LabelPool.dummy_min then
	  Format.fprintf ppf "(almost any atom)"
	else
	  Format.fprintf ppf "`%s" (AtomPool.value a)
521 522 523 524 525 526 527
    | Char c -> Chars.Unichar.print ppf c
    | Pair (x1,x2) -> Format.fprintf ppf "(%a,%a)" print x1 print x2
    | Record r ->
	Format.fprintf ppf "{ %a }"
	  (print_sep 
	     (fun ppf (l,x) -> 
		Format.fprintf ppf "%s = %a"
528
		(LabelPool.value l)
529 530 531 532 533 534 535 536 537 538 539 540 541
		print x
	     )
	     " ; "
	  ) r
    | Fun iface ->
	Format.fprintf ppf "(fun ( %a ) x -> ...)"
	  (print_sep
	     (fun ppf (t1,t2) ->
		Format.fprintf ppf "%a -> %a; "
		Print.print t1 Print.print t2
	     )
	     " ; "
	  ) iface
542 543 544 545 546 547 548
end


module Product =
struct
  type t = (descr * descr) list

549 550 551
  let other d = { d with times = empty.times }
  let is_product d = is_empty (other d)

552 553
  let need_second = function _::_::_ -> true | _ -> false

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
  let normal_aux d =
    let res = ref [] in

    let add (t1,t2) =
      let rec loop t1 t2 = function
	| [] -> res := (ref (t1,t2)) :: !res
	| ({contents = (d1,d2)} as r)::l ->
	    (*OPT*) 
	    if d1 = t1 then r := (d1,cup d2 t2) else
	      
	      let i = cap t1 d1 in
	      if is_empty i then loop t1 t2 l
	      else (
		r := (i, cup t2 d2);
		let k = diff d1 t1 in 
		if non_empty k then res := (ref (k,d2)) :: !res;
		
		let j = diff t1 d1 in 
		if non_empty j then loop j t2 l
	      )
      in
      loop t1 t2 !res
    in
    List.iter add d;
    List.map (!) !res

(*
This version explodes when dealing with
   Any - [ t1? t2? t3? ... tn? ]
==> need partitioning 
*)
  let get_aux d =
586
    let line accu (left,right) =
587
      let debug = List.length right = 28 in
588 589 590 591 592 593 594 595 596
      let rec aux accu d1 d2 = function
	| (t1,t2)::right ->
	    let accu = 
	      let d1 = diff_t d1 t1 in
              if is_empty d1 then accu else aux accu d1 d2 right in
	    let accu =
              let d2 = diff_t d2 t2 in
              if is_empty d2 then accu else aux accu d1 d2 right in
	    accu
597
	| [] -> (d1,d2) :: accu
598 599 600 601
      in
      let (d1,d2) = cap_product left in
      if (is_empty d1) || (is_empty d2) then accu else aux accu d1 d2 right
    in
602 603
    List.fold_left line [] d

604 605 606 607 608 609 610
(* Partitioning:

(t,s) - ((t1,s1) | (t2,s2) | ... | (tn,sn))
=
(t & t1, s - s1) | ... | (t & tn, s - sn) | (t - (t1|...|tn), s)

*)
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

  let get_aux d =
    let accu = ref [] in
    let line (left,right) =
      let (d1,d2) = cap_product left in
      if (non_empty d1) && (non_empty d2) then
	let right = List.map (fun (t1,t2) -> descr t1, descr t2) right in
	let right = normal_aux right in
	let resid1 = ref d1 in
	let () = 
	  List.iter
	    (fun (t1,t2) ->
	       let t1 = cap d1 t1 in
	       if (non_empty t1) then
		 let () = resid1 := diff !resid1 t1 in
		 let t2 = diff d2 t2 in
		 if (non_empty t2) then accu := (t1,t2) :: !accu
	    ) right in
	if non_empty !resid1 then accu := (!resid1, d2) :: !accu 
    in
    List.iter line d;
    !accu

  let get d = get_aux d.times
635 636 637 638 639 640 641 642 643 644 645

  let pi1 = List.fold_left (fun acc (t1,_) -> cup acc t1) empty
  let pi2 = List.fold_left (fun acc (_,t2) -> cup acc t2) empty

  let restrict_1 rects pi1 =
    let aux accu (t1,t2) = 
      let t1 = cap t1 pi1 in if is_empty t1 then accu else (t1,t2)::accu in
    List.fold_left aux [] rects
  
  type normal = t

646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
  module Memo = Map.Make(struct 
			   type t = (node * node) Boolean.t
			   let compare = compare end)
			   


  let memo = ref Memo.empty
  let normal d = 
    let d = d.times in
    try Memo.find d !memo 
    with
	Not_found ->
	  let gd = get_aux d in
	  let n = normal_aux gd in
	  memo := Memo.add d n !memo;
	  n
662 663

  let any = { empty with times = any.times }
664
  let is_empty d = d = []
665 666 667 668 669 670 671 672 673 674 675 676
end


module Record = 
struct
  type t = (label, (bool * descr)) SortedMap.t list

  let get d =
    let line r = List.for_all (fun (l,(o,d)) -> o || non_empty d) r in
    List.filter line (get_record d.record)

  let restrict_label_present t l =
677 678 679 680 681 682 683
    let restr = function 
      | (true, d) -> if non_empty d then (false,d) else raise Exit 
      | x -> x in
    let aux accu r =  
      try SortedMap.change l restr (false,any) r :: accu
      with Exit -> accu in
    List.fold_left aux [] t
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

  let restrict_label_absent t l =
    let restr = function (true, _) -> (true,empty) | _ -> raise Exit in
    let aux accu r =  
      try SortedMap.change l restr (true,empty) r :: accu
      with Exit -> accu in
    List.fold_left aux [] t

  let restrict_field t l d =
    let restr (_,d1) = 
      let d1 = cap d d1 in 
      if is_empty d1 then raise Exit else (false,d1) in
    let aux accu r = 
      try SortedMap.change l restr (false,d) r :: accu 
      with Exit -> accu in
    List.fold_left aux [] t

  let project_field t l =
    let aux accu x =
      match List.assoc l x with
	| (false,t) -> cup accu t
	| _ -> raise Not_found
    in
    List.fold_left aux empty t

709 710 711
  let project d l =
    project_field (get_record d.record) l

712 713 714 715 716 717 718 719 720
  type normal = 
      [ `Success
      | `Fail
      | `Label of label * (descr * normal) list * normal ]

  let rec merge_record n r =
    match (n, r) with
      | (`Success, _) | (_, []) -> `Success
      | (`Fail, r) ->
721 722
	  let aux (l,(o,t)) n = 
	    `Label (l, [t,n], if o then n else `Fail) in
723 724 725 726
	  List.fold_right aux r `Success
      | (`Label (l1,present,absent), (l2,(o,t2))::r') ->
	  if (l1 < l2) then
	    let pr =  List.map (fun (t,x) -> (t, merge_record x r)) present in
727 728 729 730
	    let t = List.fold_left (fun a (t,_) -> diff a t) any present in
	    let pr = 
	      if non_empty t then (t, merge_record `Fail r) :: pr
	      else pr in
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
	    `Label (l1,pr,merge_record absent r)
	  else if (l2 < l1) then
	    let n' = merge_record n r' in
	    `Label (l2, [t2, n'], if o then n' else n)
	  else
	    let res = ref [] in
	    let aux a (t,x) = 
	      (let t = diff t t2 in 
	       if non_empty t then res := (t,x) :: !res);
	      (let t = cap t t2 in
	       if non_empty t then res := (t, merge_record x r') :: !res);
	      diff a t 
	    in
	    let t2 = List.fold_left aux t2 present in
	    let () = 
	      if non_empty t2 then 
	      res := (t2, merge_record `Fail r') :: !res in
	    let abs = if o then merge_record absent r' else absent in
	    `Label (l1, !res, abs)

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
  module Unify = Map.Make(struct type t = normal let compare = compare end)

  let repository = ref Unify.empty

  let rec canonize = function
    | `Label (l,pr,ab) as x ->
	(try Unify.find x !repository 
	 with Not_found -> 
	   let pr = List.map (fun (t,n) -> canonize n,t) pr in
	   let pr = SortedMap.from_list cup pr in
	   let pr = List.map (fun (n,t) -> (t,n)) pr in
	   let x = `Label (l, pr, canonize ab) in
	   try Unify.find x !repository
	   with Not_found -> repository := Unify.add x x !repository; x
	)
    | x -> x
767 768

  let normal d =
769 770 771
    let r = canonize (List.fold_left merge_record `Fail (get d)) in
    repository := Unify.empty;
    r
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
  type normal' =
      [ `Success
      | `Label of label * (descr * descr) list * descr option ] option

(* NOTE: this function relies on the fact that generic order
         makes smallest labels appear first *)

  let first_label d =
    let d = d.record in
    let min = ref None in
    let lab (l,o,t) = match !min with 
      | Some l' when l >= l' -> () 
      | _ -> if o && (descr t = any) then () else min := Some l in
    let line (p,n) =
      (match p with f::_ -> lab f | _ -> ());
      (match n with f::_ -> lab f | _ -> ()) in
    List.iter line d;
    match !min with
      | None -> if d = [] then `Empty else `Any
      | Some l -> `Label l

  let normal' (d : descr) l =
    let ab = ref empty in
    let rec extract f = function
      | (l',o,t) :: rem when l = l' -> 
	  f o (descr t); extract f rem
      | x :: rem -> x :: (extract f rem)
      | [] -> [] in
    let line (p,n) =
      let ao = ref true and ad = ref any in
      let p = 
	extract (fun o d -> ao := !ao && o; ad := cap !ad d) p
      and n = 
	extract (fun o d -> ao := !ao && not o; ad := diff !ad d) n
      in
      (* Note: p and n are still sorted *)
      let d = { empty with record = [(p,n)] } in
      if !ao then ab := cup d !ab;
      (!ad, d) in
    let pr = List.map line d.record in
    let pr = Product.normal_aux pr in
    let ab = if is_empty !ab then None else Some !ab in
    (pr, ab)
	    
817 818 819

  let any = { empty with record = any.record }
  let is_empty d = d = []
820 821 822
  let descr l =
    let line l = map_sort (fun (l,(o,d)) -> (l,o,cons d)) l, [] in 
    { empty with record = map_sort line l }
823 824 825 826
end



827
let memo_normalize = ref DescrMap.empty
828 829 830


let rec rec_normalize d =
831
  try DescrMap.find d !memo_normalize
832 833
  with Not_found ->
    let n = make () in
834
    memo_normalize := DescrMap.add d n !memo_normalize;
835 836 837 838 839 840 841 842 843 844 845 846 847 848
    let times = 
      map_sort
	(fun (d1,d2) -> [(rec_normalize d1, rec_normalize d2)],[])
	(Product.normal d)
    in
    let record = 
      map_sort
	(fun f -> map_sort (fun (l,(o,d)) -> (l,o,rec_normalize d)) f, [])
	(Record.get d)
    in
    define n { d with times = times; record = record };
    n

let normalize n =
849
  descr (internalize (rec_normalize n))
850

851 852
module Arrow =
struct
853 854 855 856
  let check_simple left s1 s2 =
    let rec aux accu1 accu2 = function
      | (t1,t2)::left ->
          let accu1' = diff_t accu1 t1 in
857
          if non_empty accu1' then aux accu1 accu2 left;
858
          let accu2' = cap_t accu2 t2 in
859
          if non_empty accu2' then aux accu1 accu2 left
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
      | [] -> raise NotEmpty
    in
    let accu1 = descr s1 in
    (is_empty accu1) ||
    (try aux accu1 (diff any (descr s2)) left; true with NotEmpty -> false)
      
  let check_strenghten t s =
    let left = match t.arrow with [ (p,[]) ] -> p | _ -> assert false in
    let rec aux = function
      | [] -> raise Not_found
      | (p,n) :: rem ->
	  if (List.for_all (fun (a,b) -> check_simple left a b) p) &&
	    (List.for_all (fun (a,b) -> not (check_simple left a b)) n) then
	      { empty with arrow = [ (SortedList.cup left p, n) ] }
	  else aux rem
    in
    aux s.arrow

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
  let check_simple_iface left s1 s2 =
    let rec aux accu1 accu2 = function
      | (t1,t2)::left ->
          let accu1' = diff accu1 t1 in
          if non_empty accu1' then aux accu1 accu2 left;
          let accu2' = cap accu2 t2 in
          if non_empty accu2' then aux accu1 accu2 left
      | [] -> raise NotEmpty
    in
    let accu1 = descr s1 in
    (is_empty accu1) ||
    (try aux accu1 (diff any (descr s2)) left; true with NotEmpty -> false)

  let check_iface iface s =
    let rec aux = function
      | [] -> false
      | (p,n) :: rem ->
	  ((List.for_all (fun (a,b) -> check_simple_iface iface a b) p) &&
	   (List.for_all (fun (a,b) -> not (check_simple_iface iface a b)) n))
	  || (aux rem)
    in
    aux s.arrow

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
  type t = descr * (descr * descr) list list

  let get t =
    List.fold_left
      (fun ((dom,arr) as accu) (left,right) ->
	 if Sample.check_empty_arrow_line left right 
	 then accu
	 else (
	   let left =
	     List.map 
	       (fun (t,s) -> (descr t, descr s)) left in
	   let d = List.fold_left (fun d (t,_) -> cup d t) empty left in
	   (cap dom d, left :: arr)
	 )
      )
      (any, [])
      t.arrow

  let domain (dom,_) = dom

  let apply_simple t result left = 
    let rec aux result accu1 accu2 = function
      | (t1,s1)::left ->
          let result = 
	    let accu1 = diff accu1 t1 in
            if non_empty accu1 then aux result accu1 accu2 left
            else result in
          let result =
	    let accu2 = cap accu2 s1 in
            aux result accu1 accu2 left in
	  result
      | [] -> 
          if subtype accu2 result 
	  then result
	  else cup result accu2
    in
    aux result t any left
      
  let apply (_,arr) t =
    List.fold_left (apply_simple t) empty arr

942 943 944 945 946 947 948 949 950 951 952 953
  let need_arg (dom, arr) =
    List.exists (function [_] -> false | _ -> true) arr

  let apply_noarg (_,arr) =
    List.fold_left 
      (fun accu -> 
	 function 
	   | [(t,s)] -> cup accu s
	   | _ -> assert false
      )
      empty arr

954
  let any = { empty with arrow = any.arrow }
955
  let is_empty (_,arr) = arr = []
956 957 958
end
  

959
module Int = struct
960 961
  let has_int d i = Intervals.contains i d.ints

962 963 964 965 966
  let get d = d.ints
  let put i = { empty with ints = i }
  let is_int d = is_empty { d with ints = Intervals.empty }
  let any = { empty with ints = Intervals.any }
end
967

968 969 970 971
module Atom = struct
  let has_atom d a = Atoms.contains a d.atoms
end

972 973
module Char = struct
  let has_char d c = Chars.contains c d.chars
974
  let any = { empty with chars = Chars.any }
975 976
end

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
(*
let rec print_normal_record ppf = function
  | Success -> Format.fprintf ppf "Yes"
  | Fail -> Format.fprintf ppf "No"
  | FirstLabel (l,present,absent) ->
      Format.fprintf ppf "%s?@[<v>@\n" (label_name l);
      List.iter
        (fun (t,n) ->
	   Format.fprintf ppf "(%a)=>@[%a@]@\n" 
	     Print.print_descr t
	     print_normal_record n
	) present;
      if absent <> Fail then
	Format.fprintf ppf "(absent)=>@[%a@]@\n" print_normal_record absent;
      Format.fprintf ppf "@]" 
*)


(* 
let pr s = Types.Print.print Format.std_formatter (Syntax.make_type (Syntax.parse s));;

let pr' s = Types.Print.print Format.std_formatter 
   (Types.normalize (Syntax.make_type (Syntax.parse s)));;

BUG:
pr "'a | 'b where 'a = ('a , 'a) and 'b= ('b , 'b)";;
*)


(*
  let nr s =
    let t = Types.descr (Syntax.make_type (Syntax.parse s)) in
    let n = Types.normal_record' t.Types.record in
    Types.print_normal_record Format.std_formatter n;;
*)