]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/nCicTypeChecker.ml
height of constants properly handled
[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 R = NCicReduction
16 module Ref = NReference
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 type recf_entry = 
26   | Evil of int (* rno *) 
27   | UnfFix of bool list (* fixed arguments *) 
28   | Safe
29 ;;
30
31 let is_dangerous i l = 
32   List.exists (function (j,Evil _) when j=i -> true | _ -> false) l
33 ;;
34
35 let is_unfolded i l = 
36   List.exists (function (j,UnfFix _) when j=i -> true | _ -> false) l
37 ;;
38
39 let is_safe i l =
40   List.exists (function (j,Safe) when j=i -> true | _ -> false) l
41 ;;
42
43 let get_recno i l = 
44   try match List.assoc i l with Evil rno -> rno | _ -> assert false
45   with Not_found -> assert false
46 ;;
47
48 let get_fixed_args i l = 
49   try match List.assoc i l with UnfFix fa -> fa | _ -> assert false
50   with Not_found -> assert false
51 ;;
52
53 let shift_k e (c,rf,x) = e::c,List.map (fun (k,v) -> k+1,v) rf,x+1;;
54
55 (* for debugging only
56 let string_of_recfuns ~subst ~metasenv ~context l = 
57   let pp = PP.ppterm ~subst ~metasenv ~context in
58   let safe, rest = List.partition (function (_,Safe) -> true | _ -> false) l in
59   let dang,unf = List.partition (function (_,UnfFix _)-> false | _->true)rest in
60   "\n\tsafes: "^String.concat "," (List.map (fun (i,_)->pp (C.Rel i)) safe) ^
61   "\n\tfix  : "^String.concat "," 
62    (List.map 
63      (function (i,UnfFix l)-> pp(C.Rel i)^"/"^String.concat "," (List.map
64        string_of_bool l)
65      | _ ->assert false) unf) ^
66   "\n\trec  : "^String.concat "," 
67    (List.map 
68      (function (i,Evil rno)->pp(C.Rel i)^"/"^string_of_int rno
69      | _ -> assert false) dang)
70 ;;
71 *)
72
73 let fixed_args bos j n nn =
74  let rec aux k acc = function
75   | C.Appl (C.Rel i::args) when i-k > n && i-k <= nn ->
76      let rec combine l1 l2 =
77       match l1,l2 with
78          [],[] -> []
79        | he1::tl1, he2::tl2 -> (he1,he2)::combine tl1 tl2
80        | he::tl, [] -> (false,C.Rel ~-1)::combine tl [] (* dummy term *)
81        | [],_::_ -> assert false
82      in
83      let lefts, _ = HExtlib.split_nth (min j (List.length args)) args in
84       List.map (fun ((b,x),i) -> b && x = C.Rel (k-i)) 
85        (HExtlib.list_mapi (fun x i -> x,i) (combine acc lefts))
86   | t -> U.fold (fun _ k -> k+1) k aux acc t    
87  in
88   List.fold_left (aux 0) 
89    (let rec f = function 0 -> [] | n -> true :: f (n-1) in f j) bos
90 ;;
91
92 let rec split_prods ~subst context n te =
93   match (n, R.whd ~subst context te) with
94    | (0, _) -> context,te
95    | (n, C.Prod (name,so,ta)) when n > 0 ->
96        split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
97    | (_, _) -> raise (AssertFailure (lazy "split_prods"))
98 ;;
99
100 let debruijn uri number_of_types context = 
101  let rec aux k t =
102   match t with
103    | C.Meta (i,(s,C.Ctx l)) ->
104       let l1 = HExtlib.sharing_map (aux (k-s)) l in
105       if l1 == l then t else C.Meta (i,(s,C.Ctx l1))
106    | C.Meta _ -> t
107    | C.Const (Ref.Ref (uri1,(Ref.Fix (no,_,_) | Ref.CoFix no))) 
108    | C.Const (Ref.Ref (uri1,Ref.Ind (_,no))) when NUri.eq uri uri1 ->
109       C.Rel (k + number_of_types - no)
110    | t -> U.map (fun _ k -> k+1) k aux t
111  in
112   aux (List.length context)
113 ;;
114
115 let sort_of_prod ~metasenv ~subst context (name,s) (t1, t2) =
116    let t1 = R.whd ~subst context t1 in
117    let t2 = R.whd ~subst ((name,C.Decl s)::context) t2 in
118    match t1, t2 with
119    | C.Sort s1, C.Sort C.Prop -> t2
120    | C.Sort (C.Type u1), C.Sort (C.Type u2) -> C.Sort (C.Type (max u1 u2)) 
121    | C.Sort _,C.Sort (C.Type _) -> t2
122    | C.Sort (C.Type _) , C.Sort C.CProp -> t1
123    | C.Sort _, C.Sort C.CProp
124    | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))), C.Sort _
125    | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))), C.Meta (_,(_,(C.Irl 0 | C.Ctx [])))
126    | C.Sort _, C.Meta  (_,(_,(C.Irl 0 | C.Ctx []))) -> t2
127    | _ -> 
128       raise (TypeCheckerFailure (lazy (Printf.sprintf
129         "Prod: expected two sorts, found = %s, %s" 
130          (PP.ppterm ~subst ~metasenv ~context t1) 
131          (PP.ppterm ~subst ~metasenv ~context t2))))
132 ;;
133
134 let eat_prods ~subst ~metasenv context he ty_he args_with_ty = 
135   let rec aux ty_he = function 
136   | [] -> ty_he
137   | (arg, ty_arg)::tl ->
138       match R.whd ~subst context ty_he with 
139       | C.Prod (n,s,t) ->
140 (*
141           prerr_endline (PP.ppterm ~subst ~metasenv ~context s ^ " - Vs - "
142             ^ PP.ppterm ~subst ~metasenv ~context ty_arg);
143           prerr_endline (PP.ppterm ~subst ~metasenv ~context
144              (S.subst ~avoid_beta_redexes:true arg t));
145 *)
146           if R.are_convertible ~subst context ty_arg s then
147             aux (S.subst ~avoid_beta_redexes:true arg t) tl
148           else
149             raise 
150               (TypeCheckerFailure 
151                 (lazy (Printf.sprintf
152                   ("Appl: wrong application of %s: the parameter %s has type"^^
153                    "\n%s\nbut it should have type \n%s\nContext:\n%s\n")
154                   (PP.ppterm ~subst ~metasenv ~context he)
155                   (PP.ppterm ~subst ~metasenv ~context arg)
156                   (PP.ppterm ~subst ~metasenv ~context ty_arg)
157                   (PP.ppterm ~subst ~metasenv ~context s)
158                   (PP.ppcontext ~subst ~metasenv context))))
159        | _ ->
160           raise 
161             (TypeCheckerFailure
162               (lazy (Printf.sprintf
163                 "Appl: %s is not a function, it cannot be applied"
164                 (PP.ppterm ~subst ~metasenv ~context
165                  (let res = List.length tl in
166                   let eaten = List.length args_with_ty - res in
167                    (C.Appl
168                     (he::List.map fst
169                      (fst (HExtlib.split_nth eaten args_with_ty)))))))))
170   in
171     aux ty_he args_with_ty
172 ;;
173
174 (* instantiate_parameters ps (x1:T1)...(xn:Tn)C                             *)
175 (* returns ((x_|ps|:T_|ps|)...(xn:Tn)C){ps_1 / x1 ; ... ; ps_|ps| / x_|ps|} *)
176 let rec instantiate_parameters params c =
177   match c, params with
178   | c,[] -> c
179   | C.Prod (_,_,ta), he::tl -> instantiate_parameters tl (S.subst he ta)
180   | t,l -> raise (AssertFailure (lazy "1"))
181 ;;
182
183 let specialize_inductive_type_constrs ~subst context ty_term =
184   match R.whd ~subst context ty_term with
185   | C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as ref)  
186   | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as ref) :: _ ) as ty ->
187       let args = match ty with C.Appl (_::tl) -> tl | _ -> [] in
188       let is_ind, leftno, itl, attrs, i = E.get_checked_indtys ref in
189       let left_args,_ = HExtlib.split_nth leftno args in
190       let _,_,_,cl = List.nth itl i in
191       List.map 
192         (fun (rel,name,ty) -> rel, name, instantiate_parameters left_args ty) cl
193   | _ -> assert false
194 ;;
195
196 let specialize_and_abstract_constrs ~subst r_uri r_len context ty_term =
197   let cl = specialize_inductive_type_constrs ~subst context ty_term in
198   let len = List.length context in
199   let context_dcl = 
200     match E.get_checked_obj r_uri with
201     | _,_,_,_, NCic.Inductive (_,_,tys,_) -> 
202         context @ List.map (fun (_,name,arity,_) -> name,C.Decl arity) tys
203     | _ -> assert false
204   in
205   context_dcl,
206   List.map (fun (_,id,ty) -> id, debruijn r_uri r_len context ty) cl,
207   len, len + r_len
208 ;;
209
210 exception DoesOccur;;
211
212 let does_not_occur ~subst context n nn t = 
213   let rec aux k _ = function
214     | C.Rel m when m > n+k && m <= nn+k -> raise DoesOccur
215     | C.Rel m when m <= k || m > nn+k -> ()
216     | C.Rel m ->
217         (try match List.nth context (m-1-k) with
218           | _,C.Def (bo,_) -> aux (n-m) () bo
219           | _ -> ()
220          with Failure _ -> assert false)
221     | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> (* closed meta *) ()
222     | C.Meta (mno,(s,l)) ->
223          (try
224             (* possible optimization here: try does_not_occur on l and
225                perform substitution only if DoesOccur is raised *)
226             let _,_,term,_ = U.lookup_subst mno subst in
227             aux (k-s) () (S.subst_meta (0,l) term)
228           with U.Subst_not_found _ -> match l with
229           | C.Irl len -> if not (n+k >= s+len || s > nn+k) then raise DoesOccur
230           | C.Ctx lc -> List.iter (aux (k-s) ()) lc)
231     | t -> U.fold (fun _ k -> k + 1) k aux () t
232   in
233    try aux 0 () t; true
234    with DoesOccur -> false
235 ;;
236
237 let rec eat_lambdas ~subst ~metasenv context n te =
238   match (n, R.whd ~subst context te) with
239   | (0, _) -> (te, context)
240   | (n, C.Lambda (name,so,ta)) when n > 0 ->
241       eat_lambdas ~subst ~metasenv ((name,(C.Decl so))::context) (n - 1) ta
242    | (n, te) ->
243       raise (AssertFailure (lazy (Printf.sprintf "eat_lambdas (%d, %s)" n 
244         (PP.ppterm ~subst ~metasenv ~context te))))
245 ;;
246
247 let rec eat_or_subst_lambdas ~subst ~metasenv n te to_be_subst args
248      (context, recfuns, x as k)
249 =
250   match n, R.whd ~subst context te, to_be_subst, args with
251   | (n, C.Lambda (name,so,ta),true::to_be_subst,arg::args) when n > 0 ->
252       eat_or_subst_lambdas ~subst ~metasenv (n - 1) (S.subst arg ta)
253        to_be_subst args k
254   | (n, C.Lambda (name,so,ta),false::to_be_subst,arg::args) when n > 0 ->
255       eat_or_subst_lambdas ~subst ~metasenv (n - 1) ta to_be_subst args
256        (shift_k (name,(C.Decl so)) k)
257   | (_, te, _, _) -> te, k
258 ;;
259
260
261 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
262 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
263 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla  *)
264 (*CSC strictly_positive                                                  *)
265 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-)              *)
266 let rec weakly_positive ~subst context n nn uri te =
267 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
268   let dummy = C.Sort (C.Type ~-1) in
269   (*CSC: mettere in cicSubstitution *)
270   let rec subst_inductive_type_with_dummy _ = function
271     | C.Const (Ref.Ref (uri',Ref.Ind (true,0))) when NUri.eq uri' uri -> dummy
272     | C.Appl ((C.Const (Ref.Ref (uri',Ref.Ind (true,0))))::tl) 
273         when NUri.eq uri' uri -> dummy
274     | t -> U.map (fun _ x->x) () subst_inductive_type_with_dummy t
275   in
276   match R.whd context te with
277    | C.Const (Ref.Ref (uri',Ref.Ind _))
278    | C.Appl ((C.Const (Ref.Ref (uri',Ref.Ind _)))::_) 
279       when NUri.eq uri' uri -> true
280    | C.Prod (name,source,dest) when
281       does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
282        (* dummy abstraction, so we behave as in the anonimous case *)
283        strictly_positive ~subst context n nn
284         (subst_inductive_type_with_dummy () source) &&
285        weakly_positive ~subst ((name,C.Decl source)::context)
286         (n + 1) (nn + 1) uri dest
287    | C.Prod (name,source,dest) ->
288        does_not_occur ~subst context n nn
289         (subst_inductive_type_with_dummy () source)&&
290        weakly_positive ~subst ((name,C.Decl source)::context)
291         (n + 1) (nn + 1) uri dest
292    | _ ->
293      raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
294
295 and strictly_positive ~subst context n nn te =
296   match R.whd context te with
297    | t when does_not_occur ~subst context n nn t -> true
298    | C.Rel _ -> true
299    | C.Prod (name,so,ta) ->
300       does_not_occur ~subst context n nn so &&
301        strictly_positive ~subst ((name,C.Decl so)::context) (n+1) (nn+1) ta
302    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
303       List.for_all (does_not_occur ~subst context n nn) tl
304    | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as r)::tl) -> 
305       let _,paramsno,tyl,_,i = E.get_checked_indtys r in
306       let _,name,ity,cl = List.nth tyl i in
307       let ok = List.length tyl = 1 in
308       let params, arguments = HExtlib.split_nth paramsno tl in
309       let lifted_params = List.map (S.lift 1) params in
310       let cl =
311         List.map (fun (_,_,te) -> instantiate_parameters lifted_params te) cl 
312       in
313       ok &&
314       List.for_all (does_not_occur ~subst context n nn) arguments &&
315       List.for_all 
316        (weakly_positive ~subst ((name,C.Decl ity)::context) (n+1) (nn+1) uri) cl
317    | _ -> false
318        
319 (* the inductive type indexes are s.t. n < x <= nn *)
320 and are_all_occurrences_positive ~subst context uri indparamsno i n nn te =
321   match R.whd context te with
322   |  C.Appl ((C.Rel m)::tl) as reduct when m = i ->
323       let last =
324        List.fold_left
325         (fun k x ->
326           if k = 0 then 0
327           else
328            match R.whd context x with
329            |  C.Rel m when m = n - (indparamsno - k) -> k - 1
330            | y -> raise (TypeCheckerFailure (lazy 
331               ("Argument "^string_of_int (indparamsno - k + 1) ^ " (of " ^
332               string_of_int indparamsno ^ " fixed) is not homogeneous in "^
333               "appl:\n"^ PP.ppterm ~context ~subst ~metasenv:[] reduct))))
334         indparamsno tl
335       in
336        if last = 0 then
337         List.for_all (does_not_occur ~subst context n nn) tl
338        else
339         raise (TypeCheckerFailure
340          (lazy ("Non-positive occurence in mutual inductive definition(s) [2]"^
341           NUri.string_of_uri uri)))
342   | C.Rel m when m = i ->
343       if indparamsno = 0 then
344        true
345       else
346         raise (TypeCheckerFailure
347          (lazy ("Non-positive occurence in mutual inductive definition(s) [3]"^
348           NUri.string_of_uri uri)))
349   | C.Prod (name,source,dest) when
350       does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
351       strictly_positive ~subst context n nn source &&
352        are_all_occurrences_positive ~subst 
353         ((name,C.Decl source)::context) uri indparamsno
354         (i+1) (n + 1) (nn + 1) dest
355    | C.Prod (name,source,dest) ->
356        if not (does_not_occur ~subst context n nn source) then
357          raise (TypeCheckerFailure (lazy ("Non-positive occurrence in "^
358          PP.ppterm ~context ~metasenv:[] ~subst te)));
359        are_all_occurrences_positive ~subst ((name,C.Decl source)::context)
360         uri indparamsno (i+1) (n + 1) (nn + 1) dest
361    | _ ->
362      raise
363       (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
364         (NUri.string_of_uri uri))))
365 ;;
366
367 exception NotGuarded of string Lazy.t;;
368
369 let rec typeof ~subst ~metasenv context term =
370   let rec typeof_aux context = 
371     fun t -> (*prerr_endline (PP.ppterm ~metasenv ~subst ~context t);*)
372     match t with
373     | C.Rel n ->
374        (try
375          match List.nth context (n - 1) with
376          | (_,C.Decl ty) -> S.lift n ty
377          | (_,C.Def (_,ty)) -> S.lift n ty
378         with Failure _ -> raise (TypeCheckerFailure (lazy "unbound variable")))
379     | C.Sort (C.Type i) -> C.Sort (C.Type (i+1))
380     | C.Sort s -> C.Sort (C.Type 0)
381     | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
382     | C.Meta (n,l) as t -> 
383        let canonical_ctx,ty =
384         try
385          let _,c,_,ty = U.lookup_subst n subst in c,ty
386         with U.Subst_not_found _ -> try
387          let _,c,ty = U.lookup_meta n metasenv in c,ty
388         with U.Meta_not_found _ ->
389          raise (AssertFailure (lazy (Printf.sprintf
390           "%s not found" (PP.ppterm ~subst ~metasenv ~context t))))
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) (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 ~subst context ty ty_t) 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 (*
430        prerr_endline ("HEAD: " ^ PP.ppterm ~subst ~metasenv ~context ty_he);
431        prerr_endline ("TARGS: " ^ String.concat " | " (List.map (PP.ppterm
432        ~subst ~metasenv ~context) (List.map snd args_with_ty)));
433        prerr_endline ("ARGS: " ^ String.concat " | " (List.map (PP.ppterm
434        ~subst ~metasenv ~context) (List.map fst args_with_ty)));
435 *)
436        eat_prods ~subst ~metasenv context he ty_he args_with_ty
437    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
438    | C.Match (Ref.Ref (_,Ref.Ind (_,tyno)) as r,outtype,term,pl) ->
439       let outsort = typeof_aux context outtype in
440       let inductive,leftno,itl,_,_ = E.get_checked_indtys r in
441       let constructorsno =
442         let _,_,_,cl = List.nth itl tyno in List.length cl
443       in
444       let parameters, arguments =
445         let ty = R.whd ~subst context (typeof_aux context term) in
446         let r',tl =
447          match ty with
448             C.Const (Ref.Ref (_,Ref.Ind _) as r') -> r',[]
449           | C.Appl (C.Const (Ref.Ref (_,Ref.Ind _) as r') :: tl) -> r',tl
450           | _ ->
451              raise 
452                (TypeCheckerFailure (lazy (Printf.sprintf
453                  "Case analysis: analysed term %s is not an inductive one"
454                  (PP.ppterm ~subst ~metasenv ~context term)))) in
455         if not (Ref.eq r r') then
456          raise
457           (TypeCheckerFailure (lazy (Printf.sprintf
458             ("Case analysys: analysed term type is %s, but is expected " ^^
459              "to be (an application of) %s")
460             (PP.ppterm ~subst ~metasenv ~context ty) 
461             (PP.ppterm ~subst ~metasenv ~context (C.Const r')))))
462         else
463          try HExtlib.split_nth leftno tl
464          with
465           Failure _ ->
466            raise (TypeCheckerFailure (lazy (Printf.sprintf 
467            "%s is partially applied" 
468            (PP.ppterm  ~subst ~metasenv ~context ty)))) in
469       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
470       let sort_of_ind_type =
471         if parameters = [] then C.Const r
472         else C.Appl ((C.Const r)::parameters) in
473       let type_of_sort_of_ind_ty = typeof_aux context sort_of_ind_type in
474       check_allowed_sort_elimination ~subst ~metasenv r context
475        sort_of_ind_type type_of_sort_of_ind_ty outsort;
476       (* let's check if the type of branches are right *)
477       if List.length pl <> constructorsno then
478        raise (TypeCheckerFailure (lazy ("Wrong number of cases in a match")));
479       let j,branches_ok,p_ty, exp_p_ty =
480         List.fold_left
481           (fun (j,b,old_p_ty,old_exp_p_ty) p ->
482             if b then
483               let cons = 
484                 let cons = Ref.mk_constructor j r in
485                 if parameters = [] then C.Const cons
486                 else C.Appl (C.Const cons::parameters)
487               in
488               let ty_p = typeof_aux context p in
489               let ty_cons = typeof_aux context cons in
490               let ty_branch = 
491                 type_of_branch ~subst context leftno outtype cons ty_cons 0 
492               in
493               j+1, R.are_convertible ~subst context ty_p ty_branch,
494               ty_p, ty_branch
495             else
496               j,false,old_p_ty,old_exp_p_ty
497           ) (1,true,C.Sort C.Prop,C.Sort C.Prop) pl
498       in
499       if not branches_ok then
500         raise
501          (TypeCheckerFailure 
502           (lazy (Printf.sprintf ("Branch for constructor %s :=\n%s\n"^^
503           "has type %s\nnot convertible with %s") 
504           (PP.ppterm  ~subst ~metasenv ~context
505             (C.Const (Ref.mk_constructor (j-1) r)))
506           (PP.ppterm ~metasenv ~subst ~context (List.nth pl (j-2)))
507           (PP.ppterm ~metasenv ~subst ~context p_ty) 
508           (PP.ppterm ~metasenv ~subst ~context exp_p_ty)))); 
509       let res = outtype::arguments@[term] in
510       R.head_beta_reduce (C.Appl res)
511     | C.Match _ -> assert false
512
513   and type_of_branch ~subst context leftno outty cons tycons liftno = 
514     match R.whd ~subst context tycons with
515     | C.Const (Ref.Ref (_,Ref.Ind _)) -> C.Appl [S.lift liftno outty ; cons]
516     | C.Appl (C.Const (Ref.Ref (_,Ref.Ind _))::tl) ->
517         let _,arguments = HExtlib.split_nth leftno tl in
518         C.Appl (S.lift liftno outty::arguments@[cons])
519     | C.Prod (name,so,de) ->
520         let cons =
521          match S.lift 1 cons with
522          | C.Appl l -> C.Appl (l@[C.Rel 1])
523          | t -> C.Appl [t ; C.Rel 1]
524         in
525          C.Prod (name,so,
526            type_of_branch ~subst ((name,(C.Decl so))::context) 
527             leftno outty cons de (liftno+1))
528     | _ -> raise (AssertFailure (lazy "type_of_branch"))
529
530   (* check_metasenv_consistency checks that the "canonical" context of a
531      metavariable is consitent - up to relocation via the relocation list l -
532      with the actual context *)
533   and check_metasenv_consistency 
534     ~subst ~metasenv term context canonical_context l 
535   =
536    match l with
537     | shift, C.Irl n ->
538        let context = snd (HExtlib.split_nth shift context) in
539         let rec compare = function
540          | 0,_,[] -> ()
541          | 0,_,_::_
542          | _,_,[] ->
543             raise (AssertFailure (lazy (Printf.sprintf
544              "Local and canonical context %s have different lengths"
545              (PP.ppterm ~subst ~context ~metasenv term))))
546          | m,[],_::_ ->
547             raise (TypeCheckerFailure (lazy (Printf.sprintf
548              "Unbound variable -%d in %s" m 
549              (PP.ppterm ~subst ~metasenv ~context term))))
550          | m,t::tl,ct::ctl ->
551             (match t,ct with
552                 (_,C.Decl t1), (_,C.Decl t2)
553               | (_,C.Def (t1,_)), (_,C.Def (t2,_))
554               | (_,C.Def (_,t1)), (_,C.Decl t2) ->
555                  if not (R.are_convertible ~subst tl t1 t2) then
556                   raise 
557                       (TypeCheckerFailure 
558                         (lazy (Printf.sprintf 
559                       ("Not well typed metavariable local context for %s: " ^^ 
560                        "%s expected, which is not convertible with %s")
561                       (PP.ppterm ~subst ~metasenv ~context term) 
562                       (PP.ppterm ~subst ~metasenv ~context t2) 
563                       (PP.ppterm ~subst ~metasenv ~context t1))))
564               | _,_ ->
565                raise 
566                    (TypeCheckerFailure (lazy (Printf.sprintf 
567                     ("Not well typed metavariable local context for %s: " ^^ 
568                      "a definition expected, but a declaration found")
569                     (PP.ppterm ~subst ~metasenv ~context term)))));
570             compare (m - 1,tl,ctl)
571         in
572          compare (n,context,canonical_context)
573     | shift, lc_kind ->
574        (* we avoid useless lifting by shortening the context*)
575        let l,context = (0,lc_kind), snd (HExtlib.split_nth shift context) in
576        let lifted_canonical_context = 
577          let rec lift_metas i = function
578            | [] -> []
579            | (n,C.Decl t)::tl ->
580                (n,C.Decl (S.subst_meta l (S.lift i t)))::(lift_metas (i+1) tl)
581            | (n,C.Def (t,ty))::tl ->
582                (n,C.Def ((S.subst_meta l (S.lift i t)),
583                           S.subst_meta l (S.lift i ty)))::(lift_metas (i+1) tl)
584          in
585           lift_metas 1 canonical_context in
586        let l = U.expand_local_context lc_kind in
587        try
588         List.iter2 
589         (fun t ct -> 
590           match (t,ct) with
591           | t, (_,C.Def (ct,_)) ->
592              (*CSC: the following optimization is to avoid a possibly expensive
593                     reduction that can be easily avoided and that is quite
594                     frequent. However, this is better handled using levels to
595                     control reduction *)
596              let optimized_t =
597               match t with
598               | C.Rel n ->
599                   (try
600                     match List.nth context (n - 1) with
601                     | (_,C.Def (te,_)) -> S.lift n te
602                     | _ -> t
603                     with Failure _ -> t)
604               | _ -> t
605              in
606              if not (R.are_convertible ~subst context optimized_t ct)
607              then
608                raise 
609                  (TypeCheckerFailure 
610                    (lazy (Printf.sprintf 
611                      ("Not well typed metavariable local context: " ^^ 
612                       "expected a term convertible with %s, found %s")
613                      (PP.ppterm ~subst ~metasenv ~context ct) 
614                      (PP.ppterm ~subst ~metasenv ~context t))))
615           | t, (_,C.Decl ct) ->
616               let type_t = typeof_aux context t in
617               if not (R.are_convertible ~subst context type_t ct) then
618                 raise (TypeCheckerFailure 
619                  (lazy (Printf.sprintf 
620                   ("Not well typed metavariable local context: "^^
621                   "expected a term of type %s, found %s of type %s") 
622                   (PP.ppterm ~subst ~metasenv ~context ct) 
623                   (PP.ppterm ~subst ~metasenv ~context t) 
624                   (PP.ppterm ~subst ~metasenv ~context type_t))))
625         ) l lifted_canonical_context 
626        with
627         Invalid_argument _ ->
628           raise (AssertFailure (lazy (Printf.sprintf
629            "Local and canonical context %s have different lengths"
630            (PP.ppterm ~subst ~metasenv ~context term))))
631
632   and is_non_informative context paramsno c =
633    let rec aux context c =
634      match R.whd context c with
635       | C.Prod (n,so,de) ->
636          let s = typeof_aux context so in
637          s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
638       | _ -> true in
639    let context',dx = split_prods ~subst:[] context paramsno c in
640     aux context' dx
641
642   and check_allowed_sort_elimination ~subst ~metasenv r =
643    let mkapp he arg =
644      match he with
645      | C.Appl l -> C.Appl (l @ [arg])
646      | t -> C.Appl [t;arg] in
647    let rec aux context ind arity1 arity2 =
648     let arity1 = R.whd ~subst context arity1 in
649     let arity2 = R.whd ~subst context arity2 in
650       match arity1,arity2 with
651        | C.Prod (name,so1,de1), C.Prod (_,so2,de2) ->
652           if not (R.are_convertible ~subst context so1 so2) then
653            raise (TypeCheckerFailure (lazy (Printf.sprintf
654             "In outtype: expected %s, found %s"
655             (PP.ppterm ~subst ~metasenv ~context so1)
656             (PP.ppterm ~subst ~metasenv ~context so2)
657             )));
658           aux ((name, C.Decl so1)::context)
659            (mkapp (S.lift 1 ind) (C.Rel 1)) de1 de2
660        | C.Sort _, C.Prod (name,so,ta) ->
661           if not (R.are_convertible ~subst context so ind) then
662            raise (TypeCheckerFailure (lazy (Printf.sprintf
663             "In outtype: expected %s, found %s"
664             (PP.ppterm ~subst ~metasenv ~context ind)
665             (PP.ppterm ~subst ~metasenv ~context so)
666             )));
667           (match arity1,ta with
668             | (C.Sort (C.CProp | C.Type _), C.Sort _)
669             | (C.Sort C.Prop, C.Sort C.Prop) -> ()
670             | (C.Sort C.Prop, C.Sort (C.CProp | C.Type _)) ->
671         (* TODO: we should pass all these parameters since we
672          * have them already *)
673                 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
674                 let itl_len = List.length itl in
675                 let _,name,ty,cl = List.nth itl i in
676                 let cl_len = List.length cl in
677                  (* is it a singleton or empty non recursive and non informative
678                     definition? *)
679                  if not
680                   (cl_len = 0 ||
681                    (itl_len = 1 && cl_len = 1 &&
682                     is_non_informative [name,C.Decl ty] leftno
683                      (let _,_,x = List.nth cl 0 in x)))
684                  then
685                   raise (TypeCheckerFailure (lazy
686                    ("Sort elimination not allowed")));
687           | _,_ -> ())
688        | _,_ -> ()
689    in
690     aux 
691
692  in 
693    typeof_aux context term
694
695 and check_mutual_inductive_defs uri ~metasenv ~subst is_ind 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 (List.map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl) in
701   ignore
702    (List.fold_right
703     (fun (_,_,_,cl) i ->
704        List.iter
705          (fun (_,name,te) -> 
706            let debruijnedte = debruijn uri len [] te in
707            ignore (typeof ~subst ~metasenv tys debruijnedte);
708            (* let's check also the positivity conditions *)
709            if 
710              not
711                (are_all_occurrences_positive ~subst tys uri leftno i 0 len
712                   debruijnedte) 
713            then
714              raise
715                (TypeCheckerFailure
716                  (lazy ("Non positive occurence in "^NUri.string_of_uri uri))))
717          cl;
718         i + 1)
719     tyl 1)
720
721 and guarded_by_destructors r_uri r_len ~subst ~metasenv context recfuns t = 
722  let recursor f k t = U.fold shift_k k (fun k () -> f k) () t in
723  let rec aux (context, recfuns, x as k) t = 
724 (*
725    prerr_endline ("GB:\n" ^ 
726      PP.ppcontext ~subst ~metasenv context^
727      PP.ppterm ~metasenv ~subst ~context t^
728        string_of_recfuns ~subst ~metasenv ~context recfuns);
729 *)
730   try
731   match t with
732   | C.Rel m as t when is_dangerous m recfuns -> 
733       raise (NotGuarded (lazy 
734         (PP.ppterm ~subst ~metasenv ~context t ^ 
735          " is a partial application of a fix")))
736   | C.Appl ((C.Rel m)::tl) as t when is_dangerous m recfuns ->
737      let rec_no = get_recno m recfuns in
738      if not (List.length tl > rec_no) then 
739        raise (NotGuarded (lazy 
740          (PP.ppterm ~context ~subst ~metasenv t ^ 
741          " is a partial application of a fix")))
742      else
743        let rec_arg = List.nth tl rec_no in
744        if not (is_really_smaller r_uri r_len ~subst ~metasenv k rec_arg) then 
745          raise (NotGuarded (lazy (Printf.sprintf ("Recursive call %s, %s is not"
746           ^^ " smaller.\ncontext:\n%s") (PP.ppterm ~context ~subst ~metasenv
747           t) (PP.ppterm ~context ~subst ~metasenv rec_arg)
748           (PP.ppcontext ~subst ~metasenv context))));
749        List.iter (aux k) tl
750   | C.Appl ((C.Rel m)::tl) when is_unfolded m recfuns ->
751        let fixed_args = get_fixed_args m recfuns in
752        HExtlib.list_iter_default2
753         (fun x b -> if not b then aux k x) tl false fixed_args
754   | C.Rel m ->
755      (match List.nth context (m-1) with 
756      | _,C.Decl _ -> ()
757      | _,C.Def (bo,_) -> aux k (S.lift m bo))
758   | C.Meta _ -> ()
759   | C.Appl (C.Const ((Ref.Ref (uri,Ref.Fix (i,recno,_))) as r)::args) ->
760       if List.exists (fun t -> try aux k t;false with NotGuarded _ -> true) args
761       then
762       let fl,_,_ = E.get_checked_fixes_or_cofixes r in
763       let ctx_tys, bos = 
764         List.split (List.map (fun (_,name,_,ty,bo) -> (name, C.Decl ty), bo) fl)
765       in
766       let fl_len = List.length fl in
767       let bos = List.map (debruijn uri fl_len context) bos in
768       let j = List.fold_left min max_int (List.map (fun (_,_,i,_,_)->i) fl) in
769       let ctx_len = List.length context in
770         (* we may look for fixed params not only up to j ... *)
771       let fa = fixed_args bos j ctx_len (ctx_len + fl_len) in
772       HExtlib.list_iter_default2
773        (fun x b -> if not b then aux k x) args false fa; 
774       let context = context@ctx_tys in
775       let ctx_len = List.length context in
776       let extra_recfuns = 
777         HExtlib.list_mapi (fun _ i -> ctx_len - i, UnfFix fa) ctx_tys
778       in
779       let new_k = context, extra_recfuns@recfuns, x in
780       let bos_and_ks = 
781         HExtlib.list_mapi
782          (fun bo fno ->
783           let bo_and_k =
784             eat_or_subst_lambdas ~subst ~metasenv j bo fa args new_k
785           in
786            if
787             fno = i &&
788             List.length args > recno &&
789             (*case where the recursive argument is already really_smaller *)
790             is_really_smaller r_uri r_len ~subst ~metasenv k
791              (List.nth args recno)
792            then
793             let bo,(context, _, _ as new_k) = bo_and_k in
794             let bo, context' =
795              eat_lambdas ~subst ~metasenv context (recno + 1 - j) bo in
796             let new_context_part,_ =
797              HExtlib.split_nth (List.length context' - List.length context)
798               context' in
799             let k = List.fold_right shift_k new_context_part new_k in
800             let context, recfuns, x = k in
801             let k = context, (1,Safe)::recfuns, x in
802               bo,k
803            else
804             bo_and_k
805          ) bos
806       in
807        List.iter (fun (bo,k) -> aux k bo) bos_and_ks
808   | C.Match (Ref.Ref (uri,Ref.Ind (true,_)),outtype,term,pl) as t ->
809      (match R.whd ~subst context term with
810      | C.Rel m | C.Appl (C.Rel m :: _ ) as t when is_safe m recfuns || m = x ->
811          let ty = typeof ~subst ~metasenv context term in
812          let dc_ctx, dcl, start, stop = 
813            specialize_and_abstract_constrs ~subst r_uri r_len context ty in
814          let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
815          aux k outtype; 
816          List.iter (aux k) args; 
817          List.iter2
818            (fun p (_,dc) ->
819              let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
820              let p, k = get_new_safes ~subst k p rl in
821              aux k p) 
822            pl dcl
823      | _ -> recursor aux k t)
824   | t -> recursor aux k t
825   with
826    NotGuarded _ as exc ->
827     let t' = R.whd ~delta:0 ~subst context t in
828     if t = t' then raise exc
829     else aux k t'
830  in
831   try aux (context, recfuns, 1) t
832   with NotGuarded s -> raise (TypeCheckerFailure s)
833
834 and guarded_by_constructors ~subst ~metasenv context t indURI indlen nn =
835  let rec aux context n nn h te =
836   match R.whd ~subst context te with
837    | C.Rel m when m > n && m <= nn -> h
838    | C.Rel _ | C.Meta _ -> true
839    | C.Sort _
840    | C.Implicit _
841    | C.Prod _
842    | C.Const (Ref.Ref (_,Ref.Ind _))
843    | C.LetIn _ -> raise (AssertFailure (lazy "17"))
844    | C.Lambda (name,so,de) ->
845       does_not_occur ~subst context n nn so &&
846       aux ((name,C.Decl so)::context) (n + 1) (nn + 1) h de
847    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
848       h && List.for_all (does_not_occur ~subst context n nn) tl
849    | C.Const (Ref.Ref (_,Ref.Con _)) -> true
850    | C.Appl (C.Const (Ref.Ref (uri, Ref.Con (_,j)) as ref) :: tl) as t ->
851       let _, paramsno, _, _, _ = E.get_checked_indtys ref in
852       let ty_t = typeof ~subst ~metasenv context t in
853       let dc_ctx, dcl, start, stop = 
854         specialize_and_abstract_constrs ~subst indURI indlen context ty_t in
855       let _, dc = List.nth dcl (j-1) in
856 (*
857         prerr_endline (PP.ppterm ~subst ~metasenv ~context:dc_ctx dc);
858         prerr_endline (PP.ppcontext ~subst ~metasenv dc_ctx);
859  *)
860       let rec_params = recursive_args ~subst ~metasenv dc_ctx start stop dc in
861       let rec analyse_instantiated_type rec_spec args =
862        match rec_spec, args with
863        | h::rec_spec, he::args -> 
864            aux context n nn h he && analyse_instantiated_type rec_spec args 
865        | _,[] -> true
866        | _ -> raise (AssertFailure (lazy 
867          ("Too many args for constructor: " ^ String.concat " "
868          (List.map (fun x-> PP.ppterm ~subst ~metasenv ~context x) args))))
869       in
870       let left, args = HExtlib.split_nth paramsno tl in
871       List.for_all (does_not_occur ~subst context n nn) left &&
872       analyse_instantiated_type rec_params args
873    | C.Appl ((C.Match (_,out,te,pl))::_) 
874    | C.Match (_,out,te,pl) as t ->
875        let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
876        List.for_all (does_not_occur ~subst context n nn) tl &&
877        does_not_occur ~subst context n nn out &&
878        does_not_occur ~subst context n nn te &&
879        List.for_all (aux context n nn h) pl
880    | C.Const (Ref.Ref (u,(Ref.Fix _| Ref.CoFix _)) as ref)
881    | C.Appl(C.Const (Ref.Ref(u,(Ref.Fix _| Ref.CoFix _)) as ref) :: _) as t ->
882       let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
883       let fl,_,_ = E.get_checked_fixes_or_cofixes ref in 
884       let len = List.length fl in
885       let tys = List.map (fun (_,n,_,ty,_) -> n, C.Decl ty) fl in
886       List.for_all (does_not_occur ~subst context n nn) tl &&
887       List.for_all
888        (fun (_,_,_,_,bo) ->
889           aux (context@tys) n nn h (debruijn u len context bo))
890        fl
891    | C.Const _
892    | C.Appl _ as t -> does_not_occur ~subst context n nn t
893  in
894    aux context 0 nn false t
895                                                                       
896 and recursive_args ~subst ~metasenv context n nn te =
897   match R.whd context te with
898   | C.Rel _ | C.Appl _ | C.Const _ -> []
899   | C.Prod (name,so,de) ->
900      (not (does_not_occur ~subst context n nn so)) ::
901       (recursive_args ~subst ~metasenv 
902         ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
903   | t -> 
904      raise (AssertFailure (lazy ("recursive_args:" ^ PP.ppterm ~subst
905      ~metasenv ~context:[] t)))
906
907 and get_new_safes ~subst (context, recfuns, x as k) p rl =
908   match R.whd ~subst context p, rl with
909   | C.Lambda (name,so,ta), b::tl ->
910       let recfuns = (if b then [0,Safe] else []) @ recfuns in
911       get_new_safes ~subst 
912         (shift_k (name,(C.Decl so)) (context, recfuns, x)) ta tl
913   | C.Meta _ as e, _ | e, [] -> e, k
914   | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
915
916 and is_really_smaller 
917   r_uri r_len ~subst ~metasenv (context, recfuns, x as k) te 
918 =
919  match R.whd ~subst context te with
920  | C.Rel m when is_safe m recfuns -> true
921  | C.Lambda (name, s, t) ->
922     is_really_smaller r_uri r_len ~subst ~metasenv (shift_k (name,C.Decl s) k) t
923  | C.Appl (he::_) ->
924     is_really_smaller r_uri r_len ~subst ~metasenv k he
925  | C.Rel _ 
926  | C.Const (Ref.Ref (_,Ref.Con _)) -> false
927  | C.Appl [] 
928  | C.Const (Ref.Ref (_,Ref.Fix _)) -> assert false
929  | C.Meta _ -> true 
930  | C.Match (Ref.Ref (uri,_) as ref,outtype,term,pl) ->
931     (match term with
932     | C.Rel m | C.Appl (C.Rel m :: _ ) when is_safe m recfuns || m = x ->
933         (* TODO: add CoInd to references so that this call is useless *)
934         let isinductive, _, _, _, _ = E.get_checked_indtys ref in
935         if not isinductive then
936           List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl
937         else
938           let ty = typeof ~subst ~metasenv context term in
939           let dc_ctx, dcl, start, stop = 
940             specialize_and_abstract_constrs ~subst r_uri r_len context ty in
941           List.for_all2
942            (fun p (_,dc) -> 
943              let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
944              let e, k = get_new_safes ~subst k p rl in
945              is_really_smaller r_uri r_len ~subst ~metasenv k e)
946            pl dcl
947     | _ -> List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl)
948  | _ -> assert false
949
950 and returns_a_coinductive ~subst context ty =
951   match R.whd ~subst context ty with
952   | C.Const (Ref.Ref (uri,Ref.Ind (false,_)) as ref) 
953   | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (false,_)) as ref)::_) ->
954      let _, _, itl, _, _ = E.get_checked_indtys ref in
955      Some (uri,List.length itl)
956   | C.Prod (n,so,de) ->
957      returns_a_coinductive ~subst ((n,C.Decl so)::context) de
958   | _ -> None
959
960 and type_of_constant ((Ref.Ref (uri,_)) as ref) = 
961   match E.get_checked_obj uri, ref with
962   | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,Ref.Ind (_,i))  ->
963       let _,_,arity,_ = List.nth tl i in arity
964   | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,Ref.Con (i,j))  ->
965       let _,_,_,cl = List.nth tl i in 
966       let _,_,arity = List.nth cl (j-1) in 
967       arity
968   | (_,_,_,_,C.Fixpoint (_,fl,_)), Ref.Ref (_,(Ref.Fix (i,_,_)|Ref.CoFix i)) ->
969       let _,_,_,arity,_ = List.nth fl i in
970       arity
971   | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,(Ref.Def _|Ref.Decl)) -> ty
972   | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
973 ;;
974
975 let typecheck_context ~metasenv ~subst context =
976  ignore
977   (List.fold_right
978    (fun d context  ->
979      begin
980       match d with
981          _,C.Decl t -> ignore (typeof ~metasenv ~subst:[] context t)
982        | name,C.Def (te,ty) ->
983          ignore (typeof ~metasenv ~subst:[] context ty);
984          let ty' = typeof ~metasenv ~subst:[] context te in
985           if not (R.are_convertible ~subst context ty' ty) then
986            raise (AssertFailure (lazy (Printf.sprintf (
987             "the type of the definiens for %s in the context is not "^^
988             "convertible with the declared one.\n"^^
989             "inferred type:\n%s\nexpected type:\n%s")
990             name
991             (PP.ppterm ~subst ~metasenv ~context ty') 
992             (PP.ppterm ~subst ~metasenv ~context ty))))
993      end;
994      d::context
995    ) context [])
996 ;;
997
998 let typecheck_metasenv metasenv =
999  ignore
1000   (List.fold_left
1001     (fun metasenv (i,(_,context,ty) as conj) ->
1002       if List.mem_assoc i metasenv then
1003        raise (TypeCheckerFailure (lazy ("duplicate meta " ^ string_of_int i ^
1004         " in metasenv")));
1005       typecheck_context ~metasenv ~subst:[] context;
1006       ignore (typeof ~metasenv ~subst:[] context ty);
1007       metasenv @ [conj]
1008     ) [] metasenv)
1009 ;;
1010
1011 let typecheck_subst ~metasenv subst =
1012  ignore
1013   (List.fold_left
1014     (fun subst (i,(_,context,ty,bo) as conj) ->
1015       if List.mem_assoc i subst then
1016        raise (AssertFailure (lazy ("duplicate meta " ^ string_of_int i ^
1017         " in substitution")));
1018       if List.mem_assoc i metasenv then
1019        raise (AssertFailure (lazy ("meta " ^ string_of_int i ^
1020         " is both in the metasenv and in the substitution")));
1021       typecheck_context ~metasenv ~subst context;
1022       ignore (typeof ~metasenv ~subst context ty);
1023       let ty' = typeof ~metasenv ~subst context bo in
1024        if not (R.are_convertible ~subst context ty' ty) then
1025         raise (AssertFailure (lazy (Printf.sprintf (
1026          "the type of the definiens for %d in the substitution is not "^^
1027          "convertible with the declared one.\n"^^
1028          "inferred type:\n%s\nexpected type:\n%s")
1029          i
1030          (PP.ppterm ~subst ~metasenv ~context ty') 
1031          (PP.ppterm ~subst ~metasenv ~context ty))));
1032       subst @ [conj]
1033     ) [] subst)
1034 ;;
1035
1036 let typecheck_obj (uri,height,metasenv,subst,kind) =
1037  typecheck_metasenv metasenv;
1038  typecheck_subst ~metasenv subst;
1039  match kind with
1040    | C.Constant (_,_,Some te,ty,_) ->
1041       let _ = typeof ~subst ~metasenv [] ty in
1042       let ty_te = typeof ~subst ~metasenv [] te in
1043       if not (R.are_convertible ~subst [] ty_te ty) then
1044        raise (TypeCheckerFailure (lazy (Printf.sprintf (
1045         "the type of the body is not convertible with the declared one.\n"^^
1046         "inferred type:\n%s\nexpected type:\n%s")
1047         (PP.ppterm ~subst ~metasenv ~context:[] ty_te) 
1048         (PP.ppterm ~subst ~metasenv ~context:[] ty))))
1049    | C.Constant (_,_,None,ty,_) -> ignore (typeof ~subst ~metasenv [] ty)
1050    | C.Inductive (is_ind, leftno, tyl, _) -> 
1051        check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl
1052    | C.Fixpoint (inductive,fl,_) ->
1053       let types, kl =
1054         List.fold_left
1055          (fun (types,kl) (_,name,k,ty,_) ->
1056            let _ = typeof ~subst ~metasenv [] ty in
1057             ((name,C.Decl ty)::types, k::kl)
1058          ) ([],[]) fl
1059       in
1060       let len = List.length types in
1061       let dfl, kl =   
1062         List.split (List.map2 
1063           (fun (_,_,_,_,bo) rno -> 
1064              let dbo = debruijn uri len [] bo in
1065              dbo, Evil rno)
1066           fl kl)
1067       in
1068       List.iter2 (fun (_,name,x,ty,_) bo ->
1069        let ty_bo = typeof ~subst ~metasenv types bo in
1070        if not (R.are_convertible ~subst types ty_bo ty)
1071        then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1072        else
1073         if inductive then begin
1074           let m, context = eat_lambdas ~subst ~metasenv types (x + 1) bo in
1075           let r_uri, r_len =
1076             let he =
1077              match List.hd context with _,C.Decl t -> t | _ -> assert false
1078             in
1079             match R.whd ~subst (List.tl context) he with
1080             | C.Const (Ref.Ref (uri,Ref.Ind _) as ref)
1081             | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind _) as ref) :: _) ->
1082                 let _,_,itl,_,_ = E.get_checked_indtys ref in
1083                   uri, List.length itl
1084             | _ -> assert false
1085           in
1086           (* guarded by destructors conditions D{f,k,x,M} *)
1087           let rec enum_from k = 
1088             function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl 
1089           in
1090           guarded_by_destructors r_uri r_len 
1091            ~subst ~metasenv context (enum_from (x+2) kl) m
1092         end else
1093          match returns_a_coinductive ~subst [] ty with
1094           | None ->
1095              raise (TypeCheckerFailure
1096                (lazy "CoFix: does not return a coinductive type"))
1097           | Some (r_uri, r_len) ->
1098              (* guarded by constructors conditions C{f,M} *)
1099              if not 
1100              (guarded_by_constructors ~subst ~metasenv types bo r_uri r_len len)
1101              then
1102                raise (TypeCheckerFailure
1103                 (lazy "CoFix: not guarded by constructors"))
1104         ) fl dfl
1105 ;;
1106
1107 (* trust *)
1108
1109 let trust = ref  (fun _ -> false);;
1110 let set_trust f = trust := f
1111 let trust_obj obj = !trust obj
1112
1113
1114 (* web interface stuff *)
1115
1116 let logger = 
1117  ref (function (`Start_type_checking _|`Type_checking_completed _|`Type_checking_interrupted _|`Type_checking_failed _|`Trust_obj _) -> ())
1118 ;;
1119
1120 let set_logger f = logger := f;;
1121
1122 let typecheck_obj obj =
1123  let u,_,_,_,_ = obj in
1124  try
1125   !logger (`Start_type_checking u);
1126   typecheck_obj obj;
1127   !logger (`Type_checking_completed u)
1128  with
1129     Sys.Break as e ->
1130      !logger (`Type_checking_interrupted u);
1131      raise e
1132   | e ->
1133      !logger (`Type_checking_failed u);
1134      raise e
1135 ;;
1136
1137 E.set_typecheck_obj
1138  (fun obj ->
1139    if trust_obj obj then
1140     let u,_,_,_,_ = obj in
1141      !logger (`Trust_obj u)
1142    else
1143     typecheck_obj obj)
1144 ;;
1145
1146 (* EOF *)