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