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