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.
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_______________________________________________________________ *)
12 (* $Id: nCicReduction.ml 8250 2008-03-25 17:56:20Z tassi $ *)
14 (* web interface stuff *)
17 ref (function (`Start_type_checking _|`Type_checking_completed _) -> ())
20 let set_logger f = logger := f;;
22 exception TypeCheckerFailure of string Lazy.t
23 exception AssertFailure of string Lazy.t
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
29 (* $Id: cicTypeChecker.ml 8213 2008-03-13 18:48:26Z sacerdot $ *)
32 exception CicEnvironmentError;;
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 =
41 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
43 C.MutInd (HelmLibraryObjects.Datatypes.nat_URI,0,[])
45 (*CSC: mettere in cicSubstitution *)
46 let rec subst_inductive_type_with_dummy_mutind =
48 C.MutInd (uri',0,_) when UriManager.eq uri' uri ->
50 | C.Appl ((C.MutInd (uri',0,_))::tl) when UriManager.eq uri' uri ->
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)
60 C.Appl (List.map subst_inductive_type_with_dummy_mutind tl)
61 | C.MutCase (uri,i,outtype,term,pl) ->
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)
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)
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' =
77 (function (uri,t) -> (uri,subst_inductive_type_with_dummy_mutind t))
80 C.Const (uri,exp_named_subst')
81 | C.MutInd (uri,typeno,exp_named_subst) ->
82 let exp_named_subst' =
84 (function (uri,t) -> (uri,subst_inductive_type_with_dummy_mutind t))
87 C.MutInd (uri,typeno,exp_named_subst')
88 | C.MutConstruct (uri,typeno,consno,exp_named_subst) ->
89 let exp_named_subst' =
91 (function (uri,t) -> (uri,subst_inductive_type_with_dummy_mutind t))
94 C.MutConstruct (uri,typeno,consno,exp_named_subst')
97 match CicReduction.whd context te with
99 C.Appl ((C.MutInd (uri',0,_))::tl) when UriManager.eq uri' uri -> true
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
121 raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
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
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"))
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
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
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) *)
160 (lazy ("Unknown inductive type:" ^ U.string_of_uri uri)))
162 let (params,arguments) = split tl paramsno in
163 let lifted_params = List.map (CicSubstitution.lift 1) params in
167 instantiate_parameters lifted_params
168 (CicSubstitution.subst_vars exp_named_subst te)
173 (fun x i -> i && does_not_occur context n nn x)
175 (*CSC: MEGAPATCH3 (sara' quella giusta?)*)
180 ((Some (C.Name name,(Cic.Decl ity)))::context) (n+1) (nn+1) uri
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 *)
198 match CicReduction.whd context x with
199 C.Rel m when m = n - (indparamsno - k) -> k - 1
201 raise (TypeCheckerFailure
203 ("Non-positive occurence in mutual inductive definition(s) [1]" ^
204 UriManager.string_of_uri uri)))
208 List.fold_right (fun x i -> i && does_not_occur context n nn x) tl true
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
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
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
239 (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
240 (UriManager.string_of_uri uri))))
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 *)
249 let ugrap1 = List.fold_left
250 (fun ugraph (_,_,x,_) -> let _,ugraph' =
251 type_of ~logger x ugraph in ugraph')
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
261 List.map (fun (n,_,ty,_) -> Some (Cic.Name n,(Cic.Decl ty))) itl in
264 (fun (_,_,_,cl) (i,ugraph) ->
267 (fun ugraph (name,te) ->
268 let debruijnedte = debruijn uri len te in
271 (fun (name,_,ty,_) i -> Cic.Prod (Cic.Name name, ty, i))
274 let _,ugraph' = type_of ~logger augmented_term ugraph in
275 (* let's check also the positivity conditions *)
278 (are_all_occurrences_positive tys uri indparamsno i 0 len
282 prerr_endline (UriManager.string_of_uri uri);
283 prerr_endline (string_of_int (List.length tys));
286 (lazy ("Non positive occurence in " ^ U.string_of_uri uri))) end
295 (* Main function to checks the correctness of a mutual *)
296 (* inductive block definition. *)
297 and check_mutual_inductive_defs uri obj ugraph =
299 Cic.InductiveDefinition (itl, params, indparamsno, _) ->
300 typecheck_mutual_inductive_defs uri (itl,params,indparamsno) ugraph
302 raise (TypeCheckerFailure (
303 lazy ("Unknown mutual inductive definition:" ^
304 UriManager.string_of_uri uri)))
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
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 ->
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) ->
336 CicEnvironment.get_cooked_obj ~trust:false CicUniv.empty_ugraph uri
337 with Not_found -> assert false
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
345 raise (TypeCheckerFailure
346 (lazy ("Unknown mutual inductive definition:" ^ UriManager.string_of_uri uri)))
348 let rec analyse_branch context ty te =
349 match CicReduction.whd ~subst context ty with
350 C.Meta _ -> raise (AssertFailure (lazy "34"))
354 does_not_occur ~subst context n nn te
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
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 []
366 | C.Appl ((C.MutInd (uri,_,_))::_) ->
367 guarded_by_constructors ~subst context n nn true te tl
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 []
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. *)
383 raise (AssertFailure (lazy "28"))(* due to type-checking *)
385 let rec analyse_instantiated_type context ty l =
386 match CicReduction.whd ~subst context ty with
392 | C.Cast _ -> raise (AssertFailure (lazy "29"))(* due to type-checking *)
393 | C.Prod (name,so,de) ->
398 analyse_branch context so he &&
399 analyse_instantiated_type
400 ((Some (name,(C.Decl so)))::context) de tl
404 raise (AssertFailure (lazy "30"))(* due to type-checking *)
407 (fun i x -> i && does_not_occur ~subst context n nn x) true l
408 | C.Const _ -> raise (AssertFailure (lazy "31"))
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. *)
418 raise (AssertFailure (lazy "33"))(* due to type-checking *)
420 let rec instantiate_type args consty =
424 let consty' = CicReduction.whd ~subst context consty in
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
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"))
439 | [] -> analyse_instantiated_type context consty' l
440 (* These are all the other cases *)
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? *)
451 (fun (types,len) (n,ty,_) ->
452 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
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
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 &&
469 guarded_by_constructors ~subst context n nn h x args
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) ->
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) ->
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 &&
488 guarded_by_constructors ~subst context n nn h x args
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? *)
498 (fun (types,len) (n,_,ty,_) ->
499 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
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
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? *)
515 (fun (types,len) (n,ty,_) ->
516 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
522 i && does_not_occur ~subst context n nn ty &&
523 guarded_by_constructors ~subst (tys@context) n_plus_len nn_plus_len
525 args coInductiveTypeURI
529 type_of_aux ~logger context t ugraph
533 (** wrappers which instantiate fresh loggers *)
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
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)
550 Deannotate.type_of_aux' := fun context t -> fst (type_of_aux' [] context t CicUniv.oblivion_ugraph);;
555 module R = NCicReduction
556 module Ref = NReference
557 module S = NCicSubstitution
559 module E = NCicEnvironment
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"))
569 let debruijn ?(cb=fun _ _ -> ()) uri number_of_types =
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))
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
587 let sort_of_prod ~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
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
598 | C.Sort _, C.Meta _ when U.is_closed t2 -> t2
600 raise (TypeCheckerFailure (lazy (Printf.sprintf
601 "Prod: expected two sorts, found = %s, %s"
602 (NCicPp.ppterm t1) (NCicPp.ppterm t2))))
605 let eat_prods ~subst ~metasenv context ty_he args_with_ty =
606 let rec aux ty_he = function
608 | (arg, ty_arg)::tl ->
609 (match R.whd ~subst context ty_he with
611 if R.are_convertible ~subst ~metasenv context ty_arg s then
612 aux (S.subst ~avoid_beta_redexes:true arg t) tl
616 (lazy (Printf.sprintf
617 ("Appl: wrong parameter-type, expected %s, found %s")
618 (NCicPp.ppterm ty_arg) (NCicPp.ppterm s))))
622 (lazy "Appl: this is not a function, it cannot be applied")))
624 aux ty_he args_with_ty
627 let fix_lefts_in_constrs ~subst uri paramsno tyl i =
628 let len = List.length tyl in
629 let _,_,arity,cl = List.nth tyl i in
630 let tys = List.map (fun (_,n,ty,_) -> n,C.Decl ty) tyl in
634 let debruijnedty = debruijn uri len ty in
635 id, snd (split_prods ~subst tys paramsno ty),
636 snd (split_prods ~subst tys paramsno debruijnedty))
639 let lefts = fst (split_prods ~subst [] paramsno arity) in
643 exception DoesOccur;;
645 let does_not_occur ~subst context n nn t =
646 let rec aux (context,n,nn as k) _ = function
647 | C.Rel m when m > n && m <= nn -> raise DoesOccur
649 (try (match List.nth context (m-1) with
650 | _,C.Def (bo,_) -> aux k () (S.lift m bo)
652 with Failure _ -> assert false)
653 | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> (* closed meta *) ()
654 | C.Meta (mno,(s,l)) ->
656 let _,_,term,_ = U.lookup_subst mno subst in
657 aux (context,n+s,nn+s) () (S.subst_meta (0,l) term)
658 with CicUtil.Subst_not_found _ -> match l with
659 | C.Irl len -> if not (n >= s+len || s > nn) then raise DoesOccur
660 | C.Ctx lc -> List.iter (aux (context,n+s,nn+s) ()) lc)
661 | t -> U.fold (fun e (ctx,n,nn) -> (e::ctx,n+1,nn+1)) k aux () t
663 try aux (context,n,nn) () t; true
664 with DoesOccur -> false
667 exception NotGuarded;;
669 let rec typeof ~subst ~metasenv context term =
670 let rec typeof_aux context = function
673 match List.nth context (n - 1) with
674 | (_,C.Decl ty) -> S.lift n ty
675 | (_,C.Def (_,ty)) -> S.lift n ty
676 with Failure _ -> raise (TypeCheckerFailure (lazy "unbound variable")))
677 | C.Sort (C.Type i) -> C.Sort (C.Type (i+1))
678 | C.Sort s -> C.Sort (C.Type 0)
679 | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
680 | C.Meta (n,l) as t ->
681 let canonical_context,ty =
683 let _,c,_,ty = U.lookup_subst n subst in c,ty
684 with U.Subst_not_found _ -> try
685 let _,_,c,ty = U.lookup_meta n metasenv in c,ty
686 with U.Meta_not_found _ ->
687 raise (AssertFailure (lazy (Printf.sprintf
688 "%s not found" (NCicPp.ppterm t))))
690 check_metasenv_consistency t context canonical_context l;
692 | C.Const ref -> type_of_constant ref
693 | C.Prod (name,s,t) ->
694 let sort1 = typeof_aux context s in
695 let sort2 = typeof_aux ((name,(C.Decl s))::context) t in
696 sort_of_prod ~subst context (name,s) (sort1,sort2)
697 | C.Lambda (n,s,t) ->
698 let sort = typeof_aux context s in
699 (match R.whd ~subst context sort with
700 | C.Meta _ | C.Sort _ -> ()
703 (TypeCheckerFailure (lazy (Printf.sprintf
704 ("Not well-typed lambda-abstraction: " ^^
705 "the source %s should be a type; instead it is a term " ^^
706 "of type %s") (NCicPp.ppterm s) (NCicPp.ppterm sort)))));
707 let ty = typeof_aux ((n,(C.Decl s))::context) t in
709 | C.LetIn (n,ty,t,bo) ->
710 let ty_t = typeof_aux context t in
711 if not (R.are_convertible ~subst ~metasenv context ty ty_t) then
714 (lazy (Printf.sprintf
715 "The type of %s is %s but it is expected to be %s"
716 (NCicPp.ppterm t) (NCicPp.ppterm ty_t) (NCicPp.ppterm ty))))
718 let ty_bo = typeof_aux ((n,C.Def (t,ty))::context) bo in
719 S.subst ~avoid_beta_redexes:true t ty_bo
720 | C.Appl (he::(_::_ as args)) ->
721 let ty_he = typeof_aux context he in
722 let args_with_ty = List.map (fun t -> t, typeof_aux context t) args in
723 eat_prods ~subst ~metasenv context ty_he args_with_ty
724 | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
725 | C.Match (Ref.Ref (dummy_depth,uri,Ref.Ind tyno) as r,outtype,term,pl) ->
726 let outsort = typeof_aux context outtype in
727 let leftno = E.get_indty_leftno r in
728 let parameters, arguments =
729 let ty = R.whd ~subst context (typeof_aux context term) in
732 C.Const (Ref.Ref (_,_,Ref.Ind _) as r') -> r',[]
733 | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _) as r') :: tl) -> r',tl
736 (TypeCheckerFailure (lazy (Printf.sprintf
737 "Case analysis: analysed term %s is not an inductive one"
738 (NCicPp.ppterm term)))) in
739 if not (Ref.eq r r') then
741 (TypeCheckerFailure (lazy (Printf.sprintf
742 ("Case analysys: analysed term type is %s, but is expected " ^^
743 "to be (an application of) %s")
744 (NCicPp.ppterm ty) (NCicPp.ppterm (C.Const r')))))
746 try HExtlib.split_nth leftno tl
749 raise (TypeCheckerFailure (lazy (Printf.sprintf
750 "%s is partially applied" (NCicPp.ppterm ty)))) in
751 (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
752 let sort_of_ind_type =
753 if parameters = [] then C.Const r
754 else C.Appl ((C.Const r)::parameters) in
755 let type_of_sort_of_ind_ty = typeof_aux context sort_of_ind_type in
756 if not (check_allowed_sort_elimination ~subst ~metasenv r context
757 sort_of_ind_type type_of_sort_of_ind_ty outsort)
758 then raise (TypeCheckerFailure (lazy ("Sort elimination not allowed")));
759 (* let's check if the type of branches are right *)
760 let leftno,constructorsno =
761 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
762 let _,name,ty,cl = List.nth itl i in
763 let cl_len = List.length cl in
766 if List.length pl <> constructorsno then
767 raise (TypeCheckerFailure (lazy ("Wrong number of cases in a match")));
768 let j,branches_ok,p_ty, exp_p_ty =
770 (fun (j,b,old_p_ty,old_exp_p_ty) p ->
773 let cons = Ref.Ref (dummy_depth, uri, Ref.Con (tyno, j)) in
774 if parameters = [] then C.Const cons
775 else C.Appl (C.Const cons::parameters)
777 let ty_p = typeof_aux context p in
778 let ty_cons = typeof_aux context cons in
780 type_of_branch ~subst context leftno outtype cons ty_cons 0
782 j+1, R.are_convertible ~subst ~metasenv context ty_p ty_branch,
785 j,false,old_p_ty,old_exp_p_ty
786 ) (1,true,C.Sort C.Prop,C.Sort C.Prop) pl
788 if not branches_ok then
791 (lazy (Printf.sprintf ("Branch for constructor %s :=\n%s\n"^^
792 "has type %s\nnot convertible with %s") (NCicPp.ppterm (C.Const
793 (Ref.Ref (dummy_depth, uri, Ref.Con (tyno, j)))))
794 (NCicPp.ppterm ~context (List.nth pl (j-1)))
795 (NCicPp.ppterm ~context p_ty) (NCicPp.ppterm ~context exp_p_ty))));
796 let res = outtype::arguments@[term] in
797 R.head_beta_reduce (C.Appl res)
798 | C.Match _ -> assert false
800 and type_of_branch ~subst context leftno outty cons tycons liftno =
801 match R.whd ~subst context tycons with
802 | C.Const (Ref.Ref (_,_,Ref.Ind _)) -> C.Appl [S.lift liftno outty ; cons]
803 | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _))::tl) ->
804 let _,arguments = HExtlib.split_nth leftno tl in
805 C.Appl (S.lift liftno outty::arguments@[cons])
806 | C.Prod (name,so,de) ->
808 match S.lift 1 cons with
809 | C.Appl l -> C.Appl (l@[C.Rel 1])
810 | t -> C.Appl [t ; C.Rel 1]
813 type_of_branch ~subst ((name,(C.Decl so))::context)
814 leftno outty cons de (liftno+1))
815 | _ -> raise (AssertFailure (lazy "type_of_branch"))
817 (* check_metasenv_consistency checks that the "canonical" context of a
818 metavariable is consitent - up to relocation via the relocation list l -
819 with the actual context *)
820 and check_metasenv_consistency term context canonical_context l =
822 | shift, NCic.Irl n ->
823 let context = snd (HExtlib.split_nth shift context) in
824 let rec compare = function
828 raise (AssertFailure (lazy (Printf.sprintf
829 "Local and canonical context %s have different lengths"
830 (NCicPp.ppterm term))))
832 raise (TypeCheckerFailure (lazy (Printf.sprintf
833 "Unbound variable -%d in %s" m (NCicPp.ppterm term))))
836 (_,C.Decl t1), (_,C.Decl t2)
837 | (_,C.Def (t1,_)), (_,C.Def (t2,_))
838 | (_,C.Def (_,t1)), (_,C.Decl t2) ->
839 if not (R.are_convertible ~subst ~metasenv tl t1 t2) then
842 (lazy (Printf.sprintf
843 ("Not well typed metavariable local context for %s: " ^^
844 "%s expected, which is not convertible with %s")
845 (NCicPp.ppterm term) (NCicPp.ppterm t2) (NCicPp.ppterm t1)
850 (lazy (Printf.sprintf
851 ("Not well typed metavariable local context for %s: " ^^
852 "a definition expected, but a declaration found")
853 (NCicPp.ppterm term)))));
854 compare (m - 1,tl,ctl)
856 compare (n,context,canonical_context)
858 (* we avoid useless lifting by shortening the context*)
859 let l,context = (0,lc_kind), snd (HExtlib.split_nth shift context) in
860 let lifted_canonical_context =
861 let rec lift_metas i = function
863 | (n,C.Decl t)::tl ->
864 (n,C.Decl (S.subst_meta l (S.lift i t)))::(lift_metas (i+1) tl)
865 | (n,C.Def (t,ty))::tl ->
866 (n,C.Def ((S.subst_meta l (S.lift i t)),
867 S.subst_meta l (S.lift i ty)))::(lift_metas (i+1) tl)
869 lift_metas 1 canonical_context in
870 let l = U.expand_local_context lc_kind in
875 | t, (_,C.Def (ct,_)) ->
876 (*CSC: the following optimization is to avoid a possibly expensive
877 reduction that can be easily avoided and that is quite
878 frequent. However, this is better handled using levels to
884 match List.nth context (n - 1) with
885 | (_,C.Def (te,_)) -> S.lift n te
890 if not (R.are_convertible ~subst ~metasenv context optimized_t ct)
894 (lazy (Printf.sprintf
895 ("Not well typed metavariable local context: " ^^
896 "expected a term convertible with %s, found %s")
897 (NCicPp.ppterm ct) (NCicPp.ppterm t))))
898 | t, (_,C.Decl ct) ->
899 let type_t = typeof_aux context t in
900 if not (R.are_convertible ~subst ~metasenv context type_t ct) then
901 raise (TypeCheckerFailure
902 (lazy (Printf.sprintf
903 ("Not well typed metavariable local context: "^^
904 "expected a term of type %s, found %s of type %s")
905 (NCicPp.ppterm ct) (NCicPp.ppterm t) (NCicPp.ppterm type_t))))
906 ) l lifted_canonical_context
908 Invalid_argument _ ->
909 raise (AssertFailure (lazy (Printf.sprintf
910 "Local and canonical context %s have different lengths"
911 (NCicPp.ppterm term))))
913 and is_non_informative context paramsno c =
914 let rec aux context c =
915 match R.whd context c with
916 | C.Prod (n,so,de) ->
917 let s = typeof_aux context so in
918 s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
920 let context',dx = split_prods ~subst:[] context paramsno c in
923 and check_allowed_sort_elimination ~subst ~metasenv r =
926 | C.Appl l -> C.Appl (l @ [arg])
927 | t -> C.Appl [t;arg] in
928 let rec aux context ind arity1 arity2 =
929 let arity1 = R.whd ~subst context arity1 in
930 let arity2 = R.whd ~subst context arity2 in
931 match arity1,arity2 with
932 | C.Prod (name,so1,de1), C.Prod (_,so2,de2) ->
933 R.are_convertible ~subst ~metasenv context so1 so2 &&
934 aux ((name, C.Decl so1)::context)
935 (mkapp (S.lift 1 ind) (C.Rel 1)) de1 de2
936 | C.Sort _, C.Prod (name,so,ta) ->
937 (R.are_convertible ~subst ~metasenv context so ind &&
939 | (C.Sort (C.CProp | C.Type _), C.Sort _)
940 | (C.Sort C.Prop, C.Sort C.Prop) -> true
941 | (C.Sort C.Prop, C.Sort (C.CProp | C.Type _)) ->
942 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
943 let itl_len = List.length itl in
944 let _,name,ty,cl = List.nth itl i in
945 let cl_len = List.length cl in
946 (* is it a singleton or empty non recursive and non informative
949 (itl_len = 1 && cl_len = 1 &&
950 is_non_informative [name,C.Decl ty] leftno
951 (let _,_,x = List.nth cl 0 in x))
958 typeof_aux context term
960 and check_mutual_inductive_defs _ = ()
962 and eat_lambdas ~subst context n te =
963 match (n, R.whd ~subst context te) with
964 | (0, _) -> (te, context)
965 | (n, C.Lambda (name,so,ta)) when n > 0 ->
966 eat_lambdas ~subst ((name,(C.Decl so))::context) (n - 1) ta
969 (lazy (Printf.sprintf "9 (%d, %s)" n (NCicPp.ppterm te))))
971 and guarded_by_destructors ~subst context recfuns t =
972 let recursor f k t = NCicUtils.fold shift_k k (fun k () -> f k) () t in
973 let rec aux (context, recfuns, x, safes as k) = function
974 | C.Rel m when List.mem_assoc m recfuns -> raise NotGuarded
976 (match List.nth context (m-1) with
978 | _,C.Def (bo,_) -> aux (context, recfuns, x, safes) (S.lift m bo))
980 | C.Appl ((C.Rel m)::tl) when List.mem_assoc m recfuns ->
981 let rec_no = List.assoc m recfuns in
982 if not (List.length tl > rec_no) then raise NotGuarded
984 let rec_arg = List.nth tl rec_no in
985 if not (is_really_smaller ~subst k rec_arg) then raise
988 | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) as t ->
989 (match R.whd ~subst context term with
990 | C.Rel m | C.Appl (C.Rel m :: _ ) as t when List.mem m safes || m = x ->
991 let isinductive, paramsno, tl, _, i = E.get_checked_indtys ref in
992 if not isinductive then recursor aux k t
994 let c_ctx,len,cl = fix_lefts_in_constrs ~subst uri paramsno tl i in
995 let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
997 List.iter (aux k) args;
999 (fun p (_,_,bruijnedc) ->
1000 let rl = recursive_args ~subst c_ctx 0 len bruijnedc in
1001 let p, k = get_new_safes ~subst k p rl in
1004 | _ -> recursor aux k t)
1005 | t -> recursor aux k t
1007 try aux (context, recfuns, 1, []) t;true
1008 with NotGuarded -> false
1012 let len = List.length fl in
1013 let n_plus_len = n + len
1014 and nn_plus_len = nn + len
1015 and x_plus_len = x + len
1018 (fun (types,len) (n,_,ty,_) ->
1019 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1022 and safes' = List.map (fun x -> x + len) safes in
1024 (fun (_,_,ty,bo) i ->
1025 i && guarded_by_destructors ~subst context n nn kl x_plus_len safes' ty &&
1026 guarded_by_destructors ~subst (tys@context) n_plus_len nn_plus_len kl
1027 x_plus_len safes' bo
1029 | C.CoFix (_, fl) ->
1030 let len = List.length fl in
1031 let n_plus_len = n + len
1032 and nn_plus_len = nn + len
1033 and x_plus_len = x + len
1036 (fun (types,len) (n,ty,_) ->
1037 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1040 and safes' = List.map (fun x -> x + len) safes in
1044 guarded_by_destructors ~subst context n nn kl x_plus_len safes' ty &&
1045 guarded_by_destructors ~subst (tys@context) n_plus_len nn_plus_len kl
1046 x_plus_len safes' bo
1050 and guarded_by_constructors ~subst _ _ _ _ _ _ _ = assert false
1052 and recursive_args ~subst context n nn te =
1053 match R.whd context te with
1055 | C.Prod (name,so,de) ->
1056 (not (does_not_occur ~subst context n nn so)) ::
1057 (recursive_args ~subst ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
1058 | _ -> raise (AssertFailure (lazy ("recursive_args")))
1060 and get_new_safes ~subst (context, recfuns, x, safes as k) p rl =
1061 match R.whd ~subst context p, rl with
1062 | C.Lambda (name,so,ta), b::tl ->
1063 let safes = (if b then [0] else []) @ safes in
1064 get_new_safes ~subst
1065 (shift_k (name,(C.Decl so)) (context, recfuns, x, safes)) ta tl
1066 | C.Meta _ as e, _ | e, [] -> e, k
1067 | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
1069 and split_prods ~subst context n te =
1070 match n, R.whd ~subst context te with
1071 | 0, _ -> context,te
1072 | n, C.Prod (name,so,ta) when n > 0 ->
1073 split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
1074 | _ -> raise (AssertFailure (lazy "split_prods"))
1076 and is_really_smaller ~subst (context, recfuns, x, safes as k) te =
1077 match R.whd ~subst context te with
1078 | C.Rel m when List.mem m safes -> true
1080 | C.LetIn _ -> raise (AssertFailure (lazy "letin after whd"))
1081 | C.Sort _ | C.Implicit _ | C.Prod _ | C.Lambda _
1082 | C.Const (Ref.Ref (_,_,(Ref.Decl | Ref.Def | Ref.Ind _ | Ref.CoFix _))) ->
1083 raise (AssertFailure (lazy "not a constructor"))
1084 | C.Appl ([]|[_]) -> raise (AssertFailure (lazy "empty/unary appl"))
1086 (*CSC: sulla coda ci vogliono dei controlli? secondo noi no, ma *)
1087 (*CSC: solo perche' non abbiamo trovato controesempi *)
1088 (*TASSI: da capire soprattutto se he รจ un altro fix che non ha ridotto...*)
1089 is_really_smaller ~subst k he
1090 | C.Const (Ref.Ref (_,_,Ref.Con _)) -> false
1091 | C.Const (Ref.Ref (_,_,Ref.Fix _)) -> assert false
1092 (*| C.Fix (_, fl) ->
1093 let len = List.length fl in
1094 let n_plus_len = n + len
1095 and nn_plus_len = nn + len
1096 and x_plus_len = x + len
1099 (fun (types,len) (n,_,ty,_) ->
1100 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1103 and safes' = List.map (fun x -> x + len) safes in
1105 (fun (_,_,ty,bo) i ->
1107 is_really_smaller ~subst (tys@context) n_plus_len nn_plus_len kl
1108 x_plus_len safes' bo
1111 true (* XXX if this check is repeated when the user completes the
1113 | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) ->
1115 | C.Rel m | C.Appl (C.Rel m :: _ ) when List.mem m safes || m = x ->
1116 let isinductive, paramsno, tl, _, i = E.get_checked_indtys ref in
1117 if not isinductive then
1118 List.for_all (is_really_smaller ~subst k) pl
1120 let c_ctx,len,cl = fix_lefts_in_constrs ~subst uri paramsno tl i in
1122 (fun p (_,_,debruijnedte) ->
1123 let rl' = recursive_args ~subst c_ctx 0 len debruijnedte in
1124 let e, k = get_new_safes ~subst k p rl' in
1125 is_really_smaller ~subst k e)
1127 | _ -> List.for_all (is_really_smaller ~subst k) pl)
1129 and returns_a_coinductive ~subst context ty =
1130 match R.whd ~subst context ty with
1131 | C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)
1132 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)::_) ->
1133 let isinductive, _, _, _, _ = E.get_checked_indtys ref in
1134 if isinductive then None else (Some uri)
1135 | C.Prod (n,so,de) ->
1136 returns_a_coinductive ~subst ((n,C.Decl so)::context) de
1139 and type_of_constant ((Ref.Ref (_,uri,_)) as ref) =
1141 match E.get_obj uri with
1142 | true, cobj -> cobj
1144 !logger (`Start_type_checking uri);
1145 check_obj_well_typed uobj;
1147 !logger (`Type_checking_completed uri);
1148 if not (fst (E.get_obj uri)) then
1149 raise (AssertFailure (lazy "environment error"));
1152 match cobj, ref with
1153 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Ind i) ->
1154 let _,_,arity,_ = List.nth tl i in arity
1155 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Con (i,j)) ->
1156 let _,_,_,cl = List.nth tl i in
1157 let _,_,arity = List.nth cl (j-1) in
1159 | (_,_,_,_,C.Fixpoint (_,fl,_)), Ref.Ref (_,_,(Ref.Fix (i,_)|Ref.CoFix i)) ->
1160 let _,_,_,arity,_ = List.nth fl i in
1162 | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,_,(Ref.Def |Ref.Decl)) -> ty
1163 | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
1165 and check_obj_well_typed (uri,height,metasenv,subst,kind) =
1166 (* CSC: here we should typecheck the metasenv and the subst *)
1167 assert (metasenv = [] && subst = []);
1169 | C.Constant (_,_,Some te,ty,_) ->
1170 let _ = typeof ~subst ~metasenv [] ty in
1171 let ty_te = typeof ~subst ~metasenv [] te in
1172 if not (R.are_convertible ~subst ~metasenv [] ty_te ty) then
1173 raise (TypeCheckerFailure (lazy (Printf.sprintf
1174 "the type of the body is not the one expected:\n%s\nvs\n%s"
1175 (NCicPp.ppterm ty_te) (NCicPp.ppterm ty))))
1176 | C.Constant (_,_,None,ty,_) -> ignore (typeof ~subst ~metasenv [] ty)
1177 | C.Inductive _ as obj -> check_mutual_inductive_defs obj
1178 | C.Fixpoint (inductive,fl,_) ->
1181 (fun (types,kl,len) (_,name,k,ty,_) ->
1182 let _ = typeof ~subst ~metasenv [] ty in
1183 ((name,(C.Decl (S.lift len ty)))::types, k::kl,len+1)
1186 List.iter (fun (_,name,x,ty,bo) ->
1187 let bo = debruijn uri len bo in
1188 let ty_bo = typeof ~subst ~metasenv types bo in
1189 if not (R.are_convertible ~subst ~metasenv types ty_bo (S.lift len ty))
1190 then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1192 if inductive then begin
1193 let m, context = eat_lambdas ~subst types (x + 1) bo in
1194 (* guarded by destructors conditions D{f,k,x,M} *)
1195 let rec enum_from k =
1196 function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl
1198 if not (guarded_by_destructors
1199 ~subst context (enum_from (x+1) kl) m) then
1200 raise(TypeCheckerFailure(lazy("Fix: not guarded by destructors")))
1202 match returns_a_coinductive ~subst [] ty with
1204 raise (TypeCheckerFailure
1205 (lazy "CoFix: does not return a coinductive type"))
1207 (* guarded by constructors conditions C{f,M} *)
1208 if not (guarded_by_constructors ~subst
1209 types 0 len false bo [] uri)
1211 raise (TypeCheckerFailure
1212 (lazy "CoFix: not guarded by constructors"))
1215 let typecheck_obj = check_obj_well_typed;;