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