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