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