]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/nCicTypeChecker.ml
added new implementation of universes
[helm.git] / helm / software / components / ng_kernel / nCicTypeChecker.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id$ *)
13
14 module C = NCic 
15 module R = NCicReduction
16 module Ref = NReference
17 module S = NCicSubstitution 
18 module U = NCicUtils
19 module E = NCicEnvironment
20 module PP = NCicPp
21
22 exception TypeCheckerFailure of string Lazy.t
23 exception AssertFailure of string Lazy.t
24
25 let raise = function
26   | TypeCheckerFailure s as e -> prerr_endline (Lazy.force s); raise e
27   | e -> raise e
28 ;;
29
30 type recf_entry = 
31   | Evil of int (* rno *) 
32   | UnfFix of bool list (* fixed arguments *) 
33   | Safe
34 ;;
35
36 let is_dangerous i l = 
37   List.exists (function (j,Evil _) when j=i -> true | _ -> false) l
38 ;;
39
40 let is_unfolded i l = 
41   List.exists (function (j,UnfFix _) when j=i -> true | _ -> false) l
42 ;;
43
44 let is_safe i l =
45   List.exists (function (j,Safe) when j=i -> true | _ -> false) l
46 ;;
47
48 let get_recno i l = 
49   try match List.assoc i l with Evil rno -> rno | _ -> assert false
50   with Not_found -> assert false
51 ;;
52
53 let get_fixed_args i l = 
54   try match List.assoc i l with UnfFix fa -> fa | _ -> assert false
55   with Not_found -> assert false
56 ;;
57
58 let shift_k e (c,rf,x) = e::c,List.map (fun (k,v) -> k+1,v) rf,x+1;;
59
60 (* for debugging only
61 let string_of_recfuns ~subst ~metasenv ~context l = 
62   let pp = PP.ppterm ~subst ~metasenv ~context in
63   let safe, rest = List.partition (function (_,Safe) -> true | _ -> false) l in
64   let dang,unf = List.partition (function (_,UnfFix _)-> false | _->true)rest in
65   "\n\tsafes: "^String.concat "," (List.map (fun (i,_)->pp (C.Rel i)) safe) ^
66   "\n\tfix  : "^String.concat "," 
67    (List.map 
68      (function (i,UnfFix l)-> pp(C.Rel i)^"/"^String.concat "," (List.map
69        string_of_bool l)
70      | _ ->assert false) unf) ^
71   "\n\trec  : "^String.concat "," 
72    (List.map 
73      (function (i,Evil rno)->pp(C.Rel i)^"/"^string_of_int rno
74      | _ -> assert false) dang)
75 ;;
76 *)
77
78 let fixed_args bos j n nn =
79  let rec aux k acc = function
80   | C.Appl (C.Rel i::args) when i-k > n && i-k <= nn ->
81      let rec combine l1 l2 =
82       match l1,l2 with
83          [],[] -> []
84        | he1::tl1, he2::tl2 -> (he1,he2)::combine tl1 tl2
85        | he::tl, [] -> (false,C.Rel ~-1)::combine tl [] (* dummy term *)
86        | [],_::_ -> assert false
87      in
88      let lefts, _ = HExtlib.split_nth (min j (List.length args)) args in
89       List.map (fun ((b,x),i) -> b && x = C.Rel (k-i)) 
90        (HExtlib.list_mapi (fun x i -> x,i) (combine acc lefts))
91   | t -> U.fold (fun _ k -> k+1) k aux acc t    
92  in
93   List.fold_left (aux 0) 
94    (let rec f = function 0 -> [] | n -> true :: f (n-1) in f j) bos
95 ;;
96
97 let rec split_prods ~subst context n te =
98   match (n, R.whd ~subst context te) with
99    | (0, _) -> context,te
100    | (n, C.Prod (name,so,ta)) when n > 0 ->
101        split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
102    | (_, _) -> raise (AssertFailure (lazy "split_prods"))
103 ;;
104
105 let debruijn uri number_of_types context = 
106  let rec aux k t =
107   match t with
108    | C.Meta (i,(s,C.Ctx l)) ->
109       let l1 = HExtlib.sharing_map (aux (k-s)) l in
110       if l1 == l then t else C.Meta (i,(s,C.Ctx l1))
111    | C.Meta _ -> t
112    | C.Const (Ref.Ref (uri1,(Ref.Fix (no,_,_) | Ref.CoFix no))) 
113    | C.Const (Ref.Ref (uri1,Ref.Ind (_,no))) when NUri.eq uri uri1 ->
114       C.Rel (k + number_of_types - no)
115    | t -> U.map (fun _ k -> k+1) k aux t
116  in
117   aux (List.length context)
118 ;;
119
120 let sort_of_prod ~metasenv ~subst context (name,s) (t1, t2) =
121    let t1 = R.whd ~subst context t1 in
122    let t2 = R.whd ~subst ((name,C.Decl s)::context) t2 in
123    match t1, t2 with
124    | C.Sort s1, C.Sort C.Prop -> t2
125    | C.Sort (C.Type u1), C.Sort (C.Type u2) -> C.Sort (C.Type (max u1 u2)) 
126    | C.Sort _,C.Sort (C.Type _) -> t2
127    | C.Sort (C.Type _) , C.Sort C.CProp -> t1
128    | C.Sort _, C.Sort C.CProp
129    | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))), C.Sort _
130    | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))), C.Meta (_,(_,(C.Irl 0 | C.Ctx [])))
131    | C.Sort _, C.Meta  (_,(_,(C.Irl 0 | C.Ctx []))) -> t2
132    | _ -> 
133       raise (TypeCheckerFailure (lazy (Printf.sprintf
134         "Prod: expected two sorts, found = %s, %s" 
135          (PP.ppterm ~subst ~metasenv ~context t1) 
136          (PP.ppterm ~subst ~metasenv ~context t2))))
137 ;;
138
139 let eat_prods ~subst ~metasenv context he ty_he args_with_ty = 
140   let rec aux ty_he = function 
141   | [] -> ty_he
142   | (arg, ty_arg)::tl ->
143       match R.whd ~subst context ty_he with 
144       | C.Prod (n,s,t) ->
145 (*
146           prerr_endline (PP.ppterm ~subst ~metasenv ~context s ^ " - Vs - "
147             ^ PP.ppterm ~subst ~metasenv ~context ty_arg);
148           prerr_endline (PP.ppterm ~subst ~metasenv ~context
149              (S.subst ~avoid_beta_redexes:true arg t));
150 *)
151           if R.are_convertible ~subst context ty_arg s then
152             aux (S.subst ~avoid_beta_redexes:true arg t) tl
153           else
154             raise 
155               (TypeCheckerFailure 
156                 (lazy (Printf.sprintf
157                   ("Appl: wrong application of %s: the parameter %s has type"^^
158                    "\n%s\nbut it should have type \n%s\nContext:\n%s\n")
159                   (PP.ppterm ~subst ~metasenv ~context he)
160                   (PP.ppterm ~subst ~metasenv ~context arg)
161                   (PP.ppterm ~subst ~metasenv ~context ty_arg)
162                   (PP.ppterm ~subst ~metasenv ~context s)
163                   (PP.ppcontext ~subst ~metasenv context))))
164        | _ ->
165           raise 
166             (TypeCheckerFailure
167               (lazy (Printf.sprintf
168                 "Appl: %s is not a function, it cannot be applied"
169                 (PP.ppterm ~subst ~metasenv ~context
170                  (let res = List.length tl in
171                   let eaten = List.length args_with_ty - res in
172                    (C.Appl
173                     (he::List.map fst
174                      (fst (HExtlib.split_nth eaten args_with_ty)))))))))
175   in
176     aux ty_he args_with_ty
177 ;;
178
179 (* instantiate_parameters ps (x1:T1)...(xn:Tn)C                             *)
180 (* returns ((x_|ps|:T_|ps|)...(xn:Tn)C){ps_1 / x1 ; ... ; ps_|ps| / x_|ps|} *)
181 let rec instantiate_parameters params c =
182   match c, params with
183   | c,[] -> c
184   | C.Prod (_,_,ta), he::tl -> instantiate_parameters tl (S.subst he ta)
185   | t,l -> raise (AssertFailure (lazy "1"))
186 ;;
187
188 let specialize_inductive_type_constrs ~subst context ty_term =
189   match R.whd ~subst context ty_term with
190   | C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as ref)  
191   | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as ref) :: _ ) as ty ->
192       let args = match ty with C.Appl (_::tl) -> tl | _ -> [] in
193       let is_ind, leftno, itl, attrs, i = E.get_checked_indtys ref in
194       let left_args,_ = HExtlib.split_nth leftno args in
195       let _,_,_,cl = List.nth itl i in
196       List.map 
197         (fun (rel,name,ty) -> rel, name, instantiate_parameters left_args ty) cl
198   | _ -> assert false
199 ;;
200
201 let specialize_and_abstract_constrs ~subst r_uri r_len context ty_term =
202   let cl = specialize_inductive_type_constrs ~subst context ty_term in
203   let len = List.length context in
204   let context_dcl = 
205     match E.get_checked_obj r_uri with
206     | _,_,_,_, NCic.Inductive (_,_,tys,_) -> 
207         context @ List.map (fun (_,name,arity,_) -> name,C.Decl arity) tys
208     | _ -> assert false
209   in
210   context_dcl,
211   List.map (fun (_,id,ty) -> id, debruijn r_uri r_len context ty) cl,
212   len, len + r_len
213 ;;
214
215 exception DoesOccur;;
216
217 let does_not_occur ~subst context n nn t = 
218   let rec aux k _ = function
219     | C.Rel m when m > n+k && m <= nn+k -> raise DoesOccur
220     | C.Rel m when m <= k || m > nn+k -> ()
221     | C.Rel m ->
222         (try match List.nth context (m-1-k) with
223           | _,C.Def (bo,_) -> aux (n-m) () bo
224           | _ -> ()
225          with Failure _ -> assert false)
226     | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> (* closed meta *) ()
227     | C.Meta (mno,(s,l)) ->
228          (try
229             (* possible optimization here: try does_not_occur on l and
230                perform substitution only if DoesOccur is raised *)
231             let _,_,term,_ = U.lookup_subst mno subst in
232             aux (k-s) () (S.subst_meta (0,l) term)
233           with U.Subst_not_found _ -> match l with
234           | C.Irl len -> if not (n+k >= s+len || s > nn+k) then raise DoesOccur
235           | C.Ctx lc -> List.iter (aux (k-s) ()) lc)
236     | t -> U.fold (fun _ k -> k + 1) k aux () t
237   in
238    try aux 0 () t; true
239    with DoesOccur -> false
240 ;;
241
242 let rec eat_lambdas ~subst ~metasenv context n te =
243   match (n, R.whd ~subst context te) with
244   | (0, _) -> (te, context)
245   | (n, C.Lambda (name,so,ta)) when n > 0 ->
246       eat_lambdas ~subst ~metasenv ((name,(C.Decl so))::context) (n - 1) ta
247    | (n, te) ->
248       raise (AssertFailure (lazy (Printf.sprintf "eat_lambdas (%d, %s)" n 
249         (PP.ppterm ~subst ~metasenv ~context te))))
250 ;;
251
252 let rec eat_or_subst_lambdas ~subst ~metasenv n te to_be_subst args
253      (context, recfuns, x as k)
254 =
255   match n, R.whd ~subst context te, to_be_subst, args with
256   | (n, C.Lambda (name,so,ta),true::to_be_subst,arg::args) when n > 0 ->
257       eat_or_subst_lambdas ~subst ~metasenv (n - 1) (S.subst arg ta)
258        to_be_subst args k
259   | (n, C.Lambda (name,so,ta),false::to_be_subst,arg::args) when n > 0 ->
260       eat_or_subst_lambdas ~subst ~metasenv (n - 1) ta to_be_subst args
261        (shift_k (name,(C.Decl so)) k)
262   | (_, te, _, _) -> te, k
263 ;;
264
265
266 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
267 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
268 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla  *)
269 (*CSC strictly_positive                                                  *)
270 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-)              *)
271 let rec weakly_positive ~subst context n nn uri te =
272 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
273   let dummy = C.Sort C.Prop in
274   (*CSC: mettere in cicSubstitution *)
275   let rec subst_inductive_type_with_dummy _ = function
276     | C.Const (Ref.Ref (uri',Ref.Ind (true,0))) when NUri.eq uri' uri -> dummy
277     | C.Appl ((C.Const (Ref.Ref (uri',Ref.Ind (true,0))))::tl) 
278         when NUri.eq uri' uri -> dummy
279     | t -> U.map (fun _ x->x) () subst_inductive_type_with_dummy t
280   in
281   match R.whd context te with
282    | C.Const (Ref.Ref (uri',Ref.Ind _))
283    | C.Appl ((C.Const (Ref.Ref (uri',Ref.Ind _)))::_) 
284       when NUri.eq uri' uri -> true
285    | C.Prod (name,source,dest) when
286       does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
287        (* dummy abstraction, so we behave as in the anonimous case *)
288        strictly_positive ~subst context n nn
289         (subst_inductive_type_with_dummy () source) &&
290        weakly_positive ~subst ((name,C.Decl source)::context)
291         (n + 1) (nn + 1) uri dest
292    | C.Prod (name,source,dest) ->
293        does_not_occur ~subst context n nn
294         (subst_inductive_type_with_dummy () source)&&
295        weakly_positive ~subst ((name,C.Decl source)::context)
296         (n + 1) (nn + 1) uri dest
297    | _ ->
298      raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
299
300 and strictly_positive ~subst context n nn te =
301   match R.whd context te with
302    | t when does_not_occur ~subst context n nn t -> true
303    | C.Rel _ -> true
304    | C.Prod (name,so,ta) ->
305       does_not_occur ~subst context n nn so &&
306        strictly_positive ~subst ((name,C.Decl so)::context) (n+1) (nn+1) ta
307    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
308       List.for_all (does_not_occur ~subst context n nn) tl
309    | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as r)::tl) -> 
310       let _,paramsno,tyl,_,i = E.get_checked_indtys r in
311       let _,name,ity,cl = List.nth tyl i in
312       let ok = List.length tyl = 1 in
313       let params, arguments = HExtlib.split_nth paramsno tl in
314       let lifted_params = List.map (S.lift 1) params in
315       let cl =
316         List.map (fun (_,_,te) -> instantiate_parameters lifted_params te) cl 
317       in
318       ok &&
319       List.for_all (does_not_occur ~subst context n nn) arguments &&
320       List.for_all 
321        (weakly_positive ~subst ((name,C.Decl ity)::context) (n+1) (nn+1) uri) cl
322    | _ -> false
323        
324 (* the inductive type indexes are s.t. n < x <= nn *)
325 and are_all_occurrences_positive ~subst context uri indparamsno i n nn te =
326   match R.whd context te with
327   |  C.Appl ((C.Rel m)::tl) as reduct when m = i ->
328       let last =
329        List.fold_left
330         (fun k x ->
331           if k = 0 then 0
332           else
333            match R.whd context x with
334            |  C.Rel m when m = n - (indparamsno - k) -> k - 1
335            | y -> raise (TypeCheckerFailure (lazy 
336               ("Argument "^string_of_int (indparamsno - k + 1) ^ " (of " ^
337               string_of_int indparamsno ^ " fixed) is not homogeneous in "^
338               "appl:\n"^ PP.ppterm ~context ~subst ~metasenv:[] reduct))))
339         indparamsno tl
340       in
341        if last = 0 then
342         List.for_all (does_not_occur ~subst context n nn) tl
343        else
344         raise (TypeCheckerFailure
345          (lazy ("Non-positive occurence in mutual inductive definition(s) [2]"^
346           NUri.string_of_uri uri)))
347   | C.Rel m when m = i ->
348       if indparamsno = 0 then
349        true
350       else
351         raise (TypeCheckerFailure
352          (lazy ("Non-positive occurence in mutual inductive definition(s) [3]"^
353           NUri.string_of_uri uri)))
354   | C.Prod (name,source,dest) when
355       does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
356       strictly_positive ~subst context n nn source &&
357        are_all_occurrences_positive ~subst 
358         ((name,C.Decl source)::context) uri indparamsno
359         (i+1) (n + 1) (nn + 1) dest
360    | C.Prod (name,source,dest) ->
361        if not (does_not_occur ~subst context n nn source) then
362          raise (TypeCheckerFailure (lazy ("Non-positive occurrence in "^
363          PP.ppterm ~context ~metasenv:[] ~subst te)));
364        are_all_occurrences_positive ~subst ((name,C.Decl source)::context)
365         uri indparamsno (i+1) (n + 1) (nn + 1) dest
366    | _ ->
367      raise
368       (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
369         (NUri.string_of_uri uri))))
370 ;;
371
372 exception NotGuarded of string Lazy.t;;
373
374 let rec typeof ~subst ~metasenv context term =
375   let rec typeof_aux context = 
376     fun t -> (*prerr_endline (PP.ppterm ~metasenv ~subst ~context t);*)
377     match t with
378     | C.Rel n ->
379        (try
380          match List.nth context (n - 1) with
381          | (_,C.Decl ty) -> S.lift n ty
382          | (_,C.Def (_,ty)) -> S.lift n ty
383         with Failure _ -> raise (TypeCheckerFailure (lazy "unbound variable")))
384     | C.Sort (C.Type [false,u]) -> C.Sort (C.Type [true, u])
385     | C.Sort (C.Type _) -> 
386         raise (AssertFailure (lazy ("Cannot type an inferred type: "^
387           NCicPp.ppterm ~subst ~metasenv ~context t)))
388     | C.Sort _ -> C.Sort (C.Type NCicEnvironment.type0)
389     | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
390     | C.Meta (n,l) as t -> 
391        let canonical_ctx,ty =
392         try
393          let _,c,_,ty = U.lookup_subst n subst in c,ty
394         with U.Subst_not_found _ -> try
395          let _,c,ty = U.lookup_meta n metasenv in c,ty
396         with U.Meta_not_found _ ->
397          raise (AssertFailure (lazy (Printf.sprintf
398           "%s not found" (PP.ppterm ~subst ~metasenv ~context t))))
399        in
400         check_metasenv_consistency t ~subst ~metasenv context canonical_ctx l;
401         S.subst_meta l ty
402     | C.Const ref -> type_of_constant ref
403     | C.Prod (name,s,t) ->
404        let sort1 = typeof_aux context s in
405        let sort2 = typeof_aux ((name,(C.Decl s))::context) t in
406        sort_of_prod ~metasenv ~subst context (name,s) (sort1,sort2)
407     | C.Lambda (n,s,t) ->
408        let sort = typeof_aux context s in
409        (match R.whd ~subst context sort with
410        | C.Meta _ | C.Sort _ -> ()
411        | _ ->
412          raise
413            (TypeCheckerFailure (lazy (Printf.sprintf
414              ("Not well-typed lambda-abstraction: " ^^
415              "the source %s should be a type; instead it is a term " ^^ 
416              "of type %s") (PP.ppterm ~subst ~metasenv ~context s)
417              (PP.ppterm ~subst ~metasenv ~context sort)))));
418        let ty = typeof_aux ((n,(C.Decl s))::context) t in
419          C.Prod (n,s,ty)
420     | C.LetIn (n,ty,t,bo) ->
421        let ty_t = typeof_aux context t in
422        let _ = typeof_aux context ty in
423        if not (R.are_convertible ~subst context ty_t ty) then
424          raise 
425           (TypeCheckerFailure 
426             (lazy (Printf.sprintf
427               "The type of %s is %s but it is expected to be %s" 
428                 (PP.ppterm ~subst ~metasenv ~context t) 
429                 (PP.ppterm ~subst ~metasenv ~context ty_t) 
430                 (PP.ppterm ~subst ~metasenv ~context ty))))
431        else
432          let ty_bo = typeof_aux  ((n,C.Def (t,ty))::context) bo in
433          S.subst ~avoid_beta_redexes:true t ty_bo
434     | C.Appl (he::(_::_ as args)) ->
435        let ty_he = typeof_aux context he in
436        let args_with_ty = List.map (fun t -> t, typeof_aux context t) args in
437 (*
438        prerr_endline ("HEAD: " ^ PP.ppterm ~subst ~metasenv ~context ty_he);
439        prerr_endline ("TARGS: " ^ String.concat " | " (List.map (PP.ppterm
440        ~subst ~metasenv ~context) (List.map snd args_with_ty)));
441        prerr_endline ("ARGS: " ^ String.concat " | " (List.map (PP.ppterm
442        ~subst ~metasenv ~context) (List.map fst args_with_ty)));
443 *)
444        eat_prods ~subst ~metasenv context he ty_he args_with_ty
445    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
446    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno)) as r,outtype,term,pl) ->
447       let outsort = typeof_aux context outtype in
448       let inductive,leftno,itl,_,_ = E.get_checked_indtys r in
449       let constructorsno =
450         let _,_,_,cl = List.nth itl tyno in List.length cl
451       in
452       let parameters, arguments =
453         let ty = R.whd ~subst context (typeof_aux context term) in
454         let r',tl =
455          match ty with
456             C.Const (Ref.Ref (_,Ref.Ind _) as r') -> r',[]
457           | C.Appl (C.Const (Ref.Ref (_,Ref.Ind _) as r') :: tl) -> r',tl
458           | _ ->
459              raise 
460                (TypeCheckerFailure (lazy (Printf.sprintf
461                  "Case analysis: analysed term %s is not an inductive one"
462                  (PP.ppterm ~subst ~metasenv ~context term)))) in
463         if not (Ref.eq r r') then
464          raise
465           (TypeCheckerFailure (lazy (Printf.sprintf
466             ("Case analysys: analysed term type is %s, but is expected " ^^
467              "to be (an application of) %s")
468             (PP.ppterm ~subst ~metasenv ~context ty) 
469             (PP.ppterm ~subst ~metasenv ~context (C.Const r')))))
470         else
471          try HExtlib.split_nth leftno tl
472          with
473           Failure _ ->
474            raise (TypeCheckerFailure (lazy (Printf.sprintf 
475            "%s is partially applied" 
476            (PP.ppterm  ~subst ~metasenv ~context ty)))) in
477       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
478       let sort_of_ind_type =
479         if parameters = [] then C.Const r
480         else C.Appl ((C.Const r)::parameters) in
481       let type_of_sort_of_ind_ty = typeof_aux context sort_of_ind_type in
482       check_allowed_sort_elimination ~subst ~metasenv r context
483        sort_of_ind_type type_of_sort_of_ind_ty outsort;
484       (* let's check if the type of branches are right *)
485       if List.length pl <> constructorsno then
486        raise (TypeCheckerFailure (lazy ("Wrong number of cases in a match")));
487       let j,branches_ok,p_ty, exp_p_ty =
488         List.fold_left
489           (fun (j,b,old_p_ty,old_exp_p_ty) p ->
490             if b then
491               let cons = 
492                 let cons = Ref.mk_constructor j r in
493                 if parameters = [] then C.Const cons
494                 else C.Appl (C.Const cons::parameters)
495               in
496               let ty_p = typeof_aux context p in
497               let ty_cons = typeof_aux context cons in
498               let ty_branch = 
499                 type_of_branch ~subst context leftno outtype cons ty_cons 0 
500               in
501               j+1, R.are_convertible ~subst context ty_p ty_branch,
502               ty_p, ty_branch
503             else
504               j,false,old_p_ty,old_exp_p_ty
505           ) (1,true,C.Sort C.Prop,C.Sort C.Prop) pl
506       in
507       if not branches_ok then
508         raise
509          (TypeCheckerFailure 
510           (lazy (Printf.sprintf ("Branch for constructor %s :=\n%s\n"^^
511           "has type %s\nnot convertible with %s") 
512           (PP.ppterm  ~subst ~metasenv ~context
513             (C.Const (Ref.mk_constructor (j-1) r)))
514           (PP.ppterm ~metasenv ~subst ~context (List.nth pl (j-2)))
515           (PP.ppterm ~metasenv ~subst ~context p_ty) 
516           (PP.ppterm ~metasenv ~subst ~context exp_p_ty)))); 
517       let res = outtype::arguments@[term] in
518       R.head_beta_reduce (C.Appl res)
519     | C.Match _ -> assert false
520
521   and type_of_branch ~subst context leftno outty cons tycons liftno = 
522     match R.whd ~subst context tycons with
523     | C.Const (Ref.Ref (_,Ref.Ind _)) -> C.Appl [S.lift liftno outty ; cons]
524     | C.Appl (C.Const (Ref.Ref (_,Ref.Ind _))::tl) ->
525         let _,arguments = HExtlib.split_nth leftno tl in
526         C.Appl (S.lift liftno outty::arguments@[cons])
527     | C.Prod (name,so,de) ->
528         let cons =
529          match S.lift 1 cons with
530          | C.Appl l -> C.Appl (l@[C.Rel 1])
531          | t -> C.Appl [t ; C.Rel 1]
532         in
533          C.Prod (name,so,
534            type_of_branch ~subst ((name,(C.Decl so))::context) 
535             leftno outty cons de (liftno+1))
536     | _ -> raise (AssertFailure (lazy "type_of_branch"))
537
538   (* check_metasenv_consistency checks that the "canonical" context of a
539      metavariable is consitent - up to relocation via the relocation list l -
540      with the actual context *)
541   and check_metasenv_consistency 
542     ~subst ~metasenv term context canonical_context l 
543   =
544    match l with
545     | shift, C.Irl n ->
546        let context = snd (HExtlib.split_nth shift context) in
547         let rec compare = function
548          | 0,_,[] -> ()
549          | 0,_,_::_
550          | _,_,[] ->
551             raise (AssertFailure (lazy (Printf.sprintf
552              "Local and canonical context %s have different lengths"
553              (PP.ppterm ~subst ~context ~metasenv term))))
554          | m,[],_::_ ->
555             raise (TypeCheckerFailure (lazy (Printf.sprintf
556              "Unbound variable -%d in %s" m 
557              (PP.ppterm ~subst ~metasenv ~context term))))
558          | m,t::tl,ct::ctl ->
559             (match t,ct with
560                 (_,C.Decl t1), (_,C.Decl t2)
561               | (_,C.Def (t1,_)), (_,C.Def (t2,_))
562               | (_,C.Def (_,t1)), (_,C.Decl t2) ->
563                  if not (R.are_convertible ~subst tl t1 t2) then
564                   raise 
565                       (TypeCheckerFailure 
566                         (lazy (Printf.sprintf 
567                       ("Not well typed metavariable local context for %s: " ^^ 
568                        "%s expected, which is not convertible with %s")
569                       (PP.ppterm ~subst ~metasenv ~context term) 
570                       (PP.ppterm ~subst ~metasenv ~context t2) 
571                       (PP.ppterm ~subst ~metasenv ~context t1))))
572               | _,_ ->
573                raise 
574                    (TypeCheckerFailure (lazy (Printf.sprintf 
575                     ("Not well typed metavariable local context for %s: " ^^ 
576                      "a definition expected, but a declaration found")
577                     (PP.ppterm ~subst ~metasenv ~context term)))));
578             compare (m - 1,tl,ctl)
579         in
580          compare (n,context,canonical_context)
581     | shift, lc_kind ->
582        (* we avoid useless lifting by shortening the context*)
583        let l,context = (0,lc_kind), snd (HExtlib.split_nth shift context) in
584        let lifted_canonical_context = 
585          let rec lift_metas i = function
586            | [] -> []
587            | (n,C.Decl t)::tl ->
588                (n,C.Decl (S.subst_meta l (S.lift i t)))::(lift_metas (i+1) tl)
589            | (n,C.Def (t,ty))::tl ->
590                (n,C.Def ((S.subst_meta l (S.lift i t)),
591                           S.subst_meta l (S.lift i ty)))::(lift_metas (i+1) tl)
592          in
593           lift_metas 1 canonical_context in
594        let l = U.expand_local_context lc_kind in
595        try
596         List.iter2 
597         (fun t ct -> 
598           match (t,ct) with
599           | t, (_,C.Def (ct,_)) ->
600              (*CSC: the following optimization is to avoid a possibly expensive
601                     reduction that can be easily avoided and that is quite
602                     frequent. However, this is better handled using levels to
603                     control reduction *)
604              let optimized_t =
605               match t with
606               | C.Rel n ->
607                   (try
608                     match List.nth context (n - 1) with
609                     | (_,C.Def (te,_)) -> S.lift n te
610                     | _ -> t
611                     with Failure _ -> t)
612               | _ -> t
613              in
614              if not (R.are_convertible ~subst context optimized_t ct)
615              then
616                raise 
617                  (TypeCheckerFailure 
618                    (lazy (Printf.sprintf 
619                      ("Not well typed metavariable local context: " ^^ 
620                       "expected a term convertible with %s, found %s")
621                      (PP.ppterm ~subst ~metasenv ~context ct) 
622                      (PP.ppterm ~subst ~metasenv ~context t))))
623           | t, (_,C.Decl ct) ->
624               let type_t = typeof_aux context t in
625               if not (R.are_convertible ~subst context type_t ct) then
626                 raise (TypeCheckerFailure 
627                  (lazy (Printf.sprintf 
628                   ("Not well typed metavariable local context: "^^
629                   "expected a term of type %s, found %s of type %s") 
630                   (PP.ppterm ~subst ~metasenv ~context ct) 
631                   (PP.ppterm ~subst ~metasenv ~context t) 
632                   (PP.ppterm ~subst ~metasenv ~context type_t))))
633         ) l lifted_canonical_context 
634        with
635         Invalid_argument _ ->
636           raise (AssertFailure (lazy (Printf.sprintf
637            "Local and canonical context %s have different lengths"
638            (PP.ppterm ~subst ~metasenv ~context term))))
639
640   and is_non_informative context paramsno c =
641    let rec aux context c =
642      match R.whd context c with
643       | C.Prod (n,so,de) ->
644          let s = typeof_aux context so in
645          s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
646       | _ -> true in
647    let context',dx = split_prods ~subst:[] context paramsno c in
648     aux context' dx
649
650   and check_allowed_sort_elimination ~subst ~metasenv r =
651    let mkapp he arg =
652      match he with
653      | C.Appl l -> C.Appl (l @ [arg])
654      | t -> C.Appl [t;arg] in
655    let rec aux context ind arity1 arity2 =
656     let arity1 = R.whd ~subst context arity1 in
657     let arity2 = R.whd ~subst context arity2 in
658       match arity1,arity2 with
659        | C.Prod (name,so1,de1), C.Prod (_,so2,de2) ->
660           if not (R.are_convertible ~subst context so1 so2) then
661            raise (TypeCheckerFailure (lazy (Printf.sprintf
662             "In outtype: expected %s, found %s"
663             (PP.ppterm ~subst ~metasenv ~context so1)
664             (PP.ppterm ~subst ~metasenv ~context so2)
665             )));
666           aux ((name, C.Decl so1)::context)
667            (mkapp (S.lift 1 ind) (C.Rel 1)) de1 de2
668        | C.Sort _, C.Prod (name,so,ta) ->
669           if not (R.are_convertible ~subst context so ind) then
670            raise (TypeCheckerFailure (lazy (Printf.sprintf
671             "In outtype: expected %s, found %s"
672             (PP.ppterm ~subst ~metasenv ~context ind)
673             (PP.ppterm ~subst ~metasenv ~context so)
674             )));
675           (match arity1, R.whd ~subst ((name,C.Decl so)::context) ta with
676             | (C.Sort (C.CProp | C.Type _), C.Sort _)
677             | (C.Sort C.Prop, C.Sort C.Prop) -> ()
678             | (C.Sort C.Prop, C.Sort (C.CProp | C.Type _)) ->
679         (* TODO: we should pass all these parameters since we
680          * have them already *)
681                 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
682                 let itl_len = List.length itl in
683                 let _,name,ty,cl = List.nth itl i in
684                 let cl_len = List.length cl in
685                  (* is it a singleton or empty non recursive and non informative
686                     definition? *)
687                  if not
688                   (cl_len = 0 ||
689                    (itl_len = 1 && cl_len = 1 &&
690                     is_non_informative [name,C.Decl ty] leftno
691                      (let _,_,x = List.nth cl 0 in x)))
692                  then
693                   raise (TypeCheckerFailure (lazy
694                    ("Sort elimination not allowed")));
695           | _,_ -> ())
696        | _,_ -> ()
697    in
698     aux 
699
700  in 
701    typeof_aux context term
702
703 and check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl = 
704   (* let's check if the arity of the inductive types are well formed *)
705   List.iter (fun (_,_,x,_) -> ignore (typeof ~subst ~metasenv [] x)) tyl;
706   (* let's check if the types of the inductive constructors are well formed. *)
707   let len = List.length tyl in
708   let tys = List.rev (List.map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl) in
709   ignore
710    (List.fold_right
711     (fun (_,_,_,cl) i ->
712        List.iter
713          (fun (_,name,te) -> 
714            let debruijnedte = debruijn uri len [] te in
715            ignore (typeof ~subst ~metasenv tys debruijnedte);
716            (* let's check also the positivity conditions *)
717            if 
718              not
719                (are_all_occurrences_positive ~subst tys uri leftno i 0 len
720                   debruijnedte) 
721            then
722              raise
723                (TypeCheckerFailure
724                  (lazy ("Non positive occurence in "^NUri.string_of_uri uri))))
725          cl;
726         i + 1)
727     tyl 1)
728
729 and guarded_by_destructors r_uri r_len ~subst ~metasenv context recfuns t = 
730  let recursor f k t = U.fold shift_k k (fun k () -> f k) () t in
731  let rec aux (context, recfuns, x as k) t = 
732 (*
733    prerr_endline ("GB:\n" ^ 
734      PP.ppcontext ~subst ~metasenv context^
735      PP.ppterm ~metasenv ~subst ~context t^
736        string_of_recfuns ~subst ~metasenv ~context recfuns);
737 *)
738   try
739   match t with
740   | C.Rel m as t when is_dangerous m recfuns -> 
741       raise (NotGuarded (lazy 
742         (PP.ppterm ~subst ~metasenv ~context t ^ 
743          " is a partial application of a fix")))
744   | C.Appl ((C.Rel m)::tl) as t when is_dangerous m recfuns ->
745      let rec_no = get_recno m recfuns in
746      if not (List.length tl > rec_no) then 
747        raise (NotGuarded (lazy 
748          (PP.ppterm ~context ~subst ~metasenv t ^ 
749          " is a partial application of a fix")))
750      else
751        let rec_arg = List.nth tl rec_no in
752        if not (is_really_smaller r_uri r_len ~subst ~metasenv k rec_arg) then 
753          raise (NotGuarded (lazy (Printf.sprintf ("Recursive call %s, %s is not"
754           ^^ " smaller.\ncontext:\n%s") (PP.ppterm ~context ~subst ~metasenv
755           t) (PP.ppterm ~context ~subst ~metasenv rec_arg)
756           (PP.ppcontext ~subst ~metasenv context))));
757        List.iter (aux k) tl
758   | C.Appl ((C.Rel m)::tl) when is_unfolded m recfuns ->
759        let fixed_args = get_fixed_args m recfuns in
760        HExtlib.list_iter_default2
761         (fun x b -> if not b then aux k x) tl false fixed_args
762   | C.Rel m ->
763      (match List.nth context (m-1) with 
764      | _,C.Decl _ -> ()
765      | _,C.Def (bo,_) -> aux k (S.lift m bo))
766   | C.Meta _ -> ()
767   | C.Appl (C.Const ((Ref.Ref (uri,Ref.Fix (i,recno,_))) as r)::args) ->
768       if List.exists (fun t -> try aux k t;false with NotGuarded _ -> true) args
769       then
770       let fl,_,_ = E.get_checked_fixes_or_cofixes r in
771       let ctx_tys, bos = 
772         List.split (List.map (fun (_,name,_,ty,bo) -> (name, C.Decl ty), bo) fl)
773       in
774       let fl_len = List.length fl in
775       let bos = List.map (debruijn uri fl_len context) bos in
776       let j = List.fold_left min max_int (List.map (fun (_,_,i,_,_)->i) fl) in
777       let ctx_len = List.length context in
778         (* we may look for fixed params not only up to j ... *)
779       let fa = fixed_args bos j ctx_len (ctx_len + fl_len) in
780       HExtlib.list_iter_default2
781        (fun x b -> if not b then aux k x) args false fa; 
782       let context = context@ctx_tys in
783       let ctx_len = List.length context in
784       let extra_recfuns = 
785         HExtlib.list_mapi (fun _ i -> ctx_len - i, UnfFix fa) ctx_tys
786       in
787       let new_k = context, extra_recfuns@recfuns, x in
788       let bos_and_ks = 
789         HExtlib.list_mapi
790          (fun bo fno ->
791           let bo_and_k =
792             eat_or_subst_lambdas ~subst ~metasenv j bo fa args new_k
793           in
794            if
795             fno = i &&
796             List.length args > recno &&
797             (*case where the recursive argument is already really_smaller *)
798             is_really_smaller r_uri r_len ~subst ~metasenv k
799              (List.nth args recno)
800            then
801             let bo,(context, _, _ as new_k) = bo_and_k in
802             let bo, context' =
803              eat_lambdas ~subst ~metasenv context (recno + 1 - j) bo in
804             let new_context_part,_ =
805              HExtlib.split_nth (List.length context' - List.length context)
806               context' in
807             let k = List.fold_right shift_k new_context_part new_k in
808             let context, recfuns, x = k in
809             let k = context, (1,Safe)::recfuns, x in
810               bo,k
811            else
812             bo_and_k
813          ) bos
814       in
815        List.iter (fun (bo,k) -> aux k bo) bos_and_ks
816   | C.Match (Ref.Ref (uri,Ref.Ind (true,_)),outtype,term,pl) as t ->
817      (match R.whd ~subst context term with
818      | C.Rel m | C.Appl (C.Rel m :: _ ) as t when is_safe m recfuns || m = x ->
819          let ty = typeof ~subst ~metasenv context term in
820          let dc_ctx, dcl, start, stop = 
821            specialize_and_abstract_constrs ~subst r_uri r_len context ty in
822          let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
823          aux k outtype; 
824          List.iter (aux k) args; 
825          List.iter2
826            (fun p (_,dc) ->
827              let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
828              let p, k = get_new_safes ~subst k p rl in
829              aux k p) 
830            pl dcl
831      | _ -> recursor aux k t)
832   | t -> recursor aux k t
833   with
834    NotGuarded _ as exc ->
835     let t' = R.whd ~delta:0 ~subst context t in
836     if t = t' then raise exc
837     else aux k t'
838  in
839   try aux (context, recfuns, 1) t
840   with NotGuarded s -> raise (TypeCheckerFailure s)
841
842 and guarded_by_constructors ~subst ~metasenv context t indURI indlen nn =
843  let rec aux context n nn h te =
844   match R.whd ~subst context te with
845    | C.Rel m when m > n && m <= nn -> h
846    | C.Rel _ | C.Meta _ -> true
847    | C.Sort _
848    | C.Implicit _
849    | C.Prod _
850    | C.Const (Ref.Ref (_,Ref.Ind _))
851    | C.LetIn _ -> raise (AssertFailure (lazy "17"))
852    | C.Lambda (name,so,de) ->
853       does_not_occur ~subst context n nn so &&
854       aux ((name,C.Decl so)::context) (n + 1) (nn + 1) h de
855    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
856       h && List.for_all (does_not_occur ~subst context n nn) tl
857    | C.Const (Ref.Ref (_,Ref.Con _)) -> true
858    | C.Appl (C.Const (Ref.Ref (uri, Ref.Con (_,j)) as ref) :: tl) as t ->
859       let _, paramsno, _, _, _ = E.get_checked_indtys ref in
860       let ty_t = typeof ~subst ~metasenv context t in
861       let dc_ctx, dcl, start, stop = 
862         specialize_and_abstract_constrs ~subst indURI indlen context ty_t in
863       let _, dc = List.nth dcl (j-1) in
864 (*
865         prerr_endline (PP.ppterm ~subst ~metasenv ~context:dc_ctx dc);
866         prerr_endline (PP.ppcontext ~subst ~metasenv dc_ctx);
867  *)
868       let rec_params = recursive_args ~subst ~metasenv dc_ctx start stop dc in
869       let rec analyse_instantiated_type rec_spec args =
870        match rec_spec, args with
871        | h::rec_spec, he::args -> 
872            aux context n nn h he && analyse_instantiated_type rec_spec args 
873        | _,[] -> true
874        | _ -> raise (AssertFailure (lazy 
875          ("Too many args for constructor: " ^ String.concat " "
876          (List.map (fun x-> PP.ppterm ~subst ~metasenv ~context x) args))))
877       in
878       let left, args = HExtlib.split_nth paramsno tl in
879       List.for_all (does_not_occur ~subst context n nn) left &&
880       analyse_instantiated_type rec_params args
881    | C.Appl ((C.Match (_,out,te,pl))::_) 
882    | C.Match (_,out,te,pl) as t ->
883        let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
884        List.for_all (does_not_occur ~subst context n nn) tl &&
885        does_not_occur ~subst context n nn out &&
886        does_not_occur ~subst context n nn te &&
887        List.for_all (aux context n nn h) pl
888    | C.Const (Ref.Ref (u,(Ref.Fix _| Ref.CoFix _)) as ref)
889    | C.Appl(C.Const (Ref.Ref(u,(Ref.Fix _| Ref.CoFix _)) as ref) :: _) as t ->
890       let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
891       let fl,_,_ = E.get_checked_fixes_or_cofixes ref in 
892       let len = List.length fl in
893       let tys = List.map (fun (_,n,_,ty,_) -> n, C.Decl ty) fl in
894       List.for_all (does_not_occur ~subst context n nn) tl &&
895       List.for_all
896        (fun (_,_,_,_,bo) ->
897           aux (context@tys) n nn h (debruijn u len context bo))
898        fl
899    | C.Const _
900    | C.Appl _ as t -> does_not_occur ~subst context n nn t
901  in
902    aux context 0 nn false t
903                                                                       
904 and recursive_args ~subst ~metasenv context n nn te =
905   match R.whd context te with
906   | C.Rel _ | C.Appl _ | C.Const _ -> []
907   | C.Prod (name,so,de) ->
908      (not (does_not_occur ~subst context n nn so)) ::
909       (recursive_args ~subst ~metasenv 
910         ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
911   | t -> 
912      raise (AssertFailure (lazy ("recursive_args:" ^ PP.ppterm ~subst
913      ~metasenv ~context:[] t)))
914
915 and get_new_safes ~subst (context, recfuns, x as k) p rl =
916   match R.whd ~subst context p, rl with
917   | C.Lambda (name,so,ta), b::tl ->
918       let recfuns = (if b then [0,Safe] else []) @ recfuns in
919       get_new_safes ~subst 
920         (shift_k (name,(C.Decl so)) (context, recfuns, x)) ta tl
921   | C.Meta _ as e, _ | e, [] -> e, k
922   | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
923
924 and is_really_smaller 
925   r_uri r_len ~subst ~metasenv (context, recfuns, x as k) te 
926 =
927  match R.whd ~subst context te with
928  | C.Rel m when is_safe m recfuns -> true
929  | C.Lambda (name, s, t) ->
930     is_really_smaller r_uri r_len ~subst ~metasenv (shift_k (name,C.Decl s) k) t
931  | C.Appl (he::_) ->
932     is_really_smaller r_uri r_len ~subst ~metasenv k he
933  | C.Rel _ 
934  | C.Const (Ref.Ref (_,Ref.Con _)) -> false
935  | C.Appl [] 
936  | C.Const (Ref.Ref (_,Ref.Fix _)) -> assert false
937  | C.Meta _ -> true 
938  | C.Match (Ref.Ref (uri,Ref.Ind (isinductive,_)),outtype,term,pl) ->
939     (match term with
940     | C.Rel m | C.Appl (C.Rel m :: _ ) when is_safe m recfuns || m = x ->
941         if not isinductive then
942           List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl
943         else
944           let ty = typeof ~subst ~metasenv context term in
945           let dc_ctx, dcl, start, stop = 
946             specialize_and_abstract_constrs ~subst r_uri r_len context ty in
947           List.for_all2
948            (fun p (_,dc) -> 
949              let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
950              let e, k = get_new_safes ~subst k p rl in
951              is_really_smaller r_uri r_len ~subst ~metasenv k e)
952            pl dcl
953     | _ -> List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl)
954  | _ -> assert false
955
956 and returns_a_coinductive ~subst context ty =
957   match R.whd ~subst context ty with
958   | C.Const (Ref.Ref (uri,Ref.Ind (false,_)) as ref) 
959   | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (false,_)) as ref)::_) ->
960      let _, _, itl, _, _ = E.get_checked_indtys ref in
961      Some (uri,List.length itl)
962   | C.Prod (n,so,de) ->
963      returns_a_coinductive ~subst ((n,C.Decl so)::context) de
964   | _ -> None
965
966 and type_of_constant ((Ref.Ref (uri,_)) as ref) = 
967   match E.get_checked_obj uri, ref with
968   | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,Ref.Ind (_,i))  ->
969       let _,_,arity,_ = List.nth tl i in arity
970   | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,Ref.Con (i,j))  ->
971       let _,_,_,cl = List.nth tl i in 
972       let _,_,arity = List.nth cl (j-1) in 
973       arity
974   | (_,_,_,_,C.Fixpoint (_,fl,_)), Ref.Ref (_,(Ref.Fix (i,_,_)|Ref.CoFix i)) ->
975       let _,_,_,arity,_ = List.nth fl i in
976       arity
977   | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,(Ref.Def _|Ref.Decl)) -> ty
978   | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
979 ;;
980
981 let typecheck_context ~metasenv ~subst context =
982  ignore
983   (List.fold_right
984    (fun d context  ->
985      begin
986       match d with
987          _,C.Decl t -> ignore (typeof ~metasenv ~subst:[] context t)
988        | name,C.Def (te,ty) ->
989          ignore (typeof ~metasenv ~subst:[] context ty);
990          let ty' = typeof ~metasenv ~subst:[] context te in
991           if not (R.are_convertible ~subst context ty' ty) then
992            raise (AssertFailure (lazy (Printf.sprintf (
993             "the type of the definiens for %s in the context is not "^^
994             "convertible with the declared one.\n"^^
995             "inferred type:\n%s\nexpected type:\n%s")
996             name
997             (PP.ppterm ~subst ~metasenv ~context ty') 
998             (PP.ppterm ~subst ~metasenv ~context ty))))
999      end;
1000      d::context
1001    ) context [])
1002 ;;
1003
1004 let typecheck_metasenv metasenv =
1005  ignore
1006   (List.fold_left
1007     (fun metasenv (i,(_,context,ty) as conj) ->
1008       if List.mem_assoc i metasenv then
1009        raise (TypeCheckerFailure (lazy ("duplicate meta " ^ string_of_int i ^
1010         " in metasenv")));
1011       typecheck_context ~metasenv ~subst:[] context;
1012       ignore (typeof ~metasenv ~subst:[] context ty);
1013       metasenv @ [conj]
1014     ) [] metasenv)
1015 ;;
1016
1017 let typecheck_subst ~metasenv subst =
1018  ignore
1019   (List.fold_left
1020     (fun subst (i,(_,context,ty,bo) as conj) ->
1021       if List.mem_assoc i subst then
1022        raise (AssertFailure (lazy ("duplicate meta " ^ string_of_int i ^
1023         " in substitution")));
1024       if List.mem_assoc i metasenv then
1025        raise (AssertFailure (lazy ("meta " ^ string_of_int i ^
1026         " is both in the metasenv and in the substitution")));
1027       typecheck_context ~metasenv ~subst context;
1028       ignore (typeof ~metasenv ~subst context ty);
1029       let ty' = typeof ~metasenv ~subst context bo in
1030        if not (R.are_convertible ~subst context ty' ty) then
1031         raise (AssertFailure (lazy (Printf.sprintf (
1032          "the type of the definiens for %d in the substitution is not "^^
1033          "convertible with the declared one.\n"^^
1034          "inferred type:\n%s\nexpected type:\n%s")
1035          i
1036          (PP.ppterm ~subst ~metasenv ~context ty') 
1037          (PP.ppterm ~subst ~metasenv ~context ty))));
1038       subst @ [conj]
1039     ) [] subst)
1040 ;;
1041
1042 let typecheck_obj (uri,height,metasenv,subst,kind) =
1043  typecheck_metasenv metasenv;
1044  typecheck_subst ~metasenv subst;
1045  match kind with
1046    | C.Constant (_,_,Some te,ty,_) ->
1047       let _ = typeof ~subst ~metasenv [] ty in
1048       let ty_te = typeof ~subst ~metasenv [] te in
1049       if not (R.are_convertible ~subst [] ty_te ty) then
1050        raise (TypeCheckerFailure (lazy (Printf.sprintf (
1051         "the type of the body is not convertible with the declared one.\n"^^
1052         "inferred type:\n%s\nexpected type:\n%s")
1053         (PP.ppterm ~subst ~metasenv ~context:[] ty_te) 
1054         (PP.ppterm ~subst ~metasenv ~context:[] ty))))
1055    | C.Constant (_,_,None,ty,_) -> ignore (typeof ~subst ~metasenv [] ty)
1056    | C.Inductive (is_ind, leftno, tyl, _) -> 
1057        check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl
1058    | C.Fixpoint (inductive,fl,_) ->
1059       let types, kl =
1060         List.fold_left
1061          (fun (types,kl) (_,name,k,ty,_) ->
1062            let _ = typeof ~subst ~metasenv [] ty in
1063             ((name,C.Decl ty)::types, k::kl)
1064          ) ([],[]) fl
1065       in
1066       let len = List.length types in
1067       let dfl, kl =   
1068         List.split (List.map2 
1069           (fun (_,_,_,_,bo) rno -> 
1070              let dbo = debruijn uri len [] bo in
1071              dbo, Evil rno)
1072           fl kl)
1073       in
1074       List.iter2 (fun (_,name,x,ty,_) bo ->
1075        let ty_bo = typeof ~subst ~metasenv types bo in
1076        if not (R.are_convertible ~subst types ty_bo ty)
1077        then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1078        else
1079         if inductive then begin
1080           let m, context = eat_lambdas ~subst ~metasenv types (x + 1) bo in
1081           let r_uri, r_len =
1082             let he =
1083              match List.hd context with _,C.Decl t -> t | _ -> assert false
1084             in
1085             match R.whd ~subst (List.tl context) he with
1086             | C.Const (Ref.Ref (uri,Ref.Ind _) as ref)
1087             | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind _) as ref) :: _) ->
1088                 let _,_,itl,_,_ = E.get_checked_indtys ref in
1089                   uri, List.length itl
1090             | _ -> assert false
1091           in
1092           (* guarded by destructors conditions D{f,k,x,M} *)
1093           let rec enum_from k = 
1094             function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl 
1095           in
1096           guarded_by_destructors r_uri r_len 
1097            ~subst ~metasenv context (enum_from (x+2) kl) m
1098         end else
1099          match returns_a_coinductive ~subst [] ty with
1100           | None ->
1101              raise (TypeCheckerFailure
1102                (lazy "CoFix: does not return a coinductive type"))
1103           | Some (r_uri, r_len) ->
1104              (* guarded by constructors conditions C{f,M} *)
1105              if not 
1106              (guarded_by_constructors ~subst ~metasenv types bo r_uri r_len len)
1107              then
1108                raise (TypeCheckerFailure
1109                 (lazy "CoFix: not guarded by constructors"))
1110         ) fl dfl
1111 ;;
1112
1113 (* trust *)
1114
1115 let trust = ref  (fun _ -> false);;
1116 let set_trust f = trust := f
1117 let trust_obj obj = !trust obj
1118
1119
1120 (* web interface stuff *)
1121
1122 let logger = 
1123  ref (function (`Start_type_checking _|`Type_checking_completed _|`Type_checking_interrupted _|`Type_checking_failed _|`Trust_obj _) -> ())
1124 ;;
1125
1126 let set_logger f = logger := f;;
1127
1128 let typecheck_obj obj =
1129  let u,_,_,_,_ = obj in
1130  try
1131   !logger (`Start_type_checking u);
1132   typecheck_obj obj;
1133   !logger (`Type_checking_completed u)
1134  with
1135     Sys.Break as e ->
1136      !logger (`Type_checking_interrupted u);
1137      raise e
1138   | e ->
1139      !logger (`Type_checking_failed u);
1140      raise e
1141 ;;
1142
1143 E.set_typecheck_obj
1144  (fun obj ->
1145    if trust_obj obj then
1146     let u,_,_,_,_ = obj in
1147      !logger (`Trust_obj u)
1148    else
1149     typecheck_obj obj)
1150 ;;
1151
1152 (* EOF *)