1 (* Copyright (C) 2004, HELM Team.
3 * This file is part of HELM, an Hypertextual, Electronic
4 * Library of Mathematics, developed at the Computer Science
5 * Department, University of Bologna, Italy.
7 * HELM is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * HELM is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with HELM; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 * For details, see the HELM World-Wide-Web page,
23 * http://cs.unibo.it/helm/.
28 let apply_subst_counter = ref 0
29 let apply_subst_context_counter = ref 0
30 let apply_subst_metasenv_counter = ref 0
31 let lift_counter = ref 0
32 let subst_counter = ref 0
33 let whd_counter = ref 0
34 let are_convertible_counter = ref 0
35 let metasenv_length = ref 0
36 let context_length = ref 0
38 let reset_counters () =
39 apply_subst_counter := 0;
40 apply_subst_context_counter := 0;
41 apply_subst_metasenv_counter := 0;
45 are_convertible_counter := 0;
49 let print_counters () =
50 prerr_endline (Printf.sprintf
52 apply_subst_context: %d
53 apply_subst_metasenv: %d
58 metasenv length: %d (avg = %.2f)
59 context length: %d (avg = %.2f)
61 !apply_subst_counter !apply_subst_context_counter
62 !apply_subst_metasenv_counter !lift_counter !subst_counter !whd_counter
63 !are_convertible_counter !metasenv_length
64 ((float !metasenv_length) /. (float !apply_subst_metasenv_counter))
66 ((float !context_length) /. (float !apply_subst_context_counter))
69 exception MetaSubstFailure of string
70 exception Uncertain of string
71 exception AssertFailure of string
72 exception SubstNotFound of int
74 let debug_print = prerr_endline
76 type substitution = (int * (Cic.context * Cic.term)) list
78 let lookup_subst n subst =
81 with Not_found -> raise (SubstNotFound n)
83 (*** Functions to apply a substitution ***)
85 let apply_subst_gen ~appl_fun subst term =
88 let module S = CicSubstitution in
91 | C.Var (uri,exp_named_subst) ->
92 let exp_named_subst' =
93 List.map (fun (uri, t) -> (uri, um_aux t)) exp_named_subst
95 C.Var (uri, exp_named_subst')
98 let (context, t) = lookup_subst i subst in
99 um_aux (S.lift_meta l t)
100 with SubstNotFound _ -> (* unconstrained variable, i.e. free in subst*)
102 List.map (function None -> None | Some t -> Some (um_aux t)) l
106 | C.Implicit _ -> assert false
107 | C.Cast (te,ty) -> C.Cast (um_aux te, um_aux ty)
108 | C.Prod (n,s,t) -> C.Prod (n, um_aux s, um_aux t)
109 | C.Lambda (n,s,t) -> C.Lambda (n, um_aux s, um_aux t)
110 | C.LetIn (n,s,t) -> C.LetIn (n, um_aux s, um_aux t)
111 | C.Appl (hd :: tl) -> appl_fun um_aux hd tl
112 | C.Appl _ -> assert false
113 | C.Const (uri,exp_named_subst) ->
114 let exp_named_subst' =
115 List.map (fun (uri, t) -> (uri, um_aux t)) exp_named_subst
117 C.Const (uri, exp_named_subst')
118 | C.MutInd (uri,typeno,exp_named_subst) ->
119 let exp_named_subst' =
120 List.map (fun (uri, t) -> (uri, um_aux t)) exp_named_subst
122 C.MutInd (uri,typeno,exp_named_subst')
123 | C.MutConstruct (uri,typeno,consno,exp_named_subst) ->
124 let exp_named_subst' =
125 List.map (fun (uri, t) -> (uri, um_aux t)) exp_named_subst
127 C.MutConstruct (uri,typeno,consno,exp_named_subst')
128 | C.MutCase (sp,i,outty,t,pl) ->
129 let pl' = List.map um_aux pl in
130 C.MutCase (sp, i, um_aux outty, um_aux t, pl')
133 List.map (fun (name, i, ty, bo) -> (name, i, um_aux ty, um_aux bo)) fl
138 List.map (fun (name, ty, bo) -> (name, um_aux ty, um_aux bo)) fl
146 (* CSC: old code that never performs beta reduction
147 let appl_fun um_aux he tl =
148 let tl' = List.map um_aux tl in
151 Cic.Appl l -> Cic.Appl (l@tl')
152 | he' -> Cic.Appl (he'::tl')
155 apply_subst_gen ~appl_fun
157 let appl_fun um_aux he tl =
158 let tl' = List.map um_aux tl in
161 Cic.Appl l -> Cic.Appl (l@tl')
162 | he' -> Cic.Appl (he'::tl')
167 let rec beta_reduce =
169 (Cic.Appl (Cic.Lambda (_,_,t)::he'::tl')) ->
170 let he'' = CicSubstitution.subst he' t in
174 beta_reduce (Cic.Appl(he''::tl'))
182 incr apply_subst_counter;
183 apply_subst_gen ~appl_fun s t
186 let rec apply_subst_context subst context =
187 incr apply_subst_context_counter;
188 context_length := !context_length + List.length context;
192 | Some (n, Cic.Decl t) ->
193 let t' = apply_subst subst t in
194 Some (n, Cic.Decl t') :: context
195 | Some (n, Cic.Def (t, ty)) ->
199 | Some ty -> Some (apply_subst subst ty)
201 let t' = apply_subst subst t in
202 Some (n, Cic.Def (t', ty')) :: context
203 | None -> None :: context)
206 let apply_subst_metasenv subst metasenv =
207 incr apply_subst_metasenv_counter;
208 metasenv_length := !metasenv_length + List.length metasenv;
210 (fun (n, context, ty) ->
211 (n, apply_subst_context subst context, apply_subst subst ty))
213 (fun (i, _, _) -> not (List.mem_assoc i subst))
216 (***** Pretty printing functions ******)
221 (fun (idx, (_, term)) ->
222 Printf.sprintf "?%d := %s" idx (CicPp.ppterm term))
226 let ppterm subst term = CicPp.ppterm (apply_subst subst term)
228 let ppterm_in_context subst term name_context =
229 CicPp.pp (apply_subst subst term) name_context
231 let ppcontext' ?(sep = "\n") subst context =
232 let separate s = if s = "" then "" else s ^ sep in
234 (fun context_entry (i,name_context) ->
235 match context_entry with
236 Some (n,Cic.Decl t) ->
237 sprintf "%s%s : %s" (separate i) (CicPp.ppname n)
238 (ppterm_in_context subst t name_context), (Some n)::name_context
239 | Some (n,Cic.Def (bo,ty)) ->
240 sprintf "%s%s : %s := %s" (separate i) (CicPp.ppname n)
243 | Some ty -> ppterm_in_context subst ty name_context)
244 (ppterm_in_context subst bo name_context), (Some n)::name_context
246 sprintf "%s_ :? _" (separate i), None::name_context
249 let ppcontext ?sep subst context = fst (ppcontext' ?sep subst context)
251 let ppmetasenv ?(sep = "\n") metasenv subst =
255 let context,name_context = ppcontext' ~sep:"; " subst c in
256 sprintf "%s |- ?%d: %s" context i
257 (ppterm_in_context subst t name_context))
259 (fun (i, _, _) -> not (List.mem_assoc i subst))
262 (* From now on we recreate a kernel abstraction where substitutions are part of
265 let lift subst n term =
267 let term = apply_subst subst term in
269 CicSubstitution.lift n term
271 raise (MetaSubstFailure ("Lift failure: " ^ Printexc.to_string e))
273 let subst subst t1 t2 =
275 let t1 = apply_subst subst t1 in
276 let t2 = apply_subst subst t2 in
278 CicSubstitution.subst t1 t2
280 raise (MetaSubstFailure ("Subst failure: " ^ Printexc.to_string e))
282 let whd subst context term =
284 let term = apply_subst subst term in
285 let context = apply_subst_context subst context in
287 CicReduction.whd context term
289 raise (MetaSubstFailure ("Weak head reduction failure: " ^
290 Printexc.to_string e))
292 let are_convertible subst context t1 t2 =
293 incr are_convertible_counter;
294 let context = apply_subst_context subst context in
295 let t1 = apply_subst subst t1 in
296 let t2 = apply_subst subst t2 in
297 CicReduction.are_convertible context t1 t2
299 let tempi_type_of_aux_subst = ref 0.0;;
300 let tempi_subst = ref 0.0;;
301 let tempi_type_of_aux = ref 0.0;;
303 (* assumption: metasenv is already instantiated wrt subst *)
304 let type_of_aux' metasenv subst context term =
305 let time1 = Unix.gettimeofday () in
306 let term = apply_subst subst term in
307 let context = apply_subst_context subst context in
308 (* let metasenv = apply_subst_metasenv subst metasenv in *)
309 let time2 = Unix.gettimeofday () in
312 CicTypeChecker.type_of_aux' metasenv context term
313 with CicTypeChecker.TypeCheckerFailure msg ->
314 raise (MetaSubstFailure ("Type checker failure: " ^ msg))
316 let time3 = Unix.gettimeofday () in
317 tempi_type_of_aux_subst := !tempi_type_of_aux_subst +. time3 -. time1 ;
318 tempi_subst := !tempi_subst +. time2 -. time1 ;
319 tempi_type_of_aux := !tempi_type_of_aux +. time3 -. time2 ;
323 (* the delift function takes in input a metavariable index, an ordered list of
324 * optional terms [t1,...,tn] and a term t, and substitutes every tk = Some
325 * (rel(nk)) with rel(k). Typically, the list of optional terms is the explicit
326 * substitution that is applied to a metavariable occurrence and the result of
327 * the delift function is a term the implicit variable can be substituted with
328 * to make the term [t] unifiable with the metavariable occurrence. In general,
329 * the problem is undecidable if we consider equivalence in place of alpha
330 * convertibility. Our implementation, though, is even weaker than alpha
331 * convertibility, since it replace the term [tk] if and only if [tk] is a Rel
332 * (missing all the other cases). Does this matter in practice?
333 * The metavariable index is the index of the metavariable that must not occur
334 * in the term (for occur check).
337 exception NotInTheList;;
342 [] -> raise NotInTheList
343 | (Some (Cic.Rel m))::_ when m=n -> k
344 | _::tl -> aux (k+1) tl in
350 let rec force_does_not_occur subst to_be_restricted t =
351 let module C = Cic in
352 let more_to_be_restricted = ref [] in
353 let rec aux k = function
354 C.Rel r when List.mem (r - k) to_be_restricted -> raise Occur
357 | C.Implicit _ -> assert false
359 (* we do not retrieve the term associated to ?n in subst since *)
360 (* in this way we can restrict if something goes wrong *)
372 more_to_be_restricted := (n,!i) :: !more_to_be_restricted;
377 | C.Cast (te,ty) -> C.Cast (aux k te, aux k ty)
378 | C.Prod (name,so,dest) -> C.Prod (name, aux k so, aux (k+1) dest)
379 | C.Lambda (name,so,dest) -> C.Lambda (name, aux k so, aux (k+1) dest)
380 | C.LetIn (name,so,dest) -> C.LetIn (name, aux k so, aux (k+1) dest)
381 | C.Appl l -> C.Appl (List.map (aux k) l)
382 | C.Var (uri,exp_named_subst) ->
383 let exp_named_subst' =
384 List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
386 C.Var (uri, exp_named_subst')
387 | C.Const (uri, exp_named_subst) ->
388 let exp_named_subst' =
389 List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
391 C.Const (uri, exp_named_subst')
392 | C.MutInd (uri,tyno,exp_named_subst) ->
393 let exp_named_subst' =
394 List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
396 C.MutInd (uri, tyno, exp_named_subst')
397 | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
398 let exp_named_subst' =
399 List.map (fun (uri,t) -> (uri, aux k t)) exp_named_subst
401 C.MutConstruct (uri, tyno, consno, exp_named_subst')
402 | C.MutCase (uri,tyno,out,te,pl) ->
403 C.MutCase (uri, tyno, aux k out, aux k te, List.map (aux k) pl)
405 let len = List.length fl in
406 let k_plus_len = k + len in
409 (fun (name,j,ty,bo) -> (name, j, aux k ty, aux k_plus_len bo)) fl
413 let len = List.length fl in
414 let k_plus_len = k + len in
417 (fun (name,ty,bo) -> (name, aux k ty, aux k_plus_len bo)) fl
422 (!more_to_be_restricted, res)
424 let rec restrict subst to_be_restricted metasenv =
425 let names_of_context_indexes context indexes =
430 match List.nth context i with
431 | None -> assert false
432 | Some (n, _) -> CicPp.ppname n
434 Failure _ -> assert false
437 let force_does_not_occur_in_context to_be_restricted = function
439 | Some (name, Cic.Decl t) ->
440 let (more_to_be_restricted, t') =
441 force_does_not_occur subst to_be_restricted t
443 more_to_be_restricted, Some (name, Cic.Decl t')
444 | Some (name, Cic.Def (bo, ty)) ->
445 let (more_to_be_restricted, bo') =
446 force_does_not_occur subst to_be_restricted bo
448 let more_to_be_restricted, ty' =
450 | None -> more_to_be_restricted, None
452 let more_to_be_restricted', ty' =
453 force_does_not_occur subst to_be_restricted ty
455 more_to_be_restricted @ more_to_be_restricted',
458 more_to_be_restricted, Some (name, Cic.Def (bo', ty'))
460 let rec erase i to_be_restricted n = function
461 | [] -> [], to_be_restricted, []
463 let more_to_be_restricted,restricted,tl' =
464 erase (i+1) to_be_restricted n tl
466 let restrict_me = List.mem i restricted in
468 more_to_be_restricted, restricted, None:: tl'
471 let more_to_be_restricted', hd' =
472 let delifted_restricted =
476 | j::tl when j > i -> (j - i)::aux tl
481 force_does_not_occur_in_context delifted_restricted hd
483 more_to_be_restricted @ more_to_be_restricted',
484 restricted, hd' :: tl'
486 more_to_be_restricted, (i :: restricted), None :: tl')
488 let (more_to_be_restricted, metasenv) = (* restrict metasenv *)
490 (fun (n, context, t) (more, metasenv) ->
491 let to_be_restricted =
492 List.map snd (List.filter (fun (m, _) -> m = n) to_be_restricted)
494 let (more_to_be_restricted, restricted, context') =
495 (* just an optimization *)
496 if to_be_restricted = [] then
499 erase 1 to_be_restricted n context
502 let more_to_be_restricted', t' =
503 force_does_not_occur subst restricted t
505 let metasenv' = (n, context', t') :: metasenv in
506 (more @ more_to_be_restricted @ more_to_be_restricted',
509 raise (MetaSubstFailure (sprintf
510 "Cannot restrict the context of the metavariable ?%d over the hypotheses %s since metavariable's type depends on at least one of them"
511 n (names_of_context_indexes context to_be_restricted))))
514 let (more_to_be_restricted', subst) = (* restrict subst *)
516 (fun (n, (context, term)) (more, subst) ->
517 let to_be_restricted =
518 List.map snd (List.filter (fun (m, _) -> m = n) to_be_restricted)
521 let (more_to_be_restricted, restricted, context') =
522 (* just an optimization *)
523 if to_be_restricted = [] then
526 erase 1 to_be_restricted n context
528 let more_to_be_restricted', term' =
529 force_does_not_occur subst restricted term
531 let subst' = (n, (context', term')) :: subst in
532 let more = more @ more_to_be_restricted @ more_to_be_restricted' in
535 raise (MetaSubstFailure (sprintf
536 "Cannot restrict the context of the metavariable ?%d over the hypotheses %s since ?%d is already instantiated with %s and at least one of the hypotheses occurs in the substituted term"
537 n (names_of_context_indexes context to_be_restricted) n
538 (ppterm subst term)))))
541 match more_to_be_restricted @ more_to_be_restricted' with
542 | [] -> (metasenv, subst)
543 | l -> restrict subst l metasenv
546 (*CSC: maybe we should rename delift in abstract, as I did in my dissertation *)
547 let delift n subst context metasenv l t =
548 let module S = CicSubstitution in
550 let (_, canonical_context, _) = CicUtil.lookup_meta n metasenv in
551 List.map2 (fun ct lt ->
557 let to_be_restricted = ref [] in
558 let rec deliftaux k =
559 let module C = Cic in
563 C.Rel m (*CSC: che succede se c'e' un Def? Dovrebbe averlo gia' *)
564 (*CSC: deliftato la regola per il LetIn *)
565 (*CSC: FALSO! La regola per il LetIn non lo fa *)
568 match List.nth context (m-k-1) with
569 Some (_,C.Def (t,_)) ->
570 (*CSC: Hmmm. This bit of reduction is not in the spirit of *)
571 (*CSC: first order unification. Does it help or does it harm? *)
572 deliftaux k (S.lift m t)
573 | Some (_,C.Decl t) ->
574 C.Rel ((position (m-k) l) + k)
575 | None -> raise (MetaSubstFailure "RelToHiddenHypothesis")
578 raise (MetaSubstFailure "Unbound variable found in deliftaux")
580 | C.Var (uri,exp_named_subst) ->
581 let exp_named_subst' =
582 List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
584 C.Var (uri,exp_named_subst')
585 | C.Meta (i, l1) as t ->
587 raise (MetaSubstFailure (sprintf
588 "Cannot unify the metavariable ?%d with a term that has as subterm %s in which the same metavariable occurs (occur check)"
591 (* I do not consider the term associated to ?i in subst since *)
592 (* in this way I can restrict if something goes wrong. *)
596 | None::tl -> None::(deliftl (j+1) tl)
598 let l1' = (deliftl (j+1) tl) in
600 Some (deliftaux k t)::l1'
603 | MetaSubstFailure _ ->
604 to_be_restricted := (i,j)::!to_be_restricted ; None::l1'
606 let l' = deliftl 1 l1 in
609 | C.Implicit _ as t -> t
610 | C.Cast (te,ty) -> C.Cast (deliftaux k te, deliftaux k ty)
611 | C.Prod (n,s,t) -> C.Prod (n, deliftaux k s, deliftaux (k+1) t)
612 | C.Lambda (n,s,t) -> C.Lambda (n, deliftaux k s, deliftaux (k+1) t)
613 | C.LetIn (n,s,t) -> C.LetIn (n, deliftaux k s, deliftaux (k+1) t)
614 | C.Appl l -> C.Appl (List.map (deliftaux k) l)
615 | C.Const (uri,exp_named_subst) ->
616 let exp_named_subst' =
617 List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
619 C.Const (uri,exp_named_subst')
620 | C.MutInd (uri,typeno,exp_named_subst) ->
621 let exp_named_subst' =
622 List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
624 C.MutInd (uri,typeno,exp_named_subst')
625 | C.MutConstruct (uri,typeno,consno,exp_named_subst) ->
626 let exp_named_subst' =
627 List.map (function (uri,t) -> uri,deliftaux k t) exp_named_subst
629 C.MutConstruct (uri,typeno,consno,exp_named_subst')
630 | C.MutCase (sp,i,outty,t,pl) ->
631 C.MutCase (sp, i, deliftaux k outty, deliftaux k t,
632 List.map (deliftaux k) pl)
634 let len = List.length fl in
637 (fun (name, i, ty, bo) ->
638 (name, i, deliftaux k ty, deliftaux (k+len) bo))
643 let len = List.length fl in
646 (fun (name, ty, bo) -> (name, deliftaux k ty, deliftaux (k+len) bo))
649 C.CoFix (i, liftedfl)
656 (* This is the case where we fail even first order unification. *)
657 (* The reason is that our delift function is weaker than first *)
658 (* order (in the sense of alpha-conversion). See comment above *)
659 (* related to the delift function. *)
660 debug_print "\n!!!!!!!!!!! First Order UnificationFailure, but maybe it could have been successful even in a first order setting (no conversion, only alpha convertibility)! Please, implement a better delift function !!!!!!!!!!!!!!!!" ;
661 raise (Uncertain (sprintf
662 "Error trying to abstract %s over [%s]: the algorithm only tried to abstract over bound variables"
666 (function Some t -> ppterm subst t | None -> "_")
669 let (metasenv, subst) = restrict subst !to_be_restricted metasenv in
673 (**** END OF DELIFT ****)
676 (** {2 Format-like pretty printers} *)
679 Format.pp_print_string ppf s;
680 Format.pp_print_newline ppf ();
681 Format.pp_print_flush ppf ()
683 let fppsubst ppf subst = fpp_gen ppf (ppsubst subst)
684 let fppterm ppf term = fpp_gen ppf (CicPp.ppterm term)
685 let fppmetasenv ppf metasenv = fpp_gen ppf (ppmetasenv metasenv [])