/[svn]/typing/typer.ml
ViewVC logotype

Contents of /typing/typer.ml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 240 - (show annotations)
Tue Jul 10 17:18:24 2007 UTC (5 years, 10 months ago) by abate
File size: 28322 byte(s)
[r2003-03-14 18:11:21 by cvscast] Empty log message

Original author: cvscast
Date: 2003-03-14 18:13:42+00:00
1 (* TODO:
2 rewrite type-checking of operators to propagate constraint *)
3
4 (* I. Transform the abstract syntax of types and patterns into
5 the internal form *)
6
7 open Location
8 open Ast
9 open Ident
10
11 module S = struct type t = string let compare = compare end
12 module TypeEnv = Map.Make(S)
13 module Env = Map.Make(Ident.Id)
14 (*
15 module StringSet = Set.Make(S)
16 *)
17
18 exception NonExhaustive of Types.descr
19 exception Constraint of Types.descr * Types.descr * string
20 exception ShouldHave of Types.descr * string
21 exception WrongLabel of Types.descr * label
22 exception UnboundId of string
23
24 let raise_loc loc exn = raise (Location (loc,exn))
25
26 (* Internal representation as a graph (desugar recursive types and regexp),
27 to compute freevars, etc... *)
28
29 type ti = {
30 id : int;
31 mutable seen : bool;
32 mutable loc' : loc;
33 mutable fv : fv option;
34 mutable descr': descr;
35 mutable type_node: Types.node option;
36 mutable pat_node: Patterns.node option
37 }
38 and descr =
39 | IAlias of string * ti
40 | IType of Types.descr
41 | IOr of ti * ti
42 | IAnd of ti * ti
43 | IDiff of ti * ti
44 | ITimes of ti * ti
45 | IXml of ti * ti
46 | IArrow of ti * ti
47 | IOptional of ti
48 | IRecord of bool * ti label_map
49 | ICapture of id
50 | IConstant of id * Types.const
51
52
53 type glb = ti TypeEnv.t
54
55 let mk' =
56 let counter = ref 0 in
57 fun loc ->
58 incr counter;
59 let rec x = {
60 id = !counter;
61 seen = false;
62 loc' = loc;
63 fv = None;
64 descr' = IAlias ("__dummy__", x);
65 type_node = None;
66 pat_node = None
67 } in
68 x
69
70 let cons loc d =
71 let x = mk' loc in
72 x.descr' <- d;
73 x
74
75 (* Note:
76 Compilation of Regexp is implemented as a ``rewriting'' of
77 the parsed syntax, in order to be able to print its result
78 (for debugging for instance)
79
80 It would be possible (and a little more efficient) to produce
81 directly ti nodes.
82 *)
83
84 module Regexp = struct
85 let defs = ref []
86 let name =
87 let c = ref 0 in
88 fun () ->
89 incr c;
90 "#" ^ (string_of_int !c)
91
92 let rec seq_vars accu = function
93 | Epsilon | Elem _ -> accu
94 | Seq (r1,r2) | Alt (r1,r2) -> seq_vars (seq_vars accu r1) r2
95 | Star r | WeakStar r -> seq_vars accu r
96 | SeqCapture (v,r) -> seq_vars (IdSet.add v accu) r
97
98 let uniq_id = let r = ref 0 in fun () -> incr r; !r
99
100 type flat =
101 | REpsilon
102 | RElem of int * Ast.ppat (* the int arg is used
103 to stop generic comparison *)
104 | RSeq of flat * flat
105 | RAlt of flat * flat
106 | RStar of flat
107 | RWeakStar of flat
108
109 let re_loc = ref noloc
110
111 let rec propagate vars : regexp -> flat = function
112 | Epsilon -> REpsilon
113 | Elem x -> let p = vars x in RElem (uniq_id (),p)
114 | Seq (r1,r2) -> RSeq (propagate vars r1,propagate vars r2)
115 | Alt (r1,r2) -> RAlt (propagate vars r1, propagate vars r2)
116 | Star r -> RStar (propagate vars r)
117 | WeakStar r -> RWeakStar (propagate vars r)
118 | SeqCapture (v,x) ->
119 let v= mk !re_loc (Capture v) in
120 propagate (fun p -> mk !re_loc (And (vars p,v))) x
121
122 let dummy_pat = mk noloc (PatVar "DUMMY")
123 let cup r1 r2 =
124 if r1 == dummy_pat then r2 else
125 if r2 == dummy_pat then r1 else
126 mk !re_loc (Or (r1,r2))
127
128 (*TODO: review this compilation schema to avoid explosion when
129 coding (Optional x) by (Or(Epsilon,x)); memoization ... *)
130
131 module Memo = Map.Make(struct type t = flat list let compare = compare end)
132 module Coind = Set.Make(struct type t = flat list let compare = compare end)
133 let memo = ref Memo.empty
134
135
136 let rec compile fin e seq : Ast.ppat =
137 if Coind.mem seq !e then dummy_pat
138 else (
139 e := Coind.add seq !e;
140 match seq with
141 | [] ->
142 fin
143 | REpsilon :: rest ->
144 compile fin e rest
145 | RElem (_,p) :: rest ->
146 mk !re_loc (Prod (p, guard_compile fin rest))
147 | RSeq (r1,r2) :: rest ->
148 compile fin e (r1 :: r2 :: rest)
149 | RAlt (r1,r2) :: rest ->
150 cup (compile fin e (r1::rest)) (compile fin e (r2::rest))
151 | RStar r :: rest ->
152 cup (compile fin e (r::seq)) (compile fin e rest)
153 | RWeakStar r :: rest ->
154 cup (compile fin e rest) (compile fin e (r::seq))
155 )
156 and guard_compile fin seq =
157 try Memo.find seq !memo
158 with
159 Not_found ->
160 let n = name () in
161 let v = mk !re_loc (PatVar n) in
162 memo := Memo.add seq v !memo;
163 let d = compile fin (ref Coind.empty) seq in
164 assert (d != dummy_pat);
165 defs := (n,d) :: !defs;
166 v
167
168 (*
169 type trans = [ `Alt of gnode * gnode | `Elem of Ast.ppat * gnode | `Final ]
170 and gnode =
171 {
172 mutable seen : bool;
173 mutable compile : bool;
174 name : string;
175 mutable trans : trans;
176 }
177
178 let new_node() = { seen = false; compile = false;
179 name = name(); trans = `Final }
180 let to_compile = ref []
181
182 let rec compile after = function
183 | `Epsilon -> after
184 | `Elem (_,p) ->
185 if not after.compile then (after.compile <- true;
186 to_compile := after :: !to_compile);
187 { new_node () with trans = `Elem (p, after) }
188 | `Seq(r1,r2) -> compile (compile after r2) r1
189 | `Alt(r1,r2) ->
190 let r1 = compile after r1 and r2 = compile after r2 in
191 { new_node () with trans = `Alt (r1,r2) }
192 | `Star r ->
193 let n = new_node() in
194 n.trans <- `Alt (compile n r, after);
195 n
196 | `WeakStar r ->
197 let n = new_node() in
198 n.trans <- `Alt (after, compile n r);
199 n
200
201 let seens = ref []
202 let rec collect_aux accu n =
203 if n.seen then accu
204 else ( seens := n :: !seens;
205 match n.trans with
206 | `Alt (n1,n2) -> collect_aux (collect_aux accu n2) n1
207 | _ -> n :: accu
208 )
209
210 let collect fin n =
211 let l = collect_aux [] n in
212 List.iter (fun n -> n.seen <- false) !seens;
213 let l = List.map (fun n ->
214 match n.trans with
215 | `Final -> fin
216 | `Elem (p,a) ->
217 mk !re_loc (Prod(p, mk !re_loc (PatVar a.name)))
218 | _ -> assert false
219 ) l in
220 match l with
221 | h::t ->
222 List.fold_left (fun accu p -> mk !re_loc (Or (accu,p))) h t
223 | _ -> assert false
224 *)
225
226
227 let constant_nil t v =
228 mk !re_loc
229 (And (t, (mk !re_loc (Constant (v, Types.Atom Sequence.nil_atom)))))
230
231 let compile loc regexp queue : ppat =
232 re_loc := loc;
233 let vars = seq_vars IdSet.empty regexp in
234 let fin = IdSet.fold constant_nil queue vars in
235 let re = propagate (fun p -> p) regexp in
236 let n = guard_compile fin [re] in
237 memo := Memo.empty;
238 let d = !defs in
239 defs := [];
240
241 (*
242 let after = new_node() in
243 let n = collect queue (compile after re) in
244 let d = List.map (fun n -> (n.name, collect queue n)) !to_compile in
245 to_compile := [];
246 *)
247
248 mk !re_loc (Recurs (n,d))
249 end
250
251 let compile_regexp = Regexp.compile noloc
252
253
254 let rec compile env { loc = loc; descr = d } : ti =
255 match (d : Ast.ppat') with
256 | PatVar s ->
257 (try TypeEnv.find s env
258 with Not_found ->
259 raise_loc_generic loc ("Undefined type variable " ^ s)
260 )
261 | Recurs (t, b) -> compile (compile_many env b) t
262 | Regexp (r,q) -> compile env (Regexp.compile loc r q)
263 | Internal t -> cons loc (IType t)
264 | Or (t1,t2) -> cons loc (IOr (compile env t1, compile env t2))
265 | And (t1,t2) -> cons loc (IAnd (compile env t1, compile env t2))
266 | Diff (t1,t2) -> cons loc (IDiff (compile env t1, compile env t2))
267 | Prod (t1,t2) -> cons loc (ITimes (compile env t1, compile env t2))
268 | XmlT (t1,t2) -> cons loc (IXml (compile env t1, compile env t2))
269 | Arrow (t1,t2) -> cons loc (IArrow (compile env t1, compile env t2))
270 | Optional t -> cons loc (IOptional (compile env t))
271 | Record (o,r) -> cons loc (IRecord (o, LabelMap.map (compile env) r))
272 | Constant (x,v) -> cons loc (IConstant (x,v))
273 | Capture x -> cons loc (ICapture x)
274
275 and compile_many env b =
276 let b = List.map (fun (v,t) -> (v,t,mk' t.loc)) b in
277 let env =
278 List.fold_left (fun env (v,t,x) -> TypeEnv.add v x env) env b in
279 List.iter (fun (v,t,x) -> x.descr' <- IAlias (v, compile env t)) b;
280 env
281
282 module IntSet =
283 Set.Make(struct type t = int let compare (x:int) y = compare x y end)
284
285 let comp_fv_seen = ref []
286 let comp_fv_res = ref IdSet.empty
287 let rec comp_fv s =
288 match s.fv with
289 | Some fv -> comp_fv_res := IdSet.cup fv !comp_fv_res
290 | None ->
291 (match s.descr' with
292 | IAlias (_,x) ->
293 if x.seen then ()
294 else (
295 x.seen <- true;
296 comp_fv_seen := x :: !comp_fv_seen;
297 comp_fv x
298 )
299 | IOr (s1,s2)
300 | IAnd (s1,s2)
301 | IDiff (s1,s2)
302 | ITimes (s1,s2) | IXml (s1,s2)
303 | IArrow (s1,s2) -> comp_fv s1; comp_fv s2
304 | IOptional r -> comp_fv r
305 | IRecord (_,r) -> LabelMap.iter comp_fv r
306 | IType _ -> ()
307 | ICapture x
308 | IConstant (x,_) -> comp_fv_res := IdSet.add x !comp_fv_res
309 )
310
311
312 let fv s =
313 match s.fv with
314 | Some l -> l
315 | None ->
316 comp_fv s;
317 let l = !comp_fv_res in
318 comp_fv_res := IdSet.empty;
319 List.iter (fun n -> n.seen <- false) !comp_fv_seen;
320 comp_fv_seen := [];
321 s.fv <- Some l;
322 l
323
324 let rec typ seen s : Types.descr =
325 match s.descr' with
326 | IAlias (v,x) ->
327 if IntSet.mem s.id seen then
328 raise_loc_generic s.loc'
329 ("Unguarded recursion on variable " ^ v ^ " in this type")
330 else typ (IntSet.add s.id seen) x
331 | IType t -> t
332 | IOr (s1,s2) -> Types.cup (typ seen s1) (typ seen s2)
333 | IAnd (s1,s2) -> Types.cap (typ seen s1) (typ seen s2)
334 | IDiff (s1,s2) -> Types.diff (typ seen s1) (typ seen s2)
335 | ITimes (s1,s2) -> Types.times (typ_node s1) (typ_node s2)
336 | IXml (s1,s2) -> Types.xml (typ_node s1) (typ_node s2)
337 | IArrow (s1,s2) -> Types.arrow (typ_node s1) (typ_node s2)
338 | IOptional s -> Types.Record.or_absent (typ seen s)
339 | IRecord (o,r) ->
340 Types.record'
341 (o, LabelMap.map typ_node r)
342 | ICapture x | IConstant (x,_) -> assert false
343
344 and typ_node s : Types.node =
345 match s.type_node with
346 | Some x -> x
347 | None ->
348 let x = Types.make () in
349 s.type_node <- Some x;
350 let t = typ IntSet.empty s in
351 Types.define x t;
352 x
353
354 let type_node s =
355 let s = typ_node s in
356 let s = Types.internalize s in
357 (* Types.define s (Types.normalize (Types.descr s)); *)
358 s
359
360 let rec pat seen s : Patterns.descr =
361 if IdSet.is_empty (fv s)
362 then Patterns.constr (Types.descr (type_node s))
363 else
364 try pat_aux seen s
365 with Patterns.Error e -> raise_loc_generic s.loc' e
366 | Location (loc,exn) when loc = noloc -> raise (Location (s.loc', exn))
367
368
369 and pat_aux seen s = match s.descr' with
370 | IAlias (v,x) ->
371 if IntSet.mem s.id seen
372 then raise
373 (Patterns.Error
374 ("Unguarded recursion on variable " ^ v ^ " in this pattern"));
375 pat (IntSet.add s.id seen) x
376 | IOr (s1,s2) -> Patterns.cup (pat seen s1) (pat seen s2)
377 | IAnd (s1,s2) -> Patterns.cap (pat seen s1) (pat seen s2)
378 | IDiff (s1,s2) when IdSet.is_empty (fv s2) ->
379 let s2 = Types.neg (Types.descr (type_node s2)) in
380 Patterns.cap (pat seen s1) (Patterns.constr s2)
381 | IDiff _ ->
382 raise (Patterns.Error "Difference not allowed in patterns")
383 | ITimes (s1,s2) -> Patterns.times (pat_node s1) (pat_node s2)
384 | IXml (s1,s2) -> Patterns.xml (pat_node s1) (pat_node s2)
385 | IOptional _ ->
386 raise
387 (Patterns.Error
388 "Optional field not allowed in record patterns")
389 | IRecord (o,r) ->
390 let pats = ref [] in
391 let aux l s =
392 if IdSet.is_empty (fv s) then type_node s
393 else
394 ( pats := Patterns.record l (pat_node s) :: !pats;
395 Types.any_node )
396 in
397 let constr = Types.record' (o,LabelMap.mapi aux r) in
398 List.fold_left Patterns.cap (Patterns.constr constr) !pats
399 (* TODO: can avoid constr when o=true, and all fields have fv *)
400 | ICapture x -> Patterns.capture x
401 | IConstant (x,c) -> Patterns.constant x c
402 | IArrow _ ->
403 raise (Patterns.Error "Arrow not allowed in patterns")
404 | IType _ -> assert false
405
406 and pat_node s : Patterns.node =
407 match s.pat_node with
408 | Some x -> x
409 | None ->
410 let x = Patterns.make (fv s) in
411 s.pat_node <- Some x;
412 let t = pat IntSet.empty s in
413 Patterns.define x t;
414 x
415
416 let mk_typ e =
417 if IdSet.is_empty (fv e) then type_node e
418 else raise_loc_generic e.loc' "Capture variables are not allowed in types"
419
420
421 let typ glb e =
422 mk_typ (compile glb e)
423
424 let pat glb e =
425 pat_node (compile glb e)
426
427 let register_global_types glb b =
428 let env' = compile_many glb b in
429 List.fold_left
430 (fun glb (v,{ loc = loc }) ->
431 let t = TypeEnv.find v env' in
432 let d = Types.descr (mk_typ t) in
433 (* let d = Types.normalize d in*)
434 Types.Print.register_global v d;
435 if TypeEnv.mem v glb
436 then raise_loc_generic loc ("Multiple definition for type " ^ v);
437 TypeEnv.add v t glb
438 ) glb b
439
440
441
442 (* II. Build skeleton *)
443
444 module Fv = IdSet
445
446 (* IDEA: introduce a node Loc in the AST to override nolocs
447 in sub-expressions *)
448
449 let rec expr loc' glb { loc = loc; descr = d } =
450 let loc = if loc = noloc then loc' else loc in
451 let (fv,td) =
452 match d with
453 | Forget (e,t) ->
454 let (fv,e) = expr loc glb e and t = typ glb t in
455 (fv, Typed.Forget (e,t))
456 | Var s -> (Fv.singleton s, Typed.Var s)
457 | Apply (e1,e2) ->
458 let (fv1,e1) = expr loc glb e1 and (fv2,e2) = expr loc glb e2 in
459 (Fv.cup fv1 fv2, Typed.Apply (e1,e2))
460 | Abstraction a ->
461 let iface = List.map (fun (t1,t2) -> (typ glb t1, typ glb t2))
462 a.fun_iface in
463 let t = List.fold_left
464 (fun accu (t1,t2) -> Types.cap accu (Types.arrow t1 t2))
465 Types.any iface in
466 let iface = List.map
467 (fun (t1,t2) -> (Types.descr t1, Types.descr t2))
468 iface in
469 let (fv0,body) = branches loc glb a.fun_body in
470 let fv = match a.fun_name with
471 | None -> fv0
472 | Some f -> Fv.remove f fv0 in
473 (fv,
474 Typed.Abstraction
475 { Typed.fun_name = a.fun_name;
476 Typed.fun_iface = iface;
477 Typed.fun_body = body;
478 Typed.fun_typ = t;
479 Typed.fun_fv = fv
480 }
481 )
482 | Cst c -> (Fv.empty, Typed.Cst c)
483 | Pair (e1,e2) ->
484 let (fv1,e1) = expr loc glb e1 and (fv2,e2) = expr loc glb e2 in
485 (Fv.cup fv1 fv2, Typed.Pair (e1,e2))
486 | Xml (e1,e2) ->
487 let (fv1,e1) = expr loc glb e1 and (fv2,e2) = expr loc glb e2 in
488 (Fv.cup fv1 fv2, Typed.Xml (e1,e2))
489 | Dot (e,l) ->
490 let (fv,e) = expr loc glb e in
491 (fv, Typed.Dot (e,l))
492 | RemoveField (e,l) ->
493 let (fv,e) = expr loc glb e in
494 (fv, Typed.RemoveField (e,l))
495 | RecordLitt r ->
496 let fv = ref Fv.empty in
497 let r = LabelMap.map
498 (fun e ->
499 let (fv2,e) = expr loc glb e
500 in fv := Fv.cup !fv fv2; e)
501 r in
502 (!fv, Typed.RecordLitt r)
503 | Op (op,le) ->
504 let (fvs,ltes) = List.split (List.map (expr loc glb) le) in
505 let fv = List.fold_left Fv.cup Fv.empty fvs in
506 (fv, Typed.Op (op,ltes))
507 | Match (e,b) ->
508 let (fv1,e) = expr loc glb e
509 and (fv2,b) = branches loc glb b in
510 (Fv.cup fv1 fv2, Typed.Match (e, b))
511 | Map (e,b) ->
512 let (fv1,e) = expr loc glb e
513 and (fv2,b) = branches loc glb b in
514 (Fv.cup fv1 fv2, Typed.Map (e, b))
515 | Try (e,b) ->
516 let (fv1,e) = expr loc glb e
517 and (fv2,b) = branches loc glb b in
518 (Fv.cup fv1 fv2, Typed.Try (e, b))
519 in
520 fv,
521 { Typed.exp_loc = loc;
522 Typed.exp_typ = Types.empty;
523 Typed.exp_descr = td;
524 }
525
526 and branches loc glb b =
527 let fv = ref Fv.empty in
528 let accept = ref Types.empty in
529 let b = List.map
530 (fun (p,e) ->
531 let (fv2,e) = expr loc glb e in
532 let p = pat glb p in
533 let fv2 = Fv.diff fv2 (Patterns.fv p) in
534 fv := Fv.cup !fv fv2;
535 accept := Types.cup !accept (Types.descr (Patterns.accept p));
536 { Typed.br_used = false;
537 Typed.br_pat = p;
538 Typed.br_body = e }
539 ) b in
540 (!fv,
541 {
542 Typed.br_typ = Types.empty;
543 Typed.br_branches = b;
544 Typed.br_accept = !accept;
545 Typed.br_compiled = None;
546 }
547 )
548
549 let expr = expr noloc
550
551 let let_decl glb p e =
552 let (_,e) = expr glb e in
553 { Typed.let_pat = pat glb p;
554 Typed.let_body = e;
555 Typed.let_compiled = None }
556
557 (* III. Type-checks *)
558
559 type env = Types.descr Env.t
560
561 open Typed
562
563 let warning loc msg =
564 Format.fprintf !Location.warning_ppf "Warning %a:@\n%a%s@\n"
565 Location.print_loc loc
566 Location.html_hilight loc
567 msg
568
569 let check loc t s msg =
570 if not (Types.subtype t s) then raise_loc loc (Constraint (t, s, msg))
571
572 let rec type_check env e constr precise =
573 (* Format.fprintf Format.std_formatter "constr=%a precise=%b@\n"
574 Types.Print.print_descr constr precise;
575 *)
576 let d = type_check' e.exp_loc env e.exp_descr constr precise in
577 e.exp_typ <- Types.cup e.exp_typ d;
578 d
579
580 and type_check' loc env e constr precise = match e with
581 | Forget (e,t) ->
582 let t = Types.descr t in
583 ignore (type_check env e t false);
584 t
585 | Abstraction a ->
586 let t =
587 try Types.Arrow.check_strenghten a.fun_typ constr
588 with Not_found ->
589 raise_loc loc
590 (ShouldHave
591 (constr, "but the interface of the abstraction is not compatible"))
592 in
593 let env = match a.fun_name with
594 | None -> env
595 | Some f -> Env.add f a.fun_typ env in
596 List.iter
597 (fun (t1,t2) ->
598 ignore (type_check_branches loc env t1 a.fun_body t2 false)
599 ) a.fun_iface;
600 t
601
602 | Match (e,b) ->
603 let t = type_check env e b.br_accept true in
604 type_check_branches loc env t b constr precise
605
606 | Try (e,b) ->
607 let te = type_check env e constr precise in
608 let tb = type_check_branches loc env Types.any b constr precise in
609 Types.cup te tb
610
611 | Pair (e1,e2) ->
612 type_check_pair loc env e1 e2 constr precise
613 | Xml (e1,e2) ->
614 type_check_pair ~kind:`XML loc env e1 e2 constr precise
615
616 (*
617 | RecordLitt r ->
618 let rconstr = Types.Record.get constr in
619 if Types.Record.is_empty rconstr then
620 raise_loc loc (ShouldHave (constr,"but it is a record."));
621
622 (* Completely buggy ! Need to check at the end that all required labels
623 are present ...A better to do it without precise = true ? *)
624 let precise = true in
625
626 let (rconstr,res) =
627 List.fold_left
628 (fun (rconstr,res) (l,e) ->
629 let rconstr = Types.Record.restrict_label_present rconstr l in
630 let pi = Types.Record.project_field rconstr l in
631 if Types.Record.is_empty rconstr then
632 raise_loc loc
633 (ShouldHave (constr,(Printf.sprintf
634 "Field %s is not allowed here."
635 (LabelPool.value l)
636 )
637 ));
638 let t = type_check env e pi true in
639 let rconstr = Types.Record.restrict_field rconstr l t in
640
641 let res =
642 if precise
643 then Types.cap res (Types.record l false (Types.cons t))
644 else res in
645 (rconstr,res)
646 ) (rconstr, if precise then Types.Record.any else constr) r
647 in
648 (* check loc res constr ""; *)
649 res
650 *)
651
652 | Map (e,b) ->
653 let t = type_check env e (Sequence.star b.br_accept) true in
654
655 let constr' = Sequence.approx (Types.cap Sequence.any constr) in
656 let exact = Types.subtype (Sequence.star constr') constr in
657 (* Note:
658 - could be more precise by integrating the decomposition
659 of constr inside Sequence.map.
660 *)
661 let res =
662 Sequence.map
663 (fun t ->
664 type_check_branches loc env t b constr' (precise || (not exact)))
665 t in
666 if not exact then check loc res constr "";
667 if precise then res else constr
668 | Op ("@", [e1;e2]) ->
669 let constr' = Sequence.star
670 (Sequence.approx (Types.cap Sequence.any constr)) in
671 let exact = Types.subtype constr' constr in
672 if exact then
673 let t1 = type_check env e1 constr' precise
674 and t2 = type_check env e2 constr' precise in
675 if precise then Sequence.concat t1 t2 else constr
676 else
677 (* Note:
678 the knownledge of t1 may makes it useless to
679 check t2 with 'precise' ... *)
680 let t1 = type_check env e1 constr' true
681 and t2 = type_check env e2 constr' true in
682 let res = Sequence.concat t1 t2 in
683 check loc res constr "";
684 if precise then res else constr
685 | Apply (e1,e2) ->
686 (*
687 let constr' = Sequence.star
688 (Sequence.approx (Types.cap Sequence.any constr)) in
689 let t1 = type_check env e1 (Types.cup Types.Arrow.any constr') true in
690 let t1_fun = Types.Arrow.get t1 in
691
692 let has_fun = not (Types.Arrow.is_empty t1_fun)
693 and has_seq = not (Types.subtype t1 Types.Arrow.any) in
694
695 let constr' =
696 Types.cap
697 (if has_fun then Types.Arrow.domain t1_fun else Types.any)
698 (if has_seq then constr' else Types.any)
699 in
700 let need_arg = has_fun && Types.Arrow.need_arg t1_fun in
701 let precise = need_arg || has_seq in
702 let t2 = type_check env e2 constr' precise in
703 let res = Types.cup
704 (if has_fun then
705 if need_arg then Types.Arrow.apply t1_fun t2
706 else Types.Arrow.apply_noarg t1_fun
707 else Types.empty)
708 (if has_seq then Sequence.concat t1 t2
709 else Types.empty)
710 in
711 check loc res constr "";
712 res
713 *)
714 let t1 = type_check env e1 Types.Arrow.any true in
715 let t1 = Types.Arrow.get t1 in
716 let dom = Types.Arrow.domain t1 in
717 let res =
718 if Types.Arrow.need_arg t1 then
719 let t2 = type_check env e2 dom true in
720 Types.Arrow.apply t1 t2
721 else
722 (ignore (type_check env e2 dom false); Types.Arrow.apply_noarg t1)
723 in
724 check loc res constr "";
725 res
726 | Op ("flatten", [e]) ->
727 let constr' = Sequence.star
728 (Sequence.approx (Types.cap Sequence.any constr)) in
729 let sconstr' = Sequence.star constr' in
730 let exact = Types.subtype constr' constr in
731 if exact then
732 let t = type_check env e sconstr' precise in
733 if precise then Sequence.flatten t else constr
734 else
735 let t = type_check env e sconstr' true in
736 let res = Sequence.flatten t in
737 check loc res constr "";
738 if precise then res else constr
739 | _ ->
740 let t : Types.descr = compute_type' loc env e in
741 check loc t constr "";
742 t
743
744 and type_check_pair ?(kind=`Normal) loc env e1 e2 constr precise =
745 let rects = Types.Product.get ~kind constr in
746 if Types.Product.is_empty rects then
747 (match kind with
748 | `Normal -> raise_loc loc (ShouldHave (constr,"but it is a pair."))
749 | `XML -> raise_loc loc (ShouldHave (constr,"but it is an XML element.")));
750 let pi1 = Types.Product.pi1 rects in
751
752 let t1 = type_check env e1 (Types.Product.pi1 rects)
753 (precise || (Types.Product.need_second rects))in
754 let rects = Types.Product.restrict_1 rects t1 in
755 let t2 = type_check env e2 (Types.Product.pi2 rects) precise in
756 if precise then
757 match kind with
758 | `Normal -> Types.times (Types.cons t1) (Types.cons t2)
759 | `XML -> Types.xml (Types.cons t1) (Types.cons t2)
760 else
761 constr
762
763
764 and compute_type env e =
765 type_check env e Types.any true
766
767 and compute_type' loc env = function
768 | Var s ->
769 (try Env.find s env
770 with Not_found -> raise_loc loc (UnboundId (Id.value s))
771 )
772 | Cst c -> Types.constant c
773 | Dot (e,l) ->
774 let t = type_check env e Types.Record.any true in
775 (try (Types.Record.project t l)
776 with Not_found -> raise_loc loc (WrongLabel(t,l)))
777 | RemoveField (e,l) ->
778 let t = type_check env e Types.Record.any true in
779 Types.Record.remove_field t l
780 | Op (op, el) ->
781 let args = List.map (fun e -> (e.exp_loc, compute_type env e)) el in
782 type_op loc op args
783 | Map (e,b) ->
784 let t = compute_type env e in
785 Sequence.map (fun t -> type_check_branches loc env t b Types.any true) t
786
787 (* We keep these cases here to allow comparison and benchmarking ...
788 Just comment the corresponding cases in type_check' to
789 activate these ones.
790 *)
791 | Pair (e1,e2) ->
792 let t1 = compute_type env e1
793 and t2 = compute_type env e2 in
794 Types.times (Types.cons t1) (Types.cons t2)
795 | RecordLitt r ->
796 let r = LabelMap.map (fun e -> Types.cons (compute_type env e)) r in
797 Types.record' (false,r)
798 | _ -> assert false
799
800 and type_check_branches loc env targ brs constr precise =
801 if Types.is_empty targ then Types.empty
802 else (
803 brs.br_typ <- Types.cup brs.br_typ targ;
804 branches_aux loc env targ
805 (if precise then Types.empty else constr)
806 constr precise brs.br_branches
807 )
808
809 and branches_aux loc env targ tres constr precise = function
810 | [] -> raise_loc loc (NonExhaustive targ)
811 | b :: rem ->
812 let p = b.br_pat in
813 let acc = Types.descr (Patterns.accept p) in
814
815 let targ' = Types.cap targ acc in
816 if Types.is_empty targ'
817 then branches_aux loc env targ tres constr precise rem
818 else
819 ( b.br_used <- true;
820 let res = Patterns.filter targ' p in
821 let env' = List.fold_left
822 (fun env (x,t) -> Env.add x (Types.descr t) env)
823 env res in
824 let t = type_check env' b.br_body constr precise in
825 let tres = if precise then Types.cup t tres else tres in
826 let targ'' = Types.diff targ acc in
827 if (Types.non_empty targ'') then
828 branches_aux loc env targ'' tres constr precise rem
829 else
830 tres
831 )
832
833 and type_let_decl env l =
834 let acc = Types.descr (Patterns.accept l.let_pat) in
835 let t = type_check env l.let_body acc true in
836 let res = Patterns.filter t l.let_pat in
837 List.map (fun (x,t) -> (x, Types.descr t)) res
838
839 and type_rec_funs env l =
840 let types =
841 List.fold_left
842 (fun accu -> function {let_body={exp_descr=Abstraction a}} as l ->
843 let t = a.fun_typ in
844 let acc = Types.descr (Patterns.accept l.let_pat) in
845 if not (Types.subtype t acc) then
846 raise_loc l.let_body.exp_loc (NonExhaustive (Types.diff t acc));
847 let res = Patterns.filter t l.let_pat in
848 List.fold_left (fun accu (x,t) -> (x, Types.descr t)::accu) accu res
849 | _ -> assert false) [] l
850 in
851 let env' = List.fold_left (fun env (x,t) -> Env.add x t env) env types in
852 List.iter
853 (function { let_body = { exp_descr = Abstraction a } } as l ->
854 ignore (type_check env' l.let_body Types.any false)
855 | _ -> assert false) l;
856 types
857
858
859 and type_op loc op args =
860 match (op,args) with
861 | "+", [loc1,t1; loc2,t2] ->
862 type_int_binop Intervals.add loc1 t1 loc2 t2
863 | "-", [loc1,t1; loc2,t2] ->
864 type_int_binop Intervals.sub loc1 t1 loc2 t2
865 | ("*" | "/" | "mod"), [loc1,t1; loc2,t2] ->
866 type_int_binop (fun i1 i2 -> Intervals.any) loc1 t1 loc2 t2
867 | "@", [loc1,t1; loc2,t2] ->
868 check loc1 t1 Sequence.any
869 "The first argument of @ must be a sequence";
870 Sequence.concat t1 t2
871 | "flatten", [loc1,t1] ->
872 check loc1 t1 Sequence.seqseq
873 "The argument of flatten must be a sequence of sequences";
874 Sequence.flatten t1
875 | "load_xml", [loc1,t1] ->
876 check loc1 t1 Sequence.string
877 "The argument of load_xml must be a string (filename)";
878 Types.any
879 | "load_html", [loc1,t1] ->
880 check loc1 t1 Sequence.string
881 "The argument of load_html must be a string (filename)";
882 Types.any
883 | "raise", [loc1,t1] ->
884 Types.empty
885 | "print_xml", [loc1,t1] ->
886 Sequence.string
887 | "print", [loc1,t1] ->
888 check loc1 t1 Sequence.string
889 "The argument of print must be a string";
890 Sequence.nil_type
891 | "dump_to_file", [loc1,t1; loc2,t2] ->
892 check loc1 t1 Sequence.string
893 "The argument of dump_to_file must be a string (filename)";
894 check loc2 t2 Sequence.string
895 "The argument of dump_to_file must be a string (value to dump)";
896 Sequence.nil_type
897 | "int_of", [loc1,t1] ->
898 check loc1 t1 Sequence.string
899 "The argument of int_of must be a string";
900 if not (Types.subtype t1 Builtin.intstr) then
901 warning loc "This application of int_of may fail";
902 Types.interval Intervals.any
903 | "string_of", [loc1,t1] ->
904 Sequence.string
905 | "=", [loc1,t1; loc2,t2] ->
906 (* could prevent comparision of functional value here... *)
907 (* could also handle the case when t1 and t2 are the same
908 singleton type *)
909 if Types.is_empty (Types.cap t1 t2) then
910 Builtin.false_type
911 else
912 Builtin.bool
913 | ("<=" | "<" | ">" | ">=" ), [loc1,t1; loc2,t2] ->
914 (* could prevent comparision of functional value here... *)
915 Builtin.bool
916 | "++", [loc1,t1; loc2,t2] ->
917 check loc1 t1 Types.Record.any
918 "The left argument of ++ must be a record";
919 check loc2 t2 Types.Record.any
920 "The right argument of ++ must be a record";
921 Types.Record.merge t1 t2
922 | _ -> assert false
923
924 and type_int_binop f loc1 t1 loc2 t2 =
925 if not (Types.Int.is_int t1) then
926 raise_loc loc1
927 (Constraint
928 (t1,Types.Int.any,
929 "The first argument must be an integer"));
930 if not (Types.Int.is_int t2) then
931 raise_loc loc2
932 (Constraint
933 (t2,Types.Int.any,
934 "The second argument must be an integer"));
935 Types.Int.put
936 (f (Types.Int.get t1) (Types.Int.get t2));
937
938

CVS Admin">CVS Admin
ViewVC Help
Powered by ViewVC 1.1.5