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 $ *)
15 module R = NCicReduction
16 module Ref = NReference
17 module S = NCicSubstitution
19 module E = NCicEnvironment
22 (* web interface stuff *)
25 ref (function (`Start_type_checking _|`Type_checking_completed _) -> ())
28 let set_logger f = logger := f;;
30 exception TypeCheckerFailure of string Lazy.t
31 exception AssertFailure of string Lazy.t
34 | Evil of int (* rno *)
35 | UnfFix of bool list (* fixed arguments *)
39 let is_dangerous i l =
40 List.exists (function (j,Evil _) when j=i -> true | _ -> false) l
44 List.exists (function (j,UnfFix _) when j=i -> true | _ -> false) l
48 List.exists (function (j,Safe) when j=i -> true | _ -> false) l
52 try match List.assoc i l with Evil rno -> rno | _ -> assert false
53 with Not_found -> assert false
56 let get_fixed_args i l =
57 try match List.assoc i l with UnfFix fa -> fa | _ -> assert false
58 with Not_found -> assert false
61 let shift_k e (c,rf,x) = e::c,List.map (fun (k,v) -> k+1,v) rf,x+1;;
63 let string_of_recfuns ~subst ~metasenv ~context l =
64 let pp = PP.ppterm ~subst ~metasenv ~context in
65 let safe, rest = List.partition (function (_,Safe) -> true | _ -> false) l in
66 let dang,unf = List.partition (function (_,UnfFix _)-> false | _->true)rest in
67 "\n\tsafes: "^String.concat "," (List.map (fun (i,_)->pp (C.Rel i)) safe) ^
68 "\n\tfix : "^String.concat ","
70 (function (i,UnfFix l)-> pp(C.Rel i)^"/"^String.concat "," (List.map
72 | _ ->assert false) unf) ^
73 "\n\trec : "^String.concat ","
75 (function (i,Evil rno)->pp(C.Rel i)^"/"^string_of_int rno
76 | _ -> assert false) dang)
79 let fixed_args bos j n nn =
80 let rec aux k acc = function
81 | C.Appl (C.Rel i::args) when i-k > n && i-k <= nn ->
82 let rec combine l1 l2 =
85 | he1::tl1, he2::tl2 -> (he1,he2)::combine tl1 tl2
86 | he::tl, [] -> (false,C.Rel ~-1)::combine tl [] (* dummy term *)
87 | [],_::_ -> assert false
89 let lefts, _ = HExtlib.split_nth (min j (List.length args)) args in
90 List.map (fun ((b,x),i) -> b && x = C.Rel (k-i))
91 (HExtlib.list_mapi (fun x i -> x,i) (combine acc lefts))
92 | t -> U.fold (fun _ k -> k+1) k aux acc t
94 List.fold_left (aux 0)
95 (let rec f = function 0 -> [] | n -> true :: f (n-1) in f j) bos
98 let rec list_iter_default2 f l1 def l2 =
101 | a::ta, b::tb -> f a b; list_iter_default2 f ta def tb
102 | a::ta, [] -> f a def; list_iter_default2 f ta def []
105 let rec split_prods ~subst context n te =
106 match (n, R.whd ~subst context te) with
107 | (0, _) -> context,te
108 | (n, C.Prod (name,so,ta)) when n > 0 ->
109 split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
110 | (_, _) -> raise (AssertFailure (lazy "split_prods"))
113 let debruijn ?(cb=fun _ _ -> ()) uri number_of_types context =
117 | C.Meta (i,(s,C.Ctx l)) ->
118 let l1 = U.sharing_map (aux (k-s)) l in
119 if l1 == l then t else C.Meta (i,(s,C.Ctx l1))
121 | C.Const (Ref.Ref (_,uri1,(Ref.Fix (no,_) | Ref.CoFix no)))
122 | C.Const (Ref.Ref (_,uri1,Ref.Ind no)) when NUri.eq uri uri1 ->
123 C.Rel (k + number_of_types - no)
124 | t -> U.map (fun _ k -> k+1) k aux t
128 aux (List.length context)
131 let sort_of_prod ~metasenv ~subst context (name,s) (t1, t2) =
132 let t1 = R.whd ~subst context t1 in
133 let t2 = R.whd ~subst ((name,C.Decl s)::context) t2 in
135 | C.Sort s1, C.Sort C.Prop -> t2
136 | C.Sort (C.Type u1), C.Sort (C.Type u2) -> C.Sort (C.Type (max u1 u2))
137 | C.Sort _,C.Sort (C.Type _) -> t2
138 | C.Sort (C.Type _) , C.Sort C.CProp -> t1
139 | C.Sort _, C.Sort C.CProp -> t2
142 | C.Sort _, C.Meta _ when U.is_closed t2 -> t2
144 raise (TypeCheckerFailure (lazy (Printf.sprintf
145 "Prod: expected two sorts, found = %s, %s"
146 (PP.ppterm ~subst ~metasenv ~context t1)
147 (PP.ppterm ~subst ~metasenv ~context t2))))
150 let eat_prods ~subst ~metasenv context he ty_he args_with_ty =
151 let rec aux ty_he = function
153 | (arg, ty_arg)::tl ->
154 match R.whd ~subst context ty_he with
157 prerr_endline (PP.ppterm ~subst ~metasenv ~context s ^ " - Vs - "
158 ^ PP.ppterm ~subst ~metasenv ~context ty_arg);
159 prerr_endline (PP.ppterm ~subst ~metasenv ~context
160 (S.subst ~avoid_beta_redexes:true arg t));
162 if R.are_convertible ~subst ~metasenv context ty_arg s then
163 aux (S.subst ~avoid_beta_redexes:true arg t) tl
167 (lazy (Printf.sprintf
168 ("Appl: wrong application of %s: the parameter %s has type"^^
169 "\n%s\nbut it should have type \n%s\nContext:\n%s\n")
170 (PP.ppterm ~subst ~metasenv ~context he)
171 (PP.ppterm ~subst ~metasenv ~context arg)
172 (PP.ppterm ~subst ~metasenv ~context ty_arg)
173 (PP.ppterm ~subst ~metasenv ~context s)
174 (PP.ppcontext ~subst ~metasenv context))))
178 (lazy (Printf.sprintf
179 "Appl: %s is not a function, it cannot be applied"
180 (PP.ppterm ~subst ~metasenv ~context
181 (let res = List.length tl in
182 let eaten = List.length args_with_ty - res in
185 (fst (HExtlib.split_nth eaten args_with_ty)))))))))
187 aux ty_he args_with_ty
190 (* instantiate_parameters ps (x1:T1)...(xn:Tn)C *)
191 (* returns ((x_|ps|:T_|ps|)...(xn:Tn)C){ps_1 / x1 ; ... ; ps_|ps| / x_|ps|} *)
192 let rec instantiate_parameters params c =
195 | C.Prod (_,_,ta), he::tl -> instantiate_parameters tl (S.subst he ta)
196 | t,l -> raise (AssertFailure (lazy "1"))
199 let specialize_inductive_type_constrs ~subst context ty_term =
200 match R.whd ~subst context ty_term with
201 | C.Const (Ref.Ref (_,uri,Ref.Ind i) as ref)
202 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind i) as ref) :: _ ) as ty ->
203 let args = match ty with C.Appl (_::tl) -> tl | _ -> [] in
204 let is_ind, leftno, itl, attrs, i = E.get_checked_indtys ref in
205 let left_args,_ = HExtlib.split_nth leftno args in
206 let _,_,_,cl = List.nth itl i in
208 (fun (rel,name,ty) -> rel, name, instantiate_parameters left_args ty) cl
212 let specialize_and_abstract_constrs ~subst r_uri r_len context ty_term =
213 let cl = specialize_inductive_type_constrs ~subst context ty_term in
214 let len = List.length context in
216 match E.get_checked_obj r_uri with
217 | _,_,_,_, NCic.Inductive (_,_,tys,_) ->
218 context @ List.map (fun (_,name,arity,_) -> name,C.Decl arity) tys
222 List.map (fun (_,id,ty) -> id, debruijn r_uri r_len context ty) cl,
226 exception DoesOccur;;
228 let does_not_occur ~subst context n nn t =
229 let rec aux (context,n,nn as k) _ = function
230 | C.Rel m when m > n && m <= nn -> raise DoesOccur
232 (try (match List.nth context (m-1) with
233 | _,C.Def (bo,_) -> aux k () (S.lift m bo)
235 with Failure _ -> assert false)
236 | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> (* closed meta *) ()
237 | C.Meta (mno,(s,l)) ->
239 let _,_,term,_ = U.lookup_subst mno subst in
240 aux (context,n+s,nn+s) () (S.subst_meta (0,l) term)
241 with CicUtil.Subst_not_found _ -> match l with
242 | C.Irl len -> if not (n >= s+len || s > nn) then raise DoesOccur
243 | C.Ctx lc -> List.iter (aux (context,n+s,nn+s) ()) lc)
244 | t -> U.fold (fun e (ctx,n,nn) -> (e::ctx,n+1,nn+1)) k aux () t
246 try aux (context,n,nn) () t; true
247 with DoesOccur -> false
250 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
251 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
252 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla *)
253 (*CSC strictly_positive *)
254 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-) *)
255 let rec weakly_positive ~subst context n nn uri te =
256 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
257 let dummy = C.Sort (C.Type ~-1) in
258 (*CSC: mettere in cicSubstitution *)
259 let rec subst_inductive_type_with_dummy _ = function
260 | C.Const (Ref.Ref (_,uri',Ref.Ind 0)) when NUri.eq uri' uri -> dummy
261 | C.Appl ((C.Const (Ref.Ref (_,uri',Ref.Ind 0)))::tl)
262 when NUri.eq uri' uri -> dummy
263 | t -> U.map (fun _ x->x) () subst_inductive_type_with_dummy t
265 match R.whd context te with
266 | C.Const (Ref.Ref (_,uri',Ref.Ind _))
267 | C.Appl ((C.Const (Ref.Ref (_,uri',Ref.Ind _)))::_)
268 when NUri.eq uri' uri -> true
269 | C.Prod (name,source,dest) when
270 does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
271 (* dummy abstraction, so we behave as in the anonimous case *)
272 strictly_positive ~subst context n nn
273 (subst_inductive_type_with_dummy () source) &&
274 weakly_positive ~subst ((name,C.Decl source)::context)
275 (n + 1) (nn + 1) uri dest
276 | C.Prod (name,source,dest) ->
277 does_not_occur ~subst context n nn
278 (subst_inductive_type_with_dummy () source)&&
279 weakly_positive ~subst ((name,C.Decl source)::context)
280 (n + 1) (nn + 1) uri dest
282 raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
284 and strictly_positive ~subst context n nn te =
285 match R.whd context te with
286 | t when does_not_occur ~subst context n nn t -> true
288 | C.Prod (name,so,ta) ->
289 does_not_occur ~subst context n nn so &&
290 strictly_positive ~subst ((name,C.Decl so)::context) (n+1) (nn+1) ta
291 | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
292 List.for_all (does_not_occur ~subst context n nn) tl
293 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind i) as r)::tl) ->
294 let _,paramsno,tyl,_,i = E.get_checked_indtys r in
295 let _,name,ity,cl = List.nth tyl i in
296 let ok = List.length tyl = 1 in
297 let params, arguments = HExtlib.split_nth paramsno tl in
298 let lifted_params = List.map (S.lift 1) params in
300 List.map (fun (_,_,te) -> instantiate_parameters lifted_params te) cl
303 List.for_all (does_not_occur ~subst context n nn) arguments &&
305 (weakly_positive ~subst ((name,C.Decl ity)::context) (n+1) (nn+1) uri) cl
308 (* the inductive type indexes are s.t. n < x <= nn *)
309 and are_all_occurrences_positive ~subst context uri indparamsno i n nn te =
310 match R.whd context te with
311 | C.Appl ((C.Rel m)::tl) as reduct when m = i ->
317 match R.whd context x with
318 | C.Rel m when m = n - (indparamsno - k) -> k - 1
319 | y -> raise (TypeCheckerFailure (lazy
320 ("Argument "^string_of_int (indparamsno - k + 1) ^ " (of " ^
321 string_of_int indparamsno ^ " fixed) is not homogeneous in "^
322 "appl:\n"^ PP.ppterm ~context ~subst ~metasenv:[] reduct))))
326 List.for_all (does_not_occur ~subst context n nn) tl
328 raise (TypeCheckerFailure
329 (lazy ("Non-positive occurence in mutual inductive definition(s) [2]"^
330 NUri.string_of_uri uri)))
331 | C.Rel m when m = i ->
332 if indparamsno = 0 then
335 raise (TypeCheckerFailure
336 (lazy ("Non-positive occurence in mutual inductive definition(s) [3]"^
337 NUri.string_of_uri uri)))
338 | C.Prod (name,source,dest) when
339 does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
340 strictly_positive ~subst context n nn source &&
341 are_all_occurrences_positive ~subst
342 ((name,C.Decl source)::context) uri indparamsno
343 (i+1) (n + 1) (nn + 1) dest
344 | C.Prod (name,source,dest) ->
345 if not (does_not_occur ~subst context n nn source) then
346 raise (TypeCheckerFailure (lazy ("Non-positive occurrence in "^
347 PP.ppterm ~context ~metasenv:[] ~subst te)));
348 are_all_occurrences_positive ~subst ((name,C.Decl source)::context)
349 uri indparamsno (i+1) (n + 1) (nn + 1) dest
352 (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
353 (NUri.string_of_uri uri))))
356 exception NotGuarded of string Lazy.t;;
358 let rec typeof ~subst ~metasenv context term =
359 let rec typeof_aux context =
360 fun t -> (*prerr_endline (PP.ppterm ~metasenv ~subst ~context t);*)
364 match List.nth context (n - 1) with
365 | (_,C.Decl ty) -> S.lift n ty
366 | (_,C.Def (_,ty)) -> S.lift n ty
367 with Failure _ -> raise (TypeCheckerFailure (lazy "unbound variable")))
368 | C.Sort (C.Type i) -> C.Sort (C.Type (i+1))
369 | C.Sort s -> C.Sort (C.Type 0)
370 | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
371 | C.Meta (n,l) as t ->
372 let canonical_ctx,ty =
374 let _,c,_,ty = U.lookup_subst n subst in c,ty
375 with U.Subst_not_found _ -> try
376 let _,_,c,ty = U.lookup_meta n metasenv in c,ty
377 with U.Meta_not_found _ ->
378 raise (AssertFailure (lazy (Printf.sprintf
379 "%s not found" (PP.ppterm ~subst ~metasenv ~context t))))
381 check_metasenv_consistency t ~subst ~metasenv context canonical_ctx l;
383 | C.Const ref -> type_of_constant ref
384 | C.Prod (name,s,t) ->
385 let sort1 = typeof_aux context s in
386 let sort2 = typeof_aux ((name,(C.Decl s))::context) t in
387 sort_of_prod ~metasenv ~subst context (name,s) (sort1,sort2)
388 | C.Lambda (n,s,t) ->
389 let sort = typeof_aux context s in
390 (match R.whd ~subst context sort with
391 | C.Meta _ | C.Sort _ -> ()
394 (TypeCheckerFailure (lazy (Printf.sprintf
395 ("Not well-typed lambda-abstraction: " ^^
396 "the source %s should be a type; instead it is a term " ^^
397 "of type %s") (PP.ppterm ~subst ~metasenv ~context s)
398 (PP.ppterm ~subst ~metasenv ~context sort)))));
399 let ty = typeof_aux ((n,(C.Decl s))::context) t in
401 | C.LetIn (n,ty,t,bo) ->
402 let ty_t = typeof_aux context t in
403 let _ = typeof_aux context ty in
404 if not (R.are_convertible ~subst ~metasenv context ty ty_t) then
407 (lazy (Printf.sprintf
408 "The type of %s is %s but it is expected to be %s"
409 (PP.ppterm ~subst ~metasenv ~context t)
410 (PP.ppterm ~subst ~metasenv ~context ty_t)
411 (PP.ppterm ~subst ~metasenv ~context ty))))
413 let ty_bo = typeof_aux ((n,C.Def (t,ty))::context) bo in
414 S.subst ~avoid_beta_redexes:true t ty_bo
415 | C.Appl (he::(_::_ as args)) ->
416 let ty_he = typeof_aux context he in
417 let args_with_ty = List.map (fun t -> t, typeof_aux context t) args in
419 prerr_endline ("HEAD: " ^ PP.ppterm ~subst ~metasenv ~context ty_he);
420 prerr_endline ("TARGS: " ^ String.concat " | " (List.map (PP.ppterm
421 ~subst ~metasenv ~context) (List.map snd args_with_ty)));
422 prerr_endline ("ARGS: " ^ String.concat " | " (List.map (PP.ppterm
423 ~subst ~metasenv ~context) (List.map fst args_with_ty)));
425 eat_prods ~subst ~metasenv context he ty_he args_with_ty
426 | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
427 | C.Match (Ref.Ref (_,_,Ref.Ind tyno) as r,outtype,term,pl) ->
428 let outsort = typeof_aux context outtype in
429 let inductive,leftno,itl,_,_ = E.get_checked_indtys r in
431 let _,_,_,cl = List.nth itl tyno in List.length cl
433 let parameters, arguments =
434 let ty = R.whd ~subst context (typeof_aux context term) in
437 C.Const (Ref.Ref (_,_,Ref.Ind _) as r') -> r',[]
438 | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _) as r') :: tl) -> r',tl
441 (TypeCheckerFailure (lazy (Printf.sprintf
442 "Case analysis: analysed term %s is not an inductive one"
443 (PP.ppterm ~subst ~metasenv ~context term)))) in
444 if not (Ref.eq r r') then
446 (TypeCheckerFailure (lazy (Printf.sprintf
447 ("Case analysys: analysed term type is %s, but is expected " ^^
448 "to be (an application of) %s")
449 (PP.ppterm ~subst ~metasenv ~context ty)
450 (PP.ppterm ~subst ~metasenv ~context (C.Const r')))))
452 try HExtlib.split_nth leftno tl
455 raise (TypeCheckerFailure (lazy (Printf.sprintf
456 "%s is partially applied"
457 (PP.ppterm ~subst ~metasenv ~context ty)))) in
458 (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
459 let sort_of_ind_type =
460 if parameters = [] then C.Const r
461 else C.Appl ((C.Const r)::parameters) in
462 let type_of_sort_of_ind_ty = typeof_aux context sort_of_ind_type in
463 check_allowed_sort_elimination ~subst ~metasenv r context
464 sort_of_ind_type type_of_sort_of_ind_ty outsort;
465 (* let's check if the type of branches are right *)
466 if List.length pl <> constructorsno then
467 raise (TypeCheckerFailure (lazy ("Wrong number of cases in a match")));
468 let j,branches_ok,p_ty, exp_p_ty =
470 (fun (j,b,old_p_ty,old_exp_p_ty) p ->
473 let cons = Ref.mk_constructor j r in
474 if parameters = [] then C.Const cons
475 else C.Appl (C.Const cons::parameters)
477 let ty_p = typeof_aux context p in
478 let ty_cons = typeof_aux context cons in
480 type_of_branch ~subst context leftno outtype cons ty_cons 0
482 j+1, R.are_convertible ~subst ~metasenv context ty_p ty_branch,
485 j,false,old_p_ty,old_exp_p_ty
486 ) (1,true,C.Sort C.Prop,C.Sort C.Prop) pl
488 if not branches_ok then
491 (lazy (Printf.sprintf ("Branch for constructor %s :=\n%s\n"^^
492 "has type %s\nnot convertible with %s")
493 (PP.ppterm ~subst ~metasenv ~context
494 (C.Const (Ref.mk_constructor (j-1) r)))
495 (PP.ppterm ~metasenv ~subst ~context (List.nth pl (j-2)))
496 (PP.ppterm ~metasenv ~subst ~context p_ty)
497 (PP.ppterm ~metasenv ~subst ~context exp_p_ty))));
498 let res = outtype::arguments@[term] in
499 R.head_beta_reduce (C.Appl res)
500 | C.Match _ -> assert false
502 and type_of_branch ~subst context leftno outty cons tycons liftno =
503 match R.whd ~subst context tycons with
504 | C.Const (Ref.Ref (_,_,Ref.Ind _)) -> C.Appl [S.lift liftno outty ; cons]
505 | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _))::tl) ->
506 let _,arguments = HExtlib.split_nth leftno tl in
507 C.Appl (S.lift liftno outty::arguments@[cons])
508 | C.Prod (name,so,de) ->
510 match S.lift 1 cons with
511 | C.Appl l -> C.Appl (l@[C.Rel 1])
512 | t -> C.Appl [t ; C.Rel 1]
515 type_of_branch ~subst ((name,(C.Decl so))::context)
516 leftno outty cons de (liftno+1))
517 | _ -> raise (AssertFailure (lazy "type_of_branch"))
519 (* check_metasenv_consistency checks that the "canonical" context of a
520 metavariable is consitent - up to relocation via the relocation list l -
521 with the actual context *)
522 and check_metasenv_consistency
523 ~subst ~metasenv term context canonical_context l
527 let context = snd (HExtlib.split_nth shift context) in
528 let rec compare = function
532 raise (AssertFailure (lazy (Printf.sprintf
533 "Local and canonical context %s have different lengths"
534 (PP.ppterm ~subst ~context ~metasenv term))))
536 raise (TypeCheckerFailure (lazy (Printf.sprintf
537 "Unbound variable -%d in %s" m
538 (PP.ppterm ~subst ~metasenv ~context term))))
541 (_,C.Decl t1), (_,C.Decl t2)
542 | (_,C.Def (t1,_)), (_,C.Def (t2,_))
543 | (_,C.Def (_,t1)), (_,C.Decl t2) ->
544 if not (R.are_convertible ~subst ~metasenv tl t1 t2) then
547 (lazy (Printf.sprintf
548 ("Not well typed metavariable local context for %s: " ^^
549 "%s expected, which is not convertible with %s")
550 (PP.ppterm ~subst ~metasenv ~context term)
551 (PP.ppterm ~subst ~metasenv ~context t2)
552 (PP.ppterm ~subst ~metasenv ~context t1))))
555 (TypeCheckerFailure (lazy (Printf.sprintf
556 ("Not well typed metavariable local context for %s: " ^^
557 "a definition expected, but a declaration found")
558 (PP.ppterm ~subst ~metasenv ~context term)))));
559 compare (m - 1,tl,ctl)
561 compare (n,context,canonical_context)
563 (* we avoid useless lifting by shortening the context*)
564 let l,context = (0,lc_kind), snd (HExtlib.split_nth shift context) in
565 let lifted_canonical_context =
566 let rec lift_metas i = function
568 | (n,C.Decl t)::tl ->
569 (n,C.Decl (S.subst_meta l (S.lift i t)))::(lift_metas (i+1) tl)
570 | (n,C.Def (t,ty))::tl ->
571 (n,C.Def ((S.subst_meta l (S.lift i t)),
572 S.subst_meta l (S.lift i ty)))::(lift_metas (i+1) tl)
574 lift_metas 1 canonical_context in
575 let l = U.expand_local_context lc_kind in
580 | t, (_,C.Def (ct,_)) ->
581 (*CSC: the following optimization is to avoid a possibly expensive
582 reduction that can be easily avoided and that is quite
583 frequent. However, this is better handled using levels to
589 match List.nth context (n - 1) with
590 | (_,C.Def (te,_)) -> S.lift n te
595 if not (R.are_convertible ~subst ~metasenv context optimized_t ct)
599 (lazy (Printf.sprintf
600 ("Not well typed metavariable local context: " ^^
601 "expected a term convertible with %s, found %s")
602 (PP.ppterm ~subst ~metasenv ~context ct)
603 (PP.ppterm ~subst ~metasenv ~context t))))
604 | t, (_,C.Decl ct) ->
605 let type_t = typeof_aux context t in
606 if not (R.are_convertible ~subst ~metasenv context type_t ct) then
607 raise (TypeCheckerFailure
608 (lazy (Printf.sprintf
609 ("Not well typed metavariable local context: "^^
610 "expected a term of type %s, found %s of type %s")
611 (PP.ppterm ~subst ~metasenv ~context ct)
612 (PP.ppterm ~subst ~metasenv ~context t)
613 (PP.ppterm ~subst ~metasenv ~context type_t))))
614 ) l lifted_canonical_context
616 Invalid_argument _ ->
617 raise (AssertFailure (lazy (Printf.sprintf
618 "Local and canonical context %s have different lengths"
619 (PP.ppterm ~subst ~metasenv ~context term))))
621 and is_non_informative context paramsno c =
622 let rec aux context c =
623 match R.whd context c with
624 | C.Prod (n,so,de) ->
625 let s = typeof_aux context so in
626 s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
628 let context',dx = split_prods ~subst:[] context paramsno c in
631 and check_allowed_sort_elimination ~subst ~metasenv r =
634 | C.Appl l -> C.Appl (l @ [arg])
635 | t -> C.Appl [t;arg] in
636 let rec aux context ind arity1 arity2 =
637 let arity1 = R.whd ~subst context arity1 in
638 let arity2 = R.whd ~subst context arity2 in
639 match arity1,arity2 with
640 | C.Prod (name,so1,de1), C.Prod (_,so2,de2) ->
641 if not (R.are_convertible ~subst ~metasenv context so1 so2) then
642 raise (TypeCheckerFailure (lazy (Printf.sprintf
643 "In outtype: expected %s, found %s"
644 (PP.ppterm ~subst ~metasenv ~context so1)
645 (PP.ppterm ~subst ~metasenv ~context so2)
647 aux ((name, C.Decl so1)::context)
648 (mkapp (S.lift 1 ind) (C.Rel 1)) de1 de2
649 | C.Sort _, C.Prod (name,so,ta) ->
650 if not (R.are_convertible ~subst ~metasenv context so ind) then
651 raise (TypeCheckerFailure (lazy (Printf.sprintf
652 "In outtype: expected %s, found %s"
653 (PP.ppterm ~subst ~metasenv ~context ind)
654 (PP.ppterm ~subst ~metasenv ~context so)
656 (match arity1,ta with
657 | (C.Sort (C.CProp | C.Type _), C.Sort _)
658 | (C.Sort C.Prop, C.Sort C.Prop) -> ()
659 | (C.Sort C.Prop, C.Sort (C.CProp | C.Type _)) ->
660 (* TODO: we should pass all these parameters since we
661 * have them already *)
662 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
663 let itl_len = List.length itl in
664 let _,name,ty,cl = List.nth itl i in
665 let cl_len = List.length cl in
666 (* is it a singleton or empty non recursive and non informative
670 (itl_len = 1 && cl_len = 1 &&
671 is_non_informative [name,C.Decl ty] leftno
672 (let _,_,x = List.nth cl 0 in x)))
674 raise (TypeCheckerFailure (lazy
675 ("Sort elimination not allowed")));
682 typeof_aux context term
684 and check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl =
685 (* let's check if the arity of the inductive types are well formed *)
686 List.iter (fun (_,_,x,_) -> ignore (typeof ~subst ~metasenv [] x)) tyl;
687 (* let's check if the types of the inductive constructors are well formed. *)
688 let len = List.length tyl in
689 let tys = List.rev (List.map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl) in
695 let debruijnedte = debruijn uri len [] te in
696 ignore (typeof ~subst ~metasenv tys debruijnedte);
697 (* let's check also the positivity conditions *)
700 (are_all_occurrences_positive ~subst tys uri leftno i 0 len
705 (lazy ("Non positive occurence in "^NUri.string_of_uri uri))))
710 and eat_lambdas ~subst ~metasenv context n te =
711 match (n, R.whd ~subst context te) with
712 | (0, _) -> (te, context)
713 | (n, C.Lambda (name,so,ta)) when n > 0 ->
714 eat_lambdas ~subst ~metasenv ((name,(C.Decl so))::context) (n - 1) ta
716 raise (AssertFailure (lazy (Printf.sprintf "eat_lambdas (%d, %s)" n
717 (PP.ppterm ~subst ~metasenv ~context te))))
719 and eat_or_subst_lambdas ~subst ~metasenv n te to_be_subst args
720 (context, recfuns, x as k)
722 match n, R.whd ~subst context te, to_be_subst, args with
723 | (n, C.Lambda (name,so,ta),true::to_be_subst,arg::args) when n > 0 ->
724 eat_or_subst_lambdas ~subst ~metasenv (n - 1) (S.subst arg ta)
726 | (n, C.Lambda (name,so,ta),false::to_be_subst,arg::args) when n > 0 ->
727 eat_or_subst_lambdas ~subst ~metasenv (n - 1) ta to_be_subst args
728 (shift_k (name,(C.Decl so)) k)
729 | (_, te, _, _) -> te, k
731 and guarded_by_destructors r_uri r_len ~subst ~metasenv context recfuns t =
732 let recursor f k t = U.fold shift_k k (fun k () -> f k) () t in
733 let rec aux (context, recfuns, x as k) t =
735 prerr_endline ("GB:\n" ^
736 PP.ppcontext ~subst ~metasenv context^
737 PP.ppterm ~metasenv ~subst ~context t^
738 string_of_recfuns ~subst ~metasenv ~context recfuns);
742 | C.Rel m as t when is_dangerous m recfuns ->
743 raise (NotGuarded (lazy
744 (PP.ppterm ~subst ~metasenv ~context t ^
745 " is a partial application of a fix")))
746 | C.Appl ((C.Rel m)::tl) as t when is_dangerous m recfuns ->
747 let rec_no = get_recno m recfuns in
748 if not (List.length tl > rec_no) then
749 raise (NotGuarded (lazy
750 (PP.ppterm ~context ~subst ~metasenv t ^
751 " is a partial application of a fix")))
753 let rec_arg = List.nth tl rec_no in
754 if not (is_really_smaller r_uri r_len ~subst ~metasenv k rec_arg) then
755 raise (NotGuarded (lazy (Printf.sprintf ("Recursive call %s, %s is not"
756 ^^ " smaller.\ncontext:\n%s") (PP.ppterm ~context ~subst ~metasenv
757 t) (PP.ppterm ~context ~subst ~metasenv rec_arg)
758 (PP.ppcontext ~subst ~metasenv context))));
760 | C.Appl ((C.Rel m)::tl) when is_unfolded m recfuns ->
761 let fixed_args = get_fixed_args m recfuns in
762 list_iter_default2 (fun x b -> if not b then aux k x) tl false fixed_args
764 (match List.nth context (m-1) with
766 | _,C.Def (bo,_) -> aux k (S.lift m bo))
768 | C.Appl (C.Const ((Ref.Ref (_,uri,Ref.Fix (i,recno))) as r)::args) ->
769 if List.exists (fun t -> try aux k t;false with NotGuarded _ -> true) args
771 let fl,_,_ = E.get_checked_fixes_or_cofixes r in
773 List.split (List.map (fun (_,name,_,ty,bo) -> (name, C.Decl ty), bo) fl)
775 let fl_len = List.length fl in
776 let bos = List.map (debruijn uri fl_len context) bos in
777 let j = List.fold_left min max_int (List.map (fun (_,_,i,_,_)->i) fl) in
778 let ctx_len = List.length context in
779 (* we may look for fixed params not only up to j ... *)
780 let fa = fixed_args bos j ctx_len (ctx_len + fl_len) in
781 list_iter_default2 (fun x b -> if not b then aux k x) args false fa;
782 let context = context@ctx_tys in
783 let ctx_len = List.length context in
785 HExtlib.list_mapi (fun _ i -> ctx_len - i, UnfFix fa) ctx_tys
787 let new_k = context, extra_recfuns@recfuns, x in
792 eat_or_subst_lambdas ~subst ~metasenv j bo fa args new_k
796 List.length args > recno &&
797 (*case where the recursive argument is already really_smaller *)
798 is_really_smaller r_uri r_len ~subst ~metasenv k
799 (List.nth args recno)
801 let bo,(context, _, _ as new_k) = bo_and_k in
803 eat_lambdas ~subst ~metasenv context (recno + 1 - j) bo in
804 let new_context_part,_ =
805 HExtlib.split_nth (List.length context' - List.length context)
807 let k = List.fold_right shift_k new_context_part new_k in
808 let context, recfuns, x = k in
809 let k = context, (1,Safe)::recfuns, x in
815 List.iter (fun (bo,k) -> aux k bo) bos_and_ks
816 | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) as t ->
817 (match R.whd ~subst context term with
818 | C.Rel m | C.Appl (C.Rel m :: _ ) as t when is_safe m recfuns || m = x ->
819 (* TODO: add CoInd to references so that this call is useless *)
820 let isinductive, _, _, _, _ = E.get_checked_indtys ref in
821 if not isinductive then recursor aux k t
823 let ty = typeof ~subst ~metasenv context term in
824 let dc_ctx, dcl, start, stop =
825 specialize_and_abstract_constrs ~subst r_uri r_len context ty in
826 let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
828 List.iter (aux k) args;
831 let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
832 let p, k = get_new_safes ~subst k p rl in
835 | _ -> recursor aux k t)
836 | t -> recursor aux k t
838 NotGuarded _ as exc ->
839 let t' = R.whd ~delta:0 ~subst context t in
840 if t = t' then raise exc
843 try aux (context, recfuns, 1) t
844 with NotGuarded s -> raise (TypeCheckerFailure s)
846 and guarded_by_constructors ~subst ~metasenv context t indURI indlen nn =
847 let rec aux context n nn h te =
848 match R.whd ~subst context te with
849 | C.Rel m when m > n && m <= nn -> h
850 | C.Rel _ | C.Meta _ -> true
854 | C.Const (Ref.Ref (_,_,Ref.Ind _))
855 | C.LetIn _ -> raise (AssertFailure (lazy "17"))
856 | C.Lambda (name,so,de) ->
857 does_not_occur ~subst context n nn so &&
858 aux ((name,C.Decl so)::context) (n + 1) (nn + 1) h de
859 | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
860 h && List.for_all (does_not_occur ~subst context n nn) tl
861 | C.Const (Ref.Ref (_,_,Ref.Con _)) -> true
862 | C.Appl (C.Const (Ref.Ref (_,uri, Ref.Con (_,j)) as ref) :: tl) as t ->
863 let _, paramsno, _, _, _ = E.get_checked_indtys ref in
864 let ty_t = typeof ~subst ~metasenv context t in
865 let dc_ctx, dcl, start, stop =
866 specialize_and_abstract_constrs ~subst indURI indlen context ty_t in
867 let _, dc = List.nth dcl (j-1) in
869 prerr_endline (PP.ppterm ~subst ~metasenv ~context:dc_ctx dc);
870 prerr_endline (PP.ppcontext ~subst ~metasenv dc_ctx);
872 let rec_params = recursive_args ~subst ~metasenv dc_ctx start stop dc in
873 let rec analyse_instantiated_type rec_spec args =
874 match rec_spec, args with
875 | h::rec_spec, he::args ->
876 aux context n nn h he && analyse_instantiated_type rec_spec args
878 | _ -> raise (AssertFailure (lazy
879 ("Too many args for constructor: " ^ String.concat " "
880 (List.map (fun x-> PP.ppterm ~subst ~metasenv ~context x) args))))
882 let left, args = HExtlib.split_nth paramsno tl in
883 List.for_all (does_not_occur ~subst context n nn) left &&
884 analyse_instantiated_type rec_params args
885 | C.Appl ((C.Match (_,out,te,pl))::_)
886 | C.Match (_,out,te,pl) as t ->
887 let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
888 List.for_all (does_not_occur ~subst context n nn) tl &&
889 does_not_occur ~subst context n nn out &&
890 does_not_occur ~subst context n nn te &&
891 List.for_all (aux context n nn h) pl
892 | C.Const (Ref.Ref (_,u,(Ref.Fix _| Ref.CoFix _)) as ref)
893 | C.Appl(C.Const (Ref.Ref(_,u,(Ref.Fix _| Ref.CoFix _)) as ref) :: _) as t ->
894 let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
895 let fl,_,_ = E.get_checked_fixes_or_cofixes ref in
896 let len = List.length fl in
897 let tys = List.map (fun (_,n,_,ty,_) -> n, C.Decl ty) fl in
898 List.for_all (does_not_occur ~subst context n nn) tl &&
901 aux (context@tys) n nn h (debruijn u len context bo))
904 | C.Appl _ as t -> does_not_occur ~subst context n nn t
906 aux context 0 nn false t
908 and recursive_args ~subst ~metasenv context n nn te =
909 match R.whd context te with
910 | C.Rel _ | C.Appl _ | C.Const _ -> []
911 | C.Prod (name,so,de) ->
912 (not (does_not_occur ~subst context n nn so)) ::
913 (recursive_args ~subst ~metasenv
914 ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
916 raise (AssertFailure (lazy ("recursive_args:" ^ PP.ppterm ~subst
917 ~metasenv ~context:[] t)))
919 and get_new_safes ~subst (context, recfuns, x as k) p rl =
920 match R.whd ~subst context p, rl with
921 | C.Lambda (name,so,ta), b::tl ->
922 let recfuns = (if b then [0,Safe] else []) @ recfuns in
924 (shift_k (name,(C.Decl so)) (context, recfuns, x)) ta tl
925 | C.Meta _ as e, _ | e, [] -> e, k
926 | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
928 and is_really_smaller
929 r_uri r_len ~subst ~metasenv (context, recfuns, x as k) te
931 match R.whd ~subst context te with
932 | C.Rel m when is_safe m recfuns -> true
933 | C.Lambda (name, s, t) ->
934 is_really_smaller r_uri r_len ~subst ~metasenv (shift_k (name,C.Decl s) k) t
936 is_really_smaller r_uri r_len ~subst ~metasenv k he
938 | C.Const (Ref.Ref (_,_,Ref.Con _)) -> false
940 | C.Const (Ref.Ref (_,_,Ref.Fix _)) -> assert false
942 | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) ->
944 | C.Rel m | C.Appl (C.Rel m :: _ ) when is_safe m recfuns || m = x ->
945 (* TODO: add CoInd to references so that this call is useless *)
946 let isinductive, _, _, _, _ = E.get_checked_indtys ref in
947 if not isinductive then
948 List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl
950 let ty = typeof ~subst ~metasenv context term in
951 let dc_ctx, dcl, start, stop =
952 specialize_and_abstract_constrs ~subst r_uri r_len context ty in
955 let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
956 let e, k = get_new_safes ~subst k p rl in
957 is_really_smaller r_uri r_len ~subst ~metasenv k e)
959 | _ -> List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl)
962 and returns_a_coinductive ~subst context ty =
963 match R.whd ~subst context ty with
964 | C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)
965 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)::_) ->
966 let isinductive, _, itl, _, _ = E.get_checked_indtys ref in
967 if isinductive then None else (Some (uri,List.length itl))
968 | C.Prod (n,so,de) ->
969 returns_a_coinductive ~subst ((n,C.Decl so)::context) de
972 and type_of_constant ((Ref.Ref (_,uri,_)) as ref) =
974 match E.get_obj uri with
977 !logger (`Start_type_checking uri);
978 check_obj_well_typed uobj;
980 !logger (`Type_checking_completed uri);
984 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Ind i) ->
985 let _,_,arity,_ = List.nth tl i in arity
986 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Con (i,j)) ->
987 let _,_,_,cl = List.nth tl i in
988 let _,_,arity = List.nth cl (j-1) in
990 | (_,_,_,_,C.Fixpoint (_,fl,_)), Ref.Ref (_,_,(Ref.Fix (i,_)|Ref.CoFix i)) ->
991 let _,_,_,arity,_ = List.nth fl i in
993 | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,_,(Ref.Def |Ref.Decl)) -> ty
994 | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
996 and check_obj_well_typed (uri,height,metasenv,subst,kind) =
997 (* CSC: here we should typecheck the metasenv and the subst *)
998 assert (metasenv = [] && subst = []);
1000 | C.Constant (_,_,Some te,ty,_) ->
1001 let _ = typeof ~subst ~metasenv [] ty in
1002 let ty_te = typeof ~subst ~metasenv [] te in
1003 if not (R.are_convertible ~subst ~metasenv [] ty_te ty) then
1004 raise (TypeCheckerFailure (lazy (Printf.sprintf (
1005 "the type of the body is not convertible with the declared one.\n"^^
1006 "inferred type:\n%s\nexpected type:\n%s")
1007 (PP.ppterm ~subst ~metasenv ~context:[] ty_te)
1008 (PP.ppterm ~subst ~metasenv ~context:[] ty))))
1009 | C.Constant (_,_,None,ty,_) -> ignore (typeof ~subst ~metasenv [] ty)
1010 | C.Inductive (is_ind, leftno, tyl, _) ->
1011 check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl
1012 | C.Fixpoint (inductive,fl,_) ->
1015 (fun (types,kl) (_,name,k,ty,_) ->
1016 let _ = typeof ~subst ~metasenv [] ty in
1017 ((name,C.Decl ty)::types, k::kl)
1020 let len = List.length types in
1022 List.split (List.map2
1023 (fun (_,_,_,_,bo) rno ->
1024 let dbo = debruijn uri len [] bo in
1028 List.iter2 (fun (_,name,x,ty,_) bo ->
1029 let ty_bo = typeof ~subst ~metasenv types bo in
1030 if not (R.are_convertible ~subst ~metasenv types ty_bo ty)
1031 then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1033 if inductive then begin
1034 let m, context = eat_lambdas ~subst ~metasenv types (x + 1) bo in
1037 match List.hd context with _,C.Decl t -> t | _ -> assert false
1039 match R.whd ~subst (List.tl context) he with
1040 | C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)
1041 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref) :: _) ->
1042 let _,_,itl,_,_ = E.get_checked_indtys ref in
1043 uri, List.length itl
1046 (* guarded by destructors conditions D{f,k,x,M} *)
1047 let rec enum_from k =
1048 function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl
1050 guarded_by_destructors r_uri r_len
1051 ~subst ~metasenv context (enum_from (x+2) kl) m
1053 match returns_a_coinductive ~subst [] ty with
1055 raise (TypeCheckerFailure
1056 (lazy "CoFix: does not return a coinductive type"))
1057 | Some (r_uri, r_len) ->
1058 (* guarded by constructors conditions C{f,M} *)
1060 (guarded_by_constructors ~subst ~metasenv types bo r_uri r_len len)
1062 raise (TypeCheckerFailure
1063 (lazy "CoFix: not guarded by constructors"))
1066 let typecheck_obj = check_obj_well_typed;;