]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/nCicTypeChecker.ml
Missing check in positivity implemented: we did not check uniformity for
[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 get_relevance 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 get_relevance 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 get_relevance 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 get_relevance 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 get_relevance 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 get_relevance 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 get_relevance 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 _,_,_,cl = List.nth itl i in
636                 let cl_len = List.length cl in
637                  (* is it a singleton or empty non recursive and non informative
638                     definition? *)
639                  if not
640                   (cl_len = 0 ||
641                    (itl_len = 1 && cl_len = 1 &&
642                     is_non_informative leftno
643                      (let _,_,x = List.hd cl in x)))
644                  then
645                   raise (TypeCheckerFailure (lazy
646                    ("Sort elimination not allowed")));
647           | _,_ -> ())
648        | _,_ -> ()
649    in
650     aux 
651
652  in 
653    typeof_aux context term
654
655 and eat_prods ~subst ~metasenv context he ty_he args_with_ty = 
656   let rec aux ty_he = function 
657   | [] -> ty_he
658   | (arg, ty_arg)::tl ->
659       match R.whd ~subst context ty_he with 
660       | C.Prod (_,s,t) ->
661           if R.are_convertible ~subst get_relevance context ty_arg s then
662             aux (S.subst ~avoid_beta_redexes:true arg t) tl
663           else
664             raise 
665               (TypeCheckerFailure 
666                 (lazy (Printf.sprintf
667                   ("Appl: wrong application of %s: the parameter %s has type"^^
668                    "\n%s\nbut it should have type \n%s\nContext:\n%s\n")
669                   (PP.ppterm ~subst ~metasenv ~context he)
670                   (PP.ppterm ~subst ~metasenv ~context arg)
671                   (PP.ppterm ~subst ~metasenv ~context ty_arg)
672                   (PP.ppterm ~subst ~metasenv ~context s)
673                   (PP.ppcontext ~subst ~metasenv context))))
674        | _ ->
675           raise 
676             (TypeCheckerFailure
677               (lazy (Printf.sprintf
678                 "Appl: %s is not a function, it cannot be applied"
679                 (PP.ppterm ~subst ~metasenv ~context
680                  (let res = List.length tl in
681                   let eaten = List.length args_with_ty - res in
682                    (C.Appl
683                     (he::List.map fst
684                      (fst (HExtlib.split_nth eaten args_with_ty)))))))))
685   in
686     aux ty_he args_with_ty
687
688 and is_non_informative paramsno c =
689  let rec aux context c =
690    match R.whd context c with
691     | C.Prod (n,so,de) ->
692        let s = typeof ~metasenv:[] ~subst:[] context so in
693        s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
694     | _ -> true in
695  let context',dx = split_prods ~subst:[] [] paramsno c in
696   aux context' dx
697
698 and check_mutual_inductive_defs uri ~metasenv ~subst leftno tyl = 
699   (* let's check if the arity of the inductive types are well formed *)
700   List.iter (fun (_,_,x,_) -> ignore (typeof ~subst ~metasenv [] x)) tyl;
701   (* let's check if the types of the inductive constructors are well formed. *)
702   let len = List.length tyl in
703   let tys = List.rev_map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl in
704   ignore
705    (List.fold_right
706     (fun (it_relev,_,ty,cl) i ->
707        let context,ty_sort = split_prods ~subst [] ~-1 ty in
708        let sx_context_ty_rev,_ = HExtlib.split_nth leftno (List.rev context) in
709        List.iter
710          (fun (k_relev,_,te) ->
711            let _,k_relev = HExtlib.split_nth leftno k_relev in
712            let te = debruijn uri len [] te in
713            let context,te = split_prods ~subst tys leftno te in
714            let _,chopped_context_rev =
715             HExtlib.split_nth (List.length tys) (List.rev context) in
716            let sx_context_te_rev,_ =
717             HExtlib.split_nth leftno chopped_context_rev in
718            (try
719              ignore (List.fold_left2
720               (fun context item1 item2 ->
721                 let convertible =
722                  match item1,item2 with
723                    (n1,C.Decl ty1),(n2,C.Decl ty2) ->
724                      n1 = n2 && R.are_convertible ~subst get_relevance context ty1 ty2
725                  | (n1,C.Def (bo1,ty1)),(n2,C.Def (bo2,ty2)) ->
726                      n1 = n2
727                      && R.are_convertible ~subst get_relevance context ty1 ty2
728                      && R.are_convertible ~subst get_relevance context bo1 bo2
729                  | _,_ -> false
730                 in
731                  if not convertible then
732                   raise (TypeCheckerFailure (lazy
733                    ("Mismatch between the left parameters of the constructor " ^
734                     "and those of its inductive type")))
735                  else
736                   item1::context
737               ) [] sx_context_ty_rev sx_context_te_rev)
738             with Invalid_argument _ -> assert false);
739            let con_sort = typeof ~subst ~metasenv context te in
740            (match R.whd ~subst context con_sort, R.whd ~subst [] ty_sort with
741                (C.Sort (C.Type u1) as s1), (C.Sort (C.Type u2) as s2) ->
742                 if not (E.universe_leq u1 u2) then
743                  raise
744                   (TypeCheckerFailure
745                     (lazy ("The type " ^ PP.ppterm ~metasenv ~subst ~context s1^
746                       " of the constructor is not included in the inductive" ^
747                       " type sort " ^ PP.ppterm ~metasenv ~subst ~context s2)))
748              | C.Sort _, C.Sort C.Prop
749              | C.Sort _, C.Sort C.Type _ -> ()
750              | _, _ ->
751                 raise
752                  (TypeCheckerFailure
753                    (lazy ("Wrong constructor or inductive arity shape"))));
754            (* let's check also the positivity conditions *)
755            if 
756              not
757                (are_all_occurrences_positive ~subst context uri leftno
758                  (i+leftno) leftno (len+leftno) te) 
759            then
760              raise
761                (TypeCheckerFailure
762                  (lazy ("Non positive occurence in "^NUri.string_of_uri
763                  uri)))
764            else check_relevance ~subst ~metasenv context k_relev te) 
765          cl;
766         check_relevance ~subst ~metasenv [] it_relev ty;
767         i+1)
768     tyl 1)
769
770 and check_relevance ~subst ~metasenv context relevance ty =
771   let error context ty =
772     raise (TypeCheckerFailure 
773      (lazy ("Wrong relevance declaration: " ^ 
774      String.concat "," (List.map string_of_bool relevance)^ 
775      "\nfor type: "^PP.ppterm ~metasenv ~subst ~context ty)))
776   in
777   let rec aux context relevance ty =
778     match R.whd ~subst context ty with
779     | C.Prod (name,so,de) ->
780         let sort = typeof ~subst ~metasenv context so in
781         (match (relevance,R.whd ~subst context sort) with
782           | [],_ -> ()
783           | false::tl,C.Sort C.Prop -> aux ((name,(C.Decl so))::context) tl de
784           | true::_,C.Sort C.Prop
785           | false::_,C.Sort _
786           | false::_,C.Meta _ -> error context ty
787           | true::tl,C.Sort _
788           | true::tl,C.Meta _ -> aux ((name,(C.Decl so))::context) tl de
789           | _ -> raise (AssertFailure (lazy (Printf.sprintf
790                  "Prod: the type %s of the source of %s is not a sort"
791                   (PP.ppterm ~subst ~metasenv ~context sort)
792                   (PP.ppterm ~subst ~metasenv ~context so)))))
793     | _ -> (match relevance with
794       | [] -> ()
795       | _::_ -> error context ty)
796   in aux context relevance ty
797
798 and guarded_by_destructors r_uri r_len ~subst ~metasenv context recfuns t = 
799  let recursor f k t = U.fold shift_k k (fun k () -> f k) () t in
800  let rec aux (context, recfuns, x as k) t = 
801 (*
802    prerr_endline ("GB:\n" ^ 
803      PP.ppcontext ~subst ~metasenv context^
804      PP.ppterm ~metasenv ~subst ~context t^
805        string_of_recfuns ~subst ~metasenv ~context recfuns);
806 *)
807   try
808   match t with
809   | C.Rel m as t when is_dangerous m recfuns -> 
810       raise (NotGuarded (lazy 
811         (PP.ppterm ~subst ~metasenv ~context t ^ 
812          " is a partial application of a fix")))
813   | C.Appl ((C.Rel m)::tl) as t when is_dangerous m recfuns ->
814      let rec_no = get_recno m recfuns in
815      if not (List.length tl > rec_no) then 
816        raise (NotGuarded (lazy 
817          (PP.ppterm ~context ~subst ~metasenv t ^ 
818          " is a partial application of a fix")))
819      else
820        let rec_arg = List.nth tl rec_no in
821        if not (is_really_smaller r_uri r_len ~subst ~metasenv k rec_arg) then 
822          raise (NotGuarded (lazy (Printf.sprintf ("Recursive call %s, %s is not"
823           ^^ " smaller.\ncontext:\n%s") (PP.ppterm ~context ~subst ~metasenv
824           t) (PP.ppterm ~context ~subst ~metasenv rec_arg)
825           (PP.ppcontext ~subst ~metasenv context))));
826        List.iter (aux k) tl
827   | C.Appl ((C.Rel m)::tl) when is_unfolded m recfuns ->
828        let fixed_args = get_fixed_args m recfuns in
829        HExtlib.list_iter_default2
830         (fun x b -> if not b then aux k x) tl false fixed_args
831   | C.Rel m ->
832      (match List.nth context (m-1) with 
833      | _,C.Decl _ -> ()
834      | _,C.Def (bo,_) -> aux k (S.lift m bo))
835   | C.Meta _ -> ()
836   | C.Appl (C.Const ((Ref.Ref (uri,Ref.Fix (i,recno,_))) as r)::args) ->
837       if List.exists (fun t -> try aux k t;false with NotGuarded _ -> true) args
838       then
839       let fl,_,_ = E.get_checked_fixes_or_cofixes r in
840       let ctx_tys, bos = 
841         List.split (List.map (fun (_,name,_,ty,bo) -> (name, C.Decl ty), bo) fl)
842       in
843       let fl_len = List.length fl in
844       let bos = List.map (debruijn uri fl_len context) bos in
845       let j = List.fold_left min max_int (List.map (fun (_,_,i,_,_)->i) fl) in
846       let ctx_len = List.length context in
847         (* we may look for fixed params not only up to j ... *)
848       let fa = fixed_args bos j ctx_len (ctx_len + fl_len) in
849       HExtlib.list_iter_default2
850        (fun x b -> if not b then aux k x) args false fa; 
851       let context = context@ctx_tys in
852       let ctx_len = List.length context in
853       let extra_recfuns = 
854         HExtlib.list_mapi (fun _ i -> ctx_len - i, UnfFix fa) ctx_tys
855       in
856       let new_k = context, extra_recfuns@recfuns, x in
857       let bos_and_ks = 
858         HExtlib.list_mapi
859          (fun bo fno ->
860           let bo_and_k =
861             eat_or_subst_lambdas ~subst ~metasenv j bo fa args new_k
862           in
863            if
864             fno = i &&
865             List.length args > recno &&
866             (*case where the recursive argument is already really_smaller *)
867             is_really_smaller r_uri r_len ~subst ~metasenv k
868              (List.nth args recno)
869            then
870             let bo,(context, _, _ as new_k) = bo_and_k in
871             let bo, context' =
872              eat_lambdas ~subst ~metasenv context (recno + 1 - j) bo in
873             let new_context_part,_ =
874              HExtlib.split_nth (List.length context' - List.length context)
875               context' in
876             let k = List.fold_right shift_k new_context_part new_k in
877             let context, recfuns, x = k in
878             let k = context, (1,Safe)::recfuns, x in
879               bo,k
880            else
881             bo_and_k
882          ) bos
883       in
884        List.iter (fun (bo,k) -> aux k bo) bos_and_ks
885   | C.Match (Ref.Ref (_,Ref.Ind (true,_,_)),outtype,term,pl) as t ->
886      (match R.whd ~subst context term with
887      | C.Rel m | C.Appl (C.Rel m :: _ ) as t when is_safe m recfuns || m = x ->
888          let ty = typeof ~subst ~metasenv context term in
889          let dc_ctx, dcl, start, stop = 
890            specialize_and_abstract_constrs ~subst r_uri r_len context ty in
891          let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
892          aux k outtype; 
893          List.iter (aux k) args; 
894          List.iter2
895            (fun p (_,dc) ->
896              let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
897              let p, k = get_new_safes ~subst k p rl in
898              aux k p) 
899            pl dcl
900      | _ -> recursor aux k t)
901   | t -> recursor aux k t
902   with
903    NotGuarded _ as exc ->
904     let t' = R.whd ~delta:0 ~subst context t in
905     if t = t' then raise exc
906     else aux k t'
907  in
908   try aux (context, recfuns, 1) t
909   with NotGuarded s -> raise (TypeCheckerFailure s)
910
911 and guarded_by_constructors ~subst ~metasenv context t indURI indlen nn =
912  let rec aux context n nn h te =
913   match R.whd ~subst context te with
914    | C.Rel m when m > n && m <= nn -> h
915    | C.Rel _ | C.Meta _ -> true
916    | C.Sort _
917    | C.Implicit _
918    | C.Prod _
919    | C.Const (Ref.Ref (_,Ref.Ind _))
920    | C.LetIn _ -> raise (AssertFailure (lazy "17"))
921    | C.Lambda (name,so,de) ->
922       does_not_occur ~subst context n nn so &&
923       aux ((name,C.Decl so)::context) (n + 1) (nn + 1) h de
924    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
925       h && List.for_all (does_not_occur ~subst context n nn) tl
926    | C.Const (Ref.Ref (_,Ref.Con _)) -> true
927    | C.Appl (C.Const (Ref.Ref (_, Ref.Con (_,j,paramsno))) :: tl) as t ->
928       let ty_t = typeof ~subst ~metasenv context t in
929       let dc_ctx, dcl, start, stop = 
930         specialize_and_abstract_constrs ~subst indURI indlen context ty_t in
931       let _, dc = List.nth dcl (j-1) in
932 (*
933         prerr_endline (PP.ppterm ~subst ~metasenv ~context:dc_ctx dc);
934         prerr_endline (PP.ppcontext ~subst ~metasenv dc_ctx);
935  *)
936       let rec_params = recursive_args ~subst ~metasenv dc_ctx start stop dc in
937       let rec analyse_instantiated_type rec_spec args =
938        match rec_spec, args with
939        | h::rec_spec, he::args -> 
940            aux context n nn h he && analyse_instantiated_type rec_spec args 
941        | _,[] -> true
942        | _ -> raise (AssertFailure (lazy 
943          ("Too many args for constructor: " ^ String.concat " "
944          (List.map (fun x-> PP.ppterm ~subst ~metasenv ~context x) args))))
945       in
946       let _, args = HExtlib.split_nth paramsno tl in
947       analyse_instantiated_type rec_params args
948    | C.Appl ((C.Match (_,out,te,pl))::_) 
949    | C.Match (_,out,te,pl) as t ->
950        let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
951        List.for_all (does_not_occur ~subst context n nn) tl &&
952        does_not_occur ~subst context n nn out &&
953        does_not_occur ~subst context n nn te &&
954        List.for_all (aux context n nn h) pl
955 (* IMPOSSIBLE unsless we allow to pass cofix to other fix/cofix as we do for 
956    higher order fix in g_b_destructors.
957
958    | C.Const (Ref.Ref (u,(Ref.Fix _| Ref.CoFix _)) as ref)
959    | C.Appl(C.Const (Ref.Ref(u,(Ref.Fix _| Ref.CoFix _)) as ref) :: _) as t ->
960       let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
961       let fl,_,_ = E.get_checked_fixes_or_cofixes ref in 
962       let len = List.length fl in
963       let tys = List.map (fun (_,n,_,ty,_) -> n, C.Decl ty) fl in
964       List.for_all (does_not_occur ~subst context n nn) tl &&
965       List.for_all
966        (fun (_,_,_,_,bo) ->
967           aux (context@tys) n nn h (debruijn u len context bo))
968        fl
969 *)
970    | C.Const _
971    | C.Appl _ as t -> does_not_occur ~subst context n nn t
972  in
973    aux context 0 nn false t
974                                                                       
975 and recursive_args ~subst ~metasenv context n nn te =
976   match R.whd context te with
977   | C.Rel _ | C.Appl _ | C.Const _ -> []
978   | C.Prod (name,so,de) ->
979      (not (does_not_occur ~subst context n nn so)) ::
980       (recursive_args ~subst ~metasenv 
981         ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
982   | t -> 
983      raise (AssertFailure (lazy ("recursive_args:" ^ PP.ppterm ~subst
984      ~metasenv ~context:[] t)))
985
986 and get_new_safes ~subst (context, recfuns, x as k) p rl =
987   match R.whd ~subst context p, rl with
988   | C.Lambda (name,so,ta), b::tl ->
989       let recfuns = (if b then [0,Safe] else []) @ recfuns in
990       get_new_safes ~subst 
991         (shift_k (name,(C.Decl so)) (context, recfuns, x)) ta tl
992   | C.Meta _ as e, _ | e, [] -> e, k
993   | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
994
995 and is_really_smaller 
996   r_uri r_len ~subst ~metasenv (context, recfuns, x as k) te 
997 =
998  match R.whd ~subst context te with
999  | C.Rel m when is_safe m recfuns -> true
1000  | C.Lambda (name, s, t) ->
1001     is_really_smaller r_uri r_len ~subst ~metasenv (shift_k (name,C.Decl s) k) t
1002  | C.Appl (he::_) ->
1003     is_really_smaller r_uri r_len ~subst ~metasenv k he
1004  | C.Rel _ 
1005  | C.Const (Ref.Ref (_,Ref.Con _)) -> false
1006  | C.Appl [] 
1007  | C.Const (Ref.Ref (_,Ref.Fix _)) -> assert false
1008  | C.Meta _ -> true 
1009  | C.Match (Ref.Ref (_,Ref.Ind (isinductive,_,_)),_,term,pl) ->
1010     (match term with
1011     | C.Rel m | C.Appl (C.Rel m :: _ ) when is_safe m recfuns || m = x ->
1012         if not isinductive then
1013           List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl
1014         else
1015           let ty = typeof ~subst ~metasenv context term in
1016           let dc_ctx, dcl, start, stop = 
1017             specialize_and_abstract_constrs ~subst r_uri r_len context ty in
1018           List.for_all2
1019            (fun p (_,dc) -> 
1020              let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
1021              let e, k = get_new_safes ~subst k p rl in
1022              is_really_smaller r_uri r_len ~subst ~metasenv k e)
1023            pl dcl
1024     | _ -> List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl)
1025  | _ -> assert false
1026
1027 and returns_a_coinductive ~subst context ty =
1028   match R.whd ~subst context ty with
1029   | C.Const (Ref.Ref (uri,Ref.Ind (false,_,_)) as ref) 
1030   | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (false,_,_)) as ref)::_) ->
1031      let _, _, itl, _, _ = E.get_checked_indtys ref in
1032      Some (uri,List.length itl)
1033   | C.Prod (n,so,de) ->
1034      returns_a_coinductive ~subst ((n,C.Decl so)::context) de
1035   | _ -> None
1036
1037 and type_of_constant ((Ref.Ref (uri,_)) as ref) = 
1038  let error () =
1039   raise (TypeCheckerFailure (lazy "Inconsistent cached infos in reference"))
1040  in
1041   match E.get_checked_obj uri, ref with
1042   | (_,_,_,_,C.Inductive(isind1,lno1,tl,_)),Ref.Ref(_,Ref.Ind (isind2,i,lno2))->
1043       if isind1 <> isind2 || lno1 <> lno2 then error ();
1044       let _,_,arity,_ = List.nth tl i in arity
1045   | (_,_,_,_,C.Inductive (_,lno1,tl,_)), Ref.Ref (_,Ref.Con (i,j,lno2))  ->
1046       if lno1 <> lno2 then error ();
1047       let _,_,_,cl = List.nth tl i in 
1048       let _,_,arity = List.nth cl (j-1) in 
1049       arity
1050   | (_,_,_,_,C.Fixpoint (false,fl,_)), Ref.Ref (_,Ref.CoFix i) ->
1051       let _,_,_,arity,_ = List.nth fl i in
1052       arity
1053   | (_,h1,_,_,C.Fixpoint (true,fl,_)), Ref.Ref (_,Ref.Fix (i,recno2,h2)) ->
1054       let _,_,recno1,arity,_ = List.nth fl i in
1055       if h1 <> h2 || recno1 <> recno2 then error ();
1056       arity
1057   | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,Ref.Decl) -> ty
1058   | (_,h1,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,Ref.Def h2) ->
1059      if h1 <> h2 then error ();
1060      ty
1061   | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
1062
1063 and get_relevance ~subst context t args = 
1064    let ty = typeof ~subst ~metasenv:[] context t in
1065    let rec aux context ty = function
1066      | [] -> [] 
1067      | arg::tl -> match R.whd ~subst context ty with
1068        | C.Prod (_,so,de) -> 
1069            let sort = typeof ~subst ~metasenv:[] context so in
1070            let new_ty = S.subst ~avoid_beta_redexes:true arg de in
1071            (*prerr_endline ("so: " ^ PP.ppterm ~subst ~metasenv:[]
1072              ~context so);
1073            prerr_endline ("sort: " ^ PP.ppterm ~subst ~metasenv:[]
1074              ~context sort);*)
1075            (match R.whd ~subst context sort with
1076               | C.Sort C.Prop ->
1077                   false::(aux context new_ty tl)
1078               | C.Sort _
1079               | C.Meta _ -> true::(aux context new_ty tl)
1080               | _ -> raise (TypeCheckerFailure (lazy (Printf.sprintf
1081                 "Prod: the type %s of the source of %s is not a sort" 
1082                  (PP.ppterm ~subst ~metasenv:[] ~context sort)
1083                  (PP.ppterm ~subst ~metasenv:[] ~context so)))))
1084        | _ ->
1085           raise 
1086             (TypeCheckerFailure
1087               (lazy (Printf.sprintf
1088                 "Appl: %s is not a function, it cannot be applied"
1089                 (PP.ppterm ~subst ~metasenv:[] ~context
1090                  (let res = List.length tl in
1091                   let eaten = List.length args - res in
1092                    (C.Appl
1093                     (t::fst
1094                      (HExtlib.split_nth eaten args))))))))
1095    in aux context ty args
1096 ;;
1097
1098 let typecheck_context ~metasenv ~subst context =
1099  ignore
1100   (List.fold_right
1101    (fun d context  ->
1102      begin
1103       match d with
1104          _,C.Decl t -> ignore (typeof ~metasenv ~subst:[] context t)
1105        | name,C.Def (te,ty) ->
1106          ignore (typeof ~metasenv ~subst:[] context ty);
1107          let ty' = typeof ~metasenv ~subst:[] context te in
1108           if not (R.are_convertible ~subst get_relevance context ty' ty) then
1109            raise (AssertFailure (lazy (Printf.sprintf (
1110             "the type of the definiens for %s in the context is not "^^
1111             "convertible with the declared one.\n"^^
1112             "inferred type:\n%s\nexpected type:\n%s")
1113             name (PP.ppterm ~subst ~metasenv ~context ty') 
1114             (PP.ppterm ~subst ~metasenv ~context ty))))
1115      end;
1116      d::context
1117    ) context [])
1118 ;;
1119
1120 let typecheck_metasenv metasenv =
1121  ignore
1122   (List.fold_left
1123     (fun metasenv (i,(_,context,ty) as conj) ->
1124       if List.mem_assoc i metasenv then
1125        raise (TypeCheckerFailure (lazy ("duplicate meta " ^ string_of_int i ^
1126         " in metasenv")));
1127       typecheck_context ~metasenv ~subst:[] context;
1128       ignore (typeof ~metasenv ~subst:[] context ty);
1129       metasenv @ [conj]
1130     ) [] metasenv)
1131 ;;
1132
1133 let typecheck_subst ~metasenv subst =
1134  ignore
1135   (List.fold_left
1136     (fun subst (i,(_,context,ty,bo) as conj) ->
1137       if List.mem_assoc i subst then
1138        raise (AssertFailure (lazy ("duplicate meta " ^ string_of_int i ^
1139         " in substitution")));
1140       if List.mem_assoc i metasenv then
1141        raise (AssertFailure (lazy ("meta " ^ string_of_int i ^
1142         " is both in the metasenv and in the substitution")));
1143       typecheck_context ~metasenv ~subst context;
1144       ignore (typeof ~metasenv ~subst context ty);
1145       let ty' = typeof ~metasenv ~subst context bo in
1146        if not (R.are_convertible ~subst get_relevance context ty' ty) then
1147         raise (AssertFailure (lazy (Printf.sprintf (
1148          "the type of the definiens for %d in the substitution is not "^^
1149          "convertible with the declared one.\n"^^
1150          "inferred type:\n%s\nexpected type:\n%s")
1151          i
1152          (PP.ppterm ~subst ~metasenv ~context ty') 
1153          (PP.ppterm ~subst ~metasenv ~context ty))));
1154       subst @ [conj]
1155     ) [] subst)
1156 ;;
1157
1158
1159 let typecheck_obj (uri,_height,metasenv,subst,kind) =
1160  (* height is not checked since it is only used to implement an optimization *)
1161  typecheck_metasenv metasenv;
1162  typecheck_subst ~metasenv subst;
1163  match kind with
1164    | C.Constant (relevance,_,Some te,ty,_) ->
1165       let _ = typeof ~subst ~metasenv [] ty in
1166       let ty_te = typeof ~subst ~metasenv [] te in
1167       if not (R.are_convertible ~subst get_relevance [] ty_te ty) then
1168        raise (TypeCheckerFailure (lazy (Printf.sprintf (
1169         "the type of the body is not convertible with the declared one.\n"^^
1170         "inferred type:\n%s\nexpected type:\n%s")
1171         (PP.ppterm ~subst ~metasenv ~context:[] ty_te) 
1172         (PP.ppterm ~subst ~metasenv ~context:[] ty))));
1173       check_relevance ~subst ~metasenv [] relevance ty
1174       (*check_relevance ~in_type:false ~subst ~metasenv relevance te*)
1175    | C.Constant (relevance,_,None,ty,_) ->
1176       ignore (typeof ~subst ~metasenv [] ty);
1177       check_relevance ~subst ~metasenv [] relevance ty
1178    | C.Inductive (_, leftno, tyl, _) -> 
1179        check_mutual_inductive_defs uri ~metasenv ~subst leftno tyl
1180    | C.Fixpoint (inductive,fl,_) ->
1181       let types, kl =
1182         List.fold_left
1183          (fun (types,kl) (relevance,name,k,ty,_) ->
1184            let _ = typeof ~subst ~metasenv [] ty in
1185             check_relevance ~subst ~metasenv [] relevance ty;
1186             ((name,C.Decl ty)::types, k::kl)
1187          ) ([],[]) fl
1188       in
1189       let len = List.length types in
1190       let dfl, kl =   
1191         List.split (List.map2 
1192           (fun (_,_,_,_,bo) rno -> 
1193              let dbo = debruijn uri len [] bo in
1194              dbo, Evil rno)
1195           fl kl)
1196       in
1197       List.iter2 (fun (_,_,x,ty,_) bo ->
1198        let ty_bo = typeof ~subst ~metasenv types bo in
1199        if not (R.are_convertible ~subst get_relevance types ty_bo ty)
1200        then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1201        else
1202         if inductive then begin
1203           let m, context = eat_lambdas ~subst ~metasenv types (x + 1) bo in
1204           let r_uri, r_len =
1205             let he =
1206              match List.hd context with _,C.Decl t -> t | _ -> assert false
1207             in
1208             match R.whd ~subst (List.tl context) he with
1209             | C.Const (Ref.Ref (uri,Ref.Ind _) as ref)
1210             | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind _) as ref) :: _) ->
1211                 let _,_,itl,_,_ = E.get_checked_indtys ref in
1212                   uri, List.length itl
1213             | _ -> assert false
1214           in
1215           (* guarded by destructors conditions D{f,k,x,M} *)
1216           let rec enum_from k = 
1217             function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl 
1218           in
1219           guarded_by_destructors r_uri r_len 
1220            ~subst ~metasenv context (enum_from (x+2) kl) m
1221         end else
1222          match returns_a_coinductive ~subst [] ty with
1223           | None ->
1224              raise (TypeCheckerFailure
1225                (lazy "CoFix: does not return a coinductive type"))
1226           | Some (r_uri, r_len) ->
1227              (* guarded by constructors conditions C{f,M} *)
1228              if not 
1229              (guarded_by_constructors ~subst ~metasenv types bo r_uri r_len len)
1230              then
1231                raise (TypeCheckerFailure
1232                 (lazy "CoFix: not guarded by constructors"))
1233         ) fl dfl
1234 ;;
1235
1236 (* trust *)
1237
1238 let trust = ref  (fun _ -> false);;
1239 let set_trust f = trust := f
1240 let trust_obj obj = !trust obj
1241
1242
1243 (* web interface stuff *)
1244
1245 let logger = 
1246  ref (function (`Start_type_checking _|`Type_checking_completed _|`Type_checking_interrupted _|`Type_checking_failed _|`Trust_obj _) -> ())
1247 ;;
1248
1249 let set_logger f = logger := f;;
1250
1251 let typecheck_obj obj =
1252  let u,_,_,_,_ = obj in
1253  try
1254   !logger (`Start_type_checking u);
1255   typecheck_obj obj;
1256   !logger (`Type_checking_completed u)
1257  with
1258     Sys.Break as e ->
1259      !logger (`Type_checking_interrupted u);
1260      raise e
1261   | e ->
1262      !logger (`Type_checking_failed u);
1263      raise e
1264 ;;
1265
1266 E.set_typecheck_obj
1267  (fun obj ->
1268    if trust_obj obj then
1269     let u,_,_,_,_ = obj in
1270      !logger (`Trust_obj u)
1271    else
1272     typecheck_obj obj)
1273 ;;
1274
1275 (* EOF *)