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