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