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