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 (* specialized only constructors, arities are left untouched *)
200 let specialize_inductive_type_constrs ~subst context ty_term =
201 match R.whd ~subst context ty_term with
202 | C.Const (Ref.Ref (_,uri,Ref.Ind i) as ref)
203 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind i) as ref) :: _ ) as ty ->
204 let args = match ty with C.Appl (_::tl) -> tl | _ -> [] in
205 let is_ind, leftno, itl, attrs, i = E.get_checked_indtys ref in
206 let left_args,_ = HExtlib.split_nth leftno args in
208 List.map (fun (rel, name, arity, cl) ->
210 List.map (fun (rel, name, ty) ->
211 rel, name, instantiate_parameters left_args ty)
215 is_ind, leftno, itl, attrs, i
219 let fix_lefts_in_constrs ~subst r_uri r_len context ty_term =
220 assert false; (* BUG, ask enrico *)
221 let _,_,itl,_,i = specialize_inductive_type_constrs ~subst context ty_term in
222 let _,_,_,cl = List.nth itl i in
224 List.map (fun (_,id,ty) -> id, debruijn r_uri r_len context ty) cl
226 (* since arities are closed they are not lifted *)
227 List.map (fun (_,name,arity,_) -> name, C.Decl arity) itl, cl
230 exception DoesOccur;;
232 let does_not_occur ~subst context n nn t =
233 let rec aux (context,n,nn as k) _ = function
234 | C.Rel m when m > n && m <= nn -> raise DoesOccur
236 (try (match List.nth context (m-1) with
237 | _,C.Def (bo,_) -> aux k () (S.lift m bo)
239 with Failure _ -> assert false)
240 | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> (* closed meta *) ()
241 | C.Meta (mno,(s,l)) ->
243 let _,_,term,_ = U.lookup_subst mno subst in
244 aux (context,n+s,nn+s) () (S.subst_meta (0,l) term)
245 with CicUtil.Subst_not_found _ -> match l with
246 | C.Irl len -> if not (n >= s+len || s > nn) then raise DoesOccur
247 | C.Ctx lc -> List.iter (aux (context,n+s,nn+s) ()) lc)
248 | t -> U.fold (fun e (ctx,n,nn) -> (e::ctx,n+1,nn+1)) k aux () t
250 try aux (context,n,nn) () t; true
251 with DoesOccur -> false
254 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
255 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
256 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla *)
257 (*CSC strictly_positive *)
258 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-) *)
259 let rec weakly_positive ~subst context n nn uri te =
260 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
261 let dummy = C.Sort (C.Type ~-1) in
262 (*CSC: mettere in cicSubstitution *)
263 let rec subst_inductive_type_with_dummy _ = function
264 | C.Const (Ref.Ref (_,uri',Ref.Ind 0)) when NUri.eq uri' uri -> dummy
265 | C.Appl ((C.Const (Ref.Ref (_,uri',Ref.Ind 0)))::tl)
266 when NUri.eq uri' uri -> dummy
267 | t -> U.map (fun _ x->x) () subst_inductive_type_with_dummy t
269 match R.whd context te with
270 | C.Const (Ref.Ref (_,uri',Ref.Ind _))
271 | C.Appl ((C.Const (Ref.Ref (_,uri',Ref.Ind _)))::_)
272 when NUri.eq uri' uri -> true
273 | C.Prod (name,source,dest) when
274 does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
275 (* dummy abstraction, so we behave as in the anonimous case *)
276 strictly_positive ~subst context n nn
277 (subst_inductive_type_with_dummy () source) &&
278 weakly_positive ~subst ((name,C.Decl source)::context)
279 (n + 1) (nn + 1) uri dest
280 | C.Prod (name,source,dest) ->
281 does_not_occur ~subst context n nn
282 (subst_inductive_type_with_dummy () source)&&
283 weakly_positive ~subst ((name,C.Decl source)::context)
284 (n + 1) (nn + 1) uri dest
286 raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
288 and strictly_positive ~subst context n nn te =
289 match R.whd context te with
290 | t when does_not_occur ~subst context n nn t -> true
292 | C.Prod (name,so,ta) ->
293 does_not_occur ~subst context n nn so &&
294 strictly_positive ~subst ((name,C.Decl so)::context) (n+1) (nn+1) ta
295 | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
296 List.for_all (does_not_occur ~subst context n nn) tl
297 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind i) as r)::tl) ->
298 let _,paramsno,tyl,_,i = E.get_checked_indtys r in
299 let _,name,ity,cl = List.nth tyl i in
300 let ok = List.length tyl = 1 in
301 let params, arguments = HExtlib.split_nth paramsno tl in
302 let lifted_params = List.map (S.lift 1) params in
304 List.map (fun (_,_,te) -> instantiate_parameters lifted_params te) cl
307 List.for_all (does_not_occur ~subst context n nn) arguments &&
309 (weakly_positive ~subst ((name,C.Decl ity)::context) (n+1) (nn+1) uri) cl
312 (* the inductive type indexes are s.t. n < x <= nn *)
313 and are_all_occurrences_positive ~subst context uri indparamsno i n nn te =
314 match R.whd context te with
315 | C.Appl ((C.Rel m)::tl) as reduct when m = i ->
321 match R.whd context x with
322 | C.Rel m when m = n - (indparamsno - k) -> k - 1
323 | y -> raise (TypeCheckerFailure (lazy
324 ("Argument "^string_of_int (indparamsno - k + 1) ^ " (of " ^
325 string_of_int indparamsno ^ " fixed) is not homogeneous in "^
326 "appl:\n"^ PP.ppterm ~context ~subst ~metasenv:[] reduct))))
330 List.for_all (does_not_occur ~subst context n nn) tl
332 raise (TypeCheckerFailure
333 (lazy ("Non-positive occurence in mutual inductive definition(s) [2]"^
334 NUri.string_of_uri uri)))
335 | C.Rel m when m = i ->
336 if indparamsno = 0 then
339 raise (TypeCheckerFailure
340 (lazy ("Non-positive occurence in mutual inductive definition(s) [3]"^
341 NUri.string_of_uri uri)))
342 | C.Prod (name,source,dest) when
343 does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
344 strictly_positive ~subst context n nn source &&
345 are_all_occurrences_positive ~subst
346 ((name,C.Decl source)::context) uri indparamsno
347 (i+1) (n + 1) (nn + 1) dest
348 | C.Prod (name,source,dest) ->
349 if not (does_not_occur ~subst context n nn source) then
350 raise (TypeCheckerFailure (lazy ("Non-positive occurrence in "^
351 PP.ppterm ~context ~metasenv:[] ~subst te)));
352 are_all_occurrences_positive ~subst ((name,C.Decl source)::context)
353 uri indparamsno (i+1) (n + 1) (nn + 1) dest
356 (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
357 (NUri.string_of_uri uri))))
360 exception NotGuarded of string Lazy.t;;
362 let rec typeof ~subst ~metasenv context term =
363 let rec typeof_aux context =
364 fun t -> (*prerr_endline (PP.ppterm ~metasenv ~subst ~context t);*)
368 match List.nth context (n - 1) with
369 | (_,C.Decl ty) -> S.lift n ty
370 | (_,C.Def (_,ty)) -> S.lift n ty
371 with Failure _ -> raise (TypeCheckerFailure (lazy "unbound variable")))
372 | C.Sort (C.Type i) -> C.Sort (C.Type (i+1))
373 | C.Sort s -> C.Sort (C.Type 0)
374 | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
375 | C.Meta (n,l) as t ->
376 let canonical_ctx,ty =
378 let _,c,_,ty = U.lookup_subst n subst in c,ty
379 with U.Subst_not_found _ -> try
380 let _,_,c,ty = U.lookup_meta n metasenv in c,ty
381 with U.Meta_not_found _ ->
382 raise (AssertFailure (lazy (Printf.sprintf
383 "%s not found" (PP.ppterm ~subst ~metasenv ~context t))))
385 check_metasenv_consistency t ~subst ~metasenv context canonical_ctx l;
387 | C.Const ref -> type_of_constant ref
388 | C.Prod (name,s,t) ->
389 let sort1 = typeof_aux context s in
390 let sort2 = typeof_aux ((name,(C.Decl s))::context) t in
391 sort_of_prod ~metasenv ~subst context (name,s) (sort1,sort2)
392 | C.Lambda (n,s,t) ->
393 let sort = typeof_aux context s in
394 (match R.whd ~subst context sort with
395 | C.Meta _ | C.Sort _ -> ()
398 (TypeCheckerFailure (lazy (Printf.sprintf
399 ("Not well-typed lambda-abstraction: " ^^
400 "the source %s should be a type; instead it is a term " ^^
401 "of type %s") (PP.ppterm ~subst ~metasenv ~context s)
402 (PP.ppterm ~subst ~metasenv ~context sort)))));
403 let ty = typeof_aux ((n,(C.Decl s))::context) t in
405 | C.LetIn (n,ty,t,bo) ->
406 let ty_t = typeof_aux context t in
407 let _ = typeof_aux context ty in
408 if not (R.are_convertible ~subst ~metasenv context ty ty_t) then
411 (lazy (Printf.sprintf
412 "The type of %s is %s but it is expected to be %s"
413 (PP.ppterm ~subst ~metasenv ~context t)
414 (PP.ppterm ~subst ~metasenv ~context ty_t)
415 (PP.ppterm ~subst ~metasenv ~context ty))))
417 let ty_bo = typeof_aux ((n,C.Def (t,ty))::context) bo in
418 S.subst ~avoid_beta_redexes:true t ty_bo
419 | C.Appl (he::(_::_ as args)) ->
420 let ty_he = typeof_aux context he in
421 let args_with_ty = List.map (fun t -> t, typeof_aux context t) args in
423 prerr_endline ("HEAD: " ^ PP.ppterm ~subst ~metasenv ~context ty_he);
424 prerr_endline ("TARGS: " ^ String.concat " | " (List.map (PP.ppterm
425 ~subst ~metasenv ~context) (List.map snd args_with_ty)));
426 prerr_endline ("ARGS: " ^ String.concat " | " (List.map (PP.ppterm
427 ~subst ~metasenv ~context) (List.map fst args_with_ty)));
429 eat_prods ~subst ~metasenv context he ty_he args_with_ty
430 | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
431 | C.Match (Ref.Ref (_,_,Ref.Ind tyno) as r,outtype,term,pl) ->
432 let outsort = typeof_aux context outtype in
433 let inductive,leftno,itl,_,_ = E.get_checked_indtys r in
435 let _,_,_,cl = List.nth itl tyno in List.length cl
437 let parameters, arguments =
438 let ty = R.whd ~subst context (typeof_aux context term) in
441 C.Const (Ref.Ref (_,_,Ref.Ind _) as r') -> r',[]
442 | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _) as r') :: tl) -> r',tl
445 (TypeCheckerFailure (lazy (Printf.sprintf
446 "Case analysis: analysed term %s is not an inductive one"
447 (PP.ppterm ~subst ~metasenv ~context term)))) in
448 if not (Ref.eq r r') then
450 (TypeCheckerFailure (lazy (Printf.sprintf
451 ("Case analysys: analysed term type is %s, but is expected " ^^
452 "to be (an application of) %s")
453 (PP.ppterm ~subst ~metasenv ~context ty)
454 (PP.ppterm ~subst ~metasenv ~context (C.Const r')))))
456 try HExtlib.split_nth leftno tl
459 raise (TypeCheckerFailure (lazy (Printf.sprintf
460 "%s is partially applied"
461 (PP.ppterm ~subst ~metasenv ~context ty)))) in
462 (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
463 let sort_of_ind_type =
464 if parameters = [] then C.Const r
465 else C.Appl ((C.Const r)::parameters) in
466 let type_of_sort_of_ind_ty = typeof_aux context sort_of_ind_type in
467 check_allowed_sort_elimination ~subst ~metasenv r context
468 sort_of_ind_type type_of_sort_of_ind_ty outsort;
469 (* let's check if the type of branches are right *)
470 if List.length pl <> constructorsno then
471 raise (TypeCheckerFailure (lazy ("Wrong number of cases in a match")));
472 let j,branches_ok,p_ty, exp_p_ty =
474 (fun (j,b,old_p_ty,old_exp_p_ty) p ->
477 let cons = Ref.mk_constructor j r in
478 if parameters = [] then C.Const cons
479 else C.Appl (C.Const cons::parameters)
481 let ty_p = typeof_aux context p in
482 let ty_cons = typeof_aux context cons in
484 type_of_branch ~subst context leftno outtype cons ty_cons 0
486 j+1, R.are_convertible ~subst ~metasenv context ty_p ty_branch,
489 j,false,old_p_ty,old_exp_p_ty
490 ) (1,true,C.Sort C.Prop,C.Sort C.Prop) pl
492 if not branches_ok then
495 (lazy (Printf.sprintf ("Branch for constructor %s :=\n%s\n"^^
496 "has type %s\nnot convertible with %s")
497 (PP.ppterm ~subst ~metasenv ~context
498 (C.Const (Ref.mk_constructor (j-1) r)))
499 (PP.ppterm ~metasenv ~subst ~context (List.nth pl (j-2)))
500 (PP.ppterm ~metasenv ~subst ~context p_ty)
501 (PP.ppterm ~metasenv ~subst ~context exp_p_ty))));
502 let res = outtype::arguments@[term] in
503 R.head_beta_reduce (C.Appl res)
504 | C.Match _ -> assert false
506 and type_of_branch ~subst context leftno outty cons tycons liftno =
507 match R.whd ~subst context tycons with
508 | C.Const (Ref.Ref (_,_,Ref.Ind _)) -> C.Appl [S.lift liftno outty ; cons]
509 | C.Appl (C.Const (Ref.Ref (_,_,Ref.Ind _))::tl) ->
510 let _,arguments = HExtlib.split_nth leftno tl in
511 C.Appl (S.lift liftno outty::arguments@[cons])
512 | C.Prod (name,so,de) ->
514 match S.lift 1 cons with
515 | C.Appl l -> C.Appl (l@[C.Rel 1])
516 | t -> C.Appl [t ; C.Rel 1]
519 type_of_branch ~subst ((name,(C.Decl so))::context)
520 leftno outty cons de (liftno+1))
521 | _ -> raise (AssertFailure (lazy "type_of_branch"))
523 (* check_metasenv_consistency checks that the "canonical" context of a
524 metavariable is consitent - up to relocation via the relocation list l -
525 with the actual context *)
526 and check_metasenv_consistency
527 ~subst ~metasenv term context canonical_context l
531 let context = snd (HExtlib.split_nth shift context) in
532 let rec compare = function
536 raise (AssertFailure (lazy (Printf.sprintf
537 "Local and canonical context %s have different lengths"
538 (PP.ppterm ~subst ~context ~metasenv term))))
540 raise (TypeCheckerFailure (lazy (Printf.sprintf
541 "Unbound variable -%d in %s" m
542 (PP.ppterm ~subst ~metasenv ~context term))))
545 (_,C.Decl t1), (_,C.Decl t2)
546 | (_,C.Def (t1,_)), (_,C.Def (t2,_))
547 | (_,C.Def (_,t1)), (_,C.Decl t2) ->
548 if not (R.are_convertible ~subst ~metasenv tl t1 t2) then
551 (lazy (Printf.sprintf
552 ("Not well typed metavariable local context for %s: " ^^
553 "%s expected, which is not convertible with %s")
554 (PP.ppterm ~subst ~metasenv ~context term)
555 (PP.ppterm ~subst ~metasenv ~context t2)
556 (PP.ppterm ~subst ~metasenv ~context t1))))
559 (TypeCheckerFailure (lazy (Printf.sprintf
560 ("Not well typed metavariable local context for %s: " ^^
561 "a definition expected, but a declaration found")
562 (PP.ppterm ~subst ~metasenv ~context term)))));
563 compare (m - 1,tl,ctl)
565 compare (n,context,canonical_context)
567 (* we avoid useless lifting by shortening the context*)
568 let l,context = (0,lc_kind), snd (HExtlib.split_nth shift context) in
569 let lifted_canonical_context =
570 let rec lift_metas i = function
572 | (n,C.Decl t)::tl ->
573 (n,C.Decl (S.subst_meta l (S.lift i t)))::(lift_metas (i+1) tl)
574 | (n,C.Def (t,ty))::tl ->
575 (n,C.Def ((S.subst_meta l (S.lift i t)),
576 S.subst_meta l (S.lift i ty)))::(lift_metas (i+1) tl)
578 lift_metas 1 canonical_context in
579 let l = U.expand_local_context lc_kind in
584 | t, (_,C.Def (ct,_)) ->
585 (*CSC: the following optimization is to avoid a possibly expensive
586 reduction that can be easily avoided and that is quite
587 frequent. However, this is better handled using levels to
593 match List.nth context (n - 1) with
594 | (_,C.Def (te,_)) -> S.lift n te
599 if not (R.are_convertible ~subst ~metasenv context optimized_t ct)
603 (lazy (Printf.sprintf
604 ("Not well typed metavariable local context: " ^^
605 "expected a term convertible with %s, found %s")
606 (PP.ppterm ~subst ~metasenv ~context ct)
607 (PP.ppterm ~subst ~metasenv ~context t))))
608 | t, (_,C.Decl ct) ->
609 let type_t = typeof_aux context t in
610 if not (R.are_convertible ~subst ~metasenv context type_t ct) then
611 raise (TypeCheckerFailure
612 (lazy (Printf.sprintf
613 ("Not well typed metavariable local context: "^^
614 "expected a term of type %s, found %s of type %s")
615 (PP.ppterm ~subst ~metasenv ~context ct)
616 (PP.ppterm ~subst ~metasenv ~context t)
617 (PP.ppterm ~subst ~metasenv ~context type_t))))
618 ) l lifted_canonical_context
620 Invalid_argument _ ->
621 raise (AssertFailure (lazy (Printf.sprintf
622 "Local and canonical context %s have different lengths"
623 (PP.ppterm ~subst ~metasenv ~context term))))
625 and is_non_informative context paramsno c =
626 let rec aux context c =
627 match R.whd context c with
628 | C.Prod (n,so,de) ->
629 let s = typeof_aux context so in
630 s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
632 let context',dx = split_prods ~subst:[] context paramsno c in
635 and check_allowed_sort_elimination ~subst ~metasenv r =
638 | C.Appl l -> C.Appl (l @ [arg])
639 | t -> C.Appl [t;arg] in
640 let rec aux context ind arity1 arity2 =
641 let arity1 = R.whd ~subst context arity1 in
642 let arity2 = R.whd ~subst context arity2 in
643 match arity1,arity2 with
644 | C.Prod (name,so1,de1), C.Prod (_,so2,de2) ->
645 if not (R.are_convertible ~subst ~metasenv context so1 so2) then
646 raise (TypeCheckerFailure (lazy (Printf.sprintf
647 "In outtype: expected %s, found %s"
648 (PP.ppterm ~subst ~metasenv ~context so1)
649 (PP.ppterm ~subst ~metasenv ~context so2)
651 aux ((name, C.Decl so1)::context)
652 (mkapp (S.lift 1 ind) (C.Rel 1)) de1 de2
653 | C.Sort _, C.Prod (name,so,ta) ->
654 if not (R.are_convertible ~subst ~metasenv context so ind) then
655 raise (TypeCheckerFailure (lazy (Printf.sprintf
656 "In outtype: expected %s, found %s"
657 (PP.ppterm ~subst ~metasenv ~context ind)
658 (PP.ppterm ~subst ~metasenv ~context so)
660 (match arity1,ta with
661 | (C.Sort (C.CProp | C.Type _), C.Sort _)
662 | (C.Sort C.Prop, C.Sort C.Prop) -> ()
663 | (C.Sort C.Prop, C.Sort (C.CProp | C.Type _)) ->
664 (* TODO: we should pass all these parameters since we
665 * have them already *)
666 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
667 let itl_len = List.length itl in
668 let _,name,ty,cl = List.nth itl i in
669 let cl_len = List.length cl in
670 (* is it a singleton or empty non recursive and non informative
674 (itl_len = 1 && cl_len = 1 &&
675 is_non_informative [name,C.Decl ty] leftno
676 (let _,_,x = List.nth cl 0 in x)))
678 raise (TypeCheckerFailure (lazy
679 ("Sort elimination not allowed")));
686 typeof_aux context term
688 and check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl =
689 (* let's check if the arity of the inductive types are well formed *)
690 List.iter (fun (_,_,x,_) -> ignore (typeof ~subst ~metasenv [] x)) tyl;
691 (* let's check if the types of the inductive constructors are well formed. *)
692 let len = List.length tyl in
693 let tys = List.rev (List.map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl) in
699 let debruijnedte = debruijn uri len [] te in
700 ignore (typeof ~subst ~metasenv tys debruijnedte);
701 (* let's check also the positivity conditions *)
704 (are_all_occurrences_positive ~subst tys uri leftno i 0 len
709 (lazy ("Non positive occurence in "^NUri.string_of_uri uri))))
714 and eat_lambdas ~subst ~metasenv context n te =
715 match (n, R.whd ~subst context te) with
716 | (0, _) -> (te, context)
717 | (n, C.Lambda (name,so,ta)) when n > 0 ->
718 eat_lambdas ~subst ~metasenv ((name,(C.Decl so))::context) (n - 1) ta
720 raise (AssertFailure (lazy (Printf.sprintf "eat_lambdas (%d, %s)" n
721 (PP.ppterm ~subst ~metasenv ~context te))))
723 and eat_or_subst_lambdas ~subst ~metasenv n te to_be_subst args
724 (context, recfuns, x as k)
726 match n, R.whd ~subst context te, to_be_subst, args with
727 | (n, C.Lambda (name,so,ta),true::to_be_subst,arg::args) when n > 0 ->
728 eat_or_subst_lambdas ~subst ~metasenv (n - 1) (S.subst arg ta)
730 | (n, C.Lambda (name,so,ta),false::to_be_subst,arg::args) when n > 0 ->
731 eat_or_subst_lambdas ~subst ~metasenv (n - 1) ta to_be_subst args
732 (shift_k (name,(C.Decl so)) k)
733 | (_, te, _, _) -> te, k
735 and guarded_by_destructors r_uri r_len ~subst ~metasenv context recfuns t =
736 let recursor f k t = U.fold shift_k k (fun k () -> f k) () t in
737 let rec aux (context, recfuns, x as k) t =
738 let t = R.whd ~delta:max_int ~subst context t in
740 prerr_endline ("GB:\n" ^
741 PP.ppcontext ~subst ~metasenv context^
742 PP.ppterm ~metasenv ~subst ~context t^
743 string_of_recfuns ~subst ~metasenv ~context recfuns);
747 | C.Rel m as t when is_dangerous m recfuns ->
748 raise (NotGuarded (lazy
749 (PP.ppterm ~subst ~metasenv ~context t ^
750 " is a partial application of a fix")))
751 | C.Appl ((C.Rel m)::tl) as t when is_dangerous m recfuns ->
752 let rec_no = get_recno m recfuns in
753 if not (List.length tl > rec_no) then
754 raise (NotGuarded (lazy
755 (PP.ppterm ~context ~subst ~metasenv t ^
756 " is a partial application of a fix")))
758 let rec_arg = List.nth tl rec_no in
759 if not (is_really_smaller r_uri r_len ~subst ~metasenv k rec_arg) then
760 raise (NotGuarded (lazy (Printf.sprintf ("Recursive call %s, %s is not"
761 ^^ " smaller.\ncontext:\n%s") (PP.ppterm ~context ~subst ~metasenv
762 t) (PP.ppterm ~context ~subst ~metasenv rec_arg)
763 (PP.ppcontext ~subst ~metasenv context))));
765 | C.Appl ((C.Rel m)::tl) when is_unfolded m recfuns ->
766 let fixed_args = get_fixed_args m recfuns in
767 list_iter_default2 (fun x b -> if not b then aux k x) tl false fixed_args
769 (match List.nth context (m-1) with
771 | _,C.Def (bo,_) -> aux k (S.lift m bo))
773 | C.Appl (C.Const ((Ref.Ref (_,uri,Ref.Fix (i,recno))) as r)::args) ->
774 if List.exists (fun t -> try aux k t;false with NotGuarded _ -> true) args
776 let fl,_,_ = E.get_checked_fixes r in
778 List.split (List.map (fun (_,name,_,ty,bo) -> (name, C.Decl ty), bo) fl)
780 let fl_len = List.length fl in
781 let bos = List.map (debruijn uri fl_len context) bos in
782 let j = List.fold_left min max_int (List.map (fun (_,_,i,_,_)->i) fl) in
783 let ctx_len = List.length context in
784 (* we may look for fixed params not only up to j ... *)
785 let fa = fixed_args bos j ctx_len (ctx_len + fl_len) in
786 list_iter_default2 (fun x b -> if not b then aux k x) args false fa;
787 let context = context@ctx_tys in
788 let ctx_len = List.length context in
790 HExtlib.list_mapi (fun _ i -> ctx_len - i, UnfFix fa) ctx_tys
792 let new_k = context, extra_recfuns@recfuns, x in
797 eat_or_subst_lambdas ~subst ~metasenv j bo fa args new_k
801 List.length args > recno &&
802 (*case where the recursive argument is already really_smaller *)
803 is_really_smaller r_uri r_len ~subst ~metasenv k
804 (List.nth args recno)
806 let bo,(context, _, _ as new_k) = bo_and_k in
808 eat_lambdas ~subst ~metasenv context (recno + 1 - j) bo in
809 let new_context_part,_ =
810 HExtlib.split_nth (List.length context' - List.length context)
812 let k = List.fold_right shift_k new_context_part new_k in
813 let context, recfuns, x = k in
814 let k = context, (1,Safe)::recfuns, x in
820 List.iter (fun (bo,k) -> aux k bo) bos_and_ks
821 | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) as t ->
822 (match R.whd ~subst context term with
823 | C.Rel m | C.Appl (C.Rel m :: _ ) as t when is_safe m recfuns || m = x ->
824 (* TODO: add CoInd to references so that this call is useless *)
825 let isinductive, _, _, _, _ = E.get_checked_indtys ref in
826 if not isinductive then recursor aux k t
828 let ty = typeof ~subst ~metasenv context term in
829 let itl_ctx,dcl = fix_lefts_in_constrs ~subst r_uri r_len context ty in
830 let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
831 let dc_ctx = context @ itl_ctx in
832 let start, stop = List.length context, List.length context + r_len in
834 List.iter (aux k) args;
837 let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
838 let p, k = get_new_safes ~subst k p rl in
841 | _ -> recursor aux k t)
842 | t -> recursor aux k t
844 NotGuarded _ as exc ->
845 let t' = R.whd ~delta:0 ~subst context t in
846 if t = t' then raise exc
849 try aux (context, recfuns, 1) t
850 with NotGuarded s -> raise (TypeCheckerFailure s)
852 and guarded_by_constructors ~subst ~metasenv context t indURI indlen =
853 let rec aux context n nn h te =
854 match R.whd ~subst context te with
855 | C.Rel m when m > n && m <= nn -> h
856 | C.Rel _ | C.Meta _ -> true
860 | C.Const (Ref.Ref (_,_,Ref.Ind _))
861 | C.LetIn _ -> raise (AssertFailure (lazy "17"))
862 | C.Lambda (name,so,de) ->
863 does_not_occur ~subst context n nn so &&
864 aux ((name,C.Decl so)::context) (n + 1) (nn + 1) h de
865 | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
866 h && List.for_all (does_not_occur ~subst context n nn) tl
867 | C.Const (Ref.Ref (_,_,Ref.Con _)) -> true
868 | C.Appl (C.Const (Ref.Ref (_,uri, Ref.Con (i,j)) as ref) :: tl) as t ->
869 let _, paramsno, _, _, _ = E.get_checked_indtys ref in
870 let ty_t = typeof ~subst ~metasenv context t in
871 let tys, cl = fix_lefts_in_constrs ~subst indURI indlen context ty_t in
872 let len_ctx = List.length context in
873 let len_tys = List.length tys in
874 let context_c = context @ tys in
875 let _,c = List.nth cl (j-1) in
877 recursive_args ~subst ~metasenv context_c len_ctx (len_ctx+len_tys) c in
878 let rec analyse_instantiated_type rec_spec args =
879 match rec_spec, args with
880 | h::rec_spec, he::args ->
881 aux context n nn h he && analyse_instantiated_type rec_spec args
883 | _ -> raise (AssertFailure (lazy
884 ("Too many args for constructor: " ^ String.concat " "
885 (List.map (fun x-> PP.ppterm ~subst ~metasenv ~context x) args))))
887 let left, args = HExtlib.split_nth paramsno tl in
888 List.for_all (does_not_occur ~subst context n nn) left &&
889 analyse_instantiated_type rec_params args
890 | C.Appl ((C.Match (_,out,te,pl))::_)
891 | C.Match (_,out,te,pl) as t ->
892 let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
893 List.for_all (does_not_occur ~subst context n nn) tl &&
894 does_not_occur ~subst context n nn out &&
895 does_not_occur ~subst context n nn te &&
896 List.for_all (aux context n nn h) pl
897 | C.Const (Ref.Ref (_,_,(Ref.Fix _| Ref.CoFix _)) as ref)
898 | C.Appl(C.Const (Ref.Ref(_,_,(Ref.Fix _| Ref.CoFix _)) as ref) :: _) as t ->
899 let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
900 let fl,_,_ = E.get_checked_fixes ref in
901 let tys = List.map (fun (_,n,_,ty,_) -> n, C.Decl ty) fl in
902 List.for_all (does_not_occur ~subst context n nn) tl &&
904 (fun (_,_,_,ty,bo) ->
905 aux (context@tys) n nn h (debruijn indURI indlen context bo))
908 | C.Appl _ as t -> does_not_occur ~subst context n nn t
910 aux context 0 indlen false t
912 and recursive_args ~subst ~metasenv context n nn te =
913 match R.whd context te with
914 | C.Rel _ | C.Appl _ | C.Const _ -> []
915 | C.Prod (name,so,de) ->
916 (not (does_not_occur ~subst context n nn so)) ::
917 (recursive_args ~subst ~metasenv
918 ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
920 raise (AssertFailure (lazy ("recursive_args:" ^ PP.ppterm ~subst
921 ~metasenv ~context:[] t)))
923 and get_new_safes ~subst (context, recfuns, x as k) p rl =
924 match R.whd ~subst context p, rl with
925 | C.Lambda (name,so,ta), b::tl ->
926 let recfuns = (if b then [0,Safe] else []) @ recfuns in
928 (shift_k (name,(C.Decl so)) (context, recfuns, x)) ta tl
929 | C.Meta _ as e, _ | e, [] -> e, k
930 | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
932 and is_really_smaller
933 r_uri r_len ~subst ~metasenv (context, recfuns, x as k) te
935 match R.whd ~subst context te with
936 | C.Rel m when is_safe m recfuns -> true
937 | C.Lambda (name, s, t) ->
938 is_really_smaller r_uri r_len ~subst ~metasenv (shift_k (name,C.Decl s) k) t
940 is_really_smaller r_uri r_len ~subst ~metasenv k he
943 | C.Const (Ref.Ref (_,_,Ref.Con _)) -> false
944 | C.Const (Ref.Ref (_,_,Ref.Fix _)) -> assert false
946 | C.Match (Ref.Ref (_,uri,_) as ref,outtype,term,pl) ->
948 | C.Rel m | C.Appl (C.Rel m :: _ ) when is_safe m recfuns || m = x ->
949 (* TODO: add CoInd to references so that this call is useless *)
950 let isinductive, _, _, _, _ = E.get_checked_indtys ref in
951 if not isinductive then
952 List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl
954 let ty = typeof ~subst ~metasenv context term in
955 let itl_ctx,dcl= fix_lefts_in_constrs ~subst r_uri r_len context ty in
956 let start, stop = List.length context, List.length context + r_len in
957 let dc_ctx = context @ itl_ctx in
960 let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
961 let e, k = get_new_safes ~subst k p rl in
962 is_really_smaller r_uri r_len ~subst ~metasenv k e)
964 | _ -> List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl)
967 and returns_a_coinductive ~subst context ty =
968 match R.whd ~subst context ty with
969 | C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)
970 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)::_) ->
971 let isinductive, _, _, _, _ = E.get_checked_indtys ref in
972 if isinductive then None else (Some uri)
973 | C.Prod (n,so,de) ->
974 returns_a_coinductive ~subst ((n,C.Decl so)::context) de
977 and type_of_constant ((Ref.Ref (_,uri,_)) as ref) =
979 match E.get_obj uri with
982 !logger (`Start_type_checking uri);
983 check_obj_well_typed uobj;
985 !logger (`Type_checking_completed uri);
989 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Ind i) ->
990 let _,_,arity,_ = List.nth tl i in arity
991 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,_,Ref.Con (i,j)) ->
992 let _,_,_,cl = List.nth tl i in
993 let _,_,arity = List.nth cl (j-1) in
995 | (_,_,_,_,C.Fixpoint (_,fl,_)), Ref.Ref (_,_,(Ref.Fix (i,_)|Ref.CoFix i)) ->
996 let _,_,_,arity,_ = List.nth fl i in
998 | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,_,(Ref.Def |Ref.Decl)) -> ty
999 | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
1001 and check_obj_well_typed (uri,height,metasenv,subst,kind) =
1002 (* CSC: here we should typecheck the metasenv and the subst *)
1003 assert (metasenv = [] && subst = []);
1005 | C.Constant (_,_,Some te,ty,_) ->
1006 let _ = typeof ~subst ~metasenv [] ty in
1007 let ty_te = typeof ~subst ~metasenv [] te in
1008 if not (R.are_convertible ~subst ~metasenv [] ty_te ty) then
1009 raise (TypeCheckerFailure (lazy (Printf.sprintf (
1010 "the type of the body is not convertible with the declared one.\n"^^
1011 "inferred type:\n%s\nexpected type:\n%s")
1012 (PP.ppterm ~subst ~metasenv ~context:[] ty_te)
1013 (PP.ppterm ~subst ~metasenv ~context:[] ty))))
1014 | C.Constant (_,_,None,ty,_) -> ignore (typeof ~subst ~metasenv [] ty)
1015 | C.Inductive (is_ind, leftno, tyl, _) ->
1016 check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl
1017 | C.Fixpoint (inductive,fl,_) ->
1018 let types, kl, len =
1020 (fun (types,kl,len) (_,name,k,ty,_) ->
1021 let _ = typeof ~subst ~metasenv [] ty in
1022 ((name,(C.Decl (S.lift len ty)))::types, k::kl,len+1)
1026 List.split (List.map2
1027 (fun (_,_,_,_,bo) rno ->
1028 let dbo = debruijn uri len [] bo in
1032 List.iter2 (fun (_,name,x,ty,_) bo ->
1033 let ty_bo = typeof ~subst ~metasenv types bo in
1034 if not (R.are_convertible ~subst ~metasenv types ty_bo (S.lift len ty))
1035 then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1037 if inductive then begin
1038 let m, context = eat_lambdas ~subst ~metasenv types (x + 1) bo in
1041 match List.hd context with _,C.Decl t -> t | _ -> assert false
1043 match R.whd ~subst (List.tl context) he with
1044 | C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref)
1045 | C.Appl (C.Const (Ref.Ref (_,uri,Ref.Ind _) as ref) :: _) ->
1046 let _,_,itl,_,_ = E.get_checked_indtys ref in
1047 uri, List.length itl
1050 (* guarded by destructors conditions D{f,k,x,M} *)
1051 let rec enum_from k =
1052 function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl
1054 guarded_by_destructors r_uri r_len
1055 ~subst ~metasenv context (enum_from (x+2) kl) m
1057 match returns_a_coinductive ~subst [] ty with
1059 raise (TypeCheckerFailure
1060 (lazy "CoFix: does not return a coinductive type"))
1062 (* guarded by constructors conditions C{f,M} *)
1064 (guarded_by_constructors ~subst ~metasenv types bo uri len)
1066 raise (TypeCheckerFailure
1067 (lazy "CoFix: not guarded by constructors"))
1070 let typecheck_obj = check_obj_well_typed;;