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 $ *)
34 (* the boolean h means already protected *)
35 (* args is the list of arguments the type of the constructor that may be *)
36 (* found in head position must be applied to. *)
37 and guarded_by_constructors ~subst context n nn h te args coInductiveTypeURI =
39 (*CSC: There is a lot of code replication between the cases X and *)
40 (*CSC: (C.Appl X tl). Maybe it will be better to define a function *)
41 (*CSC: that maps X into (C.Appl X []) when X is not already a C.Appl *)
42 match CicReduction.whd ~subst context te with
43 C.Rel m when m > n && m <= nn -> h
51 (* the term has just been type-checked *)
52 raise (AssertFailure (lazy "17"))
53 | C.Lambda (name,so,de) ->
54 does_not_occur ~subst context n nn so &&
55 guarded_by_constructors ~subst ((Some (name,(C.Decl so)))::context)
56 (n + 1) (nn + 1) h de args coInductiveTypeURI
57 | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
59 List.fold_right (fun x i -> i && does_not_occur ~subst context n nn x) tl true
60 | C.Appl ((C.MutConstruct (uri,i,j,exp_named_subst))::tl) ->
64 CicEnvironment.get_cooked_obj ~trust:false CicUniv.empty_ugraph uri
65 with Not_found -> assert false
68 C.InductiveDefinition (itl,_,_,_) ->
69 let (_,_,_,cl) = List.nth itl i in
70 let (_,cons) = List.nth cl (j - 1) in
71 CicSubstitution.subst_vars exp_named_subst cons
73 raise (TypeCheckerFailure
74 (lazy ("Unknown mutual inductive definition:" ^ UriManager.string_of_uri uri)))
76 let rec analyse_branch context ty te =
77 match CicReduction.whd ~subst context ty with
78 C.Meta _ -> raise (AssertFailure (lazy "34"))
82 does_not_occur ~subst context n nn te
85 raise (AssertFailure (lazy "24"))(* due to type-checking *)
86 | C.Prod (name,so,de) ->
87 analyse_branch ((Some (name,(C.Decl so)))::context) de te
90 raise (AssertFailure (lazy "25"))(* due to type-checking *)
91 | C.Appl ((C.MutInd (uri,_,_))::_) when uri == coInductiveTypeURI ->
92 guarded_by_constructors ~subst context n nn true te []
94 | C.Appl ((C.MutInd (uri,_,_))::_) ->
95 guarded_by_constructors ~subst context n nn true te tl
98 does_not_occur ~subst context n nn te
99 | C.Const _ -> raise (AssertFailure (lazy "26"))
100 | C.MutInd (uri,_,_) when uri == coInductiveTypeURI ->
101 guarded_by_constructors ~subst context n nn true te []
104 does_not_occur ~subst context n nn te
105 | C.MutConstruct _ -> raise (AssertFailure (lazy "27"))
106 (*CSC: we do not consider backbones with a MutCase, Fix, Cofix *)
107 (*CSC: in head position. *)
111 raise (AssertFailure (lazy "28"))(* due to type-checking *)
113 let rec analyse_instantiated_type context ty l =
114 match CicReduction.whd ~subst context ty with
120 | C.Cast _ -> raise (AssertFailure (lazy "29"))(* due to type-checking *)
121 | C.Prod (name,so,de) ->
126 analyse_branch context so he &&
127 analyse_instantiated_type
128 ((Some (name,(C.Decl so)))::context) de tl
132 raise (AssertFailure (lazy "30"))(* due to type-checking *)
135 (fun i x -> i && does_not_occur ~subst context n nn x) true l
136 | C.Const _ -> raise (AssertFailure (lazy "31"))
139 (fun i x -> i && does_not_occur ~subst context n nn x) true l
140 | C.MutConstruct _ -> raise (AssertFailure (lazy "32"))
141 (*CSC: we do not consider backbones with a MutCase, Fix, Cofix *)
142 (*CSC: in head position. *)
146 raise (AssertFailure (lazy "33"))(* due to type-checking *)
148 let rec instantiate_type args consty =
152 let consty' = CicReduction.whd ~subst context consty in
158 let instantiated_de = CicSubstitution.subst he de in
159 (*CSC: siamo sicuri che non sia troppo forte? *)
160 does_not_occur ~subst context n nn tlhe &
161 instantiate_type tl instantiated_de tltl
163 (*CSC:We do not consider backbones with a MutCase, a *)
164 (*CSC:FixPoint, a CoFixPoint and so on in head position.*)
165 raise (AssertFailure (lazy "23"))
167 | [] -> analyse_instantiated_type context consty' l
168 (* These are all the other cases *)
170 instantiate_type args consty tl
171 | C.Appl ((C.CoFix (_,fl))::tl) ->
172 List.fold_left (fun i x -> i && does_not_occur ~subst context n nn x) true tl &&
173 let len = List.length fl in
174 let n_plus_len = n + len
175 and nn_plus_len = nn + len
176 (*CSC: Is a Decl of the ty ok or should I use Def of a Fix? *)
179 (fun (types,len) (n,ty,_) ->
180 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
186 i && does_not_occur ~subst context n nn ty &&
187 guarded_by_constructors ~subst (tys@context) n_plus_len nn_plus_len
188 h bo args coInductiveTypeURI
190 | C.Appl ((C.MutCase (_,_,out,te,pl))::tl) ->
191 List.fold_left (fun i x -> i && does_not_occur ~subst context n nn x) true tl &&
192 does_not_occur ~subst context n nn out &&
193 does_not_occur ~subst context n nn te &&
197 guarded_by_constructors ~subst context n nn h x args
201 List.fold_right (fun x i -> i && does_not_occur ~subst context n nn x) l true
202 | C.Var (_,exp_named_subst)
203 | C.Const (_,exp_named_subst) ->
205 (fun (_,x) i -> i && does_not_occur ~subst context n nn x) exp_named_subst true
206 | C.MutInd _ -> assert false
207 | C.MutConstruct (_,_,_,exp_named_subst) ->
209 (fun (_,x) i -> i && does_not_occur ~subst context n nn x) exp_named_subst true
210 | C.MutCase (_,_,out,te,pl) ->
211 does_not_occur ~subst context n nn out &&
212 does_not_occur ~subst context n nn te &&
216 guarded_by_constructors ~subst context n nn h x args
220 let len = List.length fl in
221 let n_plus_len = n + len
222 and nn_plus_len = nn + len
223 (*CSC: Is a Decl of the ty ok or should I use Def of a Fix? *)
226 (fun (types,len) (n,_,ty,_) ->
227 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
232 (fun (_,_,ty,bo) i ->
233 i && does_not_occur ~subst context n nn ty &&
234 does_not_occur ~subst (tys@context) n_plus_len nn_plus_len bo
237 let len = List.length fl in
238 let n_plus_len = n + len
239 and nn_plus_len = nn + len
240 (*CSC: Is a Decl of the ty ok or should I use Def of a Fix? *)
243 (fun (types,len) (n,ty,_) ->
244 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
250 i && does_not_occur ~subst context n nn ty &&
251 guarded_by_constructors ~subst (tys@context) n_plus_len nn_plus_len
253 args coInductiveTypeURI
257 type_of_aux ~logger context t ugraph
261 (** wrappers which instantiate fresh loggers *)
263 (* check_allowed_sort_elimination uri i s1 s2
264 This function is used outside the kernel to determine in advance whether
265 a MutCase will be allowed or not.
266 [uri,i] is the type of the term to match
267 [s1] is the sort of the term to eliminate (i.e. the head of the arity
268 of the inductive type [uri,i])
269 [s2] is the sort of the goal (i.e. the head of the type of the outtype
271 let check_allowed_sort_elimination uri i s1 s2 =
272 fst (check_allowed_sort_elimination ~subst:[] ~metasenv:[]
273 ~logger:(new CicLogger.logger) [] uri i true
274 (Cic.Implicit None) (* never used *) (Cic.Sort s1) (Cic.Sort s2)
275 CicUniv.empty_ugraph)
278 Deannotate.type_of_aux' := fun context t -> fst (type_of_aux' [] context t CicUniv.oblivion_ugraph);;
283 module R = NCicReduction
284 module Ref = NReference
285 module S = NCicSubstitution
287 module E = NCicEnvironment
289 let rec split_prods ~subst context n te =
290 match (n, R.whd ~subst context te) with
291 | (0, _) -> context,te
292 | (n, C.Prod (name,so,ta)) when n > 0 ->
293 split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
294 | (_, _) -> raise (AssertFailure (lazy "split_prods"))
297 let debruijn ?(cb=fun _ _ -> ()) uri number_of_types =
301 | C.Meta (i,(s,C.Ctx l)) ->
302 let l1 = NCicUtils.sharing_map (aux (k-s)) l in
303 if l1 == l then t else C.Meta (i,(s,C.Ctx l1))
305 | C.Const (Ref.Ref (_,uri1,(Ref.Fix (no,_) | Ref.CoFix no)))
306 | C.Const (Ref.Ref (_,uri1,Ref.Ind no)) when NUri.eq uri uri1 ->
307 C.Rel (k + number_of_types - no)
308 | t -> NCicUtils.map (fun _ k -> k+1) k aux t
315 let sort_of_prod ~metasenv ~subst context (name,s) (t1, t2) =
316 let t1 = R.whd ~subst context t1 in
317 let t2 = R.whd ~subst ((name,C.Decl s)::context) t2 in
319 | C.Sort s1, C.Sort C.Prop -> t2
320 | C.Sort (C.Type u1), C.Sort (C.Type u2) -> C.Sort (C.Type (max u1 u2))
321 | C.Sort _,C.Sort (C.Type _) -> t2
322 | C.Sort (C.Type _) , C.Sort C.CProp -> t1
323 | C.Sort _, C.Sort C.CProp -> t2
326 | C.Sort _, C.Meta _ when U.is_closed t2 -> t2
328 raise (TypeCheckerFailure (lazy (Printf.sprintf
329 "Prod: expected two sorts, found = %s, %s"
330 (NCicPp.ppterm ~subst ~metasenv ~context t1)
331 (NCicPp.ppterm ~subst ~metasenv ~context t2))))
334 let eat_prods ~subst ~metasenv context he ty_he args_with_ty =
335 let rec aux ty_he = function
337 | (arg, ty_arg)::tl ->
338 match R.whd ~subst context ty_he with
341 prerr_endline (NCicPp.ppterm ~subst ~metasenv ~context s ^ " - Vs - "
342 ^ NCicPp.ppterm ~subst ~metasenv
344 prerr_endline (NCicPp.ppterm ~subst ~metasenv ~context (S.subst ~avoid_beta_redexes:true arg t));
346 if R.are_convertible ~subst ~metasenv context ty_arg s then
347 aux (S.subst ~avoid_beta_redexes:true arg t) tl
351 (lazy (Printf.sprintf
352 ("Appl: wrong application of %s: the parameter %s has type"^^
353 "\n%s\nbut it should have type \n%s\n")
354 (NCicPp.ppterm ~subst ~metasenv ~context he)
355 (NCicPp.ppterm ~subst ~metasenv ~context arg)
356 (NCicPp.ppterm ~subst ~metasenv ~context ty_arg)
357 (NCicPp.ppterm ~subst ~metasenv ~context s))))
361 (lazy (Printf.sprintf
362 "Appl: %s is not a function, it cannot be applied"
363 (NCicPp.ppterm ~subst ~metasenv ~context
364 (let res = List.length tl in
365 let eaten = List.length args_with_ty - res in
368 (fst (HExtlib.split_nth eaten args_with_ty)))))))))
370 aux ty_he args_with_ty
373 let fix_lefts_in_constrs ~subst uri paramsno tyl i =
374 let len = List.length tyl in
375 let _,_,arity,cl = List.nth tyl i in
376 let tys = List.map (fun (_,n,ty,_) -> n,C.Decl ty) tyl in
380 let debruijnedty = debruijn uri len ty in
381 id, snd (split_prods ~subst tys paramsno ty),
382 snd (split_prods ~subst tys paramsno debruijnedty))
385 let lefts = fst (split_prods ~subst [] paramsno arity) in
389 exception DoesOccur;;
391 let does_not_occur ~subst context n nn t =
392 let rec aux (context,n,nn as k) _ = function
393 | C.Rel m when m > n && m <= nn -> raise DoesOccur
395 (try (match List.nth context (m-1) with
396 | _,C.Def (bo,_) -> aux k () (S.lift m bo)
398 with Failure _ -> assert false)
399 | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> (* closed meta *) ()
400 | C.Meta (mno,(s,l)) ->
402 let _,_,term,_ = U.lookup_subst mno subst in
403 aux (context,n+s,nn+s) () (S.subst_meta (0,l) term)
404 with CicUtil.Subst_not_found _ -> match l with
405 | C.Irl len -> if not (n >= s+len || s > nn) then raise DoesOccur
406 | C.Ctx lc -> List.iter (aux (context,n+s,nn+s) ()) lc)
407 | t -> U.fold (fun e (ctx,n,nn) -> (e::ctx,n+1,nn+1)) k aux () t
409 try aux (context,n,nn) () t; true
410 with DoesOccur -> false
413 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
414 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
415 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla *)
416 (*CSC strictly_positive *)
417 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-) *)
418 let rec weakly_positive ~subst context n nn uri te =
419 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
420 let dummy = C.Sort (C.Type ~-1) in
421 (*CSC: mettere in cicSubstitution *)
422 let rec subst_inductive_type_with_dummy _ = function
423 | C.Const (Ref.Ref (_,uri',Ref.Ind 0)) when NUri.eq uri' uri -> dummy
424 | C.Appl ((C.Const (Ref.Ref (_,uri',Ref.Ind 0)))::tl)
425 when NUri.eq uri' uri -> dummy
426 | t -> U.map (fun _ x->x) () subst_inductive_type_with_dummy t
428 match R.whd context te with
429 | C.Const (Ref.Ref (_,uri',Ref.Ind _))
430 | C.Appl ((C.Const (Ref.Ref (_,uri',Ref.Ind _)))::_)
431 when NUri.eq uri' uri -> true
432 | C.Prod (name,source,dest) when
433 does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
434 (* dummy abstraction, so we behave as in the anonimous case *)
435 strictly_positive ~subst context n nn
436 (subst_inductive_type_with_dummy () source) &&
437 weakly_positive ~subst ((name,C.Decl source)::context)
438 (n + 1) (nn + 1) uri dest
439 | C.Prod (name,source,dest) ->
440 does_not_occur ~subst context n nn
441 (subst_inductive_type_with_dummy () source)&&
442 weakly_positive ~subst ((name,C.Decl source)::context)
443 (n + 1) (nn + 1) uri dest
445 raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
447 (* instantiate_parameters ps (x1:T1)...(xn:Tn)C *)
448 (* returns ((x_|ps|:T_|ps|)...(xn:Tn)C){ps_1 / x1 ; ... ; ps_|ps| / x_|ps|} *)
449 and instantiate_parameters params c =
452 | C.Prod (_,_,ta), he::tl -> instantiate_parameters tl (S.subst he ta)
453 | t,l -> raise (AssertFailure (lazy "1"))
455 and strictly_positive ~subst context n nn te =
456 match R.whd context te with
457 | t when does_not_occur ~subst context n nn t -> true
459 | C.Prod (name,so,ta) ->
460 does_not_occur ~subst context n nn so &&
461 strictly_positive ~subst ((name,C.Decl so)::context) (n+1) (nn+1) ta
462 | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
463 List.for_all (does_not_occur ~subst context n nn) tl
464 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind i) as r)::tl) ->
465 let _,paramsno,tyl,_,i = E.get_checked_indtys r in
466 let _,name,ity,cl = List.nth tyl i in
467 let ok = List.length tyl = 1 in
468 let params, arguments = HExtlib.split_nth paramsno tl in
469 let lifted_params = List.map (S.lift 1) params in
471 List.map (fun (_,_,te) -> instantiate_parameters lifted_params te) cl
474 List.for_all (does_not_occur ~subst context n nn) arguments &&
476 (weakly_positive ~subst ((name,C.Decl ity)::context) (n+1) (nn+1) uri) cl
479 (* the inductive type indexes are s.t. n < x <= nn *)
480 and are_all_occurrences_positive ~subst context uri indparamsno i n nn te =
481 match R.whd context te with
482 | C.Appl ((C.Rel m)::tl) as reduct when m = i ->
488 match R.whd context x with
489 | C.Rel m when m = n - (indparamsno - k) -> k - 1
490 | y -> raise (TypeCheckerFailure (lazy
491 ("Argument "^string_of_int (indparamsno - k + 1) ^ " (of " ^
492 string_of_int indparamsno ^ " fixed) is not homogeneous in "^
493 "appl:\n"^ NCicPp.ppterm ~context ~subst ~metasenv:[] reduct))))
497 List.for_all (does_not_occur ~subst context n nn) tl
499 raise (TypeCheckerFailure
500 (lazy ("Non-positive occurence in mutual inductive definition(s) [2]"^
501 NUri.string_of_uri uri)))
502 | C.Rel m when m = i ->
503 if indparamsno = 0 then
506 raise (TypeCheckerFailure
507 (lazy ("Non-positive occurence in mutual inductive definition(s) [3]"^
508 NUri.string_of_uri uri)))
509 | C.Prod (name,source,dest) when
510 does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
511 strictly_positive ~subst context n nn source &&
512 are_all_occurrences_positive ~subst
513 ((name,C.Decl source)::context) uri indparamsno
514 (i+1) (n + 1) (nn + 1) dest
515 | C.Prod (name,source,dest) ->
516 if not (does_not_occur ~subst context n nn source) then
517 raise (TypeCheckerFailure (lazy ("Non-positive occurrence in "^
518 NCicPp.ppterm ~context ~metasenv:[] ~subst te)));
519 are_all_occurrences_positive ~subst ((name,C.Decl source)::context)
520 uri indparamsno (i+1) (n + 1) (nn + 1) dest
523 (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
524 (NUri.string_of_uri uri))))
527 exception NotGuarded of string Lazy.t;;
529 let rec typeof ~subst ~metasenv context term =
530 let rec typeof_aux context =
531 fun t -> (*prerr_endline (NCicPp.ppterm ~context t); *)
535 match List.nth context (n - 1) with
536 | (_,C.Decl ty) -> S.lift n ty
537 | (_,C.Def (_,ty)) -> S.lift n ty
538 with Failure _ -> raise (TypeCheckerFailure (lazy "unbound variable")))
539 | C.Sort (C.Type i) -> C.Sort (C.Type (i+1))
540 | C.Sort s -> C.Sort (C.Type 0)
541 | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
542 | C.Meta (n,l) as t ->
543 let canonical_ctx,ty =
545 let _,c,_,ty = U.lookup_subst n subst in c,ty
546 with U.Subst_not_found _ -> try
547 let _,_,c,ty = U.lookup_meta n metasenv in c,ty
548 with U.Meta_not_found _ ->
549 raise (AssertFailure (lazy (Printf.sprintf
550 "%s not found" (NCicPp.ppterm ~subst ~metasenv ~context t))))
552 check_metasenv_consistency t ~subst ~metasenv context canonical_ctx l;
554 | C.Const ref -> type_of_constant ref
555 | C.Prod (name,s,t) ->
556 let sort1 = typeof_aux context s in
557 let sort2 = typeof_aux ((name,(C.Decl s))::context) t in
558 sort_of_prod ~metasenv ~subst context (name,s) (sort1,sort2)
559 | C.Lambda (n,s,t) ->
560 let sort = typeof_aux context s in
561 (match R.whd ~subst context sort with
562 | C.Meta _ | C.Sort _ -> ()
565 (TypeCheckerFailure (lazy (Printf.sprintf
566 ("Not well-typed lambda-abstraction: " ^^
567 "the source %s should be a type; instead it is a term " ^^
568 "of type %s") (NCicPp.ppterm ~subst ~metasenv ~context s)
569 (NCicPp.ppterm ~subst ~metasenv ~context sort)))));
570 let ty = typeof_aux ((n,(C.Decl s))::context) t in
572 | C.LetIn (n,ty,t,bo) ->
573 let ty_t = typeof_aux context t in
574 let _ = typeof_aux context ty in
575 if not (R.are_convertible ~subst ~metasenv context ty ty_t) then
578 (lazy (Printf.sprintf
579 "The type of %s is %s but it is expected to be %s"
580 (NCicPp.ppterm ~subst ~metasenv ~context t)
581 (NCicPp.ppterm ~subst ~metasenv ~context ty_t)
582 (NCicPp.ppterm ~subst ~metasenv ~context ty))))
584 let ty_bo = typeof_aux ((n,C.Def (t,ty))::context) bo in
585 S.subst ~avoid_beta_redexes:true t ty_bo
586 | C.Appl (he::(_::_ as args)) ->
587 let ty_he = typeof_aux context he in
588 let args_with_ty = List.map (fun t -> t, typeof_aux context t) args in
590 prerr_endline ("HEAD: " ^ NCicPp.ppterm ~subst ~metasenv ~context ty_he);
591 prerr_endline ("TARGS: " ^ String.concat " | " (List.map (NCicPp.ppterm
592 ~subst ~metasenv ~context) (List.map snd args_with_ty)));
593 prerr_endline ("ARGS: " ^ String.concat " | " (List.map (NCicPp.ppterm
594 ~subst ~metasenv ~context) (List.map fst args_with_ty)));
596 eat_prods ~subst ~metasenv context he ty_he args_with_ty
597 | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
598 | C.Match (Ref.Ref (_,_,Ref.Ind tyno) as r,outtype,term,pl) ->
599 let outsort = typeof_aux context outtype in
600 let inductive,leftno,itl,_,_ = E.get_checked_indtys r in
602 let _,_,_,cl = List.nth itl tyno in List.length cl
604 let parameters, arguments =
605 let ty = R.whd ~subst context (typeof_aux context term) in
608 C.Const (Ref.Ref (_,_,Ref.Ind _) as r') -> r',[]
609 | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _) as r') :: tl) -> r',tl
612 (TypeCheckerFailure (lazy (Printf.sprintf
613 "Case analysis: analysed term %s is not an inductive one"
614 (NCicPp.ppterm ~subst ~metasenv ~context term)))) in
615 if not (Ref.eq r r') then
617 (TypeCheckerFailure (lazy (Printf.sprintf
618 ("Case analysys: analysed term type is %s, but is expected " ^^
619 "to be (an application of) %s")
620 (NCicPp.ppterm ~subst ~metasenv ~context ty)
621 (NCicPp.ppterm ~subst ~metasenv ~context (C.Const r')))))
623 try HExtlib.split_nth leftno tl
626 raise (TypeCheckerFailure (lazy (Printf.sprintf
627 "%s is partially applied"
628 (NCicPp.ppterm ~subst ~metasenv ~context ty)))) in
629 (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
630 let sort_of_ind_type =
631 if parameters = [] then C.Const r
632 else C.Appl ((C.Const r)::parameters) in
633 let type_of_sort_of_ind_ty = typeof_aux context sort_of_ind_type in
634 check_allowed_sort_elimination ~subst ~metasenv r context
635 sort_of_ind_type type_of_sort_of_ind_ty outsort;
636 (* let's check if the type of branches are right *)
637 if List.length pl <> constructorsno then
638 raise (TypeCheckerFailure (lazy ("Wrong number of cases in a match")));
639 let j,branches_ok,p_ty, exp_p_ty =
641 (fun (j,b,old_p_ty,old_exp_p_ty) p ->
644 let cons = Ref.mk_constructor j r in
645 if parameters = [] then C.Const cons
646 else C.Appl (C.Const cons::parameters)
648 let ty_p = typeof_aux context p in
649 let ty_cons = typeof_aux context cons in
651 type_of_branch ~subst context leftno outtype cons ty_cons 0
653 j+1, R.are_convertible ~subst ~metasenv context ty_p ty_branch,
656 j,false,old_p_ty,old_exp_p_ty
657 ) (1,true,C.Sort C.Prop,C.Sort C.Prop) pl
659 if not branches_ok then
662 (lazy (Printf.sprintf ("Branch for constructor %s :=\n%s\n"^^
663 "has type %s\nnot convertible with %s")
664 (NCicPp.ppterm ~subst ~metasenv ~context
665 (C.Const (Ref.mk_constructor (j-1) r)))
666 (NCicPp.ppterm ~metasenv ~subst ~context (List.nth pl (j-2)))
667 (NCicPp.ppterm ~metasenv ~subst ~context p_ty)
668 (NCicPp.ppterm ~metasenv ~subst ~context exp_p_ty))));
669 let res = outtype::arguments@[term] in
670 R.head_beta_reduce (C.Appl res)
671 | C.Match _ -> assert false
673 and type_of_branch ~subst context leftno outty cons tycons liftno =
674 match R.whd ~subst context tycons with
675 | C.Const (Ref.Ref (_,_,Ref.Ind _)) -> C.Appl [S.lift liftno outty ; cons]
676 | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _))::tl) ->
677 let _,arguments = HExtlib.split_nth leftno tl in
678 C.Appl (S.lift liftno outty::arguments@[cons])
679 | C.Prod (name,so,de) ->
681 match S.lift 1 cons with
682 | C.Appl l -> C.Appl (l@[C.Rel 1])
683 | t -> C.Appl [t ; C.Rel 1]
686 type_of_branch ~subst ((name,(C.Decl so))::context)
687 leftno outty cons de (liftno+1))
688 | _ -> raise (AssertFailure (lazy "type_of_branch"))
690 (* check_metasenv_consistency checks that the "canonical" context of a
691 metavariable is consitent - up to relocation via the relocation list l -
692 with the actual context *)
693 and check_metasenv_consistency
694 ~subst ~metasenv term context canonical_context l
697 | shift, NCic.Irl n ->
698 let context = snd (HExtlib.split_nth shift context) in
699 let rec compare = function
703 raise (AssertFailure (lazy (Printf.sprintf
704 "Local and canonical context %s have different lengths"
705 (NCicPp.ppterm ~subst ~context ~metasenv term))))
707 raise (TypeCheckerFailure (lazy (Printf.sprintf
708 "Unbound variable -%d in %s" m
709 (NCicPp.ppterm ~subst ~metasenv ~context term))))
712 (_,C.Decl t1), (_,C.Decl t2)
713 | (_,C.Def (t1,_)), (_,C.Def (t2,_))
714 | (_,C.Def (_,t1)), (_,C.Decl t2) ->
715 if not (R.are_convertible ~subst ~metasenv tl t1 t2) then
718 (lazy (Printf.sprintf
719 ("Not well typed metavariable local context for %s: " ^^
720 "%s expected, which is not convertible with %s")
721 (NCicPp.ppterm ~subst ~metasenv ~context term)
722 (NCicPp.ppterm ~subst ~metasenv ~context t2)
723 (NCicPp.ppterm ~subst ~metasenv ~context t1))))
726 (TypeCheckerFailure (lazy (Printf.sprintf
727 ("Not well typed metavariable local context for %s: " ^^
728 "a definition expected, but a declaration found")
729 (NCicPp.ppterm ~subst ~metasenv ~context term)))));
730 compare (m - 1,tl,ctl)
732 compare (n,context,canonical_context)
734 (* we avoid useless lifting by shortening the context*)
735 let l,context = (0,lc_kind), snd (HExtlib.split_nth shift context) in
736 let lifted_canonical_context =
737 let rec lift_metas i = function
739 | (n,C.Decl t)::tl ->
740 (n,C.Decl (S.subst_meta l (S.lift i t)))::(lift_metas (i+1) tl)
741 | (n,C.Def (t,ty))::tl ->
742 (n,C.Def ((S.subst_meta l (S.lift i t)),
743 S.subst_meta l (S.lift i ty)))::(lift_metas (i+1) tl)
745 lift_metas 1 canonical_context in
746 let l = U.expand_local_context lc_kind in
751 | t, (_,C.Def (ct,_)) ->
752 (*CSC: the following optimization is to avoid a possibly expensive
753 reduction that can be easily avoided and that is quite
754 frequent. However, this is better handled using levels to
760 match List.nth context (n - 1) with
761 | (_,C.Def (te,_)) -> S.lift n te
766 if not (R.are_convertible ~subst ~metasenv context optimized_t ct)
770 (lazy (Printf.sprintf
771 ("Not well typed metavariable local context: " ^^
772 "expected a term convertible with %s, found %s")
773 (NCicPp.ppterm ~subst ~metasenv ~context ct)
774 (NCicPp.ppterm ~subst ~metasenv ~context t))))
775 | t, (_,C.Decl ct) ->
776 let type_t = typeof_aux context t in
777 if not (R.are_convertible ~subst ~metasenv context type_t ct) then
778 raise (TypeCheckerFailure
779 (lazy (Printf.sprintf
780 ("Not well typed metavariable local context: "^^
781 "expected a term of type %s, found %s of type %s")
782 (NCicPp.ppterm ~subst ~metasenv ~context ct)
783 (NCicPp.ppterm ~subst ~metasenv ~context t)
784 (NCicPp.ppterm ~subst ~metasenv ~context type_t))))
785 ) l lifted_canonical_context
787 Invalid_argument _ ->
788 raise (AssertFailure (lazy (Printf.sprintf
789 "Local and canonical context %s have different lengths"
790 (NCicPp.ppterm ~subst ~metasenv ~context term))))
792 and is_non_informative context paramsno c =
793 let rec aux context c =
794 match R.whd context c with
795 | C.Prod (n,so,de) ->
796 let s = typeof_aux context so in
797 s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
799 let context',dx = split_prods ~subst:[] context paramsno c in
802 and check_allowed_sort_elimination ~subst ~metasenv r =
805 | C.Appl l -> C.Appl (l @ [arg])
806 | t -> C.Appl [t;arg] in
807 let rec aux context ind arity1 arity2 =
808 let arity1 = R.whd ~subst context arity1 in
809 let arity2 = R.whd ~subst context arity2 in
810 match arity1,arity2 with
811 | C.Prod (name,so1,de1), C.Prod (_,so2,de2) ->
812 if not (R.are_convertible ~subst ~metasenv context so1 so2) then
813 raise (TypeCheckerFailure (lazy (Printf.sprintf
814 "In outtype: expected %s, found %s"
815 (NCicPp.ppterm ~subst ~metasenv ~context so1)
816 (NCicPp.ppterm ~subst ~metasenv ~context so2)
818 aux ((name, C.Decl so1)::context)
819 (mkapp (S.lift 1 ind) (C.Rel 1)) de1 de2
820 | C.Sort _, C.Prod (name,so,ta) ->
821 if not (R.are_convertible ~subst ~metasenv context so ind) then
822 raise (TypeCheckerFailure (lazy (Printf.sprintf
823 "In outtype: expected %s, found %s"
824 (NCicPp.ppterm ~subst ~metasenv ~context ind)
825 (NCicPp.ppterm ~subst ~metasenv ~context so)
827 (match arity1,ta with
828 | (C.Sort (C.CProp | C.Type _), C.Sort _)
829 | (C.Sort C.Prop, C.Sort C.Prop) -> ()
830 | (C.Sort C.Prop, C.Sort (C.CProp | C.Type _)) ->
831 (* TODO: we should pass all these parameters since we
832 * have them already *)
833 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
834 let itl_len = List.length itl in
835 let _,name,ty,cl = List.nth itl i in
836 let cl_len = List.length cl in
837 (* is it a singleton or empty non recursive and non informative
841 (itl_len = 1 && cl_len = 1 &&
842 is_non_informative [name,C.Decl ty] leftno
843 (let _,_,x = List.nth cl 0 in x)))
845 raise (TypeCheckerFailure (lazy
846 ("Sort elimination not allowed")));
853 typeof_aux context term
855 and check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl =
856 (* let's check if the arity of the inductive types are well formed *)
857 List.iter (fun (_,_,x,_) -> ignore (typeof ~subst ~metasenv [] x)) tyl;
858 (* let's check if the types of the inductive constructors are well formed. *)
859 let len = List.length tyl in
860 let tys = List.rev (List.map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl) in
866 let debruijnedte = debruijn uri len te in
867 ignore (typeof ~subst ~metasenv tys debruijnedte);
868 (* let's check also the positivity conditions *)
871 (are_all_occurrences_positive ~subst tys uri leftno i 0 len
876 (lazy ("Non positive occurence in "^NUri.string_of_uri uri))))
881 and eat_lambdas ~subst ~metasenv context n te =
882 match (n, R.whd ~subst context te) with
883 | (0, _) -> (te, context)
884 | (n, C.Lambda (name,so,ta)) when n > 0 ->
885 eat_lambdas ~subst ~metasenv ((name,(C.Decl so))::context) (n - 1) ta
887 raise (AssertFailure (lazy (Printf.sprintf "9 (%d, %s)" n
888 (NCicPp.ppterm ~subst ~metasenv ~context te))))
890 and guarded_by_destructors ~subst ~metasenv context recfuns t =
891 let recursor f k t = NCicUtils.fold shift_k k (fun k () -> f k) () t in
892 let rec aux (context, recfuns, x, safes as k) t =
893 match R.whd ~subst context t with (* TODO: use ~delta:false as mush as poss*)
894 | C.Rel m as t when List.mem_assoc m recfuns ->
895 raise (NotGuarded (lazy
896 (NCicPp.ppterm ~subst ~metasenv ~context t ^ " passed around")))
898 (match List.nth context (m-1) with
900 | _,C.Def (bo,_) -> aux (context, recfuns, x, safes) (S.lift m bo))
902 | C.Appl ((C.Rel m)::tl) as t when List.mem_assoc m recfuns ->
903 let rec_no = List.assoc m recfuns in
904 if not (List.length tl > rec_no) then
905 raise (NotGuarded (lazy
906 (NCicPp.ppterm ~context ~subst ~metasenv t ^
907 " is a partial application of a fix")))
909 let rec_arg = List.nth tl rec_no in
910 if not (is_really_smaller ~subst ~metasenv k rec_arg) then
911 raise (NotGuarded (lazy
912 (NCicPp.ppterm ~context ~subst ~metasenv rec_arg ^ " not smaller")));
915 | C.Appl (C.Const ((Ref.Ref (_,_,Ref.Fix (i,j))) as r)::args) ->
916 List.iter (aux k) args;
917 let fixes,_,_ = E.get_checked_fixes r in
918 let _,_,_,_,bo = List.nth fixes i in
919 let bo_wout_lam, context = eat_lambdas ~subst ~metasenv context j in
920 (* debruijna body..... *) assert false
922 | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) as t ->
923 (match R.whd ~subst context term with
924 | C.Rel m | C.Appl (C.Rel m :: _ ) as t when List.mem m safes || m = x ->
925 let isinductive, paramsno, tl, _, i = E.get_checked_indtys ref in
926 if not isinductive then recursor aux k t
928 let c_ctx,len,cl = fix_lefts_in_constrs ~subst uri paramsno tl i in
929 let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
931 List.iter (aux k) args;
933 (fun p (_,_,bruijnedc) ->
934 let rl = recursive_args ~subst ~metasenv c_ctx 0 len bruijnedc in
935 let p, k = get_new_safes ~subst k p rl in
938 | _ -> recursor aux k t)
939 | t -> recursor aux k t
941 try aux (context, recfuns, 1, []) t
942 with NotGuarded s -> raise (TypeCheckerFailure s)
946 let len = List.length fl in
947 let n_plus_len = n + len
948 and nn_plus_len = nn + len
949 and x_plus_len = x + len
952 (fun (types,len) (n,_,ty,_) ->
953 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
956 and safes' = List.map (fun x -> x + len) safes in
958 (fun (_,_,ty,bo) i ->
959 i && guarded_by_destructors ~subst context n nn kl x_plus_len safes' ty &&
960 guarded_by_destructors ~subst (tys@context) n_plus_len nn_plus_len kl
964 let len = List.length fl in
965 let n_plus_len = n + len
966 and nn_plus_len = nn + len
967 and x_plus_len = x + len
970 (fun (types,len) (n,ty,_) ->
971 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
974 and safes' = List.map (fun x -> x + len) safes in
978 guarded_by_destructors ~subst context n nn kl x_plus_len safes' ty &&
979 guarded_by_destructors ~subst (tys@context) n_plus_len nn_plus_len kl
984 and guarded_by_constructors ~subst ~metasenv _ _ _ _ _ _ _ = true
986 and recursive_args ~subst ~metasenv context n nn te =
987 match R.whd context te with
988 | C.Rel _ | C.Appl _ -> []
989 | C.Prod (name,so,de) ->
990 (not (does_not_occur ~subst context n nn so)) ::
991 (recursive_args ~subst ~metasenv
992 ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
994 raise (AssertFailure (lazy ("recursive_args:" ^ NCicPp.ppterm ~subst
995 ~metasenv ~context:[] t)))
997 and get_new_safes ~subst (context, recfuns, x, safes as k) p rl =
998 match R.whd ~subst context p, rl with
999 | C.Lambda (name,so,ta), b::tl ->
1000 let safes = (if b then [0] else []) @ safes in
1001 get_new_safes ~subst
1002 (shift_k (name,(C.Decl so)) (context, recfuns, x, safes)) ta tl
1003 | C.Meta _ as e, _ | e, [] -> e, k
1004 | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
1006 and split_prods ~subst context n te =
1007 match n, R.whd ~subst context te with
1008 | 0, _ -> context,te
1009 | n, C.Prod (name,so,ta) when n > 0 ->
1010 split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
1011 | _ -> raise (AssertFailure (lazy "split_prods"))
1013 and is_really_smaller ~subst ~metasenv (context, recfuns, x, safes as k) te =
1014 match R.whd ~subst context te with
1015 | C.Rel m when List.mem m safes -> true
1016 | C.Lambda (name, s, t) ->
1017 is_really_smaller ~subst ~metasenv (shift_k (name, C.Decl s) k) t
1019 is_really_smaller ~subst ~metasenv k he
1022 | C.Const (Ref.Ref (_,_,Ref.Con _)) -> false
1023 | C.Const (Ref.Ref (_,_,Ref.Fix _)) -> assert false
1024 (*| C.Fix (_, fl) ->
1025 let len = List.length fl in
1026 let n_plus_len = n + len
1027 and nn_plus_len = nn + len
1028 and x_plus_len = x + len
1031 (fun (types,len) (n,_,ty,_) ->
1032 (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
1035 and safes' = List.map (fun x -> x + len) safes in
1037 (fun (_,_,ty,bo) i ->
1039 is_really_smaller ~subst (tys@context) n_plus_len nn_plus_len kl
1040 x_plus_len safes' bo
1043 | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) ->
1045 | C.Rel m | C.Appl (C.Rel m :: _ ) when List.mem m safes || m = x ->
1046 let isinductive, paramsno, tl, _, i = E.get_checked_indtys ref in
1047 if not isinductive then
1048 List.for_all (is_really_smaller ~subst ~metasenv k) pl
1050 let c_ctx,len,cl = fix_lefts_in_constrs ~subst uri paramsno tl i in
1052 (fun p (_,_,debruijnedte) ->
1053 let rl'=recursive_args ~subst ~metasenv c_ctx 0 len debruijnedte in
1054 let e, k = get_new_safes ~subst k p rl' in
1055 is_really_smaller ~subst ~metasenv k e)
1057 | _ -> List.for_all (is_really_smaller ~subst ~metasenv k) pl)
1060 and returns_a_coinductive ~subst context ty =
1061 match R.whd ~subst context ty with
1062 | C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)
1063 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)::_) ->
1064 let isinductive, _, _, _, _ = E.get_checked_indtys ref in
1065 if isinductive then None else (Some uri)
1066 | C.Prod (n,so,de) ->
1067 returns_a_coinductive ~subst ((n,C.Decl so)::context) de
1070 and type_of_constant ((Ref.Ref (_,uri,_)) as ref) =
1072 match E.get_obj uri with
1073 | true, cobj -> cobj
1075 !logger (`Start_type_checking uri);
1076 check_obj_well_typed uobj;
1078 !logger (`Type_checking_completed uri);
1081 match cobj, ref with
1082 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Ind i) ->
1083 let _,_,arity,_ = List.nth tl i in arity
1084 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Con (i,j)) ->
1085 let _,_,_,cl = List.nth tl i in
1086 let _,_,arity = List.nth cl (j-1) in
1088 | (_,_,_,_,C.Fixpoint (_,fl,_)), Ref.Ref (_,_,(Ref.Fix (i,_)|Ref.CoFix i)) ->
1089 let _,_,_,arity,_ = List.nth fl i in
1091 | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,_,(Ref.Def |Ref.Decl)) -> ty
1092 | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
1094 and check_obj_well_typed (uri,height,metasenv,subst,kind) =
1095 (* CSC: here we should typecheck the metasenv and the subst *)
1096 assert (metasenv = [] && subst = []);
1098 | C.Constant (_,_,Some te,ty,_) ->
1100 prerr_endline ("TY: " ^ NCicPp.ppterm ~subst ~metasenv ~context:[] ty);
1101 prerr_endline ("BO: " ^ NCicPp.ppterm ~subst ~metasenv ~context:[] te);
1103 let _ = typeof ~subst ~metasenv [] ty in
1104 let ty_te = typeof ~subst ~metasenv [] te in
1105 (* prerr_endline "XXXX"; *)
1106 if not (R.are_convertible ~subst ~metasenv [] ty_te ty) then
1107 raise (TypeCheckerFailure (lazy (Printf.sprintf
1108 "the type of the body is not the one expected:\n%s\nvs\n%s"
1109 (NCicPp.ppterm ~subst ~metasenv ~context:[] ty_te)
1110 (NCicPp.ppterm ~subst ~metasenv ~context:[] ty))))
1111 | C.Constant (_,_,None,ty,_) -> ignore (typeof ~subst ~metasenv [] ty)
1112 | C.Inductive (is_ind, leftno, tyl, _) ->
1113 check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl
1114 | C.Fixpoint (inductive,fl,_) ->
1117 (fun (types,kl,len) (_,name,k,ty,_) ->
1118 let _ = typeof ~subst ~metasenv [] ty in
1119 ((name,(C.Decl (S.lift len ty)))::types, k::kl,len+1)
1122 List.iter (fun (_,name,x,ty,bo) ->
1123 let bo = debruijn uri len bo in
1124 let ty_bo = typeof ~subst ~metasenv types bo in
1125 if not (R.are_convertible ~subst ~metasenv types ty_bo (S.lift len ty))
1126 then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1128 if inductive then begin
1129 let m, context = eat_lambdas ~subst ~metasenv types (x + 1) bo in
1130 (* guarded by destructors conditions D{f,k,x,M} *)
1131 let rec enum_from k =
1132 function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl
1134 guarded_by_destructors
1135 ~subst ~metasenv context (enum_from (x+2) kl) m
1137 match returns_a_coinductive ~subst [] ty with
1139 raise (TypeCheckerFailure
1140 (lazy "CoFix: does not return a coinductive type"))
1142 (* guarded by constructors conditions C{f,M} *)
1143 if not (guarded_by_constructors ~subst ~metasenv
1144 types 0 len false bo [] uri)
1146 raise (TypeCheckerFailure
1147 (lazy "CoFix: not guarded by constructors"))
1150 let typecheck_obj = check_obj_well_typed;;