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