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_______________________________________________________________ *)
15 module R = NCicReduction
16 module Ref = NReference
17 module S = NCicSubstitution
19 module E = NCicEnvironment
22 exception TypeCheckerFailure of string Lazy.t
23 exception AssertFailure of string Lazy.t
26 | Evil of int (* rno *)
27 | UnfFix of bool list (* fixed arguments *)
31 let is_dangerous i l =
32 List.exists (function (j,Evil _) when j=i -> true | _ -> false) l
36 List.exists (function (j,UnfFix _) when j=i -> true | _ -> false) l
40 List.exists (function (j,Safe) when j=i -> true | _ -> false) l
44 try match List.assoc i l with Evil rno -> rno | _ -> assert false
45 with Not_found -> assert false
48 let get_fixed_args i l =
49 try match List.assoc i l with UnfFix fa -> fa | _ -> assert false
50 with Not_found -> assert false
53 let shift_k e (c,rf,x) = e::c,List.map (fun (k,v) -> k+1,v) rf,x+1;;
56 let string_of_recfuns ~subst ~metasenv ~context l =
57 let pp = PP.ppterm ~subst ~metasenv ~context in
58 let safe, rest = List.partition (function (_,Safe) -> true | _ -> false) l in
59 let dang,unf = List.partition (function (_,UnfFix _)-> false | _->true)rest in
60 "\n\tsafes: "^String.concat "," (List.map (fun (i,_)->pp (C.Rel i)) safe) ^
61 "\n\tfix : "^String.concat ","
63 (function (i,UnfFix l)-> pp(C.Rel i)^"/"^String.concat "," (List.map
65 | _ ->assert false) unf) ^
66 "\n\trec : "^String.concat ","
68 (function (i,Evil rno)->pp(C.Rel i)^"/"^string_of_int rno
69 | _ -> assert false) dang)
73 let fixed_args bos j n nn =
74 let rec aux k acc = function
75 | C.Appl (C.Rel i::args) when i-k > n && i-k <= nn ->
76 let rec combine l1 l2 =
79 | he1::tl1, he2::tl2 -> (he1,he2)::combine tl1 tl2
80 | he::tl, [] -> (false,C.Rel ~-1)::combine tl [] (* dummy term *)
81 | [],_::_ -> assert false
83 let lefts, _ = HExtlib.split_nth (min j (List.length args)) args in
84 List.map (fun ((b,x),i) -> b && x = C.Rel (k-i))
85 (HExtlib.list_mapi (fun x i -> x,i) (combine acc lefts))
86 | t -> U.fold (fun _ k -> k+1) k aux acc t
88 List.fold_left (aux 0)
89 (let rec f = function 0 -> [] | n -> true :: f (n-1) in f j) bos
92 let rec split_prods ~subst context n te =
93 match (n, R.whd ~subst context te) with
94 | (0, _) -> context,te
95 | (n, C.Prod (name,so,ta)) when n > 0 ->
96 split_prods ~subst ((name,(C.Decl so))::context) (n - 1) ta
97 | (_, _) -> raise (AssertFailure (lazy "split_prods"))
100 let debruijn uri number_of_types context =
103 | C.Meta (i,(s,C.Ctx l)) ->
104 let l1 = HExtlib.sharing_map (aux (k-s)) l in
105 if l1 == l then t else C.Meta (i,(s,C.Ctx l1))
107 | C.Const (Ref.Ref (uri1,(Ref.Fix (no,_,_) | Ref.CoFix no)))
108 | C.Const (Ref.Ref (uri1,Ref.Ind (_,no))) when NUri.eq uri uri1 ->
109 C.Rel (k + number_of_types - no)
110 | t -> U.map (fun _ k -> k+1) k aux t
112 aux (List.length context)
115 let sort_of_prod ~metasenv ~subst context (name,s) (t1, t2) =
116 let t1 = R.whd ~subst context t1 in
117 let t2 = R.whd ~subst ((name,C.Decl s)::context) t2 in
119 | C.Sort s1, C.Sort C.Prop -> t2
120 | C.Sort (C.Type u1), C.Sort (C.Type u2) -> C.Sort (C.Type (max u1 u2))
121 | C.Sort _,C.Sort (C.Type _) -> t2
122 | C.Sort (C.Type _) , C.Sort C.CProp -> t1
123 | C.Sort _, C.Sort C.CProp
124 | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))), C.Sort _
125 | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))), C.Meta (_,(_,(C.Irl 0 | C.Ctx [])))
126 | C.Sort _, C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> t2
128 raise (TypeCheckerFailure (lazy (Printf.sprintf
129 "Prod: expected two sorts, found = %s, %s"
130 (PP.ppterm ~subst ~metasenv ~context t1)
131 (PP.ppterm ~subst ~metasenv ~context t2))))
134 let eat_prods ~subst ~metasenv context he ty_he args_with_ty =
135 let rec aux ty_he = function
137 | (arg, ty_arg)::tl ->
138 match R.whd ~subst context ty_he with
141 prerr_endline (PP.ppterm ~subst ~metasenv ~context s ^ " - Vs - "
142 ^ PP.ppterm ~subst ~metasenv ~context ty_arg);
143 prerr_endline (PP.ppterm ~subst ~metasenv ~context
144 (S.subst ~avoid_beta_redexes:true arg t));
146 if R.are_convertible ~subst context ty_arg s then
147 aux (S.subst ~avoid_beta_redexes:true arg t) tl
151 (lazy (Printf.sprintf
152 ("Appl: wrong application of %s: the parameter %s has type"^^
153 "\n%s\nbut it should have type \n%s\nContext:\n%s\n")
154 (PP.ppterm ~subst ~metasenv ~context he)
155 (PP.ppterm ~subst ~metasenv ~context arg)
156 (PP.ppterm ~subst ~metasenv ~context ty_arg)
157 (PP.ppterm ~subst ~metasenv ~context s)
158 (PP.ppcontext ~subst ~metasenv context))))
162 (lazy (Printf.sprintf
163 "Appl: %s is not a function, it cannot be applied"
164 (PP.ppterm ~subst ~metasenv ~context
165 (let res = List.length tl in
166 let eaten = List.length args_with_ty - res in
169 (fst (HExtlib.split_nth eaten args_with_ty)))))))))
171 aux ty_he args_with_ty
174 (* instantiate_parameters ps (x1:T1)...(xn:Tn)C *)
175 (* returns ((x_|ps|:T_|ps|)...(xn:Tn)C){ps_1 / x1 ; ... ; ps_|ps| / x_|ps|} *)
176 let rec instantiate_parameters params c =
179 | C.Prod (_,_,ta), he::tl -> instantiate_parameters tl (S.subst he ta)
180 | t,l -> raise (AssertFailure (lazy "1"))
183 let specialize_inductive_type_constrs ~subst context ty_term =
184 match R.whd ~subst context ty_term with
185 | C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as ref)
186 | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as ref) :: _ ) as ty ->
187 let args = match ty with C.Appl (_::tl) -> tl | _ -> [] in
188 let is_ind, leftno, itl, attrs, i = E.get_checked_indtys ref in
189 let left_args,_ = HExtlib.split_nth leftno args in
190 let _,_,_,cl = List.nth itl i in
192 (fun (rel,name,ty) -> rel, name, instantiate_parameters left_args ty) cl
196 let specialize_and_abstract_constrs ~subst r_uri r_len context ty_term =
197 let cl = specialize_inductive_type_constrs ~subst context ty_term in
198 let len = List.length context in
200 match E.get_checked_obj r_uri with
201 | _,_,_,_, NCic.Inductive (_,_,tys,_) ->
202 context @ List.map (fun (_,name,arity,_) -> name,C.Decl arity) tys
206 List.map (fun (_,id,ty) -> id, debruijn r_uri r_len context ty) cl,
210 exception DoesOccur;;
212 let does_not_occur ~subst context n nn t =
213 let rec aux k _ = function
214 | C.Rel m when m > n+k && m <= nn+k -> raise DoesOccur
215 | C.Rel m when m <= k || m > nn+k -> ()
217 (try match List.nth context (m-1-k) with
218 | _,C.Def (bo,_) -> aux (n-m) () bo
220 with Failure _ -> assert false)
221 | C.Meta (_,(_,(C.Irl 0 | C.Ctx []))) -> (* closed meta *) ()
222 | C.Meta (mno,(s,l)) ->
224 (* possible optimization here: try does_not_occur on l and
225 perform substitution only if DoesOccur is raised *)
226 let _,_,term,_ = U.lookup_subst mno subst in
227 aux (k-s) () (S.subst_meta (0,l) term)
228 with U.Subst_not_found _ -> match l with
229 | C.Irl len -> if not (n+k >= s+len || s > nn+k) then raise DoesOccur
230 | C.Ctx lc -> List.iter (aux (k-s) ()) lc)
231 | t -> U.fold (fun _ k -> k + 1) k aux () t
234 with DoesOccur -> false
237 let rec eat_lambdas ~subst ~metasenv context n te =
238 match (n, R.whd ~subst context te) with
239 | (0, _) -> (te, context)
240 | (n, C.Lambda (name,so,ta)) when n > 0 ->
241 eat_lambdas ~subst ~metasenv ((name,(C.Decl so))::context) (n - 1) ta
243 raise (AssertFailure (lazy (Printf.sprintf "eat_lambdas (%d, %s)" n
244 (PP.ppterm ~subst ~metasenv ~context te))))
247 let rec eat_or_subst_lambdas ~subst ~metasenv n te to_be_subst args
248 (context, recfuns, x as k)
250 match n, R.whd ~subst context te, to_be_subst, args with
251 | (n, C.Lambda (name,so,ta),true::to_be_subst,arg::args) when n > 0 ->
252 eat_or_subst_lambdas ~subst ~metasenv (n - 1) (S.subst arg ta)
254 | (n, C.Lambda (name,so,ta),false::to_be_subst,arg::args) when n > 0 ->
255 eat_or_subst_lambdas ~subst ~metasenv (n - 1) ta to_be_subst args
256 (shift_k (name,(C.Decl so)) k)
257 | (_, te, _, _) -> te, k
261 (*CSC l'indice x dei tipi induttivi e' t.c. n < x <= nn *)
262 (*CSC questa funzione e' simile alla are_all_occurrences_positive, ma fa *)
263 (*CSC dei controlli leggermente diversi. Viene invocata solamente dalla *)
264 (*CSC strictly_positive *)
265 (*CSC definizione (giusta???) tratta dalla mail di Hugo ;-) *)
266 let rec weakly_positive ~subst context n nn uri te =
267 (*CSC: Che schifo! Bisogna capire meglio e trovare una soluzione ragionevole!*)
268 let dummy = C.Sort (C.Type ~-1) in
269 (*CSC: mettere in cicSubstitution *)
270 let rec subst_inductive_type_with_dummy _ = function
271 | C.Const (Ref.Ref (uri',Ref.Ind (true,0))) when NUri.eq uri' uri -> dummy
272 | C.Appl ((C.Const (Ref.Ref (uri',Ref.Ind (true,0))))::tl)
273 when NUri.eq uri' uri -> dummy
274 | t -> U.map (fun _ x->x) () subst_inductive_type_with_dummy t
276 match R.whd context te with
277 | C.Const (Ref.Ref (uri',Ref.Ind _))
278 | C.Appl ((C.Const (Ref.Ref (uri',Ref.Ind _)))::_)
279 when NUri.eq uri' uri -> true
280 | C.Prod (name,source,dest) when
281 does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
282 (* dummy abstraction, so we behave as in the anonimous case *)
283 strictly_positive ~subst context n nn
284 (subst_inductive_type_with_dummy () source) &&
285 weakly_positive ~subst ((name,C.Decl source)::context)
286 (n + 1) (nn + 1) uri dest
287 | C.Prod (name,source,dest) ->
288 does_not_occur ~subst context n nn
289 (subst_inductive_type_with_dummy () source)&&
290 weakly_positive ~subst ((name,C.Decl source)::context)
291 (n + 1) (nn + 1) uri dest
293 raise (TypeCheckerFailure (lazy "Malformed inductive constructor type"))
295 and strictly_positive ~subst context n nn te =
296 match R.whd context te with
297 | t when does_not_occur ~subst context n nn t -> true
299 | C.Prod (name,so,ta) ->
300 does_not_occur ~subst context n nn so &&
301 strictly_positive ~subst ((name,C.Decl so)::context) (n+1) (nn+1) ta
302 | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
303 List.for_all (does_not_occur ~subst context n nn) tl
304 | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (_,i)) as r)::tl) ->
305 let _,paramsno,tyl,_,i = E.get_checked_indtys r in
306 let _,name,ity,cl = List.nth tyl i in
307 let ok = List.length tyl = 1 in
308 let params, arguments = HExtlib.split_nth paramsno tl in
309 let lifted_params = List.map (S.lift 1) params in
311 List.map (fun (_,_,te) -> instantiate_parameters lifted_params te) cl
314 List.for_all (does_not_occur ~subst context n nn) arguments &&
316 (weakly_positive ~subst ((name,C.Decl ity)::context) (n+1) (nn+1) uri) cl
319 (* the inductive type indexes are s.t. n < x <= nn *)
320 and are_all_occurrences_positive ~subst context uri indparamsno i n nn te =
321 match R.whd context te with
322 | C.Appl ((C.Rel m)::tl) as reduct when m = i ->
328 match R.whd context x with
329 | C.Rel m when m = n - (indparamsno - k) -> k - 1
330 | y -> raise (TypeCheckerFailure (lazy
331 ("Argument "^string_of_int (indparamsno - k + 1) ^ " (of " ^
332 string_of_int indparamsno ^ " fixed) is not homogeneous in "^
333 "appl:\n"^ PP.ppterm ~context ~subst ~metasenv:[] reduct))))
337 List.for_all (does_not_occur ~subst context n nn) tl
339 raise (TypeCheckerFailure
340 (lazy ("Non-positive occurence in mutual inductive definition(s) [2]"^
341 NUri.string_of_uri uri)))
342 | C.Rel m when m = i ->
343 if indparamsno = 0 then
346 raise (TypeCheckerFailure
347 (lazy ("Non-positive occurence in mutual inductive definition(s) [3]"^
348 NUri.string_of_uri uri)))
349 | C.Prod (name,source,dest) when
350 does_not_occur ~subst ((name,C.Decl source)::context) 0 1 dest ->
351 strictly_positive ~subst context n nn source &&
352 are_all_occurrences_positive ~subst
353 ((name,C.Decl source)::context) uri indparamsno
354 (i+1) (n + 1) (nn + 1) dest
355 | C.Prod (name,source,dest) ->
356 if not (does_not_occur ~subst context n nn source) then
357 raise (TypeCheckerFailure (lazy ("Non-positive occurrence in "^
358 PP.ppterm ~context ~metasenv:[] ~subst te)));
359 are_all_occurrences_positive ~subst ((name,C.Decl source)::context)
360 uri indparamsno (i+1) (n + 1) (nn + 1) dest
363 (TypeCheckerFailure (lazy ("Malformed inductive constructor type " ^
364 (NUri.string_of_uri uri))))
367 exception NotGuarded of string Lazy.t;;
369 let rec typeof ~subst ~metasenv context term =
370 let rec typeof_aux context =
371 fun t -> (*prerr_endline (PP.ppterm ~metasenv ~subst ~context t);*)
375 match List.nth context (n - 1) with
376 | (_,C.Decl ty) -> S.lift n ty
377 | (_,C.Def (_,ty)) -> S.lift n ty
378 with Failure _ -> raise (TypeCheckerFailure (lazy "unbound variable")))
379 | C.Sort (C.Type i) -> C.Sort (C.Type (i+1))
380 | C.Sort s -> C.Sort (C.Type 0)
381 | C.Implicit _ -> raise (AssertFailure (lazy "Implicit found"))
382 | C.Meta (n,l) as t ->
383 let canonical_ctx,ty =
385 let _,c,_,ty = U.lookup_subst n subst in c,ty
386 with U.Subst_not_found _ -> try
387 let _,c,ty = U.lookup_meta n metasenv in c,ty
388 with U.Meta_not_found _ ->
389 raise (AssertFailure (lazy (Printf.sprintf
390 "%s not found" (PP.ppterm ~subst ~metasenv ~context t))))
392 check_metasenv_consistency t ~subst ~metasenv context canonical_ctx l;
394 | C.Const ref -> type_of_constant ref
395 | C.Prod (name,s,t) ->
396 let sort1 = typeof_aux context s in
397 let sort2 = typeof_aux ((name,(C.Decl s))::context) t in
398 sort_of_prod ~metasenv ~subst context (name,s) (sort1,sort2)
399 | C.Lambda (n,s,t) ->
400 let sort = typeof_aux context s in
401 (match R.whd ~subst context sort with
402 | C.Meta _ | C.Sort _ -> ()
405 (TypeCheckerFailure (lazy (Printf.sprintf
406 ("Not well-typed lambda-abstraction: " ^^
407 "the source %s should be a type; instead it is a term " ^^
408 "of type %s") (PP.ppterm ~subst ~metasenv ~context s)
409 (PP.ppterm ~subst ~metasenv ~context sort)))));
410 let ty = typeof_aux ((n,(C.Decl s))::context) t in
412 | C.LetIn (n,ty,t,bo) ->
413 let ty_t = typeof_aux context t in
414 let _ = typeof_aux context ty in
415 if not (R.are_convertible ~subst context ty ty_t) then
418 (lazy (Printf.sprintf
419 "The type of %s is %s but it is expected to be %s"
420 (PP.ppterm ~subst ~metasenv ~context t)
421 (PP.ppterm ~subst ~metasenv ~context ty_t)
422 (PP.ppterm ~subst ~metasenv ~context ty))))
424 let ty_bo = typeof_aux ((n,C.Def (t,ty))::context) bo in
425 S.subst ~avoid_beta_redexes:true t ty_bo
426 | C.Appl (he::(_::_ as args)) ->
427 let ty_he = typeof_aux context he in
428 let args_with_ty = List.map (fun t -> t, typeof_aux context t) args in
430 prerr_endline ("HEAD: " ^ PP.ppterm ~subst ~metasenv ~context ty_he);
431 prerr_endline ("TARGS: " ^ String.concat " | " (List.map (PP.ppterm
432 ~subst ~metasenv ~context) (List.map snd args_with_ty)));
433 prerr_endline ("ARGS: " ^ String.concat " | " (List.map (PP.ppterm
434 ~subst ~metasenv ~context) (List.map fst args_with_ty)));
436 eat_prods ~subst ~metasenv context he ty_he args_with_ty
437 | C.Appl _ -> raise (AssertFailure (lazy "Appl of length < 2"))
438 | C.Match (Ref.Ref (_,Ref.Ind (_,tyno)) as r,outtype,term,pl) ->
439 let outsort = typeof_aux context outtype in
440 let inductive,leftno,itl,_,_ = E.get_checked_indtys r in
442 let _,_,_,cl = List.nth itl tyno in List.length cl
444 let parameters, arguments =
445 let ty = R.whd ~subst context (typeof_aux context term) in
448 C.Const (Ref.Ref (_,Ref.Ind _) as r') -> r',[]
449 | C.Appl (C.Const (Ref.Ref (_,Ref.Ind _) as r') :: tl) -> r',tl
452 (TypeCheckerFailure (lazy (Printf.sprintf
453 "Case analysis: analysed term %s is not an inductive one"
454 (PP.ppterm ~subst ~metasenv ~context term)))) in
455 if not (Ref.eq r r') then
457 (TypeCheckerFailure (lazy (Printf.sprintf
458 ("Case analysys: analysed term type is %s, but is expected " ^^
459 "to be (an application of) %s")
460 (PP.ppterm ~subst ~metasenv ~context ty)
461 (PP.ppterm ~subst ~metasenv ~context (C.Const r')))))
463 try HExtlib.split_nth leftno tl
466 raise (TypeCheckerFailure (lazy (Printf.sprintf
467 "%s is partially applied"
468 (PP.ppterm ~subst ~metasenv ~context ty)))) in
469 (* let's control if the sort elimination is allowed: [(I q1 ... qr)|B] *)
470 let sort_of_ind_type =
471 if parameters = [] then C.Const r
472 else C.Appl ((C.Const r)::parameters) in
473 let type_of_sort_of_ind_ty = typeof_aux context sort_of_ind_type in
474 check_allowed_sort_elimination ~subst ~metasenv r context
475 sort_of_ind_type type_of_sort_of_ind_ty outsort;
476 (* let's check if the type of branches are right *)
477 if List.length pl <> constructorsno then
478 raise (TypeCheckerFailure (lazy ("Wrong number of cases in a match")));
479 let j,branches_ok,p_ty, exp_p_ty =
481 (fun (j,b,old_p_ty,old_exp_p_ty) p ->
484 let cons = Ref.mk_constructor j r in
485 if parameters = [] then C.Const cons
486 else C.Appl (C.Const cons::parameters)
488 let ty_p = typeof_aux context p in
489 let ty_cons = typeof_aux context cons in
491 type_of_branch ~subst context leftno outtype cons ty_cons 0
493 j+1, R.are_convertible ~subst context ty_p ty_branch,
496 j,false,old_p_ty,old_exp_p_ty
497 ) (1,true,C.Sort C.Prop,C.Sort C.Prop) pl
499 if not branches_ok then
502 (lazy (Printf.sprintf ("Branch for constructor %s :=\n%s\n"^^
503 "has type %s\nnot convertible with %s")
504 (PP.ppterm ~subst ~metasenv ~context
505 (C.Const (Ref.mk_constructor (j-1) r)))
506 (PP.ppterm ~metasenv ~subst ~context (List.nth pl (j-2)))
507 (PP.ppterm ~metasenv ~subst ~context p_ty)
508 (PP.ppterm ~metasenv ~subst ~context exp_p_ty))));
509 let res = outtype::arguments@[term] in
510 R.head_beta_reduce (C.Appl res)
511 | C.Match _ -> assert false
513 and type_of_branch ~subst context leftno outty cons tycons liftno =
514 match R.whd ~subst context tycons with
515 | C.Const (Ref.Ref (_,Ref.Ind _)) -> C.Appl [S.lift liftno outty ; cons]
516 | C.Appl (C.Const (Ref.Ref (_,Ref.Ind _))::tl) ->
517 let _,arguments = HExtlib.split_nth leftno tl in
518 C.Appl (S.lift liftno outty::arguments@[cons])
519 | C.Prod (name,so,de) ->
521 match S.lift 1 cons with
522 | C.Appl l -> C.Appl (l@[C.Rel 1])
523 | t -> C.Appl [t ; C.Rel 1]
526 type_of_branch ~subst ((name,(C.Decl so))::context)
527 leftno outty cons de (liftno+1))
528 | _ -> raise (AssertFailure (lazy "type_of_branch"))
530 (* check_metasenv_consistency checks that the "canonical" context of a
531 metavariable is consitent - up to relocation via the relocation list l -
532 with the actual context *)
533 and check_metasenv_consistency
534 ~subst ~metasenv term context canonical_context l
538 let context = snd (HExtlib.split_nth shift context) in
539 let rec compare = function
543 raise (AssertFailure (lazy (Printf.sprintf
544 "Local and canonical context %s have different lengths"
545 (PP.ppterm ~subst ~context ~metasenv term))))
547 raise (TypeCheckerFailure (lazy (Printf.sprintf
548 "Unbound variable -%d in %s" m
549 (PP.ppterm ~subst ~metasenv ~context term))))
552 (_,C.Decl t1), (_,C.Decl t2)
553 | (_,C.Def (t1,_)), (_,C.Def (t2,_))
554 | (_,C.Def (_,t1)), (_,C.Decl t2) ->
555 if not (R.are_convertible ~subst tl t1 t2) then
558 (lazy (Printf.sprintf
559 ("Not well typed metavariable local context for %s: " ^^
560 "%s expected, which is not convertible with %s")
561 (PP.ppterm ~subst ~metasenv ~context term)
562 (PP.ppterm ~subst ~metasenv ~context t2)
563 (PP.ppterm ~subst ~metasenv ~context t1))))
566 (TypeCheckerFailure (lazy (Printf.sprintf
567 ("Not well typed metavariable local context for %s: " ^^
568 "a definition expected, but a declaration found")
569 (PP.ppterm ~subst ~metasenv ~context term)))));
570 compare (m - 1,tl,ctl)
572 compare (n,context,canonical_context)
574 (* we avoid useless lifting by shortening the context*)
575 let l,context = (0,lc_kind), snd (HExtlib.split_nth shift context) in
576 let lifted_canonical_context =
577 let rec lift_metas i = function
579 | (n,C.Decl t)::tl ->
580 (n,C.Decl (S.subst_meta l (S.lift i t)))::(lift_metas (i+1) tl)
581 | (n,C.Def (t,ty))::tl ->
582 (n,C.Def ((S.subst_meta l (S.lift i t)),
583 S.subst_meta l (S.lift i ty)))::(lift_metas (i+1) tl)
585 lift_metas 1 canonical_context in
586 let l = U.expand_local_context lc_kind in
591 | t, (_,C.Def (ct,_)) ->
592 (*CSC: the following optimization is to avoid a possibly expensive
593 reduction that can be easily avoided and that is quite
594 frequent. However, this is better handled using levels to
600 match List.nth context (n - 1) with
601 | (_,C.Def (te,_)) -> S.lift n te
606 if not (R.are_convertible ~subst context optimized_t ct)
610 (lazy (Printf.sprintf
611 ("Not well typed metavariable local context: " ^^
612 "expected a term convertible with %s, found %s")
613 (PP.ppterm ~subst ~metasenv ~context ct)
614 (PP.ppterm ~subst ~metasenv ~context t))))
615 | t, (_,C.Decl ct) ->
616 let type_t = typeof_aux context t in
617 if not (R.are_convertible ~subst context type_t ct) then
618 raise (TypeCheckerFailure
619 (lazy (Printf.sprintf
620 ("Not well typed metavariable local context: "^^
621 "expected a term of type %s, found %s of type %s")
622 (PP.ppterm ~subst ~metasenv ~context ct)
623 (PP.ppterm ~subst ~metasenv ~context t)
624 (PP.ppterm ~subst ~metasenv ~context type_t))))
625 ) l lifted_canonical_context
627 Invalid_argument _ ->
628 raise (AssertFailure (lazy (Printf.sprintf
629 "Local and canonical context %s have different lengths"
630 (PP.ppterm ~subst ~metasenv ~context term))))
632 and is_non_informative context paramsno c =
633 let rec aux context c =
634 match R.whd context c with
635 | C.Prod (n,so,de) ->
636 let s = typeof_aux context so in
637 s = C.Sort C.Prop && aux ((n,(C.Decl so))::context) de
639 let context',dx = split_prods ~subst:[] context paramsno c in
642 and check_allowed_sort_elimination ~subst ~metasenv r =
645 | C.Appl l -> C.Appl (l @ [arg])
646 | t -> C.Appl [t;arg] in
647 let rec aux context ind arity1 arity2 =
648 let arity1 = R.whd ~subst context arity1 in
649 let arity2 = R.whd ~subst context arity2 in
650 match arity1,arity2 with
651 | C.Prod (name,so1,de1), C.Prod (_,so2,de2) ->
652 if not (R.are_convertible ~subst context so1 so2) then
653 raise (TypeCheckerFailure (lazy (Printf.sprintf
654 "In outtype: expected %s, found %s"
655 (PP.ppterm ~subst ~metasenv ~context so1)
656 (PP.ppterm ~subst ~metasenv ~context so2)
658 aux ((name, C.Decl so1)::context)
659 (mkapp (S.lift 1 ind) (C.Rel 1)) de1 de2
660 | C.Sort _, C.Prod (name,so,ta) ->
661 if not (R.are_convertible ~subst context so ind) then
662 raise (TypeCheckerFailure (lazy (Printf.sprintf
663 "In outtype: expected %s, found %s"
664 (PP.ppterm ~subst ~metasenv ~context ind)
665 (PP.ppterm ~subst ~metasenv ~context so)
667 (match arity1,ta with
668 | (C.Sort (C.CProp | C.Type _), C.Sort _)
669 | (C.Sort C.Prop, C.Sort C.Prop) -> ()
670 | (C.Sort C.Prop, C.Sort (C.CProp | C.Type _)) ->
671 (* TODO: we should pass all these parameters since we
672 * have them already *)
673 let inductive,leftno,itl,_,i = E.get_checked_indtys r in
674 let itl_len = List.length itl in
675 let _,name,ty,cl = List.nth itl i in
676 let cl_len = List.length cl in
677 (* is it a singleton or empty non recursive and non informative
681 (itl_len = 1 && cl_len = 1 &&
682 is_non_informative [name,C.Decl ty] leftno
683 (let _,_,x = List.nth cl 0 in x)))
685 raise (TypeCheckerFailure (lazy
686 ("Sort elimination not allowed")));
693 typeof_aux context term
695 and check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl =
696 (* let's check if the arity of the inductive types are well formed *)
697 List.iter (fun (_,_,x,_) -> ignore (typeof ~subst ~metasenv [] x)) tyl;
698 (* let's check if the types of the inductive constructors are well formed. *)
699 let len = List.length tyl in
700 let tys = List.rev (List.map (fun (_,n,ty,_) -> (n,(C.Decl ty))) tyl) in
706 let debruijnedte = debruijn uri len [] te in
707 ignore (typeof ~subst ~metasenv tys debruijnedte);
708 (* let's check also the positivity conditions *)
711 (are_all_occurrences_positive ~subst tys uri leftno i 0 len
716 (lazy ("Non positive occurence in "^NUri.string_of_uri uri))))
721 and guarded_by_destructors r_uri r_len ~subst ~metasenv context recfuns t =
722 let recursor f k t = U.fold shift_k k (fun k () -> f k) () t in
723 let rec aux (context, recfuns, x as k) t =
725 prerr_endline ("GB:\n" ^
726 PP.ppcontext ~subst ~metasenv context^
727 PP.ppterm ~metasenv ~subst ~context t^
728 string_of_recfuns ~subst ~metasenv ~context recfuns);
732 | C.Rel m as t when is_dangerous m recfuns ->
733 raise (NotGuarded (lazy
734 (PP.ppterm ~subst ~metasenv ~context t ^
735 " is a partial application of a fix")))
736 | C.Appl ((C.Rel m)::tl) as t when is_dangerous m recfuns ->
737 let rec_no = get_recno m recfuns in
738 if not (List.length tl > rec_no) then
739 raise (NotGuarded (lazy
740 (PP.ppterm ~context ~subst ~metasenv t ^
741 " is a partial application of a fix")))
743 let rec_arg = List.nth tl rec_no in
744 if not (is_really_smaller r_uri r_len ~subst ~metasenv k rec_arg) then
745 raise (NotGuarded (lazy (Printf.sprintf ("Recursive call %s, %s is not"
746 ^^ " smaller.\ncontext:\n%s") (PP.ppterm ~context ~subst ~metasenv
747 t) (PP.ppterm ~context ~subst ~metasenv rec_arg)
748 (PP.ppcontext ~subst ~metasenv context))));
750 | C.Appl ((C.Rel m)::tl) when is_unfolded m recfuns ->
751 let fixed_args = get_fixed_args m recfuns in
752 HExtlib.list_iter_default2
753 (fun x b -> if not b then aux k x) tl false fixed_args
755 (match List.nth context (m-1) with
757 | _,C.Def (bo,_) -> aux k (S.lift m bo))
759 | C.Appl (C.Const ((Ref.Ref (uri,Ref.Fix (i,recno,_))) as r)::args) ->
760 if List.exists (fun t -> try aux k t;false with NotGuarded _ -> true) args
762 let fl,_,_ = E.get_checked_fixes_or_cofixes r in
764 List.split (List.map (fun (_,name,_,ty,bo) -> (name, C.Decl ty), bo) fl)
766 let fl_len = List.length fl in
767 let bos = List.map (debruijn uri fl_len context) bos in
768 let j = List.fold_left min max_int (List.map (fun (_,_,i,_,_)->i) fl) in
769 let ctx_len = List.length context in
770 (* we may look for fixed params not only up to j ... *)
771 let fa = fixed_args bos j ctx_len (ctx_len + fl_len) in
772 HExtlib.list_iter_default2
773 (fun x b -> if not b then aux k x) args false fa;
774 let context = context@ctx_tys in
775 let ctx_len = List.length context in
777 HExtlib.list_mapi (fun _ i -> ctx_len - i, UnfFix fa) ctx_tys
779 let new_k = context, extra_recfuns@recfuns, x in
784 eat_or_subst_lambdas ~subst ~metasenv j bo fa args new_k
788 List.length args > recno &&
789 (*case where the recursive argument is already really_smaller *)
790 is_really_smaller r_uri r_len ~subst ~metasenv k
791 (List.nth args recno)
793 let bo,(context, _, _ as new_k) = bo_and_k in
795 eat_lambdas ~subst ~metasenv context (recno + 1 - j) bo in
796 let new_context_part,_ =
797 HExtlib.split_nth (List.length context' - List.length context)
799 let k = List.fold_right shift_k new_context_part new_k in
800 let context, recfuns, x = k in
801 let k = context, (1,Safe)::recfuns, x in
807 List.iter (fun (bo,k) -> aux k bo) bos_and_ks
808 | C.Match (Ref.Ref (uri,Ref.Ind (true,_)),outtype,term,pl) as t ->
809 (match R.whd ~subst context term with
810 | C.Rel m | C.Appl (C.Rel m :: _ ) as t when is_safe m recfuns || m = x ->
811 let ty = typeof ~subst ~metasenv context term in
812 let dc_ctx, dcl, start, stop =
813 specialize_and_abstract_constrs ~subst r_uri r_len context ty in
814 let args = match t with C.Appl (_::tl) -> tl | _ -> [] in
816 List.iter (aux k) args;
819 let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
820 let p, k = get_new_safes ~subst k p rl in
823 | _ -> recursor aux k t)
824 | t -> recursor aux k t
826 NotGuarded _ as exc ->
827 let t' = R.whd ~delta:0 ~subst context t in
828 if t = t' then raise exc
831 try aux (context, recfuns, 1) t
832 with NotGuarded s -> raise (TypeCheckerFailure s)
834 and guarded_by_constructors ~subst ~metasenv context t indURI indlen nn =
835 let rec aux context n nn h te =
836 match R.whd ~subst context te with
837 | C.Rel m when m > n && m <= nn -> h
838 | C.Rel _ | C.Meta _ -> true
842 | C.Const (Ref.Ref (_,Ref.Ind _))
843 | C.LetIn _ -> raise (AssertFailure (lazy "17"))
844 | C.Lambda (name,so,de) ->
845 does_not_occur ~subst context n nn so &&
846 aux ((name,C.Decl so)::context) (n + 1) (nn + 1) h de
847 | C.Appl ((C.Rel m)::tl) when m > n && m <= nn ->
848 h && List.for_all (does_not_occur ~subst context n nn) tl
849 | C.Const (Ref.Ref (_,Ref.Con _)) -> true
850 | C.Appl (C.Const (Ref.Ref (uri, Ref.Con (_,j)) as ref) :: tl) as t ->
851 let _, paramsno, _, _, _ = E.get_checked_indtys ref in
852 let ty_t = typeof ~subst ~metasenv context t in
853 let dc_ctx, dcl, start, stop =
854 specialize_and_abstract_constrs ~subst indURI indlen context ty_t in
855 let _, dc = List.nth dcl (j-1) in
857 prerr_endline (PP.ppterm ~subst ~metasenv ~context:dc_ctx dc);
858 prerr_endline (PP.ppcontext ~subst ~metasenv dc_ctx);
860 let rec_params = recursive_args ~subst ~metasenv dc_ctx start stop dc in
861 let rec analyse_instantiated_type rec_spec args =
862 match rec_spec, args with
863 | h::rec_spec, he::args ->
864 aux context n nn h he && analyse_instantiated_type rec_spec args
866 | _ -> raise (AssertFailure (lazy
867 ("Too many args for constructor: " ^ String.concat " "
868 (List.map (fun x-> PP.ppterm ~subst ~metasenv ~context x) args))))
870 let left, args = HExtlib.split_nth paramsno tl in
871 List.for_all (does_not_occur ~subst context n nn) left &&
872 analyse_instantiated_type rec_params args
873 | C.Appl ((C.Match (_,out,te,pl))::_)
874 | C.Match (_,out,te,pl) as t ->
875 let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
876 List.for_all (does_not_occur ~subst context n nn) tl &&
877 does_not_occur ~subst context n nn out &&
878 does_not_occur ~subst context n nn te &&
879 List.for_all (aux context n nn h) pl
880 | C.Const (Ref.Ref (u,(Ref.Fix _| Ref.CoFix _)) as ref)
881 | C.Appl(C.Const (Ref.Ref(u,(Ref.Fix _| Ref.CoFix _)) as ref) :: _) as t ->
882 let tl = match t with C.Appl (_::tl) -> tl | _ -> [] in
883 let fl,_,_ = E.get_checked_fixes_or_cofixes ref in
884 let len = List.length fl in
885 let tys = List.map (fun (_,n,_,ty,_) -> n, C.Decl ty) fl in
886 List.for_all (does_not_occur ~subst context n nn) tl &&
889 aux (context@tys) n nn h (debruijn u len context bo))
892 | C.Appl _ as t -> does_not_occur ~subst context n nn t
894 aux context 0 nn false t
896 and recursive_args ~subst ~metasenv context n nn te =
897 match R.whd context te with
898 | C.Rel _ | C.Appl _ | C.Const _ -> []
899 | C.Prod (name,so,de) ->
900 (not (does_not_occur ~subst context n nn so)) ::
901 (recursive_args ~subst ~metasenv
902 ((name,(C.Decl so))::context) (n+1) (nn + 1) de)
904 raise (AssertFailure (lazy ("recursive_args:" ^ PP.ppterm ~subst
905 ~metasenv ~context:[] t)))
907 and get_new_safes ~subst (context, recfuns, x as k) p rl =
908 match R.whd ~subst context p, rl with
909 | C.Lambda (name,so,ta), b::tl ->
910 let recfuns = (if b then [0,Safe] else []) @ recfuns in
912 (shift_k (name,(C.Decl so)) (context, recfuns, x)) ta tl
913 | C.Meta _ as e, _ | e, [] -> e, k
914 | _ -> raise (AssertFailure (lazy "Ill formed pattern"))
916 and is_really_smaller
917 r_uri r_len ~subst ~metasenv (context, recfuns, x as k) te
919 match R.whd ~subst context te with
920 | C.Rel m when is_safe m recfuns -> true
921 | C.Lambda (name, s, t) ->
922 is_really_smaller r_uri r_len ~subst ~metasenv (shift_k (name,C.Decl s) k) t
924 is_really_smaller r_uri r_len ~subst ~metasenv k he
926 | C.Const (Ref.Ref (_,Ref.Con _)) -> false
928 | C.Const (Ref.Ref (_,Ref.Fix _)) -> assert false
930 | C.Match (Ref.Ref (uri,_) as ref,outtype,term,pl) ->
932 | C.Rel m | C.Appl (C.Rel m :: _ ) when is_safe m recfuns || m = x ->
933 (* TODO: add CoInd to references so that this call is useless *)
934 let isinductive, _, _, _, _ = E.get_checked_indtys ref in
935 if not isinductive then
936 List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl
938 let ty = typeof ~subst ~metasenv context term in
939 let dc_ctx, dcl, start, stop =
940 specialize_and_abstract_constrs ~subst r_uri r_len context ty in
943 let rl = recursive_args ~subst ~metasenv dc_ctx start stop dc in
944 let e, k = get_new_safes ~subst k p rl in
945 is_really_smaller r_uri r_len ~subst ~metasenv k e)
947 | _ -> List.for_all (is_really_smaller r_uri r_len ~subst ~metasenv k) pl)
950 and returns_a_coinductive ~subst context ty =
951 match R.whd ~subst context ty with
952 | C.Const (Ref.Ref (uri,Ref.Ind (false,_)) as ref)
953 | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind (false,_)) as ref)::_) ->
954 let _, _, itl, _, _ = E.get_checked_indtys ref in
955 Some (uri,List.length itl)
956 | C.Prod (n,so,de) ->
957 returns_a_coinductive ~subst ((n,C.Decl so)::context) de
960 and type_of_constant ((Ref.Ref (uri,_)) as ref) =
961 match E.get_checked_obj uri, ref with
962 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,Ref.Ind (_,i)) ->
963 let _,_,arity,_ = List.nth tl i in arity
964 | (_,_,_,_,C.Inductive (_,_,tl,_)), Ref.Ref (_,Ref.Con (i,j)) ->
965 let _,_,_,cl = List.nth tl i in
966 let _,_,arity = List.nth cl (j-1) in
968 | (_,_,_,_,C.Fixpoint (_,fl,_)), Ref.Ref (_,(Ref.Fix (i,_,_)|Ref.CoFix i)) ->
969 let _,_,_,arity,_ = List.nth fl i in
971 | (_,_,_,_,C.Constant (_,_,_,ty,_)), Ref.Ref (_,(Ref.Def _|Ref.Decl)) -> ty
972 | _ -> raise (AssertFailure (lazy "type_of_constant: environment/reference"))
975 let typecheck_context ~metasenv ~subst context =
981 _,C.Decl t -> ignore (typeof ~metasenv ~subst:[] context t)
982 | name,C.Def (te,ty) ->
983 ignore (typeof ~metasenv ~subst:[] context ty);
984 let ty' = typeof ~metasenv ~subst:[] context te in
985 if not (R.are_convertible ~subst context ty' ty) then
986 raise (AssertFailure (lazy (Printf.sprintf (
987 "the type of the definiens for %s in the context is not "^^
988 "convertible with the declared one.\n"^^
989 "inferred type:\n%s\nexpected type:\n%s")
991 (PP.ppterm ~subst ~metasenv ~context ty')
992 (PP.ppterm ~subst ~metasenv ~context ty))))
998 let typecheck_metasenv metasenv =
1001 (fun metasenv (i,(_,context,ty) as conj) ->
1002 if List.mem_assoc i metasenv then
1003 raise (TypeCheckerFailure (lazy ("duplicate meta " ^ string_of_int i ^
1005 typecheck_context ~metasenv ~subst:[] context;
1006 ignore (typeof ~metasenv ~subst:[] context ty);
1011 let typecheck_subst ~metasenv subst =
1014 (fun subst (i,(_,context,ty,bo) as conj) ->
1015 if List.mem_assoc i subst then
1016 raise (AssertFailure (lazy ("duplicate meta " ^ string_of_int i ^
1017 " in substitution")));
1018 if List.mem_assoc i metasenv then
1019 raise (AssertFailure (lazy ("meta " ^ string_of_int i ^
1020 " is both in the metasenv and in the substitution")));
1021 typecheck_context ~metasenv ~subst context;
1022 ignore (typeof ~metasenv ~subst context ty);
1023 let ty' = typeof ~metasenv ~subst context bo in
1024 if not (R.are_convertible ~subst context ty' ty) then
1025 raise (AssertFailure (lazy (Printf.sprintf (
1026 "the type of the definiens for %d in the substitution is not "^^
1027 "convertible with the declared one.\n"^^
1028 "inferred type:\n%s\nexpected type:\n%s")
1030 (PP.ppterm ~subst ~metasenv ~context ty')
1031 (PP.ppterm ~subst ~metasenv ~context ty))));
1036 let typecheck_obj (uri,height,metasenv,subst,kind) =
1037 typecheck_metasenv metasenv;
1038 typecheck_subst ~metasenv subst;
1040 | C.Constant (_,_,Some te,ty,_) ->
1041 let _ = typeof ~subst ~metasenv [] ty in
1042 let ty_te = typeof ~subst ~metasenv [] te in
1043 if not (R.are_convertible ~subst [] ty_te ty) then
1044 raise (TypeCheckerFailure (lazy (Printf.sprintf (
1045 "the type of the body is not convertible with the declared one.\n"^^
1046 "inferred type:\n%s\nexpected type:\n%s")
1047 (PP.ppterm ~subst ~metasenv ~context:[] ty_te)
1048 (PP.ppterm ~subst ~metasenv ~context:[] ty))))
1049 | C.Constant (_,_,None,ty,_) -> ignore (typeof ~subst ~metasenv [] ty)
1050 | C.Inductive (is_ind, leftno, tyl, _) ->
1051 check_mutual_inductive_defs uri ~metasenv ~subst is_ind leftno tyl
1052 | C.Fixpoint (inductive,fl,_) ->
1055 (fun (types,kl) (_,name,k,ty,_) ->
1056 let _ = typeof ~subst ~metasenv [] ty in
1057 ((name,C.Decl ty)::types, k::kl)
1060 let len = List.length types in
1062 List.split (List.map2
1063 (fun (_,_,_,_,bo) rno ->
1064 let dbo = debruijn uri len [] bo in
1068 List.iter2 (fun (_,name,x,ty,_) bo ->
1069 let ty_bo = typeof ~subst ~metasenv types bo in
1070 if not (R.are_convertible ~subst types ty_bo ty)
1071 then raise (TypeCheckerFailure (lazy ("(Co)Fix: ill-typed bodies")))
1073 if inductive then begin
1074 let m, context = eat_lambdas ~subst ~metasenv types (x + 1) bo in
1077 match List.hd context with _,C.Decl t -> t | _ -> assert false
1079 match R.whd ~subst (List.tl context) he with
1080 | C.Const (Ref.Ref (uri,Ref.Ind _) as ref)
1081 | C.Appl (C.Const (Ref.Ref (uri,Ref.Ind _) as ref) :: _) ->
1082 let _,_,itl,_,_ = E.get_checked_indtys ref in
1083 uri, List.length itl
1086 (* guarded by destructors conditions D{f,k,x,M} *)
1087 let rec enum_from k =
1088 function [] -> [] | v::tl -> (k,v)::enum_from (k+1) tl
1090 guarded_by_destructors r_uri r_len
1091 ~subst ~metasenv context (enum_from (x+2) kl) m
1093 match returns_a_coinductive ~subst [] ty with
1095 raise (TypeCheckerFailure
1096 (lazy "CoFix: does not return a coinductive type"))
1097 | Some (r_uri, r_len) ->
1098 (* guarded by constructors conditions C{f,M} *)
1100 (guarded_by_constructors ~subst ~metasenv types bo r_uri r_len len)
1102 raise (TypeCheckerFailure
1103 (lazy "CoFix: not guarded by constructors"))
1109 let trust = ref (fun _ -> false);;
1110 let set_trust f = trust := f
1111 let trust_obj obj = !trust obj
1114 (* web interface stuff *)
1117 ref (function (`Start_type_checking _|`Type_checking_completed _|`Type_checking_interrupted _|`Type_checking_failed _|`Trust_obj _) -> ())
1120 let set_logger f = logger := f;;
1122 let typecheck_obj obj =
1123 let u,_,_,_,_ = obj in
1125 !logger (`Start_type_checking u);
1127 !logger (`Type_checking_completed u)
1130 !logger (`Type_checking_interrupted u);
1133 !logger (`Type_checking_failed u);
1139 if trust_obj obj then
1140 let u,_,_,_,_ = obj in
1141 !logger (`Trust_obj u)