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