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