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