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