src/Pure/proofterm.ML
author haftmann
Fri Apr 13 16:40:16 2007 +0200 (2007-04-13)
changeset 22662 3e492ba59355
parent 21646 c07b5b0e8492
child 22846 fb79144af9a3
permissions -rw-r--r--
canonical merge operations
     1 (*  Title:      Pure/proofterm.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4 
     5 LF style proof terms.
     6 *)
     7 
     8 infix 8 % %% %>;
     9 
    10 signature BASIC_PROOFTERM =
    11 sig
    12   val proofs: int ref
    13 
    14   datatype proof =
    15      PBound of int
    16    | Abst of string * typ option * proof
    17    | AbsP of string * term option * proof
    18    | % of proof * term option
    19    | %% of proof * proof
    20    | Hyp of term
    21    | PThm of string * proof * term * typ list option
    22    | PAxm of string * term * typ list option
    23    | Oracle of string * term * typ list option
    24    | MinProof of ((string * term) * proof) list * (string * term) list * (string * term) list;
    25 
    26   val %> : proof * term -> proof
    27 end;
    28 
    29 signature PROOFTERM =
    30 sig
    31   include BASIC_PROOFTERM
    32 
    33   val infer_derivs : (proof -> proof -> proof) -> bool * proof -> bool * proof -> bool * proof
    34   val infer_derivs' : (proof -> proof) -> (bool * proof -> bool * proof)
    35 
    36   (** primitive operations **)
    37   val proof_combt : proof * term list -> proof
    38   val proof_combt' : proof * term option list -> proof
    39   val proof_combP : proof * proof list -> proof
    40   val strip_combt : proof -> proof * term option list
    41   val strip_combP : proof -> proof * proof list
    42   val strip_thm : proof -> proof
    43   val map_proof_terms_option : (term -> term option) -> (typ -> typ option) -> proof -> proof
    44   val map_proof_terms : (term -> term) -> (typ -> typ) -> proof -> proof
    45   val fold_proof_terms : (term -> 'a -> 'a) -> (typ -> 'a -> 'a) -> proof -> 'a -> 'a
    46   val maxidx_proof : proof -> int -> int
    47   val size_of_proof : proof -> int
    48   val change_type : typ list option -> proof -> proof
    49   val prf_abstract_over : term -> proof -> proof
    50   val prf_incr_bv : int -> int -> int -> int -> proof -> proof
    51   val incr_pboundvars : int -> int -> proof -> proof
    52   val prf_loose_bvar1 : proof -> int -> bool
    53   val prf_loose_Pbvar1 : proof -> int -> bool
    54   val prf_add_loose_bnos : int -> int -> proof ->
    55     int list * int list -> int list * int list
    56   val norm_proof : Envir.env -> proof -> proof
    57   val norm_proof' : Envir.env -> proof -> proof
    58   val prf_subst_bounds : term list -> proof -> proof
    59   val prf_subst_pbounds : proof list -> proof -> proof
    60   val freeze_thaw_prf : proof -> proof * (proof -> proof)
    61   val proof_of_min_axm : string * term -> proof
    62   val proof_of_min_thm : (string * term) * proof -> proof
    63 
    64   val thms_of_proof : proof -> (term * proof) list Symtab.table ->
    65     (term * proof) list Symtab.table
    66   val thms_of_proof' : proof -> (term * proof) list Symtab.table ->
    67     (term * proof) list Symtab.table
    68   val axms_of_proof : proof -> proof Symtab.table -> proof Symtab.table
    69   val oracles_of_proof : (string * term) list -> proof -> (string * term) list
    70 
    71   (** proof terms for specific inference rules **)
    72   val implies_intr_proof : term -> proof -> proof
    73   val forall_intr_proof : term -> string -> proof -> proof
    74   val varify_proof : term -> (string * sort) list -> proof -> proof
    75   val freezeT : term -> proof -> proof
    76   val rotate_proof : term list -> term -> int -> proof -> proof
    77   val permute_prems_prf : term list -> int -> int -> proof -> proof
    78   val generalize: string list * string list -> int -> proof -> proof
    79   val instantiate : ((indexname * sort) * typ) list * ((indexname * typ) * term) list
    80     -> proof -> proof
    81   val lift_proof : term -> int -> term -> proof -> proof
    82   val assumption_proof : term list -> term -> int -> proof -> proof
    83   val bicompose_proof : bool -> term list -> term list -> term list -> term option ->
    84     int -> proof -> proof -> proof
    85   val equality_axms : (string * term) list
    86   val reflexive_axm : proof
    87   val symmetric_axm : proof
    88   val transitive_axm : proof
    89   val equal_intr_axm : proof
    90   val equal_elim_axm : proof
    91   val abstract_rule_axm : proof
    92   val combination_axm : proof
    93   val reflexive : proof
    94   val symmetric : proof -> proof
    95   val transitive : term -> typ -> proof -> proof -> proof
    96   val abstract_rule : term -> string -> proof -> proof
    97   val combination : term -> term -> term -> term -> typ -> proof -> proof -> proof
    98   val equal_intr : term -> term -> proof -> proof -> proof
    99   val equal_elim : term -> term -> proof -> proof -> proof
   100   val axm_proof : string -> term -> proof
   101   val oracle_proof : string -> term -> proof
   102   val thm_proof : theory -> string -> term list -> term -> proof -> proof
   103   val get_name : term list -> term -> proof -> string
   104 
   105   (** rewriting on proof terms **)
   106   val add_prf_rrule : proof * proof -> theory -> theory
   107   val add_prf_rproc : string * (Term.typ list -> proof -> proof option) ->
   108     theory -> theory
   109   val rewrite_proof : theory -> (proof * proof) list *
   110     (string * (typ list -> proof -> proof option)) list -> proof -> proof
   111   val rewrite_proof_notypes : (proof * proof) list *
   112     (string * (typ list -> proof -> proof option)) list -> proof -> proof
   113   val init_data: theory -> theory
   114 
   115 end
   116 
   117 structure Proofterm : PROOFTERM =
   118 struct
   119 
   120 open Envir;
   121 
   122 datatype proof =
   123    PBound of int
   124  | Abst of string * typ option * proof
   125  | AbsP of string * term option * proof
   126  | op % of proof * term option
   127  | op %% of proof * proof
   128  | Hyp of term
   129  | PThm of string * proof * term * typ list option
   130  | PAxm of string * term * typ list option
   131  | Oracle of string * term * typ list option
   132  | MinProof of ((string * term) * proof) list * (string * term) list * (string * term) list;
   133 
   134 fun proof_of_min_axm (s, prop) = PAxm (s, prop, NONE);
   135 fun proof_of_min_thm ((s, prop), prf) = PThm (s, prf, prop, NONE);
   136 
   137 val string_term_ord = prod_ord fast_string_ord Term.fast_term_ord;
   138 
   139 fun oracles_of_proof oras prf =
   140   let
   141     fun oras_of (Abst (_, _, prf)) = oras_of prf
   142       | oras_of (AbsP (_, _, prf)) = oras_of prf
   143       | oras_of (prf % _) = oras_of prf
   144       | oras_of (prf1 %% prf2) = oras_of prf1 #> oras_of prf2
   145       | oras_of (PThm (name, prf, prop, _)) = (fn tabs as (thms, oras) =>
   146           case Symtab.lookup thms name of
   147             NONE => oras_of prf (Symtab.update (name, [prop]) thms, oras)
   148           | SOME ps => if member (op =) ps prop then tabs else
   149               oras_of prf (Symtab.update (name, prop::ps) thms, oras))
   150       | oras_of (Oracle (s, prop, _)) =
   151           apsnd (OrdList.insert string_term_ord (s, prop))
   152       | oras_of (MinProof (thms, _, oras)) =
   153           apsnd (OrdList.union string_term_ord oras) #>
   154           fold (oras_of o proof_of_min_thm) thms
   155       | oras_of _ = I
   156   in
   157     snd (oras_of prf (Symtab.empty, oras))
   158   end;
   159 
   160 fun thms_of_proof (Abst (_, _, prf)) = thms_of_proof prf
   161   | thms_of_proof (AbsP (_, _, prf)) = thms_of_proof prf
   162   | thms_of_proof (prf1 %% prf2) = thms_of_proof prf1 #> thms_of_proof prf2
   163   | thms_of_proof (prf % _) = thms_of_proof prf
   164   | thms_of_proof (prf' as PThm (s, prf, prop, _)) = (fn tab =>
   165       case Symtab.lookup tab s of
   166         NONE => thms_of_proof prf (Symtab.update (s, [(prop, prf')]) tab)
   167       | SOME ps => if exists (fn (p, _) => p = prop) ps then tab else
   168           thms_of_proof prf (Symtab.update (s, (prop, prf')::ps) tab))
   169   | thms_of_proof (MinProof (prfs, _, _)) = fold (thms_of_proof o proof_of_min_thm) prfs
   170   | thms_of_proof _ = I;
   171 
   172 (* this version does not recursively descend into proofs of (named) theorems *)
   173 fun thms_of_proof' (Abst (_, _, prf)) = thms_of_proof' prf
   174   | thms_of_proof' (AbsP (_, _, prf)) = thms_of_proof' prf
   175   | thms_of_proof' (prf1 %% prf2) = thms_of_proof' prf1 #> thms_of_proof' prf2
   176   | thms_of_proof' (prf % _) = thms_of_proof' prf
   177   | thms_of_proof' (PThm ("", prf, prop, _)) = thms_of_proof' prf
   178   | thms_of_proof' (prf' as PThm (s, _, prop, _)) = (fn tab =>
   179       case Symtab.lookup tab s of
   180         NONE => Symtab.update (s, [(prop, prf')]) tab
   181       | SOME ps => if exists (fn (p, _) => p = prop) ps then tab else
   182           Symtab.update (s, (prop, prf')::ps) tab)
   183   | thms_of_proof' (MinProof (prfs, _, _)) = fold (thms_of_proof' o proof_of_min_thm) prfs
   184   | thms_of_proof' _ = I;
   185 
   186 fun axms_of_proof (Abst (_, _, prf)) = axms_of_proof prf
   187   | axms_of_proof (AbsP (_, _, prf)) = axms_of_proof prf
   188   | axms_of_proof (prf1 %% prf2) = axms_of_proof prf1 #> axms_of_proof prf2
   189   | axms_of_proof (prf % _) = axms_of_proof prf
   190   | axms_of_proof (prf as PAxm (s, _, _)) = Symtab.update (s, prf)
   191   | axms_of_proof (MinProof (_, prfs, _)) = fold (axms_of_proof o proof_of_min_axm) prfs
   192   | axms_of_proof _ = I;
   193 
   194 (** collect all theorems, axioms and oracles **)
   195 
   196 fun map3 f g h (thms, axms, oras) = (f thms, g axms, h oras);
   197 
   198 fun mk_min_proof (Abst (_, _, prf)) = mk_min_proof prf
   199   | mk_min_proof (AbsP (_, _, prf)) = mk_min_proof prf
   200   | mk_min_proof (prf % _) = mk_min_proof prf
   201   | mk_min_proof (prf1 %% prf2) = mk_min_proof prf1 #> mk_min_proof prf2
   202   | mk_min_proof (PThm (s, prf, prop, _)) =
   203       map3 (OrdList.insert (string_term_ord o pairself fst) ((s, prop), prf)) I I
   204   | mk_min_proof (PAxm (s, prop, _)) =
   205       map3 I (OrdList.insert string_term_ord (s, prop)) I
   206   | mk_min_proof (Oracle (s, prop, _)) =
   207       map3 I I (OrdList.insert string_term_ord (s, prop))
   208   | mk_min_proof (MinProof (thms, axms, oras)) =
   209       map3 (OrdList.union (string_term_ord o pairself fst) thms)
   210         (OrdList.union string_term_ord axms) (OrdList.union string_term_ord oras)
   211   | mk_min_proof _ = I;
   212 
   213 (** proof objects with different levels of detail **)
   214 
   215 val proofs = ref 2;
   216 
   217 fun err_illegal_level i =
   218   error ("Illegal level of detail for proof objects: " ^ string_of_int i);
   219 
   220 fun if_ora b = if b then oracles_of_proof else K;
   221 val min_proof = MinProof ([], [], []);
   222 
   223 fun infer_derivs f (ora1, prf1) (ora2, prf2) =
   224   let val ora = ora1 orelse ora2 in
   225     (ora,
   226       case !proofs of
   227         2 => f prf1 prf2
   228       | 1 => MinProof (([], [], []) |> mk_min_proof prf1 |> mk_min_proof prf2)
   229       | 0 => if ora then MinProof ([], [], if_ora ora2 (if_ora ora1 [] prf1) prf2) else min_proof
   230       | i => err_illegal_level i)
   231   end;
   232 
   233 fun infer_derivs' f = infer_derivs (K f) (false, min_proof);
   234 
   235 fun (prf %> t) = prf % SOME t;
   236 
   237 val proof_combt = Library.foldl (op %>);
   238 val proof_combt' = Library.foldl (op %);
   239 val proof_combP = Library.foldl (op %%);
   240 
   241 fun strip_combt prf =
   242     let fun stripc (prf % t, ts) = stripc (prf, t::ts)
   243           | stripc  x =  x
   244     in  stripc (prf, [])  end;
   245 
   246 fun strip_combP prf =
   247     let fun stripc (prf %% prf', prfs) = stripc (prf, prf'::prfs)
   248           | stripc  x =  x
   249     in  stripc (prf, [])  end;
   250 
   251 fun strip_thm prf = (case strip_combt (fst (strip_combP prf)) of
   252       (PThm (_, prf', _, _), _) => prf'
   253     | _ => prf);
   254 
   255 val mk_Abst = foldr (fn ((s, T:typ), prf) => Abst (s, NONE, prf));
   256 fun mk_AbsP (i, prf) = funpow i (fn prf => AbsP ("H", NONE, prf)) prf;
   257 
   258 fun apsome f NONE = raise SAME
   259   | apsome f (SOME x) = (case f x of NONE => raise SAME | some => some);
   260 
   261 fun apsome' f NONE = raise SAME
   262   | apsome' f (SOME x) = SOME (f x);
   263 
   264 fun map_proof_terms_option f g =
   265   let
   266     fun map_typs (T :: Ts) =
   267           (case g T of
   268             NONE => T :: map_typs Ts
   269           | SOME T' => T' :: (map_typs Ts handle SAME => Ts))
   270       | map_typs [] = raise SAME;
   271 
   272     fun mapp (Abst (s, T, prf)) = (Abst (s, apsome g T, mapph prf)
   273           handle SAME => Abst (s, T, mapp prf))
   274       | mapp (AbsP (s, t, prf)) = (AbsP (s, apsome f t, mapph prf)
   275           handle SAME => AbsP (s, t, mapp prf))
   276       | mapp (prf % t) = (mapp prf % (apsome f t handle SAME => t)
   277           handle SAME => prf % apsome f t)
   278       | mapp (prf1 %% prf2) = (mapp prf1 %% mapph prf2
   279           handle SAME => prf1 %% mapp prf2)
   280       | mapp (PThm (a, prf, prop, SOME Ts)) =
   281           PThm (a, prf, prop, SOME (map_typs Ts))
   282       | mapp (PAxm (a, prop, SOME Ts)) =
   283           PAxm (a, prop, SOME (map_typs Ts))
   284       | mapp _ = raise SAME
   285     and mapph prf = (mapp prf handle SAME => prf)
   286 
   287   in mapph end;
   288 
   289 fun same eq f x =
   290   let val x' = f x
   291   in if eq (x, x') then raise SAME else x' end;
   292 
   293 fun map_proof_terms f g =
   294   map_proof_terms_option
   295    (fn t => SOME (same (op =) f t) handle SAME => NONE)
   296    (fn T => SOME (same (op =) g T) handle SAME => NONE);
   297 
   298 fun fold_proof_terms f g (Abst (_, SOME T, prf)) = g T #> fold_proof_terms f g prf
   299   | fold_proof_terms f g (Abst (_, NONE, prf)) = fold_proof_terms f g prf
   300   | fold_proof_terms f g (AbsP (_, SOME t, prf)) = f t #> fold_proof_terms f g prf
   301   | fold_proof_terms f g (AbsP (_, NONE, prf)) = fold_proof_terms f g prf
   302   | fold_proof_terms f g (prf % SOME t) = fold_proof_terms f g prf #> f t
   303   | fold_proof_terms f g (prf % NONE) = fold_proof_terms f g prf
   304   | fold_proof_terms f g (prf1 %% prf2) =
   305       fold_proof_terms f g prf1 #> fold_proof_terms f g prf2
   306   | fold_proof_terms _ g (PThm (_, _, _, SOME Ts)) = fold g Ts
   307   | fold_proof_terms _ g (PAxm (_, _, SOME Ts)) = fold g Ts
   308   | fold_proof_terms _ _ _ = I;
   309 
   310 fun maxidx_proof prf = fold_proof_terms Term.maxidx_term Term.maxidx_typ prf;
   311 
   312 fun size_of_proof (Abst (_, _, prf)) = 1 + size_of_proof prf
   313   | size_of_proof (AbsP (_, t, prf)) = 1 + size_of_proof prf
   314   | size_of_proof (prf1 %% prf2) = size_of_proof prf1 + size_of_proof prf2
   315   | size_of_proof (prf % _) = 1 + size_of_proof prf
   316   | size_of_proof _ = 1;
   317 
   318 fun change_type opTs (PThm (name, prf, prop, _)) = PThm (name, prf, prop, opTs)
   319   | change_type opTs (PAxm (name, prop, _)) = PAxm (name, prop, opTs)
   320   | change_type opTs (Oracle (name, prop, _)) = Oracle (name, prop, opTs)
   321   | change_type _ prf = prf;
   322 
   323 
   324 (***** utilities *****)
   325 
   326 fun strip_abs (_::Ts) (Abs (_, _, t)) = strip_abs Ts t
   327   | strip_abs _ t = t;
   328 
   329 fun mk_abs Ts t = Library.foldl (fn (t', T) => Abs ("", T, t')) (t, Ts);
   330 
   331 
   332 (*Abstraction of a proof term over its occurrences of v,
   333     which must contain no loose bound variables.
   334   The resulting proof term is ready to become the body of an Abst.*)
   335 
   336 fun prf_abstract_over v =
   337   let
   338     fun abst' lev u = if v aconv u then Bound lev else
   339       (case u of
   340          Abs (a, T, t) => Abs (a, T, abst' (lev + 1) t)
   341        | f $ t => (abst' lev f $ absth' lev t handle SAME => f $ abst' lev t)
   342        | _ => raise SAME)
   343     and absth' lev t = (abst' lev t handle SAME => t);
   344 
   345     fun abst lev (AbsP (a, t, prf)) =
   346           (AbsP (a, apsome' (abst' lev) t, absth lev prf)
   347            handle SAME => AbsP (a, t, abst lev prf))
   348       | abst lev (Abst (a, T, prf)) = Abst (a, T, abst (lev + 1) prf)
   349       | abst lev (prf1 %% prf2) = (abst lev prf1 %% absth lev prf2
   350           handle SAME => prf1 %% abst lev prf2)
   351       | abst lev (prf % t) = (abst lev prf % Option.map (absth' lev) t
   352           handle SAME => prf % apsome' (abst' lev) t)
   353       | abst _ _ = raise SAME
   354     and absth lev prf = (abst lev prf handle SAME => prf)
   355 
   356   in absth 0 end;
   357 
   358 
   359 (*increments a proof term's non-local bound variables
   360   required when moving a proof term within abstractions
   361      inc is  increment for bound variables
   362      lev is  level at which a bound variable is considered 'loose'*)
   363 
   364 fun incr_bv' inct tlev t = incr_bv (inct, tlev, t);
   365 
   366 fun prf_incr_bv' incP inct Plev tlev (PBound i) =
   367       if i >= Plev then PBound (i+incP) else raise SAME
   368   | prf_incr_bv' incP inct Plev tlev (AbsP (a, t, body)) =
   369       (AbsP (a, apsome' (same (op =) (incr_bv' inct tlev)) t,
   370          prf_incr_bv incP inct (Plev+1) tlev body) handle SAME =>
   371            AbsP (a, t, prf_incr_bv' incP inct (Plev+1) tlev body))
   372   | prf_incr_bv' incP inct Plev tlev (Abst (a, T, body)) =
   373       Abst (a, T, prf_incr_bv' incP inct Plev (tlev+1) body)
   374   | prf_incr_bv' incP inct Plev tlev (prf %% prf') =
   375       (prf_incr_bv' incP inct Plev tlev prf %% prf_incr_bv incP inct Plev tlev prf'
   376        handle SAME => prf %% prf_incr_bv' incP inct Plev tlev prf')
   377   | prf_incr_bv' incP inct Plev tlev (prf % t) =
   378       (prf_incr_bv' incP inct Plev tlev prf % Option.map (incr_bv' inct tlev) t
   379        handle SAME => prf % apsome' (same (op =) (incr_bv' inct tlev)) t)
   380   | prf_incr_bv' _ _ _ _ _ = raise SAME
   381 and prf_incr_bv incP inct Plev tlev prf =
   382       (prf_incr_bv' incP inct Plev tlev prf handle SAME => prf);
   383 
   384 fun incr_pboundvars  0 0 prf = prf
   385   | incr_pboundvars incP inct prf = prf_incr_bv incP inct 0 0 prf;
   386 
   387 
   388 fun prf_loose_bvar1 (prf1 %% prf2) k = prf_loose_bvar1 prf1 k orelse prf_loose_bvar1 prf2 k
   389   | prf_loose_bvar1 (prf % SOME t) k = prf_loose_bvar1 prf k orelse loose_bvar1 (t, k)
   390   | prf_loose_bvar1 (_ % NONE) _ = true
   391   | prf_loose_bvar1 (AbsP (_, SOME t, prf)) k = loose_bvar1 (t, k) orelse prf_loose_bvar1 prf k
   392   | prf_loose_bvar1 (AbsP (_, NONE, _)) k = true
   393   | prf_loose_bvar1 (Abst (_, _, prf)) k = prf_loose_bvar1 prf (k+1)
   394   | prf_loose_bvar1 _ _ = false;
   395 
   396 fun prf_loose_Pbvar1 (PBound i) k = i = k
   397   | prf_loose_Pbvar1 (prf1 %% prf2) k = prf_loose_Pbvar1 prf1 k orelse prf_loose_Pbvar1 prf2 k
   398   | prf_loose_Pbvar1 (prf % _) k = prf_loose_Pbvar1 prf k
   399   | prf_loose_Pbvar1 (AbsP (_, _, prf)) k = prf_loose_Pbvar1 prf (k+1)
   400   | prf_loose_Pbvar1 (Abst (_, _, prf)) k = prf_loose_Pbvar1 prf k
   401   | prf_loose_Pbvar1 _ _ = false;
   402 
   403 fun prf_add_loose_bnos plev tlev (PBound i) (is, js) =
   404       if i < plev then (is, js) else (insert (op =) (i-plev) is, js)
   405   | prf_add_loose_bnos plev tlev (prf1 %% prf2) p =
   406       prf_add_loose_bnos plev tlev prf2
   407         (prf_add_loose_bnos plev tlev prf1 p)
   408   | prf_add_loose_bnos plev tlev (prf % opt) (is, js) =
   409       prf_add_loose_bnos plev tlev prf (case opt of
   410           NONE => (is, insert (op =) ~1 js)
   411         | SOME t => (is, add_loose_bnos (t, tlev, js)))
   412   | prf_add_loose_bnos plev tlev (AbsP (_, opt, prf)) (is, js) =
   413       prf_add_loose_bnos (plev+1) tlev prf (case opt of
   414           NONE => (is, insert (op =) ~1 js)
   415         | SOME t => (is, add_loose_bnos (t, tlev, js)))
   416   | prf_add_loose_bnos plev tlev (Abst (_, _, prf)) p =
   417       prf_add_loose_bnos plev (tlev+1) prf p
   418   | prf_add_loose_bnos _ _ _ _ = ([], []);
   419 
   420 
   421 (**** substitutions ****)
   422 
   423 fun del_conflicting_tvars envT T = TermSubst.instantiateT
   424   (map_filter (fn ixnS as (_, S) =>
   425      (Type.lookup (envT, ixnS); NONE) handle TYPE _ =>
   426         SOME (ixnS, TFree ("'dummy", S))) (typ_tvars T)) T;
   427 
   428 fun del_conflicting_vars env t = TermSubst.instantiate
   429   (map_filter (fn ixnS as (_, S) =>
   430      (Type.lookup (type_env env, ixnS); NONE) handle TYPE _ =>
   431         SOME (ixnS, TFree ("'dummy", S))) (term_tvars t),
   432    map_filter (fn Var (ixnT as (_, T)) =>
   433      (Envir.lookup (env, ixnT); NONE) handle TYPE _ =>
   434         SOME (ixnT, Free ("dummy", T))) (term_vars t)) t;
   435 
   436 fun norm_proof env =
   437   let
   438     val envT = type_env env;
   439     fun msg s = warning ("type conflict in norm_proof:\n" ^ s);
   440     fun htype f t = f env t handle TYPE (s, _, _) =>
   441       (msg s; f env (del_conflicting_vars env t));
   442     fun htypeT f T = f envT T handle TYPE (s, _, _) =>
   443       (msg s; f envT (del_conflicting_tvars envT T));
   444     fun htypeTs f Ts = f envT Ts handle TYPE (s, _, _) =>
   445       (msg s; f envT (map (del_conflicting_tvars envT) Ts));
   446     fun norm (Abst (s, T, prf)) = (Abst (s, apsome' (htypeT norm_type_same) T, normh prf)
   447           handle SAME => Abst (s, T, norm prf))
   448       | norm (AbsP (s, t, prf)) = (AbsP (s, apsome' (htype norm_term_same) t, normh prf)
   449           handle SAME => AbsP (s, t, norm prf))
   450       | norm (prf % t) = (norm prf % Option.map (htype norm_term) t
   451           handle SAME => prf % apsome' (htype norm_term_same) t)
   452       | norm (prf1 %% prf2) = (norm prf1 %% normh prf2
   453           handle SAME => prf1 %% norm prf2)
   454       | norm (PThm (s, prf, t, Ts)) = PThm (s, prf, t, apsome' (htypeTs norm_types_same) Ts)
   455       | norm (PAxm (s, prop, Ts)) = PAxm (s, prop, apsome' (htypeTs norm_types_same) Ts)
   456       | norm _ = raise SAME
   457     and normh prf = (norm prf handle SAME => prf);
   458   in normh end;
   459 
   460 (***** Remove some types in proof term (to save space) *****)
   461 
   462 fun remove_types (Abs (s, _, t)) = Abs (s, dummyT, remove_types t)
   463   | remove_types (t $ u) = remove_types t $ remove_types u
   464   | remove_types (Const (s, _)) = Const (s, dummyT)
   465   | remove_types t = t;
   466 
   467 fun remove_types_env (Envir.Envir {iTs, asol, maxidx}) =
   468   Envir.Envir {iTs = iTs, asol = Vartab.map (apsnd remove_types) asol,
   469     maxidx = maxidx};
   470 
   471 fun norm_proof' env prf = norm_proof (remove_types_env env) prf;
   472 
   473 (**** substitution of bound variables ****)
   474 
   475 fun prf_subst_bounds args prf =
   476   let
   477     val n = length args;
   478     fun subst' lev (Bound i) =
   479          (if i<lev then raise SAME    (*var is locally bound*)
   480           else  incr_boundvars lev (List.nth (args, i-lev))
   481                   handle Subscript => Bound (i-n)  (*loose: change it*))
   482       | subst' lev (Abs (a, T, body)) = Abs (a, T,  subst' (lev+1) body)
   483       | subst' lev (f $ t) = (subst' lev f $ substh' lev t
   484           handle SAME => f $ subst' lev t)
   485       | subst' _ _ = raise SAME
   486     and substh' lev t = (subst' lev t handle SAME => t);
   487 
   488     fun subst lev (AbsP (a, t, body)) = (AbsP (a, apsome' (subst' lev) t, substh lev body)
   489           handle SAME => AbsP (a, t, subst lev body))
   490       | subst lev (Abst (a, T, body)) = Abst (a, T, subst (lev+1) body)
   491       | subst lev (prf %% prf') = (subst lev prf %% substh lev prf'
   492           handle SAME => prf %% subst lev prf')
   493       | subst lev (prf % t) = (subst lev prf % Option.map (substh' lev) t
   494           handle SAME => prf % apsome' (subst' lev) t)
   495       | subst _ _ = raise SAME
   496     and substh lev prf = (subst lev prf handle SAME => prf)
   497   in case args of [] => prf | _ => substh 0 prf end;
   498 
   499 fun prf_subst_pbounds args prf =
   500   let
   501     val n = length args;
   502     fun subst (PBound i) Plev tlev =
   503          (if i < Plev then raise SAME    (*var is locally bound*)
   504           else incr_pboundvars Plev tlev (List.nth (args, i-Plev))
   505                  handle Subscript => PBound (i-n)  (*loose: change it*))
   506       | subst (AbsP (a, t, body)) Plev tlev = AbsP (a, t, subst body (Plev+1) tlev)
   507       | subst (Abst (a, T, body)) Plev tlev = Abst (a, T, subst body Plev (tlev+1))
   508       | subst (prf %% prf') Plev tlev = (subst prf Plev tlev %% substh prf' Plev tlev
   509           handle SAME => prf %% subst prf' Plev tlev)
   510       | subst (prf % t) Plev tlev = subst prf Plev tlev % t
   511       | subst  prf _ _ = raise SAME
   512     and substh prf Plev tlev = (subst prf Plev tlev handle SAME => prf)
   513   in case args of [] => prf | _ => substh prf 0 0 end;
   514 
   515 
   516 (**** Freezing and thawing of variables in proof terms ****)
   517 
   518 fun frzT names =
   519   map_type_tvar (fn (ixn, xs) => TFree ((the o AList.lookup (op =) names) ixn, xs));
   520 
   521 fun thawT names =
   522   map_type_tfree (fn (s, xs) => case AList.lookup (op =) names s of
   523       NONE => TFree (s, xs)
   524     | SOME ixn => TVar (ixn, xs));
   525 
   526 fun freeze names names' (t $ u) =
   527       freeze names names' t $ freeze names names' u
   528   | freeze names names' (Abs (s, T, t)) =
   529       Abs (s, frzT names' T, freeze names names' t)
   530   | freeze names names' (Const (s, T)) = Const (s, frzT names' T)
   531   | freeze names names' (Free (s, T)) = Free (s, frzT names' T)
   532   | freeze names names' (Var (ixn, T)) =
   533       Free ((the o AList.lookup (op =) names) ixn, frzT names' T)
   534   | freeze names names' t = t;
   535 
   536 fun thaw names names' (t $ u) =
   537       thaw names names' t $ thaw names names' u
   538   | thaw names names' (Abs (s, T, t)) =
   539       Abs (s, thawT names' T, thaw names names' t)
   540   | thaw names names' (Const (s, T)) = Const (s, thawT names' T)
   541   | thaw names names' (Free (s, T)) =
   542       let val T' = thawT names' T
   543       in case AList.lookup (op =) names s of
   544           NONE => Free (s, T')
   545         | SOME ixn => Var (ixn, T')
   546       end
   547   | thaw names names' (Var (ixn, T)) = Var (ixn, thawT names' T)
   548   | thaw names names' t = t;
   549 
   550 fun freeze_thaw_prf prf =
   551   let
   552     val (fs, Tfs, vs, Tvs) = fold_proof_terms
   553       (fn t => fn (fs, Tfs, vs, Tvs) =>
   554          (add_term_frees (t, fs), add_term_tfree_names (t, Tfs),
   555           add_term_vars (t, vs), add_term_tvar_ixns (t, Tvs)))
   556       (fn T => fn (fs, Tfs, vs, Tvs) =>
   557          (fs, add_typ_tfree_names (T, Tfs),
   558           vs, add_typ_ixns (Tvs, T)))
   559       prf ([], [], [], []);
   560     val fs' = map (fst o dest_Free) fs;
   561     val vs' = map (fst o dest_Var) vs;
   562     val names = vs' ~~ Name.variant_list fs' (map fst vs');
   563     val names' = Tvs ~~ Name.variant_list Tfs (map fst Tvs);
   564     val rnames = map swap names;
   565     val rnames' = map swap names';
   566   in
   567     (map_proof_terms (freeze names names') (frzT names') prf,
   568      map_proof_terms (thaw rnames rnames') (thawT rnames'))
   569   end;
   570 
   571 
   572 (***** implication introduction *****)
   573 
   574 fun implies_intr_proof h prf =
   575   let
   576     fun abshyp i (Hyp t) = if h aconv t then PBound i else raise SAME
   577       | abshyp i (Abst (s, T, prf)) = Abst (s, T, abshyp i prf)
   578       | abshyp i (AbsP (s, t, prf)) = AbsP (s, t, abshyp (i+1) prf)
   579       | abshyp i (prf % t) = abshyp i prf % t
   580       | abshyp i (prf1 %% prf2) = (abshyp i prf1 %% abshyph i prf2
   581           handle SAME => prf1 %% abshyp i prf2)
   582       | abshyp _ _ = raise SAME
   583     and abshyph i prf = (abshyp i prf handle SAME => prf)
   584   in
   585     AbsP ("H", NONE (*h*), abshyph 0 prf)
   586   end;
   587 
   588 
   589 (***** forall introduction *****)
   590 
   591 fun forall_intr_proof x a prf = Abst (a, NONE, prf_abstract_over x prf);
   592 
   593 
   594 (***** varify *****)
   595 
   596 fun varify_proof t fixed prf =
   597   let
   598     val fs = Term.fold_types (Term.fold_atyps
   599       (fn TFree v => if member (op =) fixed v then I else insert (op =) v | _ => I)) t [];
   600     val ixns = add_term_tvar_ixns (t, []);
   601     val fmap = fs ~~ Name.variant_list (map #1 ixns) (map fst fs)
   602     fun thaw (f as (a, S)) =
   603       (case AList.lookup (op =) fmap f of
   604         NONE => TFree f
   605       | SOME b => TVar ((b, 0), S));
   606   in map_proof_terms (map_types (map_type_tfree thaw)) (map_type_tfree thaw) prf
   607   end;
   608 
   609 
   610 local
   611 
   612 fun new_name (ix, (pairs,used)) =
   613   let val v = Name.variant used (string_of_indexname ix)
   614   in  ((ix, v) :: pairs, v :: used)  end;
   615 
   616 fun freeze_one alist (ix, sort) = (case AList.lookup (op =) alist ix of
   617     NONE => TVar (ix, sort)
   618   | SOME name => TFree (name, sort));
   619 
   620 in
   621 
   622 fun freezeT t prf =
   623   let
   624     val used = it_term_types add_typ_tfree_names (t, [])
   625     and tvars = map #1 (it_term_types add_typ_tvars (t, []));
   626     val (alist, _) = foldr new_name ([], used) tvars;
   627   in
   628     (case alist of
   629       [] => prf (*nothing to do!*)
   630     | _ =>
   631       let val frzT = map_type_tvar (freeze_one alist)
   632       in map_proof_terms (map_types frzT) frzT prf end)
   633   end;
   634 
   635 end;
   636 
   637 
   638 (***** rotate assumptions *****)
   639 
   640 fun rotate_proof Bs Bi m prf =
   641   let
   642     val params = Term.strip_all_vars Bi;
   643     val asms = Logic.strip_imp_prems (Term.strip_all_body Bi);
   644     val i = length asms;
   645     val j = length Bs;
   646   in
   647     mk_AbsP (j+1, proof_combP (prf, map PBound
   648       (j downto 1) @ [mk_Abst (mk_AbsP (i,
   649         proof_combP (proof_combt (PBound i, map Bound ((length params - 1) downto 0)),
   650           map PBound (((i-m-1) downto 0) @ ((i-1) downto (i-m)))))) params]))
   651   end;
   652 
   653 
   654 (***** permute premises *****)
   655 
   656 fun permute_prems_prf prems j k prf =
   657   let val n = length prems
   658   in mk_AbsP (n, proof_combP (prf,
   659     map PBound ((n-1 downto n-j) @ (k-1 downto 0) @ (n-j-1 downto k))))
   660   end;
   661 
   662 
   663 (***** generalization *****)
   664 
   665 fun generalize (tfrees, frees) idx =
   666   map_proof_terms_option
   667     (TermSubst.generalize_option (tfrees, frees) idx)
   668     (TermSubst.generalizeT_option tfrees idx);
   669 
   670 
   671 (***** instantiation *****)
   672 
   673 fun instantiate (instT, inst) =
   674   map_proof_terms_option
   675     (TermSubst.instantiate_option (instT, map (apsnd remove_types) inst))
   676     (TermSubst.instantiateT_option instT);
   677 
   678 
   679 (***** lifting *****)
   680 
   681 fun lift_proof Bi inc prop prf =
   682   let
   683     fun lift'' Us Ts t = strip_abs Ts (Logic.incr_indexes (Us, inc) (mk_abs Ts t));
   684 
   685     fun lift' Us Ts (Abst (s, T, prf)) =
   686           (Abst (s, apsome' (same (op =) (Logic.incr_tvar inc)) T, lifth' Us (dummyT::Ts) prf)
   687            handle SAME => Abst (s, T, lift' Us (dummyT::Ts) prf))
   688       | lift' Us Ts (AbsP (s, t, prf)) =
   689           (AbsP (s, apsome' (same (op =) (lift'' Us Ts)) t, lifth' Us Ts prf)
   690            handle SAME => AbsP (s, t, lift' Us Ts prf))
   691       | lift' Us Ts (prf % t) = (lift' Us Ts prf % Option.map (lift'' Us Ts) t
   692           handle SAME => prf % apsome' (same (op =) (lift'' Us Ts)) t)
   693       | lift' Us Ts (prf1 %% prf2) = (lift' Us Ts prf1 %% lifth' Us Ts prf2
   694           handle SAME => prf1 %% lift' Us Ts prf2)
   695       | lift' _ _ (PThm (s, prf, prop, Ts)) =
   696           PThm (s, prf, prop, apsome' (same (op =) (map (Logic.incr_tvar inc))) Ts)
   697       | lift' _ _ (PAxm (s, prop, Ts)) =
   698           PAxm (s, prop, apsome' (same (op =) (map (Logic.incr_tvar inc))) Ts)
   699       | lift' _ _ _ = raise SAME
   700     and lifth' Us Ts prf = (lift' Us Ts prf handle SAME => prf);
   701 
   702     val ps = map (Logic.lift_all inc Bi) (Logic.strip_imp_prems prop);
   703     val k = length ps;
   704 
   705     fun mk_app (b, (i, j, prf)) =
   706           if b then (i-1, j, prf %% PBound i) else (i, j-1, prf %> Bound j);
   707 
   708     fun lift Us bs i j (Const ("==>", _) $ A $ B) =
   709             AbsP ("H", NONE (*A*), lift Us (true::bs) (i+1) j B)
   710       | lift Us bs i j (Const ("all", _) $ Abs (a, T, t)) =
   711             Abst (a, NONE (*T*), lift (T::Us) (false::bs) i (j+1) t)
   712       | lift Us bs i j _ = proof_combP (lifth' (rev Us) [] prf,
   713             map (fn k => (#3 (foldr mk_app (i-1, j-1, PBound k) bs)))
   714               (i + k - 1 downto i));
   715   in
   716     mk_AbsP (k, lift [] [] 0 0 Bi)
   717   end;
   718 
   719 
   720 (***** proof by assumption *****)
   721 
   722 fun mk_asm_prf (Const ("==>", _) $ A $ B) i = AbsP ("H", NONE (*A*), mk_asm_prf B (i+1))
   723   | mk_asm_prf (Const ("all", _) $ Abs (a, T, t)) i = Abst (a, NONE (*T*), mk_asm_prf t i)
   724   | mk_asm_prf _ i = PBound i;
   725 
   726 fun assumption_proof Bs Bi n prf =
   727   mk_AbsP (length Bs, proof_combP (prf,
   728     map PBound (length Bs - 1 downto 0) @ [mk_asm_prf Bi (~n)]));
   729 
   730 
   731 (***** Composition of object rule with proof state *****)
   732 
   733 fun flatten_params_proof i j n (Const ("==>", _) $ A $ B, k) =
   734       AbsP ("H", NONE (*A*), flatten_params_proof (i+1) j n (B, k))
   735   | flatten_params_proof i j n (Const ("all", _) $ Abs (a, T, t), k) =
   736       Abst (a, NONE (*T*), flatten_params_proof i (j+1) n (t, k))
   737   | flatten_params_proof i j n (_, k) = proof_combP (proof_combt (PBound (k+i),
   738       map Bound (j-1 downto 0)), map PBound (remove (op =) (i-n) (i-1 downto 0)));
   739 
   740 fun bicompose_proof flatten Bs oldAs newAs A n rprf sprf =
   741   let
   742     val la = length newAs;
   743     val lb = length Bs;
   744   in
   745     mk_AbsP (lb+la, proof_combP (sprf,
   746       map PBound (lb + la - 1 downto la)) %%
   747         proof_combP (rprf, (if n>0 then [mk_asm_prf (the A) (~n)] else []) @
   748           map (if flatten then flatten_params_proof 0 0 n else PBound o snd)
   749             (oldAs ~~ (la - 1 downto 0))))
   750   end;
   751 
   752 
   753 (***** axioms for equality *****)
   754 
   755 val aT = TFree ("'a", []);
   756 val bT = TFree ("'b", []);
   757 val x = Free ("x", aT);
   758 val y = Free ("y", aT);
   759 val z = Free ("z", aT);
   760 val A = Free ("A", propT);
   761 val B = Free ("B", propT);
   762 val f = Free ("f", aT --> bT);
   763 val g = Free ("g", aT --> bT);
   764 
   765 local open Logic in
   766 
   767 val equality_axms =
   768   [("reflexive", mk_equals (x, x)),
   769    ("symmetric", mk_implies (mk_equals (x, y), mk_equals (y, x))),
   770    ("transitive", list_implies ([mk_equals (x, y), mk_equals (y, z)], mk_equals (x, z))),
   771    ("equal_intr", list_implies ([mk_implies (A, B), mk_implies (B, A)], mk_equals (A, B))),
   772    ("equal_elim", list_implies ([mk_equals (A, B), A], B)),
   773    ("abstract_rule", Logic.mk_implies
   774       (all aT $ Abs ("x", aT, equals bT $ (f $ Bound 0) $ (g $ Bound 0)),
   775        equals (aT --> bT) $
   776          Abs ("x", aT, f $ Bound 0) $ Abs ("x", aT, g $ Bound 0))),
   777    ("combination", Logic.list_implies
   778       ([Logic.mk_equals (f, g), Logic.mk_equals (x, y)],
   779        Logic.mk_equals (f $ x, g $ y)))];
   780 
   781 val [reflexive_axm, symmetric_axm, transitive_axm, equal_intr_axm,
   782   equal_elim_axm, abstract_rule_axm, combination_axm] =
   783     map (fn (s, t) => PAxm ("ProtoPure." ^ s, varify t, NONE)) equality_axms;
   784 
   785 end;
   786 
   787 val reflexive = reflexive_axm % NONE;
   788 
   789 fun symmetric (prf as PAxm ("ProtoPure.reflexive", _, _) % _) = prf
   790   | symmetric prf = symmetric_axm % NONE % NONE %% prf;
   791 
   792 fun transitive _ _ (PAxm ("ProtoPure.reflexive", _, _) % _) prf2 = prf2
   793   | transitive _ _ prf1 (PAxm ("ProtoPure.reflexive", _, _) % _) = prf1
   794   | transitive u (Type ("prop", [])) prf1 prf2 =
   795       transitive_axm % NONE % SOME (remove_types u) % NONE %% prf1 %% prf2
   796   | transitive u T prf1 prf2 =
   797       transitive_axm % NONE % NONE % NONE %% prf1 %% prf2;
   798 
   799 fun abstract_rule x a prf =
   800   abstract_rule_axm % NONE % NONE %% forall_intr_proof x a prf;
   801 
   802 fun check_comb (PAxm ("ProtoPure.combination", _, _) % f % g % _ % _ %% prf %% _) =
   803       is_some f orelse check_comb prf
   804   | check_comb (PAxm ("ProtoPure.transitive", _, _) % _ % _ % _ %% prf1 %% prf2) =
   805       check_comb prf1 andalso check_comb prf2
   806   | check_comb (PAxm ("ProtoPure.symmetric", _, _) % _ % _ %% prf) = check_comb prf
   807   | check_comb _ = false;
   808 
   809 fun combination f g t u (Type (_, [T, U])) prf1 prf2 =
   810   let
   811     val f = Envir.beta_norm f;
   812     val g = Envir.beta_norm g;
   813     val prf =  if check_comb prf1 then
   814         combination_axm % NONE % NONE
   815       else (case prf1 of
   816           PAxm ("ProtoPure.reflexive", _, _) % _ =>
   817             combination_axm %> remove_types f % NONE
   818         | _ => combination_axm %> remove_types f %> remove_types g)
   819   in
   820     (case T of
   821        Type ("fun", _) => prf %
   822          (case head_of f of
   823             Abs _ => SOME (remove_types t)
   824           | Var _ => SOME (remove_types t)
   825           | _ => NONE) %
   826          (case head_of g of
   827             Abs _ => SOME (remove_types u)
   828           | Var _ => SOME (remove_types u)
   829           | _ => NONE) %% prf1 %% prf2
   830      | _ => prf % NONE % NONE %% prf1 %% prf2)
   831   end;
   832 
   833 fun equal_intr A B prf1 prf2 =
   834   equal_intr_axm %> remove_types A %> remove_types B %% prf1 %% prf2;
   835 
   836 fun equal_elim A B prf1 prf2 =
   837   equal_elim_axm %> remove_types A %> remove_types B %% prf1 %% prf2;
   838 
   839 
   840 (***** axioms and theorems *****)
   841 
   842 fun vars_of t = rev (fold_aterms (fn v as Var _ => insert (op =) v | _ => I) t []);
   843 
   844 fun test_args _ [] = true
   845   | test_args is (Bound i :: ts) =
   846       not (member (op =) is i) andalso test_args (i :: is) ts
   847   | test_args _ _ = false;
   848 
   849 fun is_fun (Type ("fun", _)) = true
   850   | is_fun (TVar _) = true
   851   | is_fun _ = false;
   852 
   853 fun add_funvars Ts (vs, t) =
   854   if is_fun (fastype_of1 (Ts, t)) then
   855     vs union map_filter (fn Var (ixn, T) =>
   856       if is_fun T then SOME ixn else NONE | _ => NONE) (vars_of t)
   857   else vs;
   858 
   859 fun add_npvars q p Ts (vs, Const ("==>", _) $ t $ u) =
   860       add_npvars q p Ts (add_npvars q (not p) Ts (vs, t), u)
   861   | add_npvars q p Ts (vs, Const ("all", Type (_, [Type (_, [T, _]), _])) $ t) =
   862       add_npvars q p Ts (vs, if p andalso q then betapply (t, Var (("",0), T)) else t)
   863   | add_npvars q p Ts (vs, Abs (_, T, t)) = add_npvars q p (T::Ts) (vs, t)
   864   | add_npvars _ _ Ts (vs, t) = add_npvars' Ts (vs, t)
   865 and add_npvars' Ts (vs, t) = (case strip_comb t of
   866     (Var (ixn, _), ts) => if test_args [] ts then vs
   867       else Library.foldl (add_npvars' Ts)
   868         (AList.update (op =) (ixn,
   869           Library.foldl (add_funvars Ts) ((these ooo AList.lookup) (op =) vs ixn, ts)) vs, ts)
   870   | (Abs (_, T, u), ts) => Library.foldl (add_npvars' (T::Ts)) (vs, u :: ts)
   871   | (_, ts) => Library.foldl (add_npvars' Ts) (vs, ts));
   872 
   873 fun prop_vars (Const ("==>", _) $ P $ Q) = prop_vars P union prop_vars Q
   874   | prop_vars (Const ("all", _) $ Abs (_, _, t)) = prop_vars t
   875   | prop_vars t = (case strip_comb t of
   876       (Var (ixn, _), _) => [ixn] | _ => []);
   877 
   878 fun is_proj t =
   879   let
   880     fun is_p i t = (case strip_comb t of
   881         (Bound j, []) => false
   882       | (Bound j, ts) => j >= i orelse exists (is_p i) ts
   883       | (Abs (_, _, u), _) => is_p (i+1) u
   884       | (_, ts) => exists (is_p i) ts)
   885   in (case strip_abs_body t of
   886         Bound _ => true
   887       | t' => is_p 0 t')
   888   end;
   889 
   890 fun needed_vars prop =
   891   Library.foldl (op union)
   892     ([], map (uncurry (insert (op =))) (add_npvars true true [] ([], prop))) union
   893   prop_vars prop;
   894 
   895 fun gen_axm_proof c name prop =
   896   let
   897     val nvs = needed_vars prop;
   898     val args = map (fn (v as Var (ixn, _)) =>
   899         if member (op =) nvs ixn then SOME v else NONE) (vars_of prop) @
   900       map SOME (sort Term.term_ord (term_frees prop));
   901   in
   902     proof_combt' (c (name, prop, NONE), args)
   903   end;
   904 
   905 val axm_proof = gen_axm_proof PAxm;
   906 
   907 val dummy = Const (Term.dummy_patternN, dummyT);
   908 
   909 fun oracle_proof name prop =
   910   if !proofs = 0 then Oracle (name, dummy, NONE)
   911   else gen_axm_proof Oracle name prop;
   912 
   913 fun shrink_proof thy =
   914   let
   915     val compress_typ = Compress.typ thy;
   916     val compress_term = Compress.term thy;
   917 
   918     fun shrink ls lev (prf as Abst (a, T, body)) =
   919           let val (b, is, ch, body') = shrink ls (lev+1) body
   920           in (b, is, ch, if ch then Abst (a, Option.map compress_typ T, body') else prf) end
   921       | shrink ls lev (prf as AbsP (a, t, body)) =
   922           let val (b, is, ch, body') = shrink (lev::ls) lev body
   923           in (b orelse member (op =) is 0, map_filter (fn 0 => NONE | i => SOME (i-1)) is,
   924             ch, if ch then AbsP (a, Option.map compress_term t, body') else prf)
   925           end
   926       | shrink ls lev prf =
   927           let val (is, ch, _, prf') = shrink' ls lev [] [] prf
   928           in (false, is, ch, prf') end
   929     and shrink' ls lev ts prfs (prf as prf1 %% prf2) =
   930           let
   931             val p as (_, is', ch', prf') = shrink ls lev prf2;
   932             val (is, ch, ts', prf'') = shrink' ls lev ts (p::prfs) prf1
   933           in (is union is', ch orelse ch', ts',
   934               if ch orelse ch' then prf'' %% prf' else prf)
   935           end
   936       | shrink' ls lev ts prfs (prf as prf1 % t) =
   937           let val (is, ch, (ch', t')::ts', prf') = shrink' ls lev (t::ts) prfs prf1
   938           in (is, ch orelse ch', ts',
   939               if ch orelse ch' then prf' % Option.map compress_term t' else prf) end
   940       | shrink' ls lev ts prfs (prf as PBound i) =
   941           (if exists (fn SOME (Bound j) => lev-j <= List.nth (ls, i) | _ => true) ts
   942              orelse has_duplicates (op =)
   943                (Library.foldl (fn (js, SOME (Bound j)) => j :: js | (js, _) => js) ([], ts))
   944              orelse exists #1 prfs then [i] else [], false, map (pair false) ts, prf)
   945       | shrink' ls lev ts prfs (Hyp t) = ([], false, map (pair false) ts, Hyp (compress_term t))
   946       | shrink' ls lev ts prfs (prf as MinProof _) =
   947           ([], false, map (pair false) ts, prf)
   948       | shrink' ls lev ts prfs prf =
   949           let
   950             val prop = (case prf of PThm (_, _, prop, _) => prop | PAxm (_, prop, _) => prop
   951               | Oracle (_, prop, _) => prop | _ => error "shrink: proof not in normal form");
   952             val vs = vars_of prop;
   953             val (ts', ts'') = chop (length vs) ts;
   954             val insts = Library.take (length ts', map (fst o dest_Var) vs) ~~ ts';
   955             val nvs = Library.foldl (fn (ixns', (ixn, ixns)) =>
   956               insert (op =) ixn (case AList.lookup (op =) insts ixn of
   957                   SOME (SOME t) => if is_proj t then ixns union ixns' else ixns'
   958                 | _ => ixns union ixns'))
   959                   (needed prop ts'' prfs, add_npvars false true [] ([], prop));
   960             val insts' = map
   961               (fn (ixn, x as SOME _) => if member (op =) nvs ixn then (false, x) else (true, NONE)
   962                 | (_, x) => (false, x)) insts
   963           in ([], false, insts' @ map (pair false) ts'', prf) end
   964     and needed (Const ("==>", _) $ t $ u) ts ((b, _, _, _)::prfs) =
   965           (if b then map (fst o dest_Var) (vars_of t) else []) union needed u ts prfs
   966       | needed (Var (ixn, _)) (_::_) _ = [ixn]
   967       | needed _ _ _ = [];
   968   in shrink end;
   969 
   970 
   971 (**** Simple first order matching functions for terms and proofs ****)
   972 
   973 exception PMatch;
   974 
   975 (** see pattern.ML **)
   976 
   977 fun flt (i: int) = List.filter (fn n => n < i);
   978 
   979 fun fomatch Ts tymatch j =
   980   let
   981     fun mtch (instsp as (tyinsts, insts)) = fn
   982         (Var (ixn, T), t)  =>
   983           if j>0 andalso not (null (flt j (loose_bnos t)))
   984           then raise PMatch
   985           else (tymatch (tyinsts, fn () => (T, fastype_of1 (Ts, t))),
   986             (ixn, t) :: insts)
   987       | (Free (a, T), Free (b, U)) =>
   988           if a=b then (tymatch (tyinsts, K (T, U)), insts) else raise PMatch
   989       | (Const (a, T), Const (b, U))  =>
   990           if a=b then (tymatch (tyinsts, K (T, U)), insts) else raise PMatch
   991       | (f $ t, g $ u) => mtch (mtch instsp (f, g)) (t, u)
   992       | (Bound i, Bound j) => if i=j then instsp else raise PMatch
   993       | _ => raise PMatch
   994   in mtch end;
   995 
   996 fun match_proof Ts tymatch =
   997   let
   998     fun optmatch _ inst (NONE, _) = inst
   999       | optmatch _ _ (SOME _, NONE) = raise PMatch
  1000       | optmatch mtch inst (SOME x, SOME y) = mtch inst (x, y)
  1001 
  1002     fun matcht Ts j (pinst, tinst) (t, u) =
  1003       (pinst, fomatch Ts tymatch j tinst (t, Envir.beta_norm u));
  1004     fun matchT (pinst, (tyinsts, insts)) p =
  1005       (pinst, (tymatch (tyinsts, K p), insts));
  1006     fun matchTs inst (Ts, Us) = Library.foldl (uncurry matchT) (inst, Ts ~~ Us);
  1007 
  1008     fun mtch Ts i j (pinst, tinst) (Hyp (Var (ixn, _)), prf) =
  1009           if i = 0 andalso j = 0 then ((ixn, prf) :: pinst, tinst)
  1010           else (case apfst (flt i) (apsnd (flt j)
  1011                   (prf_add_loose_bnos 0 0 prf ([], []))) of
  1012               ([], []) => ((ixn, incr_pboundvars (~i) (~j) prf) :: pinst, tinst)
  1013             | ([], _) => if j = 0 then
  1014                    ((ixn, incr_pboundvars (~i) (~j) prf) :: pinst, tinst)
  1015                  else raise PMatch
  1016             | _ => raise PMatch)
  1017       | mtch Ts i j inst (prf1 % opt1, prf2 % opt2) =
  1018           optmatch (matcht Ts j) (mtch Ts i j inst (prf1, prf2)) (opt1, opt2)
  1019       | mtch Ts i j inst (prf1 %% prf2, prf1' %% prf2') =
  1020           mtch Ts i j (mtch Ts i j inst (prf1, prf1')) (prf2, prf2')
  1021       | mtch Ts i j inst (Abst (_, opT, prf1), Abst (_, opU, prf2)) =
  1022           mtch (the_default dummyT opU :: Ts) i (j+1)
  1023             (optmatch matchT inst (opT, opU)) (prf1, prf2)
  1024       | mtch Ts i j inst (prf1, Abst (_, opU, prf2)) =
  1025           mtch (the_default dummyT opU :: Ts) i (j+1) inst
  1026             (incr_pboundvars 0 1 prf1 %> Bound 0, prf2)
  1027       | mtch Ts i j inst (AbsP (_, opt, prf1), AbsP (_, opu, prf2)) =
  1028           mtch Ts (i+1) j (optmatch (matcht Ts j) inst (opt, opu)) (prf1, prf2)
  1029       | mtch Ts i j inst (prf1, AbsP (_, _, prf2)) =
  1030           mtch Ts (i+1) j inst (incr_pboundvars 1 0 prf1 %% PBound 0, prf2)
  1031       | mtch Ts i j inst (PThm (name1, _, prop1, opTs), PThm (name2, _, prop2, opUs)) =
  1032           if name1=name2 andalso prop1=prop2 then
  1033             optmatch matchTs inst (opTs, opUs)
  1034           else raise PMatch
  1035       | mtch Ts i j inst (PAxm (s1, _, opTs), PAxm (s2, _, opUs)) =
  1036           if s1=s2 then optmatch matchTs inst (opTs, opUs)
  1037           else raise PMatch
  1038       | mtch _ _ _ inst (PBound i, PBound j) = if i = j then inst else raise PMatch
  1039       | mtch _ _ _ _ _ = raise PMatch
  1040   in mtch Ts 0 0 end;
  1041 
  1042 fun prf_subst (pinst, (tyinsts, insts)) =
  1043   let
  1044     val substT = Envir.typ_subst_TVars tyinsts;
  1045 
  1046     fun subst' lev (t as Var (ixn, _)) = (case AList.lookup (op =) insts ixn of
  1047           NONE => t
  1048         | SOME u => incr_boundvars lev u)
  1049       | subst' lev (Const (s, T)) = Const (s, substT T)
  1050       | subst' lev (Free (s, T)) = Free (s, substT T)
  1051       | subst' lev (Abs (a, T, body)) = Abs (a, substT T, subst' (lev+1) body)
  1052       | subst' lev (f $ t) = subst' lev f $ subst' lev t
  1053       | subst' _ t = t;
  1054 
  1055     fun subst plev tlev (AbsP (a, t, body)) =
  1056           AbsP (a, Option.map (subst' tlev) t, subst (plev+1) tlev body)
  1057       | subst plev tlev (Abst (a, T, body)) =
  1058           Abst (a, Option.map substT T, subst plev (tlev+1) body)
  1059       | subst plev tlev (prf %% prf') = subst plev tlev prf %% subst plev tlev prf'
  1060       | subst plev tlev (prf % t) = subst plev tlev prf % Option.map (subst' tlev) t
  1061       | subst plev tlev (prf as Hyp (Var (ixn, _))) = (case AList.lookup (op =) pinst ixn of
  1062           NONE => prf
  1063         | SOME prf' => incr_pboundvars plev tlev prf')
  1064       | subst _ _ (PThm (id, prf, prop, Ts)) =
  1065           PThm (id, prf, prop, Option.map (map substT) Ts)
  1066       | subst _ _ (PAxm (id, prop, Ts)) =
  1067           PAxm (id, prop, Option.map (map substT) Ts)
  1068       | subst _ _ t = t
  1069   in subst 0 0 end;
  1070 
  1071 (*A fast unification filter: true unless the two terms cannot be unified.
  1072   Terms must be NORMAL.  Treats all Vars as distinct. *)
  1073 fun could_unify prf1 prf2 =
  1074   let
  1075     fun matchrands (prf1 %% prf2) (prf1' %% prf2') =
  1076           could_unify prf2 prf2' andalso matchrands prf1 prf1'
  1077       | matchrands (prf % SOME t) (prf' % SOME t') =
  1078           Term.could_unify (t, t') andalso matchrands prf prf'
  1079       | matchrands (prf % _) (prf' % _) = matchrands prf prf'
  1080       | matchrands _ _ = true
  1081 
  1082     fun head_of (prf %% _) = head_of prf
  1083       | head_of (prf % _) = head_of prf
  1084       | head_of prf = prf
  1085 
  1086   in case (head_of prf1, head_of prf2) of
  1087         (_, Hyp (Var _)) => true
  1088       | (Hyp (Var _), _) => true
  1089       | (PThm (a, _, propa, _), PThm (b, _, propb, _)) =>
  1090           a = b andalso propa = propb andalso matchrands prf1 prf2
  1091       | (PAxm (a, _, _), PAxm (b, _, _)) => a = b andalso matchrands prf1 prf2
  1092       | (PBound i, PBound j) =>  i = j andalso matchrands prf1 prf2
  1093       | (AbsP _, _) =>  true   (*because of possible eta equality*)
  1094       | (Abst _, _) =>  true
  1095       | (_, AbsP _) =>  true
  1096       | (_, Abst _) =>  true
  1097       | _ => false
  1098   end;
  1099 
  1100 (**** rewriting on proof terms ****)
  1101 
  1102 val skel0 = PBound 0;
  1103 
  1104 fun rewrite_prf tymatch (rules, procs) prf =
  1105   let
  1106     fun rew _ (Abst (_, _, body) % SOME t) = SOME (prf_subst_bounds [t] body, skel0)
  1107       | rew _ (AbsP (_, _, body) %% prf) = SOME (prf_subst_pbounds [prf] body, skel0)
  1108       | rew Ts prf = (case get_first (fn (_, r) => r Ts prf) procs of
  1109           SOME prf' => SOME (prf', skel0)
  1110         | NONE => get_first (fn (prf1, prf2) => SOME (prf_subst
  1111             (match_proof Ts tymatch ([], (Vartab.empty, [])) (prf1, prf)) prf2, prf2)
  1112                handle PMatch => NONE) (List.filter (could_unify prf o fst) rules));
  1113 
  1114     fun rew0 Ts (prf as AbsP (_, _, prf' %% PBound 0)) =
  1115           if prf_loose_Pbvar1 prf' 0 then rew Ts prf
  1116           else
  1117             let val prf'' = incr_pboundvars (~1) 0 prf'
  1118             in SOME (the_default (prf'', skel0) (rew Ts prf'')) end
  1119       | rew0 Ts (prf as Abst (_, _, prf' % SOME (Bound 0))) =
  1120           if prf_loose_bvar1 prf' 0 then rew Ts prf
  1121           else
  1122             let val prf'' = incr_pboundvars 0 (~1) prf'
  1123             in SOME (the_default (prf'', skel0) (rew Ts prf'')) end
  1124       | rew0 Ts prf = rew Ts prf;
  1125 
  1126     fun rew1 _ (Hyp (Var _)) _ = NONE
  1127       | rew1 Ts skel prf = (case rew2 Ts skel prf of
  1128           SOME prf1 => (case rew0 Ts prf1 of
  1129               SOME (prf2, skel') => SOME (the_default prf2 (rew1 Ts skel' prf2))
  1130             | NONE => SOME prf1)
  1131         | NONE => (case rew0 Ts prf of
  1132               SOME (prf1, skel') => SOME (the_default prf1 (rew1 Ts skel' prf1))
  1133             | NONE => NONE))
  1134 
  1135     and rew2 Ts skel (prf % SOME t) = (case prf of
  1136             Abst (_, _, body) =>
  1137               let val prf' = prf_subst_bounds [t] body
  1138               in SOME (the_default prf' (rew2 Ts skel0 prf')) end
  1139           | _ => (case rew1 Ts (case skel of skel' % _ => skel' | _ => skel0) prf of
  1140               SOME prf' => SOME (prf' % SOME t)
  1141             | NONE => NONE))
  1142       | rew2 Ts skel (prf % NONE) = Option.map (fn prf' => prf' % NONE)
  1143           (rew1 Ts (case skel of skel' % _ => skel' | _ => skel0) prf)
  1144       | rew2 Ts skel (prf1 %% prf2) = (case prf1 of
  1145             AbsP (_, _, body) =>
  1146               let val prf' = prf_subst_pbounds [prf2] body
  1147               in SOME (the_default prf' (rew2 Ts skel0 prf')) end
  1148           | _ =>
  1149             let val (skel1, skel2) = (case skel of
  1150                 skel1 %% skel2 => (skel1, skel2)
  1151               | _ => (skel0, skel0))
  1152             in case rew1 Ts skel1 prf1 of
  1153                 SOME prf1' => (case rew1 Ts skel2 prf2 of
  1154                     SOME prf2' => SOME (prf1' %% prf2')
  1155                   | NONE => SOME (prf1' %% prf2))
  1156               | NONE => (case rew1 Ts skel2 prf2 of
  1157                     SOME prf2' => SOME (prf1 %% prf2')
  1158                   | NONE => NONE)
  1159             end)
  1160       | rew2 Ts skel (Abst (s, T, prf)) = (case rew1 (the_default dummyT T :: Ts)
  1161               (case skel of Abst (_, _, skel') => skel' | _ => skel0) prf of
  1162             SOME prf' => SOME (Abst (s, T, prf'))
  1163           | NONE => NONE)
  1164       | rew2 Ts skel (AbsP (s, t, prf)) = (case rew1 Ts
  1165               (case skel of AbsP (_, _, skel') => skel' | _ => skel0) prf of
  1166             SOME prf' => SOME (AbsP (s, t, prf'))
  1167           | NONE => NONE)
  1168       | rew2 _ _ _ = NONE
  1169 
  1170   in the_default prf (rew1 [] skel0 prf) end;
  1171 
  1172 fun rewrite_proof thy = rewrite_prf (fn (tyenv, f) =>
  1173   Sign.typ_match thy (f ()) tyenv handle Type.TYPE_MATCH => raise PMatch);
  1174 
  1175 fun rewrite_proof_notypes rews = rewrite_prf fst rews;
  1176 
  1177 
  1178 (**** theory data ****)
  1179 
  1180 structure ProofData = TheoryDataFun
  1181 (struct
  1182   val name = "Pure/proof";
  1183   type T = ((proof * proof) list *
  1184     (string * (typ list -> proof -> proof option)) list);
  1185 
  1186   val empty = ([], []);
  1187   val copy = I;
  1188   val extend = I;
  1189   fun merge _ ((rules1, procs1) : T, (rules2, procs2)) =
  1190     (Library.merge (op =) (rules1, rules2),
  1191       AList.merge (op =) (K true) (procs1, procs2));
  1192   fun print _ _ = ();
  1193 end);
  1194 
  1195 val init_data = ProofData.init;
  1196 
  1197 fun add_prf_rrule r = (ProofData.map o apfst) (insert (op =) r);
  1198 
  1199 fun add_prf_rproc p = (ProofData.map o apsnd) (AList.update (op =) p);
  1200 
  1201 fun thm_proof thy name hyps prop prf =
  1202   let
  1203     val prop = Logic.list_implies (hyps, prop);
  1204     val nvs = needed_vars prop;
  1205     val args = map (fn (v as Var (ixn, _)) =>
  1206         if member (op =) nvs ixn then SOME v else NONE) (vars_of prop) @
  1207       map SOME (sort Term.term_ord (term_frees prop));
  1208     val opt_prf = if ! proofs = 2 then
  1209         #4 (shrink_proof thy [] 0 (rewrite_prf fst (ProofData.get thy)
  1210           (foldr (uncurry implies_intr_proof) prf hyps)))
  1211       else MinProof (mk_min_proof prf ([], [], []));
  1212     val head = (case strip_combt (fst (strip_combP prf)) of
  1213         (PThm (old_name, prf', prop', NONE), args') =>
  1214           if (old_name="" orelse old_name=name) andalso
  1215              prop = prop' andalso args = args' then
  1216             PThm (name, prf', prop, NONE)
  1217           else
  1218             PThm (name, opt_prf, prop, NONE)
  1219       | _ => PThm (name, opt_prf, prop, NONE))
  1220   in
  1221     proof_combP (proof_combt' (head, args), map Hyp hyps)
  1222   end;
  1223 
  1224 fun get_name hyps prop prf =
  1225   let val prop = Logic.list_implies (hyps, prop) in
  1226     (case strip_combt (fst (strip_combP prf)) of
  1227       (PThm (name, _, prop', _), _) => if prop=prop' then name else ""
  1228     | (PAxm (name, prop', _), _) => if prop=prop' then name else ""
  1229     | _ => "")
  1230   end;
  1231 
  1232 end;
  1233 
  1234 structure BasicProofterm : BASIC_PROOFTERM = Proofterm;
  1235 open BasicProofterm;