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