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