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