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