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