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