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