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