typer.ml 28 KB
Newer Older
1
(* TODO:
2
3
4
5
 - rewrite type-checking of operators to propagate constraint
 - rewrite translation of types and patterns -> hash cons
*)

6

7
8
(* I. Transform the abstract syntax of types and patterns into
      the internal form *)
9
10
11

open Location
open Ast
12
open Ident
13

14
module S = struct type t = string let compare = compare end
15
16
17
module TypeEnv = Map.Make(S)
module Env = Map.Make(Ident.Id)
(*
18
module StringSet = Set.Make(S)
19
*)
20

21
22
exception NonExhaustive of Types.descr
exception Constraint of Types.descr * Types.descr * string
23
exception ShouldHave of Types.descr * string
24
exception WrongLabel of Types.descr * label
25
exception UnboundId of string
26
27

let raise_loc loc exn = raise (Location (loc,exn))
28
29
30
31

(* Internal representation as a graph (desugar recursive types and regexp),
   to compute freevars, etc... *)

32
type ti = {
33
  id : int; 
34
  mutable seen : bool;
35
  mutable loc' : loc;
36
  mutable fv : fv option; 
37
38
39
40
41
  mutable descr': descr;
  mutable type_node: Types.node option;
  mutable pat_node: Patterns.node option
} 
and descr =
42
43
44
45
46
47
48
49
  | IAlias of string * ti
  | IType of Types.descr
  | IOr of ti * ti
  | IAnd of ti * ti
  | IDiff of ti * ti
  | ITimes of ti * ti
  | IXml of ti * ti
  | IArrow of ti * ti
50
  | IOptional of ti
51
  | IRecord of bool * ti label_map
52
53
  | ICapture of id
  | IConstant of id * Types.const
54
55
    

56
type glb = ti TypeEnv.t
57

58
59
let mk' =
  let counter = ref 0 in
60
  fun loc ->
61
    incr counter;
62
63
    let rec x = { 
      id = !counter; 
64
      seen = false;
65
      loc' = loc; 
66
      fv = None; 
67
      descr' = IAlias ("__dummy__", x);
68
69
70
      type_node = None; 
      pat_node = None 
    } in
71
72
73
    x

let cons loc d =
74
  let x = mk' loc in
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  x.descr' <- d;
  x
    
(* Note:
   Compilation of Regexp is implemented as a ``rewriting'' of
   the parsed syntax, in order to be able to print its result
   (for debugging for instance)
   
   It would be possible (and a little more efficient) to produce
   directly ti nodes.
*)
    
module Regexp = struct
  let defs = ref []
  let name =
    let c = ref 0 in
    fun () ->
      incr c;
      "#" ^ (string_of_int !c)

  let rec seq_vars accu = function
    | Epsilon | Elem _ -> accu
    | Seq (r1,r2) | Alt (r1,r2) -> seq_vars (seq_vars accu r1) r2
    | Star r | WeakStar r -> seq_vars accu r
99
    | SeqCapture (v,r) -> seq_vars (IdSet.add v accu) r
100

101
102
  let uniq_id = let r = ref 0 in fun () -> incr r; !r

103
104
105
  type flat =  
    | REpsilon 
    | RElem of int * Ast.ppat  (* the int arg is used
106
					    to stop generic comparison *)
107
108
109
110
    | RSeq of flat * flat
    | RAlt of flat * flat
    | RStar of flat
    | RWeakStar of flat
111

112
113
  let re_loc = ref noloc

114
  let rec propagate vars : regexp -> flat = function
115
116
117
118
119
120
    | Epsilon -> REpsilon
    | Elem x -> let p = vars x in RElem (uniq_id (),p)
    | Seq (r1,r2) -> RSeq (propagate vars r1,propagate vars r2)
    | Alt (r1,r2) -> RAlt (propagate vars r1, propagate vars r2)
    | Star r -> RStar (propagate vars r)
    | WeakStar r -> RWeakStar (propagate vars r)
121
    | SeqCapture (v,x) -> 
122
123
	let v= mk_loc !re_loc (Capture v) in
	propagate (fun p -> mk_loc !re_loc (And (vars p,v))) x
124

125
  let dummy_pat = mknoloc (PatVar "DUMMY")
126
127
128
  let cup r1 r2 =
    if r1 == dummy_pat then r2 else
      if r2 == dummy_pat then r1 else
129
	mk_loc !re_loc (Or (r1,r2))
130

131
132
133
134
135
136
137
(*TODO: review this compilation schema to avoid explosion when
  coding (Optional x) by  (Or(Epsilon,x)); memoization ... *)

  module Memo = Map.Make(struct type t = flat list let compare = compare end)
  module Coind = Set.Make(struct type t = flat list let compare = compare end)
  let memo = ref Memo.empty

138

139
140
  let rec compile fin e seq : Ast.ppat = 
    if Coind.mem seq !e then dummy_pat
