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