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