141
    else (
142
      e := Coind.add seq !e;
143
144
      match seq with
	| [] ->
145
146
	    fin
	| REpsilon :: rest -> 
147
	    compile fin e rest
148
	| RElem (_,p) :: rest -> 
149
	    mk_loc !re_loc (Prod (p, guard_compile fin rest))
150
	| RSeq (r1,r2) :: rest -> 
151
	    compile fin e (r1 :: r2 :: rest)
152
	| RAlt (r1,r2) :: rest -> 
153
	    cup (compile fin e (r1::rest)) (compile fin e (r2::rest))
154
	| RStar r :: rest -> 
155
	    cup (compile fin e (r::seq)) (compile fin e rest) 
156
	| RWeakStar r :: rest -> 
157
158
	    cup (compile fin e rest) (compile fin e (r::seq))
    )
159
  and guard_compile fin seq =
160
    try Memo.find seq !memo
161
162
163
    with
	Not_found ->
          let n = name () in
164
	  let v = mk_loc !re_loc (PatVar n) in
165
166
          memo := Memo.add seq v !memo;
	  let d = compile fin (ref Coind.empty) seq in
167
168
	  assert (d != dummy_pat);
	  defs := (n,d) :: !defs;
169
170
	  v

171
  let constant_nil t v = 
172
173
    mk_loc !re_loc 
      (And (t, (mk_loc !re_loc (Constant (v, Types.Atom Sequence.nil_atom)))))
174

175
176
  let compile loc regexp queue : ppat =
    re_loc := loc;
177
178
    let vars = seq_vars IdSet.empty regexp in
    let fin = IdSet.fold constant_nil queue vars in
179
180
    let re = propagate (fun p -> p) regexp in
    let n = guard_compile fin [re] in
181
    memo := Memo.empty; 
182
183
    let d = !defs in
    defs := [];
184
    mk_loc !re_loc (Recurs (n,d))
185

186
187
188
189
190
191
192
193
194
195
  module H = Hashtbl.Make(
    struct
      type t = Ast.regexp * Ast.ppat
      let equal (r1,p1) (r2,p2) = 
	(Ast.equal_regexp r1 r2) &&
	(Ast.equal_ppat p1 p2)
      let hash (r,p) = 
	(Ast.hash_regexp r) + 16637 * (Ast.hash_ppat p)
    end)
  let hash = H.create 67
196

197
198
199
200
201
202
203
204
205
206
  let compile loc regexp queue : ppat =
    try 
      let c = H.find hash (regexp,queue) in
(*      Printf.eprintf "regexp cached\n"; flush stderr; *)
      c
    with
	Not_found ->
	  let c = compile loc regexp queue in
	  H.add hash (regexp,queue) c;
	  c
207
208
end

209
let compile_regexp = Regexp.compile noloc
210
211
212
213
214


