]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_kernel/nCicTypeChecker.ml
quinck and untested implementation of positivity conditions check
[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 (* $Id: cicTypeChecker.ml 8213 2008-03-13 18:48:26Z sacerdot $ *)
30
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 = 
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 0
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\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        | _ ->
359           raise 
360             (TypeCheckerFailure
361               (lazy (Printf.sprintf
362                 "Appl: %s is not a function, it cannot be applied"
363                 (NCicPp.ppterm ~subst ~metasenv ~context
364                  (let res = List.length tl in
365                   let eaten = List.length args_with_ty - res in
366                    (NCic.Appl
367                     (he::List.map fst
368                      (fst (HExtlib.split_nth eaten args_with_ty)))))))))
369   in
370     aux ty_he args_with_ty
371 ;;
372
373 let fix_lefts_in_constrs ~subst uri paramsno tyl i =
374   let len = List.length tyl in
375   let _,_,arity,cl = List.nth tyl i in
376   let tys = List.map (fun (_,n,ty,_) -> n,C.Decl ty) tyl in
377   let cl' =
378    List.map
379     (fun (_,id,ty) ->
380       let debruijnedty = debruijn uri len ty in
381       id, snd (split_prods ~subst tys paramsno ty),
382        snd (split_prods ~subst tys paramsno debruijnedty))
383     cl 
384   in
385   let lefts = fst (split_prods ~subst [] paramsno arity) in
386   lefts@tys, len, cl'
387 ;;
388
389 exception DoesOccur;;
390
391 let does_not_occur ~subst context n nn t = 
392   let rec aux (context,n,nn as k) _ = function
393     | C.Rel m when m > n && m <= nn -> raise DoesOccur
394     | C.Rel m ->
395         (try (match List.nth context (m-1) with
396           | _,C.Def (bo,_) -> aux k () (S.lift m bo)
397           | _ -> ())
398          with Failure _ -> assert false)
399     | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> (* closed meta *) ()
400     | C.Meta (mno,(s,l)) ->
401          (try
402            let _,_,term,_ = U.lookup_subst mno subst in
403            aux (context,n+s,nn+s) () (S.subst_meta (0,l) term)
404           with CicUtil.Subst_not_found _ -> match l with
405           | C.Irl len -> if not (n >= s+len || s > nn) then raise DoesOccur
406           | C.Ctx lc -> List.iter (aux (context,n+s,nn+s) ()) lc)
407     | t -> U.fold (fun e (ctx,n,nn) -> (e::ctx,n+1,nn+1)) k aux () t
408   in
409    try aux (context,n,nn) () t; true
410    with DoesOccur -> false
411 ;;
412
413 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
414 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
415 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla  *)
416 (*CSC strictly_positive                                                  *)
417 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-)              *)
418 let rec weakly_positive ~subst context n nn uri te =
419 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
420   let dummy_mutind = C.Implicit `Hole in
421   (*CSC: mettere in cicSubstitution *)
422   let rec subst_inductive_type_with_dummy_mutind _ = function
423     | C.Const (Ref.Ref (_,uri',Ref.Ind 0)) when NUri.eq uri' uri -> dummy_mutind
424     | C.Appl ((C.Const (Ref.Ref (_,uri',Ref.Ind 0)))::tl) when NUri.eq uri' uri ->
425        dummy_mutind
426     | t -> U.map (fun _ x->x) () subst_inductive_type_with_dummy_mutind t
427   in
428   match R.whd context te with
429    | C.Const (Ref.Ref (_,uri',Ref.Ind _))
430    | C.Appl ((C.Const (Ref.Ref (_,uri',Ref.Ind _)))::_) when NUri.eq uri' uri -> true
431    | C.Prod (name,source,dest) when
432       does_not_occur ~subst ((name,C.Decl source)::context) 0 n dest ->
433        (* dummy abstraction, so we behave as in the anonimous case *)
434        strictly_positive ~subst context n nn
435         (subst_inductive_type_with_dummy_mutind () source) &&
436          weakly_positive ~subst ((name,C.Decl source)::context)
437          (n + 1) (nn + 1) uri dest
438    | C.Prod (name,source,dest) ->
439        does_not_occur ~subst context n nn
440          (subst_inductive_type_with_dummy_mutind () source)&&
441          weakly_positive ~subst ((name,C.Decl source)::context)
442          (n + 1) (nn + 1) uri dest
443    | _ ->
444      raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
445
446 (* instantiate_parameters ps (x1:T1)...(xn:Tn)C                             *)
447 (* returns ((x_|ps|:T_|ps|)...(xn:Tn)C){ps_1 / x1 ; ... ; ps_|ps| / x_|ps|} *)
448 and instantiate_parameters params c =
449   match c, params with
450   | c,[] -> c
451   | C.Prod (_,_,ta), he::tl -> instantiate_parameters tl (S.subst he ta)
452   | t,l -> raise (AssertFailure (lazy "1"))
453
454 and strictly_positive ~subst context n nn te =
455   match R.whd context te with
456    | t when does_not_occur ~subst context n nn t -> true
457    | C.Rel _ -> true
458    | C.Prod (name,so,ta) ->
459       does_not_occur ~subst context n nn so &&
460        strictly_positive ~subst ((name,C.Decl so)::context) (n+1) (nn+1) ta
461    | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
462       List.for_all (does_not_occur ~subst context n nn) tl
463    | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind i) as r)::tl) -> 
464       let _,paramsno,tyl,_,i = E.get_checked_indtys r in
465       let _,name,ity,cl = List.nth tyl i in
466       let ok = List.length tyl = 1 in
467       let params, arguments = HExtlib.split_nth paramsno tl in
468       let lifted_params = List.map (S.lift 1) params in
469       let cl =
470         List.map (fun (_,_,te) -> instantiate_parameters lifted_params te) cl 
471       in
472       ok &&
473       List.for_all (does_not_occur ~subst context n nn) arguments &&
474       List.for_all 
475         (weakly_positive ~subst ((name,C.Decl ity)::context) (n+1) (nn+1) uri) cl
476    | _ -> false
477        
478 (* the inductive type indexes are s.t. n < x <= nn *)
479 and are_all_occurrences_positive ~subst context uri indparamsno i n nn te =
480   match R.whd context te with
481   |  C.Appl ((C.Rel m)::tl) when m = i ->
482       let last =
483        List.fold_left
484         (fun k x ->
485           if k = 0 then 0
486           else
487            match R.whd context x with
488            |  C.Rel m when m = n - (indparamsno - k) -> k - 1
489            | _ -> raise (TypeCheckerFailure (lazy 
490               ("Non-positive occurence in mutual inductive definition(s) [1]" ^
491               NUri.string_of_uri uri))))
492         indparamsno tl
493       in
494        if last = 0 then
495         List.for_all (does_not_occur ~subst context n nn) tl
496        else
497         raise (TypeCheckerFailure
498          (lazy ("Non-positive occurence in mutual inductive definition(s) [2]"^
499           NUri.string_of_uri uri)))
500   | C.Rel m when m = i ->
501       if indparamsno = 0 then
502        true
503       else
504         raise (TypeCheckerFailure
505          (lazy ("Non-positive occurence in mutual inductive definition(s) [3]"^
506           NUri.string_of_uri uri)))
507   | C.Prod (name,source,dest) when
508       does_not_occur ~subst ((name,C.Decl source)::context) 0 n dest ->
509       strictly_positive ~subst context n nn source &&
510        are_all_occurrences_positive ~subst 
511         ((name,C.Decl source)::context) uri indparamsno
512         (i+1) (n + 1) (nn + 1) dest
513    | C.Prod (name,source,dest) ->
514       does_not_occur ~subst context n nn source &&
515        are_all_occurrences_positive ~subst ((name,C.Decl source)::context)
516         uri indparamsno (i+1) (n + 1) (nn + 1) dest
517    | _ ->
518      raise
519       (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
520         (NUri.string_of_uri uri))))
521 ;;
522
523 exception NotGuarded of string Lazy.t;;
524
525 let rec typeof ~subst ~metasenv context term =
526   let rec typeof_aux context = 
527     fun t -> (*prerr_endline (NCicPp.ppterm ~context t); *)
528     match t with
529     | C.Rel n ->
530        (try
531          match List.nth context (n - 1) with
532          | (_,C.Decl ty) -> S.lift n ty
533          | (_,C.Def (_,ty)) -> S.lift n ty
534         with Failure _ -> raise (TypeCheckerFailure (lazy "unbound variable")))
535     | C.Sort (C.Type i) -> C.Sort (C.Type (i+1))
536     | C.Sort s -> C.Sort (C.Type 0)
537     | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
538     | C.Meta (n,l) as t -> 
539        let canonical_ctx,ty =
540         try
541          let _,c,_,ty = U.lookup_subst n subst in c,ty
542         with U.Subst_not_found _ -> try
543          let _,_,c,ty = U.lookup_meta n metasenv in c,ty
544         with U.Meta_not_found _ ->
545          raise (AssertFailure (lazy (Printf.sprintf
546           "%s not found" (NCicPp.ppterm ~subst ~metasenv ~context t))))
547        in
548         check_metasenv_consistency t ~subst ~metasenv context canonical_ctx l;
549         S.subst_meta l ty
550     | C.Const ref -> type_of_constant ref
551     | C.Prod (name,s,t) ->
552        let sort1 = typeof_aux context s in
553        let sort2 = typeof_aux ((name,(C.Decl s))::context) t in
554        sort_of_prod ~metasenv ~subst context (name,s) (sort1,sort2)
555     | C.Lambda (n,s,t) ->
556        let sort = typeof_aux context s in
557        (match R.whd ~subst context sort with
558        | C.Meta _ | C.Sort _ -> ()
559        | _ ->
560          raise
561            (TypeCheckerFailure (lazy (Printf.sprintf
562              ("Not well-typed lambda-abstraction: " ^^
563              "the source %s should be a type; instead it is a term " ^^ 
564              "of type %s") (NCicPp.ppterm ~subst ~metasenv ~context s)
565              (NCicPp.ppterm ~subst ~metasenv ~context sort)))));
566        let ty = typeof_aux ((n,(C.Decl s))::context) t in
567          C.Prod (n,s,ty)
568     | C.LetIn (n,ty,t,bo) ->
569        let ty_t = typeof_aux context t in
570        let _ = typeof_aux context ty in
571        if not (R.are_convertible ~subst ~metasenv context ty ty_t) then
572          raise 
573           (TypeCheckerFailure 
574             (lazy (Printf.sprintf
575               "The type of %s is %s but it is expected to be %s" 
576                 (NCicPp.ppterm ~subst ~metasenv ~context t) 
577                 (NCicPp.ppterm ~subst ~metasenv ~context ty_t) 
578                 (NCicPp.ppterm ~subst ~metasenv ~context ty))))
579        else
580          let ty_bo = typeof_aux  ((n,C.Def (t,ty))::context) bo in
581          S.subst ~avoid_beta_redexes:true t ty_bo
582     | C.Appl (he::(_::_ as args)) ->
583        let ty_he = typeof_aux context he in
584        let args_with_ty = List.map (fun t -> t, typeof_aux context t) args in
585 (*
586        prerr_endline ("HEAD: " ^ NCicPp.ppterm ~subst ~metasenv ~context ty_he);
587        prerr_endline ("TARGS: " ^ String.concat " | " (List.map (NCicPp.ppterm
588        ~subst ~metasenv ~context) (List.map snd args_with_ty)));
589        prerr_endline ("ARGS: " ^ String.concat " | " (List.map (NCicPp.ppterm
590        ~subst ~metasenv ~context) (List.map fst args_with_ty)));
591 *)
592        eat_prods ~subst ~metasenv context he ty_he args_with_ty
593    | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
594    | C.Match (Ref.Ref (_,_,Ref.Ind tyno) as r,outtype,term,pl) ->
595       let outsort = typeof_aux context outtype in
596       let inductive,leftno,itl,_,_ = E.get_checked_indtys r in
597       let constructorsno =
598         let _,_,_,cl = List.nth itl tyno in List.length cl
599       in
600       let parameters, arguments =
601         let ty = R.whd ~subst context (typeof_aux context term) in
602         let r',tl =
603          match ty with
604             C.Const (Ref.Ref (_,_,Ref.Ind _) as r') -> r',[]
605           | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _) as r') :: tl) -> r',tl
606           | _ ->
607              raise 
608                (TypeCheckerFailure (lazy (Printf.sprintf
609                  "Case analysis: analysed term %s is not an inductive one"
610                  (NCicPp.ppterm ~subst ~metasenv ~context term)))) in
611         if not (Ref.eq r r') then
612          raise
613           (TypeCheckerFailure (lazy (Printf.sprintf
614             ("Case analysys: analysed term type is %s, but is expected " ^^
615              "to be (an application of) %s")
616             (NCicPp.ppterm ~subst ~metasenv ~context ty) 
617             (NCicPp.ppterm ~subst ~metasenv ~context (C.Const r')))))
618         else
619          try HExtlib.split_nth leftno tl
620          with
621           Failure _ ->
622            raise (TypeCheckerFailure (lazy (Printf.sprintf 
623            "%s is partially applied" 
624            (NCicPp.ppterm  ~subst ~metasenv ~context ty)))) in
625       (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
626       let sort_of_ind_type =
627         if parameters = [] then C.Const r
628         else C.Appl ((C.Const r)::parameters) in
629       let type_of_sort_of_ind_ty = typeof_aux context sort_of_ind_type in
630       check_allowed_sort_elimination ~subst ~metasenv r context
631        sort_of_ind_type type_of_sort_of_ind_ty outsort;
632       (* let's check if the type of branches are right *)
633       if List.length pl <> constructorsno then
634        raise (TypeCheckerFailure (lazy ("Wrong number of cases in a match")));
635       let j,branches_ok,p_ty, exp_p_ty =
636         List.fold_left
637           (fun (j,b,old_p_ty,old_exp_p_ty) p ->
638             if b then
639               let cons = 
640                 let cons = Ref.mk_constructor j r in
641                 if parameters = [] then C.Const cons
642                 else C.Appl (C.Const cons::parameters)
643               in
644               let ty_p = typeof_aux context p in
645               let ty_cons = typeof_aux context cons in
646               let ty_branch = 
647                 type_of_branch ~subst context leftno outtype cons ty_cons 0 
648               in
649               j+1, R.are_convertible ~subst ~metasenv context ty_p ty_branch,
650               ty_p, ty_branch
651             else
652               j,false,old_p_ty,old_exp_p_ty
653           ) (1,true,C.Sort C.Prop,C.Sort C.Prop) pl
654       in
655       if not branches_ok then
656         raise
657          (TypeCheckerFailure 
658           (lazy (Printf.sprintf ("Branch for constructor %s :=\n%s\n"^^
659           "has type %s\nnot convertible with %s") 
660           (NCicPp.ppterm  ~subst ~metasenv ~context
661             (C.Const (Ref.mk_constructor (j-1) r)))
662           (NCicPp.ppterm ~metasenv ~subst ~context (List.nth pl (j-2)))
663           (NCicPp.ppterm ~metasenv ~subst ~context p_ty) 
664           (NCicPp.ppterm ~metasenv ~subst ~context exp_p_ty)))); 
665       let res = outtype::arguments@[term] in
666       R.head_beta_reduce (C.Appl res)
667     | C.Match _ -> assert false
668
669   and type_of_branch ~subst context leftno outty cons tycons liftno = 
670     match R.whd ~subst context tycons with
671     | C.Const (Ref.Ref (_,_,Ref.Ind _)) -> C.Appl [S.lift liftno outty ; cons]
672     | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _))::tl) ->
673         let _,arguments = HExtlib.split_nth leftno tl in
674         C.Appl (S.lift liftno outty::arguments@[cons])
675     | C.Prod (name,so,de) ->
676         let cons =
677          match S.lift 1 cons with
678          | C.Appl l -> C.Appl (l@[C.Rel 1])
679          | t -> C.Appl [t ; C.Rel 1]
680         in
681          C.Prod (name,so,
682            type_of_branch ~subst ((name,(C.Decl so))::context) 
683             leftno outty cons de (liftno+1))
684     | _ -> raise (AssertFailure (lazy "type_of_branch"))
685
686   (* check_metasenv_consistency checks that the "canonical" context of a
687      metavariable is consitent - up to relocation via the relocation list l -
688      with the actual context *)
689   and check_metasenv_consistency 
690     ~subst ~metasenv term context canonical_context l 
691   =
692    match l with
693     | shift, NCic.Irl n ->
694        let context = snd (HExtlib.split_nth shift context) in
695         let rec compare = function
696          | 0,_,[] -> ()
697          | 0,_,_::_
698          | _,_,[] ->
699             raise (AssertFailure (lazy (Printf.sprintf
700              "Local and canonical context %s have different lengths"
701              (NCicPp.ppterm ~subst ~context ~metasenv term))))
702          | m,[],_::_ ->
703             raise (TypeCheckerFailure (lazy (Printf.sprintf
704              "Unbound variable -%d in %s" m 
705              (NCicPp.ppterm ~subst ~metasenv ~context term))))
706          | m,t::tl,ct::ctl ->
707             (match t,ct with
708                 (_,C.Decl t1), (_,C.Decl t2)
709               | (_,C.Def (t1,_)), (_,C.Def (t2,_))
710               | (_,C.Def (_,t1)), (_,C.Decl t2) ->
711                  if not (R.are_convertible ~subst ~metasenv tl t1 t2) then
712                   raise 
713                       (TypeCheckerFailure 
714                         (lazy (Printf.sprintf 
715                       ("Not well typed metavariable local context for %s: " ^^ 
716                        "%s expected, which is not convertible with %s")
717                       (NCicPp.ppterm ~subst ~metasenv ~context term) 
718                       (NCicPp.ppterm ~subst ~metasenv ~context t2) 
719                       (NCicPp.ppterm ~subst ~metasenv ~context t1))))
720               | _,_ ->
721                raise 
722                    (TypeCheckerFailure (lazy (Printf.sprintf 
723                     ("Not well typed metavariable local context for %s: " ^^ 
724                      "a definition expected, but a declaration found")
725                     (NCicPp.ppterm ~subst ~metasenv ~context term)))));
726             compare (m - 1,tl,ctl)
727         in
728          compare (n,context,canonical_context)
729     | shift, lc_kind ->
730        (* we avoid useless lifting by shortening the context*)
731        let l,context = (0,lc_kind), snd (HExtlib.split_nth shift context) in
732        let lifted_canonical_context = 
733          let rec lift_metas i = function
734            | [] -> []
735            | (n,C.Decl t)::tl ->
736                (n,C.Decl (S.subst_meta l (S.lift i t)))::(lift_metas (i+1) tl)
737            | (n,C.Def (t,ty))::tl ->
738                (n,C.Def ((S.subst_meta l (S.lift i t)),
739                           S.subst_meta l (S.lift i ty)))::(lift_metas (i+1) tl)
740          in
741           lift_metas 1 canonical_context in
742        let l = U.expand_local_context lc_kind in
743        try
744         List.iter2 
745         (fun t ct -> 
746           match (t,ct) with
747           | t, (_,C.Def (ct,_)) ->
748              (*CSC: the following optimization is to avoid a possibly expensive
749                     reduction that can be easily avoided and that is quite
750                     frequent. However, this is better handled using levels to
751                     control reduction *)
752              let optimized_t =
753               match t with
754               | C.Rel n ->
755                   (try
756                     match List.nth context (n - 1) with
757                     | (_,C.Def (te,_)) -> S.lift n te
758                     | _ -> t
759                     with Failure _ -> t)
760               | _ -> t
761              in
762              if not (R.are_convertible ~subst ~metasenv context optimized_t ct)
763              then
764                raise 
765                  (TypeCheckerFailure 
766                    (lazy (Printf.sprintf 
767                      ("Not well typed metavariable local context: " ^^ 
768                       "expected a term convertible with %s, found %s")
769                      (NCicPp.ppterm ~subst ~metasenv ~context ct) 
770                      (NCicPp.ppterm ~subst ~metasenv ~context t))))
771           | t, (_,C.Decl ct) ->
772               let type_t = typeof_aux context t in
773               if not (R.are_convertible ~subst ~metasenv context type_t ct) then
774                 raise (TypeCheckerFailure 
775                  (lazy (Printf.sprintf 
776                   ("Not well typed metavariable local context: "^^
777                   "expected a term of type %s, found %s of type %s") 
778                   (NCicPp.ppterm ~subst ~metasenv ~context ct) 
779                   (NCicPp.ppterm ~subst ~metasenv ~context t) 
780                   (NCicPp.ppterm ~subst ~metasenv ~context type_t))))
781         ) l lifted_canonical_context 
782        with
783         Invalid_argument _ ->
784           raise (AssertFailure (lazy (Printf.sprintf
785            "Local and canonical context %s have different lengths"
786            (NCicPp.ppterm ~subst ~metasenv ~context term))))
787
788   and is_non_informative context paramsno c =
789    let rec aux context c =
790      match R.whd context c with
791       | C.Prod (n,so,de) ->
792          let s = typeof_aux context so in
793          s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
794       | _ -> true in
795    let context',dx = split_prods ~subst:[] context paramsno c in
796     aux context' dx
797
798   and check_allowed_sort_elimination ~subst ~metasenv r =
799    let mkapp he arg =
800      match he with
801      | C.Appl l -> C.Appl (l @ [arg])
802      | t -> C.Appl [t;arg] in
803    let rec aux context ind arity1 arity2 =
804     let arity1 = R.whd ~subst context arity1 in
805     let arity2 = R.whd ~subst context arity2 in
806       match arity1,arity2 with
807        | C.Prod (name,so1,de1), C.Prod (_,so2,de2) ->
808           if not (R.are_convertible ~subst ~metasenv context so1 so2) then
809            raise (TypeCheckerFailure (lazy (Printf.sprintf
810             "In outtype: expected %s, found %s"
811             (NCicPp.ppterm ~subst ~metasenv ~context so1)
812             (NCicPp.ppterm ~subst ~metasenv ~context so2)
813             )));
814           aux ((name, C.Decl so1)::context)
815            (mkapp (S.lift 1 ind) (C.Rel 1)) de1 de2
816        | C.Sort _, C.Prod (name,so,ta) ->
817           if not (R.are_convertible ~subst ~metasenv context so ind) then
818            raise (TypeCheckerFailure (lazy (Printf.sprintf
819             "In outtype: expected %s, found %s"
820             (NCicPp.ppterm ~subst ~metasenv ~context ind)
821             (NCicPp.ppterm ~subst ~metasenv ~context so)
822             )));
823           (match arity1,ta with
824             | (C.Sort (C.CProp | C.Type _), C.Sort _)
825             | (C.Sort C.Prop, C.Sort C.Prop) -> ()
826             | (C.Sort C.Prop, C.Sort (C.CProp | C.Type _)) ->
827         (* TODO: we should pass all these parameters since we
828          * have them already *)
829                 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
830                 let itl_len = List.length itl in
831                 let _,name,ty,cl = List.nth itl i in
832                 let cl_len = List.length cl in
833                  (* is it a singleton or empty non recursive and non informative
834                     definition? *)
835                  if not
836                   (cl_len = 0 ||
837                    (itl_len = 1 && cl_len = 1 &&
838                     is_non_informative [name,C.Decl ty] leftno
839                      (let _,_,x = List.nth cl 0 in x)))
840                  then
841                   raise (TypeCheckerFailure (lazy
842                    ("Sort elimination not allowed")));
843           | _,_ -> ())
844        | _,_ -> ()
845    in
846     aux 
847
848  in 
849    typeof_aux context term
850
851 and check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl = 
852   (* let's check if the arity of the inductive types are well formed *)
853   List.iter (fun (_,_,x,_) -> ignore (typeof ~subst ~metasenv [] x)) tyl;
854   (* let's check if the types of the inductive constructors are well formed. *)
855   let len = List.length tyl in
856   let tys = List.rev (List.map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl) in
857   ignore
858    (List.fold_right
859     (fun (_,_,_,cl) i ->
860        List.iter
861          (fun (_,name,te) -> 
862            let debruijnedte = debruijn uri len te in
863            ignore (typeof ~subst ~metasenv tys debruijnedte);
864            (* let's check also the positivity conditions *)
865            if 
866              not
867                (are_all_occurrences_positive ~subst tys uri leftno i 0 len
868                   debruijnedte) 
869            then
870              raise
871                (TypeCheckerFailure
872                  (lazy ("Non positive occurence in "^NUri.string_of_uri uri))))
873          cl;
874         i + 1)
875     tyl 1)
876
877 and eat_lambdas ~subst ~metasenv context n te =
878   match (n, R.whd ~subst context te) with
879   | (0, _) -> (te, context)
880   | (n, C.Lambda (name,so,ta)) when n > 0 ->
881       eat_lambdas ~subst ~metasenv ((name,(C.Decl so))::context) (n - 1) ta
882    | (n, te) ->
883       raise (AssertFailure (lazy (Printf.sprintf "9 (%d, %s)" n 
884         (NCicPp.ppterm ~subst ~metasenv ~context te))))
885
886 and guarded_by_destructors ~subst ~metasenv context recfuns t = 
887  let recursor f k t = NCicUtils.fold shift_k k (fun k () -> f k) () t in
888  let rec aux (context, recfuns, x, safes as k) = function
889   | C.Rel m as t when List.mem_assoc m recfuns -> 
890       raise (NotGuarded (lazy 
891         (NCicPp.ppterm ~subst ~metasenv ~context t ^ " passed around")))
892   | C.Rel m ->
893      (match List.nth context (m-1) with 
894      | _,C.Decl _ -> ()
895      | _,C.Def (bo,_) -> aux (context, recfuns, x, safes) (S.lift m bo))
896   | C.Meta _ -> ()
897   | C.Appl ((C.Rel m)::tl) as t when List.mem_assoc m recfuns ->
898      let rec_no = List.assoc m recfuns in
899      if not (List.length tl > rec_no) then 
900        raise (NotGuarded (lazy 
901          (NCicPp.ppterm ~context ~subst ~metasenv t ^ 
902          " is a partial application of a fix")))
903      else
904        let rec_arg = List.nth tl rec_no in
905        if not (is_really_smaller ~subst ~metasenv k rec_arg) then 
906          raise (NotGuarded (lazy 
907            (NCicPp.ppterm ~context ~subst ~metasenv rec_arg ^ " not smaller")));
908        List.iter (aux k) tl
909   | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) as t ->
910      (match R.whd ~subst context term with
911      | C.Rel m | C.Appl (C.Rel m :: _ ) as t when List.mem m safes || m = x ->
912         let isinductive, paramsno, tl, _, i = E.get_checked_indtys ref in
913         if not isinductive then recursor aux k t
914         else
915          let c_ctx,len,cl = fix_lefts_in_constrs ~subst uri paramsno tl i in
916          let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
917          aux k outtype; 
918          List.iter (aux k) args; 
919          List.iter2
920            (fun p (_,_,bruijnedc) ->
921              let rl = recursive_args ~subst ~metasenv c_ctx 0 len bruijnedc in
922              let p, k = get_new_safes ~subst k p rl in
923              aux k p) 
924            pl cl
925      | _ -> recursor aux k t)
926   | t -> recursor aux k t
927  in
928   try aux (context, recfuns, 1, []) t
929   with NotGuarded s -> raise (TypeCheckerFailure s)
930
931 (*
932  | C.Fix (_, fl) ->
933     let len = List.length fl in
934      let n_plus_len = n + len
935      and nn_plus_len = nn + len
936      and x_plus_len = x + len
937      and tys,_ =
938       List.fold_left
939         (fun (types,len) (n,_,ty,_) ->
940            (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
941             len+1)
942         ) ([],0) fl
943      and safes' = List.map (fun x -> x + len) safes in
944       List.fold_right
945        (fun (_,_,ty,bo) i ->
946          i && guarded_by_destructors ~subst context n nn kl x_plus_len safes' ty &&
947           guarded_by_destructors ~subst (tys@context) n_plus_len nn_plus_len kl
948            x_plus_len safes' bo
949        ) fl true
950  | C.CoFix (_, fl) ->
951     let len = List.length fl in
952      let n_plus_len = n + len
953      and nn_plus_len = nn + len
954      and x_plus_len = x + len
955      and tys,_ =
956       List.fold_left
957         (fun (types,len) (n,ty,_) ->
958            (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
959             len+1)
960         ) ([],0) fl
961      and safes' = List.map (fun x -> x + len) safes in
962       List.fold_right
963        (fun (_,ty,bo) i ->
964          i &&
965           guarded_by_destructors ~subst context n nn kl x_plus_len safes' ty &&
966           guarded_by_destructors ~subst (tys@context) n_plus_len nn_plus_len kl
967            x_plus_len safes' bo
968        ) fl true
969 *)
970
971 and guarded_by_constructors ~subst ~metasenv _ _ _ _ _ _ _ = true
972
973 and recursive_args ~subst ~metasenv context n nn te =
974   match R.whd context te with
975   | C.Rel _ | C.Appl _ -> []
976   | C.Prod (name,so,de) ->
977      (not (does_not_occur ~subst context n nn so)) ::
978       (recursive_args ~subst ~metasenv 
979         ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
980   | t -> 
981      raise (AssertFailure (lazy ("recursive_args:" ^ NCicPp.ppterm ~subst
982      ~metasenv ~context:[] t)))
983
984 and get_new_safes ~subst (context, recfuns, x, safes as k) p rl =
985   match R.whd ~subst context p, rl with
986   | C.Lambda (name,so,ta), b::tl ->
987       let safes = (if b then [0] else []) @ safes in
988       get_new_safes ~subst 
989         (shift_k (name,(C.Decl so)) (context, recfuns, x, safes)) ta tl
990   | C.Meta _ as e, _ | e, [] -> e, k
991   | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
992
993 and split_prods ~subst context n te =
994   match n, R.whd ~subst context te with
995   | 0, _ -> context,te
996   | n, C.Prod (name,so,ta) when n > 0 ->
997        split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
998   | _ -> raise (AssertFailure (lazy "split_prods"))
999
1000 and is_really_smaller ~subst ~metasenv (context, recfuns, x, safes as k) te =
1001  match R.whd ~subst context te with
1002  | C.Rel m when List.mem m safes -> true
1003  | C.Rel _ -> false
1004  | C.LetIn _ -> raise (AssertFailure (lazy "letin after whd"))
1005  | C.Sort _ | C.Implicit _ | C.Prod _ | C.Lambda _ 
1006  | C.Const (Ref.Ref (_,_,(Ref.Decl | Ref.Def | Ref.Ind _ | Ref.CoFix _))) ->
1007     raise (AssertFailure (lazy "not a constructor"))
1008  | C.Appl ([]|[_]) -> raise (AssertFailure (lazy "empty/unary appl"))
1009  | C.Appl (he::_) ->
1010     (*CSC: sulla coda ci vogliono dei controlli? secondo noi no, ma *)
1011     (*CSC: solo perche' non abbiamo trovato controesempi            *)
1012     (*TASSI: da capire soprattutto se he รจ un altro fix che non ha ridotto...*)
1013     is_really_smaller ~subst ~metasenv k he
1014  | C.Const (Ref.Ref (_,_,Ref.Con _)) -> false
1015  | C.Const (Ref.Ref (_,_,Ref.Fix _)) -> assert false
1016    (*| C.Fix (_, fl) ->
1017       let len = List.length fl in
1018        let n_plus_len = n + len
1019        and nn_plus_len = nn + len
1020        and x_plus_len = x + len
1021        and tys,_ =
1022         List.fold_left
1023           (fun (types,len) (n,_,ty,_) ->
1024              (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1025               len+1)
1026           ) ([],0) fl
1027        and safes' = List.map (fun x -> x + len) safes in
1028         List.fold_right
1029          (fun (_,_,ty,bo) i ->
1030            i &&
1031             is_really_smaller ~subst (tys@context) n_plus_len nn_plus_len kl
1032              x_plus_len safes' bo
1033          ) fl true*)
1034  | C.Meta _ -> 
1035      true (* XXX if this check is repeated when the user completes the
1036              definition *)
1037  | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) ->
1038     (match term with
1039     | C.Rel m | C.Appl (C.Rel m :: _ ) when List.mem m safes || m = x ->
1040         let isinductive, paramsno, tl, _, i = E.get_checked_indtys ref in
1041         if not isinductive then
1042           List.for_all (is_really_smaller ~subst ~metasenv k) pl
1043         else
1044           let c_ctx,len,cl = fix_lefts_in_constrs ~subst uri paramsno tl i in
1045           List.for_all2
1046            (fun p (_,_,debruijnedte) -> 
1047              let rl'=recursive_args ~subst ~metasenv c_ctx 0 len debruijnedte in
1048              let e, k = get_new_safes ~subst k p rl' in
1049              is_really_smaller ~subst ~metasenv k e)
1050            pl cl
1051     | _ -> List.for_all (is_really_smaller ~subst ~metasenv k) pl)
1052
1053 and returns_a_coinductive ~subst context ty =
1054   match R.whd ~subst context ty with
1055   | C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref) 
1056   | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)::_) ->
1057      let isinductive, _, _, _, _ = E.get_checked_indtys ref in
1058      if isinductive then None else (Some uri)
1059   | C.Prod (n,so,de) ->
1060      returns_a_coinductive ~subst ((n,C.Decl so)::context) de
1061   | _ -> None
1062
1063 and type_of_constant ((Ref.Ref (_,uri,_)) as ref) = 
1064   let cobj =
1065     match E.get_obj uri with
1066     | true, cobj -> cobj
1067     | false, uobj ->
1068        !logger (`Start_type_checking uri);
1069        check_obj_well_typed uobj;
1070        E.add_obj uobj;
1071        !logger (`Type_checking_completed uri);
1072        uobj
1073   in
1074   match cobj, ref with
1075   | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Ind i)  ->
1076       let _,_,arity,_ = List.nth tl i in arity
1077   | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Con (i,j))  ->
1078       let _,_,_,cl = List.nth tl i in 
1079       let _,_,arity = List.nth cl (j-1) in 
1080       arity
1081   | (_,_,_,_,C.Fixpoint (_,fl,_)), Ref.Ref (_,_,(Ref.Fix (i,_)|Ref.CoFix i)) ->
1082       let _,_,_,arity,_ = List.nth fl i in
1083       arity
1084   | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,_,(Ref.Def |Ref.Decl)) -> ty
1085   | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
1086
1087 and check_obj_well_typed (uri,height,metasenv,subst,kind) =
1088  (* CSC: here we should typecheck the metasenv and the subst *)
1089  assert (metasenv = [] && subst = []);
1090  match kind with
1091    | C.Constant (_,_,Some te,ty,_) ->
1092 (*
1093       prerr_endline ("TY: " ^ NCicPp.ppterm ~subst ~metasenv ~context:[] ty);
1094       prerr_endline ("BO: " ^ NCicPp.ppterm ~subst ~metasenv ~context:[] te);
1095 *)
1096       let _ = typeof ~subst ~metasenv [] ty in
1097       let ty_te = typeof ~subst ~metasenv [] te in
1098 (*       prerr_endline "XXXX"; *)
1099       if not (R.are_convertible ~subst ~metasenv [] ty_te ty) then
1100        raise (TypeCheckerFailure (lazy (Printf.sprintf
1101         "the type of the body is not the one expected:\n%s\nvs\n%s"
1102         (NCicPp.ppterm ~subst ~metasenv ~context:[] ty_te) 
1103         (NCicPp.ppterm ~subst ~metasenv ~context:[] ty))))
1104    | C.Constant (_,_,None,ty,_) -> ignore (typeof ~subst ~metasenv [] ty)
1105    | C.Inductive (is_ind, leftno, tyl, _) -> 
1106        check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl
1107    | C.Fixpoint (inductive,fl,_) ->
1108       let types,kl,len =
1109         List.fold_left
1110          (fun (types,kl,len) (_,name,k,ty,_) ->
1111            let _ = typeof ~subst ~metasenv [] ty in
1112             ((name,(C.Decl (S.lift len ty)))::types, k::kl,len+1)
1113          ) ([],[],0) fl
1114       in
1115         List.iter (fun (_,name,x,ty,bo) ->
1116          let bo = debruijn uri len bo in
1117          let ty_bo = typeof ~subst ~metasenv types bo in
1118          if not (R.are_convertible ~subst ~metasenv types ty_bo (S.lift len ty))
1119          then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1120          else
1121           if inductive then begin
1122             let m, context = eat_lambdas ~subst ~metasenv types (x + 1) bo in
1123             (* guarded by destructors conditions D{f,k,x,M} *)
1124             let rec enum_from k = 
1125               function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl 
1126             in
1127             guarded_by_destructors 
1128              ~subst ~metasenv context (enum_from (x+2) kl) m
1129           end else
1130            match returns_a_coinductive ~subst [] ty with
1131             | None ->
1132                 raise (TypeCheckerFailure
1133                   (lazy "CoFix: does not return a coinductive type"))
1134             | Some uri ->
1135                 (* guarded by constructors conditions C{f,M} *)
1136                 if not (guarded_by_constructors ~subst ~metasenv
1137                     types 0 len false bo [] uri)
1138                 then
1139                   raise (TypeCheckerFailure
1140                    (lazy "CoFix: not guarded by constructors"))
1141           ) fl
1142
1143 let typecheck_obj = check_obj_well_typed;;
1144
1145 (* EOF *)