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