let rec compile env { loc = loc; descr = d } : ti = 
  match (d : Ast.ppat') with
  | PatVar s -> 
215
      (try TypeEnv.find s env
216
       with Not_found -> 
217
	 raise_loc_generic loc ("Undefined type variable " ^ s)
218
      )
219
  | Recurs (t, b) -> compile (compile_many env b) t
220
  | Regexp (r,q) -> compile env (Regexp.compile loc r q)
221
222
223
224
225
226
227
  | Internal t -> cons loc (IType t)
  | Or (t1,t2) -> cons loc (IOr (compile env t1, compile env t2))
  | And (t1,t2) -> cons loc (IAnd (compile env t1, compile env t2))
  | Diff (t1,t2) -> cons loc (IDiff (compile env t1, compile env t2))
  | Prod (t1,t2) -> cons loc (ITimes (compile env t1, compile env t2))
  | XmlT (t1,t2) -> cons loc (IXml (compile env t1, compile env t2))
  | Arrow (t1,t2) -> cons loc (IArrow (compile env t1, compile env t2))
228
  | Optional t -> cons loc (IOptional (compile env t))
229
  | Record (o,r) ->  cons loc (IRecord (o, LabelMap.map (compile env) r))
230
231
  | Constant (x,v) -> cons loc (IConstant (x,v))
  | Capture x -> cons loc (ICapture x)
232

233
234
235
and compile_many env b = 
  let b = List.map (fun (v,t) -> (v,t,mk' t.loc)) b in
  let env = 
236
    List.fold_left (fun env (v,t,x) -> TypeEnv.add v x env) env b in
237
  List.iter (fun (v,t,x) -> x.descr' <- IAlias (v, compile env t)) b;
238
239
  env

240
241
242
module IntSet = 
  Set.Make(struct type t = int let compare (x:int) y = compare x y end)

243
let comp_fv_seen = ref []
244
let comp_fv_res = ref IdSet.empty
245
let rec comp_fv s =
246
  match s.fv with
247
    | Some fv -> comp_fv_res := IdSet.cup fv !comp_fv_res
248
249
    | None ->
	(match s.descr' with
250
	   | IAlias (_,x) -> 
251
	       if x.seen then ()
252
	       else ( 
253
254
		 x.seen <- true;
		 comp_fv_seen := x :: !comp_fv_seen; 
255
256
		 comp_fv x
	       ) 
257
258
259
260
261
	   | IOr (s1,s2) 
	   | IAnd (s1,s2)
	   | IDiff (s1,s2)
	   | ITimes (s1,s2) | IXml (s1,s2)
	   | IArrow (s1,s2) -> comp_fv s1; comp_fv s2
262
	   | IOptional r -> comp_fv r
263
	   | IRecord (_,r) -> LabelMap.iter comp_fv r
264
265
	   | IType _ -> ()
	   | ICapture x
266
	   | IConstant (x,_) -> comp_fv_res := IdSet.add x !comp_fv_res
267
	)
268
269
270


let fv s =   
271
272
  match s.fv with
    | Some l -> l
273
274
    | None -> 
	comp_fv s;
275
	let l = !comp_fv_res in
276
	comp_fv_res := IdSet.empty;
277
278
	List.iter (fun n -> n.seen <- false) !comp_fv_seen;
	comp_fv_seen := [];
279
	s.fv <- Some l; 
280
281
282
283
	l

let rec typ seen s : Types.descr =
  match s.descr' with
284
    | IAlias (v,x) ->
285
	if IntSet.mem s.id seen then 
286
287
	  raise_loc_generic s.loc' 
	    ("Unguarded recursion on variable " ^ v ^ " in this type")
288
	else typ (IntSet.add s.id seen) x
289
290
291
292
293
294
295
    | IType t -> t
    | IOr (s1,s2) -> Types.cup (typ seen s1) (typ seen s2)
    | IAnd (s1,s2) ->  Types.cap (typ seen s1) (typ seen s2)
    | IDiff (s1,s2) -> Types.diff (typ seen s1) (typ seen s2)
    | ITimes (s1,s2) ->	Types.times (typ_node s1) (typ_node s2)
    | IXml (s1,s2) ->	Types.xml (typ_node s1) (typ_node s2)
    | IArrow (s1,s2) ->	Types.arrow (typ_node s1) (typ_node s2)
296
    | IOptional s -> Types.Record.or_absent (typ seen s)
297
    | IRecord (o,r) -> 
298
	Types.record' 
299
	  (o, LabelMap.map typ_node r)
300
    | ICapture x | IConstant (x,_) -> assert false
301
302
303
304
305
306
307

and typ_node s : Types.node =
  match s.type_node with
    | Some x -> x
    | None ->
	let x = Types.make () in
	s.type_node <- Some x;
308
	let t = typ IntSet.empty s in
309
310
311
	Types.define x t;
	x

312
313
314
let type_node s = 
  let s = typ_node s in
  let s = Types.internalize s in
315
(*  Types.define s (Types.normalize (Types.descr s)); *)
316
  s
317
318

let rec pat seen s : Patterns.descr =
319
  if IdSet.is_empty (fv s) 
320
321
  then Patterns.constr (Types.descr (type_node s)) 
  else
322
323
324
325
326
327
    try pat_aux seen s
    with Patterns.Error e -> raise_loc_generic s.loc' e
      | Location (loc,exn) when loc = noloc -> raise (Location (s.loc', exn))


and pat_aux seen s = match s.descr' with
328
  | IAlias (v,x) ->
329
      if IntSet.mem s.id seen 
330
331
332
      then raise 
	(Patterns.Error
	   ("Unguarded recursion on variable " ^ v ^ " in this pattern"));
333
      pat (IntSet.add s.id seen) x
334
335
  | IOr (s1,s2) -> Patterns.cup (pat seen s1) (pat seen s2)
  | IAnd (s1,s2) -> Patterns.cap (pat seen s1) (pat seen s2)
336
  | IDiff (s1,s2) when IdSet.is_empty (fv s2) ->
337
338
      let s2 = Types.neg (Types.descr (type_node s2)) in
      Patterns.cap (pat seen s1) (Patterns.constr s2)
339
  | IDiff _ ->
340
      raise (Patterns.Error "Difference not allowed in patterns")
341
342
  | ITimes (s1,s2) -> Patterns.times (pat_node s1) (pat_node s2)
  | IXml (s1,s2) -> Patterns.xml (pat_node s1) (pat_node s2)
343
344
345
346
  | IOptional _ -> 
      raise 
      (Patterns.Error 
	 "Optional field not allowed in record patterns")
347
  | IRecord (o,r) ->
348
      let pats = ref [] in
349
350
      let aux l s = 
	if IdSet.is_empty (fv s) then type_node s
351
	else
352
353
354
355
	  ( pats := Patterns.record l (pat_node s) :: !pats;
	    Types.any_node )
      in
      let constr = Types.record' (o,LabelMap.mapi aux r) in
356
357
      List.fold_left Patterns.cap (Patterns.constr constr) !pats
(* TODO: can avoid constr when o=true, and all fields have fv *)
358
359
360
  | ICapture x ->  Patterns.capture x
  | IConstant (x,c) -> Patterns.constant x c
  | IArrow _ ->
361
      raise (Patterns.Error "Arrow not allowed in patterns")
362
  | IType _ -> assert false
363
364
365
366
367

and pat_node s : Patterns.node =
  match s.pat_node with
    | Some x -> x
    | None ->
368
	let x = Patterns.make (fv s) in
369
	s.pat_node <- Some x;
370
	let t = pat IntSet.empty s in
371
372
373
	Patterns.define x t;
	x

374
let mk_typ e =
375
  if IdSet.is_empty (fv e) then type_node e
376
  else raise_loc_generic e.loc' "Capture variables are not allowed in types"
377
378
    

379
380
381
382
383
let typ glb e =
  mk_typ (compile glb e)

let pat glb e =
  pat_node (compile glb e)
384

385
386
387
388
let register_global_types glb b =
  let env' = compile_many glb b in
  List.fold_left 
    (fun glb (v,{ loc = loc }) -> 
389
       let t = TypeEnv.find v env' in
390
391
392
       let d = Types.descr (mk_typ t) in
       (*	       let d = Types.normalize d in*)
       Types.Print.register_global v d;
393
       if TypeEnv.mem v glb
394
       then raise_loc_generic loc ("Multiple definition for type " ^ v);
395
       TypeEnv.add v t glb
396
    ) glb b
397
398
399



400
401
(* II. Build skeleton *)

402
module Fv = IdSet
403

404
405
406
407
408
(* IDEA: introduce a node Loc in the AST to override nolocs
   in sub-expressions *)
   
let rec expr loc' glb { loc = loc; descr = d } = 
  let loc =  if loc = noloc then loc' else loc in
409
  let (fv,td) = 
410
    match d with
411
      | Forget (e,t) ->
412
	  let (fv,e) = expr loc glb e and t = typ glb t in
413
	  (fv, Typed.Forget (e,t))
414
415
      | Var s -> (Fv.singleton s, Typed.Var s)
      | Apply (e1,e2) -> 
416
	  let (fv1,e1) = expr loc glb e1 and (fv2,e2) = expr loc glb e2 in
417
	  (Fv.cup fv1 fv2, Typed.Apply (e1,e2))
418
      | Abstraction a ->
419
420
	  let iface = List.map (fun (t1,t2) -> (typ glb t1, typ glb t2)) 
			a.fun_iface in
421
422
423
	  let t = List.fold_left 
		    (fun accu (t1,t2) -> Types.cap accu (Types.arrow t1 t2)) 
		    Types.any iface in
424
425
426
	  let iface = List.map 
			(fun (t1,t2) -> (Types.descr t1, Types.descr t2)) 
			iface in
427
	  let (fv0,body) = branches loc glb a.fun_body in
428
429
430
431
432
433
434
435
436
	  let fv = match a.fun_name with
	    | None -> fv0
	    | Some f -> Fv.remove f fv0 in
	  (fv,
	   Typed.Abstraction 
	     { Typed.fun_name = a.fun_name;
	       Typed.fun_iface = iface;
	       Typed.fun_body = body;
	       Typed.fun_typ = t;
437
	       Typed.fun_fv = fv
438
439
440
441
	     }
	  )
      | Cst c -> (Fv.empty, Typed.Cst c)
      | Pair (e1,e2) ->
442
	  let (fv1,e1) = expr loc glb e1 and (fv2,e2) = expr loc glb e2 in
443
	  (Fv.cup fv1 fv2, Typed.Pair (e1,e2))
444
      | Xml (e1,e2) ->
445
	  let (fv1,e1) = expr loc glb e1 and (fv2,e2) = expr loc glb e2 in
446
	  (Fv.cup fv1 fv2, Typed.Xml (e1,e2))
447
      | Dot (e,l) ->
448
	  let (fv,e) = expr loc glb e in
449
	  (fv,  Typed.Dot (e,l))
450
451
452
      | RemoveField (e,l) ->
	  let (fv,e) = expr loc glb e in
	  (fv,  Typed.RemoveField (e,l))
453
454
      | RecordLitt r -> 
	  let fv = ref Fv.empty in
455
456
	  let r = LabelMap.map 
		    (fun e -> 
457
		       let (fv2,e) = expr loc glb e 
458
		       in fv := Fv.cup !fv fv2; e)
459
		    r in
460
	  (!fv, Typed.RecordLitt r)
461
      | Op (op,le) ->
462
	  let (fvs,ltes) = List.split (List.map (expr loc glb) le) in
463
	  let fv = List.fold_left Fv.cup Fv.empty fvs in
464
	  (fv, Typed.Op (op,ltes))
465
      | Match (e,b) -> 
466
467
	  let (fv1,e) = expr loc glb e
	  and (fv2,b) = branches loc glb b in
468
	  (Fv.cup fv1 fv2, Typed.Match (e, b))
469
      | Map (e,b) ->
470
471
	  let (fv1,e) = expr loc glb e
	  and (fv2,b) = branches loc glb b in
472
	  (Fv.cup fv1 fv2, Typed.Map (e, b))
473
474
475
476
477
478
      | Ttree (e,b) ->
	  let b = b @ [ (mknoloc (Internal Types.any)), mknoloc MatchFail ] in
	  let (fv1,e) = expr loc glb e
	  and (fv2,b) = branches loc glb b in
	  (Fv.cup fv1 fv2, Typed.Ttree (e, b))
      | MatchFail -> (Fv.empty, Typed.MatchFail)
479
      | Try (e,b) ->
480
481
	  let (fv1,e) = expr loc glb e
	  and (fv2,b) = branches loc glb b in
482
	  (Fv.cup fv1 fv2, Typed.Try (e, b))
483
  in
484
485
  fv,
  { Typed.exp_loc = loc;
486
487
488
489
    Typed.exp_typ = Types.empty;
    Typed.exp_descr = td;
  }
	      
490
  and branches loc glb b = 
491
    let fv = ref Fv.empty in
492
    let accept = ref Types.empty in
493
494
    let b = List.map 
	      (fun (p,e) ->
495
		 let (fv2,e) = expr loc glb e in
496
		 let p = pat glb p in
497
498
		 let fv2 = Fv.diff fv2 (Patterns.fv p) in
		 fv := Fv.cup !fv fv2;
499
		 accept := Types.cup !accept (Types.descr (Patterns.accept p));
500
		 { Typed.br_used = false;
501
		   Typed.br_pat = p;
502
503
		   Typed.br_body = e }
	      ) b in
504
505
506
507
    (!fv, 
     { 
       Typed.br_typ = Types.empty; 
       Typed.br_branches = b; 
508
509
       Typed.br_accept = !accept;
       Typed.br_compiled = None;
510
511
     } 
    )
512

513
514
let expr = expr noloc

515
516
517
let let_decl glb p e =
  let (_,e) = expr glb e in
  { Typed.let_pat = pat glb p;
518
519
520
521
522
    Typed.let_body = e;
    Typed.let_compiled = None }

(* III. Type-checks *)

523
524
525
let int_cup_record = Types.cup Types.Int.any Types.Record.any


526
type env = Types.descr Env.t
527

528
529
let match_fail = ref Types.empty

530
531
open Typed

532
let warning loc msg =
533
534
535
536
  Format.fprintf !Location.warning_ppf "Warning %a:@\n%a%s@\n" 
    Location.print_loc loc
    Location.html_hilight loc
    msg
537
538
539
540

let check loc t s msg =
  if not (Types.subtype t s) then raise_loc loc (Constraint (t, s, msg))

541
let rec type_check env e constr precise = 
542
(*  Format.fprintf Format.std_formatter "constr=%a precise=%b@\n"
543
544
    Types.Print.print_descr constr precise; 
*)
545
  let d = type_check' e.exp_loc env e.exp_descr constr precise in
546
547
548
  e.exp_typ <- Types.cup e.exp_typ d;
  d

549
and type_check' loc env e constr precise = match e with
550
551
552
553
  | Forget (e,t) ->
      let t = Types.descr t in
      ignore (type_check env e t false);
      t
554
  | Abstraction a ->
555
556
557
558
559
560
561
      let t =
	try Types.Arrow.check_strenghten a.fun_typ constr 
	with Not_found -> 
	  raise_loc loc 
	  (ShouldHave
	     (constr, "but the interface of the abstraction is not compatible"))
      in
562
563
564
      let env = match a.fun_name with
	| None -> env
	| Some f -> Env.add f a.fun_typ env in
565
566
      List.iter 
	(fun (t1,t2) ->
567
	   ignore (type_check_branches loc env t1 a.fun_body t2 false)
568
569
	) a.fun_iface;
      t
570

571
572
  | Match (e,b) ->
      let t = type_check env e b.br_accept true in
573
      type_check_branches loc env t b constr precise
574
575
576

  | Try (e,b) ->
      let te = type_check env e constr precise in
577
      let tb = type_check_branches loc env Types.any b constr precise in
578
      Types.cup te tb
579

580
581
582
583
  | Pair (e1,e2) ->
      type_check_pair loc env e1 e2 constr precise
  | Xml (e1,e2) ->
      type_check_pair ~kind:`XML loc env e1 e2 constr precise
584

585
  | RecordLitt r ->
586
(* try to get rid of precise = true for values of fields *)
587
      if not (Types.Record.has_record constr) then
588
589
	raise_loc loc (ShouldHave (constr,"but it is a record."));
      let (rconstr,res) = 
590
	List.fold_left
591
	  (fun (rconstr,res) (l,e) ->
592
593
594
	     (* could compute (split l e) once... *)
	     let pi = Types.Record.project_opt rconstr l in
	     if Types.is_empty pi then 
595
596
597
	       raise_loc loc 
		 (ShouldHave (constr,(Printf.sprintf 
					"Field %s is not allowed here."
598
					(LabelPool.value l)
599
600
601
				     )
			     ));
	     let t = type_check env e pi true in
602
603
	     let rconstr = Types.Record.condition rconstr l t in
	     let res = if precise then (l,Types.cons t) :: res else res in
604
	     (rconstr,res)
605
	  ) (constr, []) (LabelMap.get r)
606
      in
607
608
609
610
611
612
      if not (Types.Record.has_empty_record rconstr) then
	raise_loc loc 
	  (ShouldHave (constr,"More field should be present"));
      if precise then
	Types.record' (false, LabelMap.from_list (fun _ _ -> assert false) res)
      else constr
613
614
615
616
617
  | Map (e,b) ->
      let t = type_check env e (Sequence.star b.br_accept) true in

      let constr' = Sequence.approx (Types.cap Sequence.any constr) in
      let exact = Types.subtype (Sequence.star constr') constr in
618
619
620
621
622
623
624
      (* Note: 
	 - could be more precise by integrating the decomposition
	 of constr inside Sequence.map.
      *)
      let res = 
	Sequence.map 
	  (fun t -> 
625
	     type_check_branches loc env t b constr' (precise || (not exact)))
626
627
628
	  t in
      if not exact then check loc res constr "";
      if precise then res else constr
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
  | Op ("@", [e1;e2]) ->
      let constr' = Sequence.star 
		      (Sequence.approx (Types.cap Sequence.any constr)) in
      let exact = Types.subtype constr' constr in
      if exact then
	let t1 = type_check env e1 constr' precise
	and t2 = type_check env e2 constr' precise in
	if precise then Sequence.concat t1 t2 else constr
      else
	(* Note:
	   the knownledge of t1 may makes it useless to
	   check t2 with 'precise' ... *)
	let t1 = type_check env e1 constr' true
	and t2 = type_check env e2 constr' true in
	let res = Sequence.concat t1 t2 in
	check loc res constr "";
	if precise then res else constr
646
  | Apply (e1,e2) ->
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
      let constr' = Sequence.star 
		      (Sequence.approx (Types.cap Sequence.any constr)) in
      let t1 = type_check env e1 (Types.cup Types.Arrow.any constr') true in
      let t1_fun = Types.Arrow.get t1 in

      let has_fun = not (Types.Arrow.is_empty t1_fun)
      and has_seq = not (Types.subtype t1 Types.Arrow.any) in

      let constr' =
	Types.cap 
	  (if has_fun then Types.Arrow.domain t1_fun else Types.any)
	  (if has_seq then constr' else Types.any)
      in
      let need_arg = has_fun && Types.Arrow.need_arg t1_fun in
      let precise  = need_arg || has_seq in
      let t2 = type_check env e2 constr' precise in
      let res = Types.cup 
		  (if has_fun then 
		     if need_arg then Types.Arrow.apply t1_fun t2
		     else Types.Arrow.apply_noarg t1_fun
		   else Types.empty)
		  (if has_seq then Sequence.concat t1 t2
		   else Types.empty)
      in
      check loc res constr "";
      res
674
*)
675
676
677
      let t1 = type_check env e1 Types.Arrow.any true in
      let t1 = Types.Arrow.get t1 in
      let dom = Types.Arrow.domain t1 in
678
679
680
681
682
683
684
685
686
      let res =
	if Types.Arrow.need_arg t1 then
	  let t2 = type_check env e2 dom true in
	  Types.Arrow.apply t1 t2
	else
	  (ignore (type_check env e2 dom false); Types.Arrow.apply_noarg t1)
      in
      check loc res constr "";
      res
687
688
689
690
691
692
693
694
695
696
697
698
699
  | Op ("flatten", [e]) ->
      let constr' = Sequence.star 
		      (Sequence.approx (Types.cap Sequence.any constr)) in
      let sconstr' = Sequence.star constr' in
      let exact = Types.subtype constr' constr in
      if exact then
	let t = type_check env e sconstr' precise in
	if precise then Sequence.flatten t else constr
      else
	let t = type_check env e sconstr' true in
	let res = Sequence.flatten t in
	check loc res constr "";
	if precise then res else constr
700
701
702
703
704
  | _ -> 
      let t : Types.descr = compute_type' loc env e in
      check loc t constr "";
      t

705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
and type_check_pair ?(kind=`Normal) loc env e1 e2 constr precise =
  let rects = Types.Product.get ~kind constr in
  if Types.Product.is_empty rects then 
    (match kind with
      | `Normal -> raise_loc loc (ShouldHave (constr,"but it is a pair."))
      | `XML -> raise_loc loc (ShouldHave (constr,"but it is an XML element.")));
  let pi1 = Types.Product.pi1 rects in
  
  let t1 = type_check env e1 (Types.Product.pi1 rects) 
	     (precise || (Types.Product.need_second rects))in
  let rects = Types.Product.restrict_1 rects t1 in
  let t2 = type_check env e2 (Types.Product.pi2 rects) precise in
  if precise then 
    match kind with
      | `Normal -> Types.times (Types.cons t1) (Types.cons t2)
      | `XML -> Types.xml (Types.cons t1) (Types.cons t2)
  else
    constr


725
726
727
728
and compute_type env e =
  type_check env e Types.any true

and compute_type' loc env = function
729
730
  | Var s -> 
      (try Env.find s env 
731
       with Not_found -> raise_loc loc (UnboundId (Id.value s))
732
      )
733
  | Cst c -> Types.constant c
734
735
736
737
  | Dot (e,l) ->
      let t = type_check env e Types.Record.any true in
         (try (Types.Record.project t l) 
          with Not_found -> raise_loc loc (WrongLabel(t,l)))
738
739
740
  | RemoveField (e,l) ->
      let t = type_check env e Types.Record.any true in
      Types.Record.remove_field t l
741
742
743
  | Op (op, el) ->
      let args = List.map (fun e -> (e.exp_loc, compute_type env e)) el in
      type_op loc op args
744
745
746
747
748
749
750
751
752
753
754
755
  | Ttree (e,b) ->
      let t = type_check env e Sequence.any true in
      let r = 
	Sequence.map_tree 
	  (fun t -> 
	     let res = type_check_branches loc env t b Sequence.any true in
	     let resid = !match_fail in
	     match_fail := Types.empty;
	     (res,resid)
	  ) t
      in
      r
756
757
758
759
760

(* We keep these cases here to allow comparison and benchmarking ...
   Just comment the corresponding cases in type_check' to
   activate these ones.
*)
761
762
763
  | Map (e,b) ->
      let t = compute_type env e in
      Sequence.map (fun t -> type_check_branches loc env t b Types.any true) t
764
765
766
767
768
  | Pair (e1,e2) -> 
      let t1 = compute_type env e1 
      and t2 = compute_type env e2 in
      Types.times (Types.cons t1) (Types.cons t2)
  | RecordLitt r ->
769
      let r = LabelMap.map (fun e -> Types.cons (compute_type env e)) r in
770
      Types.record' (false,r)
771
  | _ -> assert false
772

773
and type_check_branches loc env targ brs constr precise =
774
  if Types.is_empty targ then Types.empty 
775
776
  else (
    brs.br_typ <- Types.cup brs.br_typ targ;
777
    branches_aux loc env targ 
778
779
      (if precise then Types.empty else constr) 
      constr precise brs.br_branches
780
  )
781
    
782
783
and branches_aux loc env targ tres constr precise = function
  | [] -> raise_loc loc (NonExhaustive targ)
784
785
786
  | { br_body = { exp_descr = MatchFail } } :: _ ->
      match_fail := Types.cup !match_fail targ;
      tres
787
788
789
790
791
792
  | b :: rem ->
      let p = b.br_pat in
      let acc = Types.descr (Patterns.accept p) in

      let targ' = Types.cap targ acc in
      if Types.is_empty targ' 
793
      then branches_aux loc env targ tres constr precise rem
794
795
796
797
798
799
      else 
	( b.br_used <- true;
	  let res = Patterns.filter targ' p in
	  let env' = List.fold_left 
		       (fun env (x,t) -> Env.add x (Types.descr t) env) 
		       env res in
800
801
	  let t = type_check env' b.br_body constr precise in
	  let tres = if precise then Types.cup t tres else tres in
802
803
	  let targ'' = Types.diff targ acc in
	  if (Types.non_empty targ'') then 
804
	    branches_aux loc env targ'' tres constr precise rem 
805
806
	  else
	    tres
807
	)
808

809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
and type_let_decl env l =
  let acc = Types.descr (Patterns.accept l.let_pat) in
  let t = type_check env l.let_body acc true in
  let res = Patterns.filter t l.let_pat in
  List.map (fun (x,t) -> (x, Types.descr t)) res

and type_rec_funs env l =
  let types = 
    List.fold_left
      (fun accu -> function  {let_body={exp_descr=Abstraction a}} as l ->
	 let t = a.fun_typ in
	 let acc = Types.descr (Patterns.accept l.let_pat) in
	 if not (Types.subtype t acc) then
	   raise_loc l.let_body.exp_loc (NonExhaustive (Types.diff t acc));
	 let res = Patterns.filter t l.let_pat in
	 List.fold_left (fun accu (x,t) -> (x, Types.descr t)::accu) accu res
	 | _ -> assert false) [] l
  in
  let env' = List.fold_left (fun env (x,t) -> Env.add x t env) env types in
  List.iter 
    (function  { let_body = { exp_descr = Abstraction a } } as l ->
       ignore (type_check env' l.let_body Types.any false)
       | _ -> assert false) l;
  types


835
836
and type_op loc op args =
  match (op,args) with
837
    | "+", [loc1,t1; loc2,t2] ->
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
	check loc1 t1 int_cup_record
	"The first argument of + must be an integer or a record";
	let int = Types.Int.get t1 in
	let int = if Intervals.is_empty int then None else Some int in
	let r = if Types.Record.has_record t1 then Some t1 else None in
	(match (int,r) with
	   | Some t1, None ->
	       if not (Types.Int.is_int t2) then
		 raise_loc loc2
		   (Constraint 
		      (t2,Types.Int.any,
		       "The second argument of + must be an integer"));
	       Types.Int.put
		 (Intervals.add t1 (Types.Int.get t2));
	   | None, Some r1 ->
	       check loc2 t2 Types.Record.any 
	       "The second argument of + must be a record";
	       Types.Record.merge r1 t2
	   | None, None ->
	       Types.empty
	   | Some t1, Some r1 ->
	       check loc2 t2 int_cup_record
	       "The second argument of + must be an integer or a record";
	       Types.cup 
		 (Types.Int.put (Intervals.add t1 (Types.Int.get t2)))
		 (Types.Record.merge r1 t2)
	)
865
866
    | "-", [loc1,t1; loc2,t2] ->
	type_int_binop Intervals.sub loc1 t1 loc2 t2
867
    | ("*" | "/" | "mod"), [loc1,t1; loc2,t2] ->
868
	type_int_binop (fun i1 i2 -> Intervals.any) loc1 t1 loc2 t2
869
    | "@", [loc1,t1; loc2,t2] ->
870
871
872
	check loc1 t1 Sequence.any
	  "The first argument of @ must be a sequence";
	Sequence.concat t1 t2
873
    | "flatten", [loc1,t1] ->
874
875
876
	check loc1 t1 Sequence.seqseq 
	  "The argument of flatten must be a sequence of sequences";
	Sequence.flatten t1
877
878
879
880
    | "load_xml", [loc1,t1] ->
	check loc1 t1 Sequence.string
	  "The argument of load_xml must be a string (filename)";
	Types.any
881
882
883
884
    | "load_file", [loc1,t1] ->
	check loc1 t1 Sequence.string
	  "The argument of load_file must be a string (filename)";
	Sequence.string
885
886
887
888
    | "load_html", [loc1,t1] ->
	check loc1 t1 Sequence.string
	  "The argument of load_html must be a string (filename)";
	Types.any
889
890
    | "raise", [loc1,t1] ->
	Types.empty
891
892
    | "print_xml", [loc1,t1] ->
	Sequence.string
893
894
    | "print", [loc1,t1] ->
	check loc1 t1 Sequence.string
895
896
897
898
899
900
901
902
	  "The argument of print must be a string";
	Sequence.nil_type
    | "dump_to_file", [loc1,t1; loc2,t2] ->
	check loc1 t1 Sequence.string
	  "The argument of dump_to_file must be a string (filename)";
	check loc2 t2 Sequence.string
	  "The argument of dump_to_file must be a string (value to dump)";
	Sequence.nil_type
903
904
    | "int_of", [loc1,t1] ->
	check loc1 t1 Sequence.string
905
	  "The argument of int_of must be a string";
906
907
908
	if not (Types.subtype t1 Builtin.intstr) then
	  warning loc "This application of int_of may fail";
	Types.interval Intervals.any
909
910
    | "string_of", [loc1,t1] ->
	Sequence.string
911
    | "=", [loc1,t1; loc2,t2] ->
912
913
914
915
916
917
918
	(* could prevent comparision of functional value here... *)
	(* could also handle the case when t1 and t2 are the same 
	   singleton type *)
	if Types.is_empty (Types.cap t1 t2) then
	  Builtin.false_type
	else 
	  Builtin.bool
919
920
921
    | ("<=" | "<" | ">" | ">=" ), [loc1,t1; loc2,t2] ->
	(* could prevent comparision of functional value here... *)
	Builtin.bool
922
923
924
925
926
927
928
929
930
931
932
    | _ -> assert false

and type_int_binop f loc1 t1 loc2 t2 =
  if not (Types.Int.is_int t1) then
    raise_loc loc1 
      (Constraint 
	 (t1,Types.Int.any,
	  "The first argument must be an integer"));
  if not (Types.Int.is_int t2) then
    raise_loc loc2
      (Constraint 
933
	       (t2,Types.Int.any,
934
935
936
937
938
		"The second argument must be an integer"));
  Types.Int.put
    (f (Types.Int.get t1) (Types.Int.get t2));