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