src/Pure/thm.ML
author haftmann
Wed, 19 May 2010 10:17:05 +0200
changeset 36983 e922a5124428
parent 36931 4ed0d72def50
child 37297 a1acd424645a
permissions -rw-r--r--
dropped legacy_unconstrainT
     1 (*  Title:      Pure/thm.ML
     2     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     3     Author:     Makarius
     4 
     5 The very core of Isabelle's Meta Logic: certified types and terms,
     6 derivations, theorems, framework rules (including lifting and
     7 resolution), oracles.
     8 *)
     9 
    10 signature BASIC_THM =
    11   sig
    12   (*certified types*)
    13   type ctyp
    14   val rep_ctyp: ctyp ->
    15    {thy_ref: theory_ref,
    16     T: typ,
    17     maxidx: int,
    18     sorts: sort OrdList.T}
    19   val theory_of_ctyp: ctyp -> theory
    20   val typ_of: ctyp -> typ
    21   val ctyp_of: theory -> typ -> ctyp
    22 
    23   (*certified terms*)
    24   type cterm
    25   exception CTERM of string * cterm list
    26   val rep_cterm: cterm ->
    27    {thy_ref: theory_ref,
    28     t: term,
    29     T: typ,
    30     maxidx: int,
    31     sorts: sort OrdList.T}
    32   val crep_cterm: cterm ->
    33     {thy_ref: theory_ref, t: term, T: ctyp, maxidx: int, sorts: sort OrdList.T}
    34   val theory_of_cterm: cterm -> theory
    35   val term_of: cterm -> term
    36   val cterm_of: theory -> term -> cterm
    37   val ctyp_of_term: cterm -> ctyp
    38 
    39   (*theorems*)
    40   type thm
    41   type conv = cterm -> thm
    42   type attribute = Context.generic * thm -> Context.generic * thm
    43   val rep_thm: thm ->
    44    {thy_ref: theory_ref,
    45     tags: Properties.T,
    46     maxidx: int,
    47     shyps: sort OrdList.T,
    48     hyps: term OrdList.T,
    49     tpairs: (term * term) list,
    50     prop: term}
    51   val crep_thm: thm ->
    52    {thy_ref: theory_ref,
    53     tags: Properties.T,
    54     maxidx: int,
    55     shyps: sort OrdList.T,
    56     hyps: cterm OrdList.T,
    57     tpairs: (cterm * cterm) list,
    58     prop: cterm}
    59   exception THM of string * int * thm list
    60   val theory_of_thm: thm -> theory
    61   val prop_of: thm -> term
    62   val tpairs_of: thm -> (term * term) list
    63   val concl_of: thm -> term
    64   val prems_of: thm -> term list
    65   val nprems_of: thm -> int
    66   val cprop_of: thm -> cterm
    67   val cprem_of: thm -> int -> cterm
    68   val transfer: theory -> thm -> thm
    69   val weaken: cterm -> thm -> thm
    70   val weaken_sorts: sort list -> cterm -> cterm
    71   val extra_shyps: thm -> sort list
    72 
    73   (*meta rules*)
    74   val assume: cterm -> thm
    75   val implies_intr: cterm -> thm -> thm
    76   val implies_elim: thm -> thm -> thm
    77   val forall_intr: cterm -> thm -> thm
    78   val forall_elim: cterm -> thm -> thm
    79   val reflexive: cterm -> thm
    80   val symmetric: thm -> thm
    81   val transitive: thm -> thm -> thm
    82   val beta_conversion: bool -> conv
    83   val eta_conversion: conv
    84   val eta_long_conversion: conv
    85   val abstract_rule: string -> cterm -> thm -> thm
    86   val combination: thm -> thm -> thm
    87   val equal_intr: thm -> thm -> thm
    88   val equal_elim: thm -> thm -> thm
    89   val flexflex_rule: thm -> thm Seq.seq
    90   val generalize: string list * string list -> int -> thm -> thm
    91   val instantiate: (ctyp * ctyp) list * (cterm * cterm) list -> thm -> thm
    92   val instantiate_cterm: (ctyp * ctyp) list * (cterm * cterm) list -> cterm -> cterm
    93   val trivial: cterm -> thm
    94   val dest_state: thm * int -> (term * term) list * term list * term * term
    95   val lift_rule: cterm -> thm -> thm
    96   val incr_indexes: int -> thm -> thm
    97 end;
    98 
    99 signature THM =
   100 sig
   101   include BASIC_THM
   102   val dest_ctyp: ctyp -> ctyp list
   103   val dest_comb: cterm -> cterm * cterm
   104   val dest_fun: cterm -> cterm
   105   val dest_arg: cterm -> cterm
   106   val dest_fun2: cterm -> cterm
   107   val dest_arg1: cterm -> cterm
   108   val dest_abs: string option -> cterm -> cterm * cterm
   109   val capply: cterm -> cterm -> cterm
   110   val cabs_name: string * cterm -> cterm -> cterm
   111   val cabs: cterm -> cterm -> cterm
   112   val adjust_maxidx_cterm: int -> cterm -> cterm
   113   val incr_indexes_cterm: int -> cterm -> cterm
   114   val match: cterm * cterm -> (ctyp * ctyp) list * (cterm * cterm) list
   115   val first_order_match: cterm * cterm -> (ctyp * ctyp) list * (cterm * cterm) list
   116   val fold_terms: (term -> 'a -> 'a) -> thm -> 'a -> 'a
   117   val terms_of_tpairs: (term * term) list -> term list
   118   val full_prop_of: thm -> term
   119   val maxidx_of: thm -> int
   120   val maxidx_thm: thm -> int -> int
   121   val hyps_of: thm -> term list
   122   val no_prems: thm -> bool
   123   val major_prem_of: thm -> term
   124   val join_proofs: thm list -> unit
   125   val proof_body_of: thm -> proof_body
   126   val proof_of: thm -> proof
   127   val status_of: thm -> {oracle: bool, unfinished: bool, failed: bool}
   128   val future: thm future -> cterm -> thm
   129   val derivation_name: thm -> string
   130   val name_derivation: string -> thm -> thm
   131   val axiom: theory -> string -> thm
   132   val axioms_of: theory -> (string * thm) list
   133   val get_tags: thm -> Properties.T
   134   val map_tags: (Properties.T -> Properties.T) -> thm -> thm
   135   val norm_proof: thm -> thm
   136   val adjust_maxidx_thm: int -> thm -> thm
   137   val varifyT_global: thm -> thm
   138   val varifyT_global': (string * sort) list -> thm -> ((string * sort) * indexname) list * thm
   139   val of_class: ctyp * class -> thm
   140   val strip_shyps: thm -> thm
   141   val unconstrainT: thm -> thm
   142   val legacy_freezeT: thm -> thm
   143   val assumption: int -> thm -> thm Seq.seq
   144   val eq_assumption: int -> thm -> thm
   145   val rotate_rule: int -> int -> thm -> thm
   146   val permute_prems: int -> int -> thm -> thm
   147   val rename_params_rule: string list * int -> thm -> thm
   148   val compose_no_flatten: bool -> thm * int -> int -> thm -> thm Seq.seq
   149   val bicompose: bool -> bool * thm * int -> int -> thm -> thm Seq.seq
   150   val biresolution: bool -> (bool * thm) list -> int -> thm -> thm Seq.seq
   151   val rename_boundvars: term -> term -> thm -> thm
   152   val extern_oracles: theory -> xstring list
   153   val add_oracle: binding * ('a -> cterm) -> theory -> (string * ('a -> thm)) * theory
   154 end;
   155 
   156 structure Thm: THM =
   157 struct
   158 
   159 structure Pt = Proofterm;
   160 
   161 
   162 (*** Certified terms and types ***)
   163 
   164 (** certified types **)
   165 
   166 abstype ctyp = Ctyp of
   167  {thy_ref: theory_ref,
   168   T: typ,
   169   maxidx: int,
   170   sorts: sort OrdList.T}
   171 with
   172 
   173 fun rep_ctyp (Ctyp args) = args;
   174 fun theory_of_ctyp (Ctyp {thy_ref, ...}) = Theory.deref thy_ref;
   175 fun typ_of (Ctyp {T, ...}) = T;
   176 
   177 fun ctyp_of thy raw_T =
   178   let
   179     val T = Sign.certify_typ thy raw_T;
   180     val maxidx = Term.maxidx_of_typ T;
   181     val sorts = Sorts.insert_typ T [];
   182   in Ctyp {thy_ref = Theory.check_thy thy, T = T, maxidx = maxidx, sorts = sorts} end;
   183 
   184 fun dest_ctyp (Ctyp {thy_ref, T = Type (_, Ts), maxidx, sorts}) =
   185       map (fn T => Ctyp {thy_ref = thy_ref, T = T, maxidx = maxidx, sorts = sorts}) Ts
   186   | dest_ctyp cT = raise TYPE ("dest_ctyp", [typ_of cT], []);
   187 
   188 
   189 
   190 (** certified terms **)
   191 
   192 (*certified terms with checked typ, maxidx, and sorts*)
   193 abstype cterm = Cterm of
   194  {thy_ref: theory_ref,
   195   t: term,
   196   T: typ,
   197   maxidx: int,
   198   sorts: sort OrdList.T}
   199 with
   200 
   201 exception CTERM of string * cterm list;
   202 
   203 fun rep_cterm (Cterm args) = args;
   204 
   205 fun crep_cterm (Cterm {thy_ref, t, T, maxidx, sorts}) =
   206   {thy_ref = thy_ref, t = t, maxidx = maxidx, sorts = sorts,
   207     T = Ctyp {thy_ref = thy_ref, T = T, maxidx = maxidx, sorts = sorts}};
   208 
   209 fun theory_of_cterm (Cterm {thy_ref, ...}) = Theory.deref thy_ref;
   210 fun term_of (Cterm {t, ...}) = t;
   211 
   212 fun ctyp_of_term (Cterm {thy_ref, T, maxidx, sorts, ...}) =
   213   Ctyp {thy_ref = thy_ref, T = T, maxidx = maxidx, sorts = sorts};
   214 
   215 fun cterm_of thy tm =
   216   let
   217     val (t, T, maxidx) = Sign.certify_term thy tm;
   218     val sorts = Sorts.insert_term t [];
   219   in Cterm {thy_ref = Theory.check_thy thy, t = t, T = T, maxidx = maxidx, sorts = sorts} end;
   220 
   221 fun merge_thys0 (Cterm {thy_ref = r1, ...}) (Cterm {thy_ref = r2, ...}) =
   222   Theory.merge_refs (r1, r2);
   223 
   224 
   225 (* destructors *)
   226 
   227 fun dest_comb (Cterm {t = c $ a, T, thy_ref, maxidx, sorts}) =
   228       let val A = Term.argument_type_of c 0 in
   229         (Cterm {t = c, T = A --> T, thy_ref = thy_ref, maxidx = maxidx, sorts = sorts},
   230          Cterm {t = a, T = A, thy_ref = thy_ref, maxidx = maxidx, sorts = sorts})
   231       end
   232   | dest_comb ct = raise CTERM ("dest_comb", [ct]);
   233 
   234 fun dest_fun (Cterm {t = c $ _, T, thy_ref, maxidx, sorts}) =
   235       let val A = Term.argument_type_of c 0
   236       in Cterm {t = c, T = A --> T, thy_ref = thy_ref, maxidx = maxidx, sorts = sorts} end
   237   | dest_fun ct = raise CTERM ("dest_fun", [ct]);
   238 
   239 fun dest_arg (Cterm {t = c $ a, T = _, thy_ref, maxidx, sorts}) =
   240       let val A = Term.argument_type_of c 0
   241       in Cterm {t = a, T = A, thy_ref = thy_ref, maxidx = maxidx, sorts = sorts} end
   242   | dest_arg ct = raise CTERM ("dest_arg", [ct]);
   243 
   244 
   245 fun dest_fun2 (Cterm {t = c $ _ $ _, T, thy_ref, maxidx, sorts}) =
   246       let
   247         val A = Term.argument_type_of c 0;
   248         val B = Term.argument_type_of c 1;
   249       in Cterm {t = c, T = A --> B --> T, thy_ref = thy_ref, maxidx = maxidx, sorts = sorts} end
   250   | dest_fun2 ct = raise CTERM ("dest_fun2", [ct]);
   251 
   252 fun dest_arg1 (Cterm {t = c $ a $ _, T = _, thy_ref, maxidx, sorts}) =
   253       let val A = Term.argument_type_of c 0
   254       in Cterm {t = a, T = A, thy_ref = thy_ref, maxidx = maxidx, sorts = sorts} end
   255   | dest_arg1 ct = raise CTERM ("dest_arg1", [ct]);
   256 
   257 fun dest_abs a (Cterm {t = Abs (x, T, t), T = Type ("fun", [_, U]), thy_ref, maxidx, sorts}) =
   258       let val (y', t') = Term.dest_abs (the_default x a, T, t) in
   259         (Cterm {t = Free (y', T), T = T, thy_ref = thy_ref, maxidx = maxidx, sorts = sorts},
   260           Cterm {t = t', T = U, thy_ref = thy_ref, maxidx = maxidx, sorts = sorts})
   261       end
   262   | dest_abs _ ct = raise CTERM ("dest_abs", [ct]);
   263 
   264 
   265 (* constructors *)
   266 
   267 fun capply
   268   (cf as Cterm {t = f, T = Type ("fun", [dty, rty]), maxidx = maxidx1, sorts = sorts1, ...})
   269   (cx as Cterm {t = x, T, maxidx = maxidx2, sorts = sorts2, ...}) =
   270     if T = dty then
   271       Cterm {thy_ref = merge_thys0 cf cx,
   272         t = f $ x,
   273         T = rty,
   274         maxidx = Int.max (maxidx1, maxidx2),
   275         sorts = Sorts.union sorts1 sorts2}
   276       else raise CTERM ("capply: types don't agree", [cf, cx])
   277   | capply cf cx = raise CTERM ("capply: first arg is not a function", [cf, cx]);
   278 
   279 fun cabs_name
   280   (x, ct1 as Cterm {t = t1, T = T1, maxidx = maxidx1, sorts = sorts1, ...})
   281   (ct2 as Cterm {t = t2, T = T2, maxidx = maxidx2, sorts = sorts2, ...}) =
   282     let val t = Term.lambda_name (x, t1) t2 in
   283       Cterm {thy_ref = merge_thys0 ct1 ct2,
   284         t = t, T = T1 --> T2,
   285         maxidx = Int.max (maxidx1, maxidx2),
   286         sorts = Sorts.union sorts1 sorts2}
   287     end;
   288 
   289 fun cabs t u = cabs_name ("", t) u;
   290 
   291 
   292 (* indexes *)
   293 
   294 fun adjust_maxidx_cterm i (ct as Cterm {thy_ref, t, T, maxidx, sorts}) =
   295   if maxidx = i then ct
   296   else if maxidx < i then
   297     Cterm {maxidx = i, thy_ref = thy_ref, t = t, T = T, sorts = sorts}
   298   else
   299     Cterm {maxidx = Int.max (maxidx_of_term t, i), thy_ref = thy_ref, t = t, T = T, sorts = sorts};
   300 
   301 fun incr_indexes_cterm i (ct as Cterm {thy_ref, t, T, maxidx, sorts}) =
   302   if i < 0 then raise CTERM ("negative increment", [ct])
   303   else if i = 0 then ct
   304   else Cterm {thy_ref = thy_ref, t = Logic.incr_indexes ([], i) t,
   305     T = Logic.incr_tvar i T, maxidx = maxidx + i, sorts = sorts};
   306 
   307 
   308 (* matching *)
   309 
   310 local
   311 
   312 fun gen_match match
   313     (ct1 as Cterm {t = t1, sorts = sorts1, ...},
   314      ct2 as Cterm {t = t2, sorts = sorts2, maxidx = maxidx2, ...}) =
   315   let
   316     val thy = Theory.deref (merge_thys0 ct1 ct2);
   317     val (Tinsts, tinsts) = match thy (t1, t2) (Vartab.empty, Vartab.empty);
   318     val sorts = Sorts.union sorts1 sorts2;
   319     fun mk_cTinst ((a, i), (S, T)) =
   320       (Ctyp {T = TVar ((a, i), S), thy_ref = Theory.check_thy thy, maxidx = i, sorts = sorts},
   321        Ctyp {T = T, thy_ref = Theory.check_thy thy, maxidx = maxidx2, sorts = sorts});
   322     fun mk_ctinst ((x, i), (T, t)) =
   323       let val T = Envir.subst_type Tinsts T in
   324         (Cterm {t = Var ((x, i), T), T = T, thy_ref = Theory.check_thy thy,
   325           maxidx = i, sorts = sorts},
   326          Cterm {t = t, T = T, thy_ref = Theory.check_thy thy, maxidx = maxidx2, sorts = sorts})
   327       end;
   328   in (Vartab.fold (cons o mk_cTinst) Tinsts [], Vartab.fold (cons o mk_ctinst) tinsts []) end;
   329 
   330 in
   331 
   332 val match = gen_match Pattern.match;
   333 val first_order_match = gen_match Pattern.first_order_match;
   334 
   335 end;
   336 
   337 
   338 
   339 (*** Derivations and Theorems ***)
   340 
   341 abstype thm = Thm of
   342  deriv *                                        (*derivation*)
   343  {thy_ref: theory_ref,                          (*dynamic reference to theory*)
   344   tags: Properties.T,                           (*additional annotations/comments*)
   345   maxidx: int,                                  (*maximum index of any Var or TVar*)
   346   shyps: sort OrdList.T,                        (*sort hypotheses*)
   347   hyps: term OrdList.T,                         (*hypotheses*)
   348   tpairs: (term * term) list,                   (*flex-flex pairs*)
   349   prop: term}                                   (*conclusion*)
   350 and deriv = Deriv of
   351  {promises: (serial * thm future) OrdList.T,
   352   body: Pt.proof_body}
   353 with
   354 
   355 type conv = cterm -> thm;
   356 
   357 (*attributes subsume any kind of rules or context modifiers*)
   358 type attribute = Context.generic * thm -> Context.generic * thm;
   359 
   360 (*errors involving theorems*)
   361 exception THM of string * int * thm list;
   362 
   363 fun rep_thm (Thm (_, args)) = args;
   364 
   365 fun crep_thm (Thm (_, {thy_ref, tags, maxidx, shyps, hyps, tpairs, prop})) =
   366   let fun cterm max t = Cterm {thy_ref = thy_ref, t = t, T = propT, maxidx = max, sorts = shyps} in
   367    {thy_ref = thy_ref, tags = tags, maxidx = maxidx, shyps = shyps,
   368     hyps = map (cterm ~1) hyps,
   369     tpairs = map (pairself (cterm maxidx)) tpairs,
   370     prop = cterm maxidx prop}
   371   end;
   372 
   373 fun fold_terms f (Thm (_, {tpairs, prop, hyps, ...})) =
   374   fold (fn (t, u) => f t #> f u) tpairs #> f prop #> fold f hyps;
   375 
   376 fun terms_of_tpairs tpairs = fold_rev (fn (t, u) => cons t o cons u) tpairs [];
   377 
   378 fun eq_tpairs ((t, u), (t', u')) = t aconv t' andalso u aconv u';
   379 fun union_tpairs ts us = Library.merge eq_tpairs (ts, us);
   380 val maxidx_tpairs = fold (fn (t, u) => Term.maxidx_term t #> Term.maxidx_term u);
   381 
   382 fun attach_tpairs tpairs prop =
   383   Logic.list_implies (map Logic.mk_equals tpairs, prop);
   384 
   385 fun full_prop_of (Thm (_, {tpairs, prop, ...})) = attach_tpairs tpairs prop;
   386 
   387 val union_hyps = OrdList.union Term_Ord.fast_term_ord;
   388 val insert_hyps = OrdList.insert Term_Ord.fast_term_ord;
   389 val remove_hyps = OrdList.remove Term_Ord.fast_term_ord;
   390 
   391 
   392 (* merge theories of cterms/thms -- trivial absorption only *)
   393 
   394 fun merge_thys1 (Cterm {thy_ref = r1, ...}) (Thm (_, {thy_ref = r2, ...})) =
   395   Theory.merge_refs (r1, r2);
   396 
   397 fun merge_thys2 (Thm (_, {thy_ref = r1, ...})) (Thm (_, {thy_ref = r2, ...})) =
   398   Theory.merge_refs (r1, r2);
   399 
   400 
   401 (* basic components *)
   402 
   403 val theory_of_thm = Theory.deref o #thy_ref o rep_thm;
   404 val maxidx_of = #maxidx o rep_thm;
   405 fun maxidx_thm th i = Int.max (maxidx_of th, i);
   406 val hyps_of = #hyps o rep_thm;
   407 val prop_of = #prop o rep_thm;
   408 val tpairs_of = #tpairs o rep_thm;
   409 
   410 val concl_of = Logic.strip_imp_concl o prop_of;
   411 val prems_of = Logic.strip_imp_prems o prop_of;
   412 val nprems_of = Logic.count_prems o prop_of;
   413 fun no_prems th = nprems_of th = 0;
   414 
   415 fun major_prem_of th =
   416   (case prems_of th of
   417     prem :: _ => Logic.strip_assums_concl prem
   418   | [] => raise THM ("major_prem_of: rule with no premises", 0, [th]));
   419 
   420 (*the statement of any thm is a cterm*)
   421 fun cprop_of (Thm (_, {thy_ref, maxidx, shyps, prop, ...})) =
   422   Cterm {thy_ref = thy_ref, maxidx = maxidx, T = propT, t = prop, sorts = shyps};
   423 
   424 fun cprem_of (th as Thm (_, {thy_ref, maxidx, shyps, prop, ...})) i =
   425   Cterm {thy_ref = thy_ref, maxidx = maxidx, T = propT, sorts = shyps,
   426     t = Logic.nth_prem (i, prop) handle TERM _ => raise THM ("cprem_of", i, [th])};
   427 
   428 (*explicit transfer to a super theory*)
   429 fun transfer thy' thm =
   430   let
   431     val Thm (der, {thy_ref, tags, maxidx, shyps, hyps, tpairs, prop}) = thm;
   432     val thy = Theory.deref thy_ref;
   433     val _ = Theory.subthy (thy, thy') orelse raise THM ("transfer: not a super theory", 0, [thm]);
   434     val is_eq = Theory.eq_thy (thy, thy');
   435     val _ = Theory.check_thy thy;
   436   in
   437     if is_eq then thm
   438     else
   439       Thm (der,
   440        {thy_ref = Theory.check_thy thy',
   441         tags = tags,
   442         maxidx = maxidx,
   443         shyps = shyps,
   444         hyps = hyps,
   445         tpairs = tpairs,
   446         prop = prop})
   447   end;
   448 
   449 (*explicit weakening: maps |- B to A |- B*)
   450 fun weaken raw_ct th =
   451   let
   452     val ct as Cterm {t = A, T, sorts, maxidx = maxidxA, ...} = adjust_maxidx_cterm ~1 raw_ct;
   453     val Thm (der, {tags, maxidx, shyps, hyps, tpairs, prop, ...}) = th;
   454   in
   455     if T <> propT then
   456       raise THM ("weaken: assumptions must have type prop", 0, [])
   457     else if maxidxA <> ~1 then
   458       raise THM ("weaken: assumptions may not contain schematic variables", maxidxA, [])
   459     else
   460       Thm (der,
   461        {thy_ref = merge_thys1 ct th,
   462         tags = tags,
   463         maxidx = maxidx,
   464         shyps = Sorts.union sorts shyps,
   465         hyps = insert_hyps A hyps,
   466         tpairs = tpairs,
   467         prop = prop})
   468   end;
   469 
   470 fun weaken_sorts raw_sorts ct =
   471   let
   472     val Cterm {thy_ref, t, T, maxidx, sorts} = ct;
   473     val thy = Theory.deref thy_ref;
   474     val more_sorts = Sorts.make (map (Sign.certify_sort thy) raw_sorts);
   475     val sorts' = Sorts.union sorts more_sorts;
   476   in Cterm {thy_ref = Theory.check_thy thy, t = t, T = T, maxidx = maxidx, sorts = sorts'} end;
   477 
   478 (*dangling sort constraints of a thm*)
   479 fun extra_shyps (th as Thm (_, {shyps, ...})) =
   480   Sorts.subtract (fold_terms Sorts.insert_term th []) shyps;
   481 
   482 
   483 
   484 (** derivations and promised proofs **)
   485 
   486 fun make_deriv promises oracles thms proof =
   487   Deriv {promises = promises, body = PBody {oracles = oracles, thms = thms, proof = proof}};
   488 
   489 val empty_deriv = make_deriv [] [] [] Pt.MinProof;
   490 
   491 
   492 (* inference rules *)
   493 
   494 fun promise_ord ((i, _), (j, _)) = int_ord (j, i);
   495 
   496 fun deriv_rule2 f
   497     (Deriv {promises = ps1, body = PBody {oracles = oras1, thms = thms1, proof = prf1}})
   498     (Deriv {promises = ps2, body = PBody {oracles = oras2, thms = thms2, proof = prf2}}) =
   499   let
   500     val ps = OrdList.union promise_ord ps1 ps2;
   501     val oras = Pt.merge_oracles oras1 oras2;
   502     val thms = Pt.merge_thms thms1 thms2;
   503     val prf =
   504       (case ! Pt.proofs of
   505         2 => f prf1 prf2
   506       | 1 => MinProof
   507       | 0 => MinProof
   508       | i => error ("Illegal level of detail for proof objects: " ^ string_of_int i));
   509   in make_deriv ps oras thms prf end;
   510 
   511 fun deriv_rule1 f = deriv_rule2 (K f) empty_deriv;
   512 fun deriv_rule0 prf = deriv_rule1 I (make_deriv [] [] [] prf);
   513 
   514 fun deriv_rule_unconditional f (Deriv {promises, body = PBody {oracles, thms, proof}}) =
   515   make_deriv promises oracles thms (f proof);
   516 
   517 
   518 (* fulfilled proofs *)
   519 
   520 fun raw_body (Thm (Deriv {body, ...}, _)) = body;
   521 
   522 fun fulfill_body (Thm (Deriv {promises, body}, {thy_ref, ...})) =
   523   Pt.fulfill_norm_proof (Theory.deref thy_ref)
   524     (map #1 promises ~~ fulfill_bodies (map #2 promises)) body
   525 and fulfill_bodies futures = map fulfill_body (Exn.release_all (Future.join_results futures));
   526 
   527 val join_proofs = Pt.join_bodies o map fulfill_body;
   528 
   529 fun proof_body_of thm = (Pt.join_bodies [raw_body thm]; fulfill_body thm);
   530 val proof_of = Pt.proof_of o proof_body_of;
   531 
   532 
   533 (* derivation status *)
   534 
   535 fun status_of (Thm (Deriv {promises, body}, _)) =
   536   let
   537     val ps = map (Future.peek o snd) promises;
   538     val bodies = body ::
   539       map_filter (fn SOME (Exn.Result th) => SOME (raw_body th) | _ => NONE) ps;
   540     val {oracle, unfinished, failed} = Pt.status_of bodies;
   541   in
   542    {oracle = oracle,
   543     unfinished = unfinished orelse exists is_none ps,
   544     failed = failed orelse exists (fn SOME (Exn.Exn _) => true | _ => false) ps}
   545   end;
   546 
   547 
   548 (* future rule *)
   549 
   550 fun future_result i orig_thy orig_shyps orig_prop thm =
   551   let
   552     fun err msg = raise THM ("future_result: " ^ msg, 0, [thm]);
   553     val Thm (Deriv {promises, ...}, {thy_ref, shyps, hyps, tpairs, prop, ...}) = thm;
   554 
   555     val _ = Theory.eq_thy (Theory.deref thy_ref, orig_thy) orelse err "bad theory";
   556     val _ = Theory.check_thy orig_thy;
   557     val _ = prop aconv orig_prop orelse err "bad prop";
   558     val _ = null tpairs orelse err "bad tpairs";
   559     val _ = null hyps orelse err "bad hyps";
   560     val _ = Sorts.subset (shyps, orig_shyps) orelse err "bad shyps";
   561     val _ = forall (fn (j, _) => i <> j) promises orelse err "bad dependencies";
   562     val _ = fulfill_bodies (map #2 promises);
   563   in thm end;
   564 
   565 fun future future_thm ct =
   566   let
   567     val Cterm {thy_ref = thy_ref, t = prop, T, maxidx, sorts} = ct;
   568     val thy = Context.reject_draft (Theory.deref thy_ref);
   569     val _ = T <> propT andalso raise CTERM ("future: prop expected", [ct]);
   570 
   571     val i = serial ();
   572     val future = future_thm |> Future.map (future_result i thy sorts prop);
   573   in
   574     Thm (make_deriv [(i, future)] [] [] (Pt.promise_proof thy i prop),
   575      {thy_ref = thy_ref,
   576       tags = [],
   577       maxidx = maxidx,
   578       shyps = sorts,
   579       hyps = [],
   580       tpairs = [],
   581       prop = prop})
   582   end;
   583 
   584 
   585 (* closed derivations with official name *)
   586 
   587 fun derivation_name thm =
   588   Pt.guess_name (Pt.proof_of (raw_body thm));   (* FIXME tmp *)
   589 
   590 fun name_derivation name (thm as Thm (der, args)) =
   591   let
   592     val Deriv {promises, body} = der;
   593     val {thy_ref, shyps, hyps, prop, tpairs, ...} = args;
   594     val _ = null tpairs orelse raise THM ("put_name: unsolved flex-flex constraints", 0, [thm]);
   595 
   596     val ps = map (apsnd (Future.map proof_body_of)) promises;
   597     val thy = Theory.deref thy_ref;
   598     val (pthm, proof) = Pt.thm_proof thy name shyps hyps prop ps body;
   599     val der' = make_deriv [] [] [pthm] proof;
   600     val _ = Theory.check_thy thy;
   601   in Thm (der', args) end;
   602 
   603 
   604 
   605 (** Axioms **)
   606 
   607 fun axiom theory name =
   608   let
   609     fun get_ax thy =
   610       Symtab.lookup (Theory.axiom_table thy) name
   611       |> Option.map (fn prop =>
   612            let
   613              val der = deriv_rule0 (Pt.axm_proof name prop);
   614              val maxidx = maxidx_of_term prop;
   615              val shyps = Sorts.insert_term prop [];
   616            in
   617              Thm (der, {thy_ref = Theory.check_thy thy, tags = [],
   618                maxidx = maxidx, shyps = shyps, hyps = [], tpairs = [], prop = prop})
   619            end);
   620   in
   621     (case get_first get_ax (theory :: Theory.ancestors_of theory) of
   622       SOME thm => thm
   623     | NONE => raise THEORY ("No axiom " ^ quote name, [theory]))
   624   end;
   625 
   626 (*return additional axioms of this theory node*)
   627 fun axioms_of thy =
   628   map (fn s => (s, axiom thy s)) (Symtab.keys (Theory.axiom_table thy));
   629 
   630 
   631 (* tags *)
   632 
   633 val get_tags = #tags o rep_thm;
   634 
   635 fun map_tags f (Thm (der, {thy_ref, tags, maxidx, shyps, hyps, tpairs, prop})) =
   636   Thm (der, {thy_ref = thy_ref, tags = f tags, maxidx = maxidx,
   637     shyps = shyps, hyps = hyps, tpairs = tpairs, prop = prop});
   638 
   639 
   640 fun norm_proof (Thm (der, args as {thy_ref, ...})) =
   641   let
   642     val thy = Theory.deref thy_ref;
   643     val der' = deriv_rule1 (Pt.rew_proof thy) der;
   644     val _ = Theory.check_thy thy;
   645   in Thm (der', args) end;
   646 
   647 fun adjust_maxidx_thm i (th as Thm (der, {thy_ref, tags, maxidx, shyps, hyps, tpairs, prop})) =
   648   if maxidx = i then th
   649   else if maxidx < i then
   650     Thm (der, {maxidx = i, thy_ref = thy_ref, tags = tags, shyps = shyps,
   651       hyps = hyps, tpairs = tpairs, prop = prop})
   652   else
   653     Thm (der, {maxidx = Int.max (maxidx_tpairs tpairs (maxidx_of_term prop), i), thy_ref = thy_ref,
   654       tags = tags, shyps = shyps, hyps = hyps, tpairs = tpairs, prop = prop});
   655 
   656 
   657 
   658 (*** Meta rules ***)
   659 
   660 (** primitive rules **)
   661 
   662 (*The assumption rule A |- A*)
   663 fun assume raw_ct =
   664   let val Cterm {thy_ref, t = prop, T, maxidx, sorts} = adjust_maxidx_cterm ~1 raw_ct in
   665     if T <> propT then
   666       raise THM ("assume: prop", 0, [])
   667     else if maxidx <> ~1 then
   668       raise THM ("assume: variables", maxidx, [])
   669     else Thm (deriv_rule0 (Pt.Hyp prop),
   670      {thy_ref = thy_ref,
   671       tags = [],
   672       maxidx = ~1,
   673       shyps = sorts,
   674       hyps = [prop],
   675       tpairs = [],
   676       prop = prop})
   677   end;
   678 
   679 (*Implication introduction
   680     [A]
   681      :
   682      B
   683   -------
   684   A ==> B
   685 *)
   686 fun implies_intr
   687     (ct as Cterm {t = A, T, maxidx = maxidxA, sorts, ...})
   688     (th as Thm (der, {maxidx, hyps, shyps, tpairs, prop, ...})) =
   689   if T <> propT then
   690     raise THM ("implies_intr: assumptions must have type prop", 0, [th])
   691   else
   692     Thm (deriv_rule1 (Pt.implies_intr_proof A) der,
   693      {thy_ref = merge_thys1 ct th,
   694       tags = [],
   695       maxidx = Int.max (maxidxA, maxidx),
   696       shyps = Sorts.union sorts shyps,
   697       hyps = remove_hyps A hyps,
   698       tpairs = tpairs,
   699       prop = Logic.mk_implies (A, prop)});
   700 
   701 
   702 (*Implication elimination
   703   A ==> B    A
   704   ------------
   705         B
   706 *)
   707 fun implies_elim thAB thA =
   708   let
   709     val Thm (derA, {maxidx = maxA, hyps = hypsA, shyps = shypsA, tpairs = tpairsA,
   710       prop = propA, ...}) = thA
   711     and Thm (der, {maxidx, hyps, shyps, tpairs, prop, ...}) = thAB;
   712     fun err () = raise THM ("implies_elim: major premise", 0, [thAB, thA]);
   713   in
   714     case prop of
   715       Const ("==>", _) $ A $ B =>
   716         if A aconv propA then
   717           Thm (deriv_rule2 (curry Pt.%%) der derA,
   718            {thy_ref = merge_thys2 thAB thA,
   719             tags = [],
   720             maxidx = Int.max (maxA, maxidx),
   721             shyps = Sorts.union shypsA shyps,
   722             hyps = union_hyps hypsA hyps,
   723             tpairs = union_tpairs tpairsA tpairs,
   724             prop = B})
   725         else err ()
   726     | _ => err ()
   727   end;
   728 
   729 (*Forall introduction.  The Free or Var x must not be free in the hypotheses.
   730     [x]
   731      :
   732      A
   733   ------
   734   !!x. A
   735 *)
   736 fun forall_intr
   737     (ct as Cterm {t = x, T, sorts, ...})
   738     (th as Thm (der, {maxidx, shyps, hyps, tpairs, prop, ...})) =
   739   let
   740     fun result a =
   741       Thm (deriv_rule1 (Pt.forall_intr_proof x a) der,
   742        {thy_ref = merge_thys1 ct th,
   743         tags = [],
   744         maxidx = maxidx,
   745         shyps = Sorts.union sorts shyps,
   746         hyps = hyps,
   747         tpairs = tpairs,
   748         prop = Term.all T $ Abs (a, T, abstract_over (x, prop))});
   749     fun check_occs a x ts =
   750       if exists (fn t => Logic.occs (x, t)) ts then
   751         raise THM ("forall_intr: variable " ^ quote a ^ " free in assumptions", 0, [th])
   752       else ();
   753   in
   754     case x of
   755       Free (a, _) => (check_occs a x hyps; check_occs a x (terms_of_tpairs tpairs); result a)
   756     | Var ((a, _), _) => (check_occs a x (terms_of_tpairs tpairs); result a)
   757     | _ => raise THM ("forall_intr: not a variable", 0, [th])
   758   end;
   759 
   760 (*Forall elimination
   761   !!x. A
   762   ------
   763   A[t/x]
   764 *)
   765 fun forall_elim
   766     (ct as Cterm {t, T, maxidx = maxt, sorts, ...})
   767     (th as Thm (der, {maxidx, shyps, hyps, tpairs, prop, ...})) =
   768   (case prop of
   769     Const ("all", Type ("fun", [Type ("fun", [qary, _]), _])) $ A =>
   770       if T <> qary then
   771         raise THM ("forall_elim: type mismatch", 0, [th])
   772       else
   773         Thm (deriv_rule1 (Pt.% o rpair (SOME t)) der,
   774          {thy_ref = merge_thys1 ct th,
   775           tags = [],
   776           maxidx = Int.max (maxidx, maxt),
   777           shyps = Sorts.union sorts shyps,
   778           hyps = hyps,
   779           tpairs = tpairs,
   780           prop = Term.betapply (A, t)})
   781   | _ => raise THM ("forall_elim: not quantified", 0, [th]));
   782 
   783 
   784 (* Equality *)
   785 
   786 (*Reflexivity
   787   t == t
   788 *)
   789 fun reflexive (Cterm {thy_ref, t, T = _, maxidx, sorts}) =
   790   Thm (deriv_rule0 Pt.reflexive,
   791    {thy_ref = thy_ref,
   792     tags = [],
   793     maxidx = maxidx,
   794     shyps = sorts,
   795     hyps = [],
   796     tpairs = [],
   797     prop = Logic.mk_equals (t, t)});
   798 
   799 (*Symmetry
   800   t == u
   801   ------
   802   u == t
   803 *)
   804 fun symmetric (th as Thm (der, {thy_ref, maxidx, shyps, hyps, tpairs, prop, ...})) =
   805   (case prop of
   806     (eq as Const ("==", _)) $ t $ u =>
   807       Thm (deriv_rule1 Pt.symmetric der,
   808        {thy_ref = thy_ref,
   809         tags = [],
   810         maxidx = maxidx,
   811         shyps = shyps,
   812         hyps = hyps,
   813         tpairs = tpairs,
   814         prop = eq $ u $ t})
   815     | _ => raise THM ("symmetric", 0, [th]));
   816 
   817 (*Transitivity
   818   t1 == u    u == t2
   819   ------------------
   820        t1 == t2
   821 *)
   822 fun transitive th1 th2 =
   823   let
   824     val Thm (der1, {maxidx = max1, hyps = hyps1, shyps = shyps1, tpairs = tpairs1,
   825       prop = prop1, ...}) = th1
   826     and Thm (der2, {maxidx = max2, hyps = hyps2, shyps = shyps2, tpairs = tpairs2,
   827       prop = prop2, ...}) = th2;
   828     fun err msg = raise THM ("transitive: " ^ msg, 0, [th1, th2]);
   829   in
   830     case (prop1, prop2) of
   831       ((eq as Const ("==", Type (_, [T, _]))) $ t1 $ u, Const ("==", _) $ u' $ t2) =>
   832         if not (u aconv u') then err "middle term"
   833         else
   834           Thm (deriv_rule2 (Pt.transitive u T) der1 der2,
   835            {thy_ref = merge_thys2 th1 th2,
   836             tags = [],
   837             maxidx = Int.max (max1, max2),
   838             shyps = Sorts.union shyps1 shyps2,
   839             hyps = union_hyps hyps1 hyps2,
   840             tpairs = union_tpairs tpairs1 tpairs2,
   841             prop = eq $ t1 $ t2})
   842      | _ =>  err "premises"
   843   end;
   844 
   845 (*Beta-conversion
   846   (%x. t)(u) == t[u/x]
   847   fully beta-reduces the term if full = true
   848 *)
   849 fun beta_conversion full (Cterm {thy_ref, t, T = _, maxidx, sorts}) =
   850   let val t' =
   851     if full then Envir.beta_norm t
   852     else
   853       (case t of Abs (_, _, bodt) $ u => subst_bound (u, bodt)
   854       | _ => raise THM ("beta_conversion: not a redex", 0, []));
   855   in
   856     Thm (deriv_rule0 Pt.reflexive,
   857      {thy_ref = thy_ref,
   858       tags = [],
   859       maxidx = maxidx,
   860       shyps = sorts,
   861       hyps = [],
   862       tpairs = [],
   863       prop = Logic.mk_equals (t, t')})
   864   end;
   865 
   866 fun eta_conversion (Cterm {thy_ref, t, T = _, maxidx, sorts}) =
   867   Thm (deriv_rule0 Pt.reflexive,
   868    {thy_ref = thy_ref,
   869     tags = [],
   870     maxidx = maxidx,
   871     shyps = sorts,
   872     hyps = [],
   873     tpairs = [],
   874     prop = Logic.mk_equals (t, Envir.eta_contract t)});
   875 
   876 fun eta_long_conversion (Cterm {thy_ref, t, T = _, maxidx, sorts}) =
   877   Thm (deriv_rule0 Pt.reflexive,
   878    {thy_ref = thy_ref,
   879     tags = [],
   880     maxidx = maxidx,
   881     shyps = sorts,
   882     hyps = [],
   883     tpairs = [],
   884     prop = Logic.mk_equals (t, Pattern.eta_long [] t)});
   885 
   886 (*The abstraction rule.  The Free or Var x must not be free in the hypotheses.
   887   The bound variable will be named "a" (since x will be something like x320)
   888       t == u
   889   --------------
   890   %x. t == %x. u
   891 *)
   892 fun abstract_rule a
   893     (Cterm {t = x, T, sorts, ...})
   894     (th as Thm (der, {thy_ref, maxidx, hyps, shyps, tpairs, prop, ...})) =
   895   let
   896     val (t, u) = Logic.dest_equals prop
   897       handle TERM _ => raise THM ("abstract_rule: premise not an equality", 0, [th]);
   898     val result =
   899       Thm (deriv_rule1 (Pt.abstract_rule x a) der,
   900        {thy_ref = thy_ref,
   901         tags = [],
   902         maxidx = maxidx,
   903         shyps = Sorts.union sorts shyps,
   904         hyps = hyps,
   905         tpairs = tpairs,
   906         prop = Logic.mk_equals
   907           (Abs (a, T, abstract_over (x, t)), Abs (a, T, abstract_over (x, u)))});
   908     fun check_occs a x ts =
   909       if exists (fn t => Logic.occs (x, t)) ts then
   910         raise THM ("abstract_rule: variable " ^ quote a ^ " free in assumptions", 0, [th])
   911       else ();
   912   in
   913     case x of
   914       Free (a, _) => (check_occs a x hyps; check_occs a x (terms_of_tpairs tpairs); result)
   915     | Var ((a, _), _) => (check_occs a x (terms_of_tpairs tpairs); result)
   916     | _ => raise THM ("abstract_rule: not a variable", 0, [th])
   917   end;
   918 
   919 (*The combination rule
   920   f == g  t == u
   921   --------------
   922     f t == g u
   923 *)
   924 fun combination th1 th2 =
   925   let
   926     val Thm (der1, {maxidx = max1, shyps = shyps1, hyps = hyps1, tpairs = tpairs1,
   927       prop = prop1, ...}) = th1
   928     and Thm (der2, {maxidx = max2, shyps = shyps2, hyps = hyps2, tpairs = tpairs2,
   929       prop = prop2, ...}) = th2;
   930     fun chktypes fT tT =
   931       (case fT of
   932         Type ("fun", [T1, _]) =>
   933           if T1 <> tT then
   934             raise THM ("combination: types", 0, [th1, th2])
   935           else ()
   936       | _ => raise THM ("combination: not function type", 0, [th1, th2]));
   937   in
   938     case (prop1, prop2) of
   939       (Const ("==", Type ("fun", [fT, _])) $ f $ g,
   940        Const ("==", Type ("fun", [tT, _])) $ t $ u) =>
   941         (chktypes fT tT;
   942           Thm (deriv_rule2 (Pt.combination f g t u fT) der1 der2,
   943            {thy_ref = merge_thys2 th1 th2,
   944             tags = [],
   945             maxidx = Int.max (max1, max2),
   946             shyps = Sorts.union shyps1 shyps2,
   947             hyps = union_hyps hyps1 hyps2,
   948             tpairs = union_tpairs tpairs1 tpairs2,
   949             prop = Logic.mk_equals (f $ t, g $ u)}))
   950      | _ => raise THM ("combination: premises", 0, [th1, th2])
   951   end;
   952 
   953 (*Equality introduction
   954   A ==> B  B ==> A
   955   ----------------
   956        A == B
   957 *)
   958 fun equal_intr th1 th2 =
   959   let
   960     val Thm (der1, {maxidx = max1, shyps = shyps1, hyps = hyps1, tpairs = tpairs1,
   961       prop = prop1, ...}) = th1
   962     and Thm (der2, {maxidx = max2, shyps = shyps2, hyps = hyps2, tpairs = tpairs2,
   963       prop = prop2, ...}) = th2;
   964     fun err msg = raise THM ("equal_intr: " ^ msg, 0, [th1, th2]);
   965   in
   966     case (prop1, prop2) of
   967       (Const("==>", _) $ A $ B, Const("==>", _) $ B' $ A') =>
   968         if A aconv A' andalso B aconv B' then
   969           Thm (deriv_rule2 (Pt.equal_intr A B) der1 der2,
   970            {thy_ref = merge_thys2 th1 th2,
   971             tags = [],
   972             maxidx = Int.max (max1, max2),
   973             shyps = Sorts.union shyps1 shyps2,
   974             hyps = union_hyps hyps1 hyps2,
   975             tpairs = union_tpairs tpairs1 tpairs2,
   976             prop = Logic.mk_equals (A, B)})
   977         else err "not equal"
   978     | _ =>  err "premises"
   979   end;
   980 
   981 (*The equal propositions rule
   982   A == B  A
   983   ---------
   984       B
   985 *)
   986 fun equal_elim th1 th2 =
   987   let
   988     val Thm (der1, {maxidx = max1, shyps = shyps1, hyps = hyps1,
   989       tpairs = tpairs1, prop = prop1, ...}) = th1
   990     and Thm (der2, {maxidx = max2, shyps = shyps2, hyps = hyps2,
   991       tpairs = tpairs2, prop = prop2, ...}) = th2;
   992     fun err msg = raise THM ("equal_elim: " ^ msg, 0, [th1, th2]);
   993   in
   994     case prop1 of
   995       Const ("==", _) $ A $ B =>
   996         if prop2 aconv A then
   997           Thm (deriv_rule2 (Pt.equal_elim A B) der1 der2,
   998            {thy_ref = merge_thys2 th1 th2,
   999             tags = [],
  1000             maxidx = Int.max (max1, max2),
  1001             shyps = Sorts.union shyps1 shyps2,
  1002             hyps = union_hyps hyps1 hyps2,
  1003             tpairs = union_tpairs tpairs1 tpairs2,
  1004             prop = B})
  1005         else err "not equal"
  1006      | _ =>  err"major premise"
  1007   end;
  1008 
  1009 
  1010 
  1011 (**** Derived rules ****)
  1012 
  1013 (*Smash unifies the list of term pairs leaving no flex-flex pairs.
  1014   Instantiates the theorem and deletes trivial tpairs.  Resulting
  1015   sequence may contain multiple elements if the tpairs are not all
  1016   flex-flex.*)
  1017 fun flexflex_rule (th as Thm (der, {thy_ref, maxidx, shyps, hyps, tpairs, prop, ...})) =
  1018   let val thy = Theory.deref thy_ref in
  1019     Unify.smash_unifiers thy tpairs (Envir.empty maxidx)
  1020     |> Seq.map (fn env =>
  1021         if Envir.is_empty env then th
  1022         else
  1023           let
  1024             val tpairs' = tpairs |> map (pairself (Envir.norm_term env))
  1025               (*remove trivial tpairs, of the form t==t*)
  1026               |> filter_out (op aconv);
  1027             val der' = deriv_rule1 (Pt.norm_proof' env) der;
  1028             val prop' = Envir.norm_term env prop;
  1029             val maxidx = maxidx_tpairs tpairs' (maxidx_of_term prop');
  1030             val shyps = Envir.insert_sorts env shyps;
  1031           in
  1032             Thm (der', {thy_ref = Theory.check_thy thy, tags = [], maxidx = maxidx,
  1033               shyps = shyps, hyps = hyps, tpairs = tpairs', prop = prop'})
  1034           end)
  1035   end;
  1036 
  1037 
  1038 (*Generalization of fixed variables
  1039            A
  1040   --------------------
  1041   A[?'a/'a, ?x/x, ...]
  1042 *)
  1043 
  1044 fun generalize ([], []) _ th = th
  1045   | generalize (tfrees, frees) idx th =
  1046       let
  1047         val Thm (der, {thy_ref, maxidx, shyps, hyps, tpairs, prop, ...}) = th;
  1048         val _ = idx <= maxidx andalso raise THM ("generalize: bad index", idx, [th]);
  1049 
  1050         val bad_type =
  1051           if null tfrees then K false
  1052           else Term.exists_subtype (fn TFree (a, _) => member (op =) tfrees a | _ => false);
  1053         fun bad_term (Free (x, T)) = bad_type T orelse member (op =) frees x
  1054           | bad_term (Var (_, T)) = bad_type T
  1055           | bad_term (Const (_, T)) = bad_type T
  1056           | bad_term (Abs (_, T, t)) = bad_type T orelse bad_term t
  1057           | bad_term (t $ u) = bad_term t orelse bad_term u
  1058           | bad_term (Bound _) = false;
  1059         val _ = exists bad_term hyps andalso
  1060           raise THM ("generalize: variable free in assumptions", 0, [th]);
  1061 
  1062         val gen = Term_Subst.generalize (tfrees, frees) idx;
  1063         val prop' = gen prop;
  1064         val tpairs' = map (pairself gen) tpairs;
  1065         val maxidx' = maxidx_tpairs tpairs' (maxidx_of_term prop');
  1066       in
  1067         Thm (deriv_rule1 (Pt.generalize (tfrees, frees) idx) der,
  1068          {thy_ref = thy_ref,
  1069           tags = [],
  1070           maxidx = maxidx',
  1071           shyps = shyps,
  1072           hyps = hyps,
  1073           tpairs = tpairs',
  1074           prop = prop'})
  1075       end;
  1076 
  1077 
  1078 (*Instantiation of schematic variables
  1079            A
  1080   --------------------
  1081   A[t1/v1, ..., tn/vn]
  1082 *)
  1083 
  1084 local
  1085 
  1086 fun pretty_typing thy t T = Pretty.block
  1087   [Syntax.pretty_term_global thy t, Pretty.str " ::", Pretty.brk 1, Syntax.pretty_typ_global thy T];
  1088 
  1089 fun add_inst (ct, cu) (thy_ref, sorts) =
  1090   let
  1091     val Cterm {t = t, T = T, ...} = ct;
  1092     val Cterm {t = u, T = U, sorts = sorts_u, maxidx = maxidx_u, ...} = cu;
  1093     val thy_ref' = Theory.merge_refs (thy_ref, merge_thys0 ct cu);
  1094     val sorts' = Sorts.union sorts_u sorts;
  1095   in
  1096     (case t of Var v =>
  1097       if T = U then ((v, (u, maxidx_u)), (thy_ref', sorts'))
  1098       else raise TYPE (Pretty.string_of (Pretty.block
  1099        [Pretty.str "instantiate: type conflict",
  1100         Pretty.fbrk, pretty_typing (Theory.deref thy_ref') t T,
  1101         Pretty.fbrk, pretty_typing (Theory.deref thy_ref') u U]), [T, U], [t, u])
  1102     | _ => raise TYPE (Pretty.string_of (Pretty.block
  1103        [Pretty.str "instantiate: not a variable",
  1104         Pretty.fbrk, Syntax.pretty_term_global (Theory.deref thy_ref') t]), [], [t]))
  1105   end;
  1106 
  1107 fun add_instT (cT, cU) (thy_ref, sorts) =
  1108   let
  1109     val Ctyp {T, thy_ref = thy_ref1, ...} = cT
  1110     and Ctyp {T = U, thy_ref = thy_ref2, sorts = sorts_U, maxidx = maxidx_U, ...} = cU;
  1111     val thy' = Theory.deref (Theory.merge_refs (thy_ref, Theory.merge_refs (thy_ref1, thy_ref2)));
  1112     val sorts' = Sorts.union sorts_U sorts;
  1113   in
  1114     (case T of TVar (v as (_, S)) =>
  1115       if Sign.of_sort thy' (U, S) then ((v, (U, maxidx_U)), (Theory.check_thy thy', sorts'))
  1116       else raise TYPE ("Type not of sort " ^ Syntax.string_of_sort_global thy' S, [U], [])
  1117     | _ => raise TYPE (Pretty.string_of (Pretty.block
  1118         [Pretty.str "instantiate: not a type variable",
  1119          Pretty.fbrk, Syntax.pretty_typ_global thy' T]), [T], []))
  1120   end;
  1121 
  1122 in
  1123 
  1124 (*Left-to-right replacements: ctpairs = [..., (vi, ti), ...].
  1125   Instantiates distinct Vars by terms of same type.
  1126   Does NOT normalize the resulting theorem!*)
  1127 fun instantiate ([], []) th = th
  1128   | instantiate (instT, inst) th =
  1129       let
  1130         val Thm (der, {thy_ref, hyps, shyps, tpairs, prop, ...}) = th;
  1131         val (inst', (instT', (thy_ref', shyps'))) =
  1132           (thy_ref, shyps) |> fold_map add_inst inst ||> fold_map add_instT instT;
  1133         val subst = Term_Subst.instantiate_maxidx (instT', inst');
  1134         val (prop', maxidx1) = subst prop ~1;
  1135         val (tpairs', maxidx') =
  1136           fold_map (fn (t, u) => fn i => subst t i ||>> subst u) tpairs maxidx1;
  1137       in
  1138         Thm (deriv_rule1 (fn d => Pt.instantiate (map (apsnd #1) instT', map (apsnd #1) inst') d) der,
  1139          {thy_ref = thy_ref',
  1140           tags = [],
  1141           maxidx = maxidx',
  1142           shyps = shyps',
  1143           hyps = hyps,
  1144           tpairs = tpairs',
  1145           prop = prop'})
  1146       end
  1147       handle TYPE (msg, _, _) => raise THM (msg, 0, [th]);
  1148 
  1149 fun instantiate_cterm ([], []) ct = ct
  1150   | instantiate_cterm (instT, inst) ct =
  1151       let
  1152         val Cterm {thy_ref, t, T, sorts, ...} = ct;
  1153         val (inst', (instT', (thy_ref', sorts'))) =
  1154           (thy_ref, sorts) |> fold_map add_inst inst ||> fold_map add_instT instT;
  1155         val subst = Term_Subst.instantiate_maxidx (instT', inst');
  1156         val substT = Term_Subst.instantiateT_maxidx instT';
  1157         val (t', maxidx1) = subst t ~1;
  1158         val (T', maxidx') = substT T maxidx1;
  1159       in Cterm {thy_ref = thy_ref', t = t', T = T', sorts = sorts', maxidx = maxidx'} end
  1160       handle TYPE (msg, _, _) => raise CTERM (msg, [ct]);
  1161 
  1162 end;
  1163 
  1164 
  1165 (*The trivial implication A ==> A, justified by assume and forall rules.
  1166   A can contain Vars, not so for assume!*)
  1167 fun trivial (Cterm {thy_ref, t =A, T, maxidx, sorts}) =
  1168   if T <> propT then
  1169     raise THM ("trivial: the term must have type prop", 0, [])
  1170   else
  1171     Thm (deriv_rule0 (Pt.AbsP ("H", NONE, Pt.PBound 0)),
  1172      {thy_ref = thy_ref,
  1173       tags = [],
  1174       maxidx = maxidx,
  1175       shyps = sorts,
  1176       hyps = [],
  1177       tpairs = [],
  1178       prop = Logic.mk_implies (A, A)});
  1179 
  1180 (*Axiom-scheme reflecting signature contents
  1181         T :: c
  1182   -------------------
  1183   OFCLASS(T, c_class)
  1184 *)
  1185 fun of_class (cT, raw_c) =
  1186   let
  1187     val Ctyp {thy_ref, T, ...} = cT;
  1188     val thy = Theory.deref thy_ref;
  1189     val c = Sign.certify_class thy raw_c;
  1190     val Cterm {t = prop, maxidx, sorts, ...} = cterm_of thy (Logic.mk_of_class (T, c));
  1191   in
  1192     if Sign.of_sort thy (T, [c]) then
  1193       Thm (deriv_rule0 (Pt.OfClass (T, c)),
  1194        {thy_ref = Theory.check_thy thy,
  1195         tags = [],
  1196         maxidx = maxidx,
  1197         shyps = sorts,
  1198         hyps = [],
  1199         tpairs = [],
  1200         prop = prop})
  1201     else raise THM ("of_class: type not of class " ^ Syntax.string_of_sort_global thy [c], 0, [])
  1202   end;
  1203 
  1204 (*Remove extra sorts that are witnessed by type signature information*)
  1205 fun strip_shyps (thm as Thm (_, {shyps = [], ...})) = thm
  1206   | strip_shyps (thm as Thm (der, {thy_ref, tags, maxidx, shyps, hyps, tpairs, prop})) =
  1207       let
  1208         val thy = Theory.deref thy_ref;
  1209         val algebra = Sign.classes_of thy;
  1210 
  1211         val present = (fold_terms o fold_types o fold_atyps_sorts) (insert (eq_fst op =)) thm [];
  1212         val extra = fold (Sorts.remove_sort o #2) present shyps;
  1213         val witnessed = Sign.witness_sorts thy present extra;
  1214         val extra' = fold (Sorts.remove_sort o #2) witnessed extra
  1215           |> Sorts.minimal_sorts algebra;
  1216         val shyps' = fold (Sorts.insert_sort o #2) present extra';
  1217       in
  1218         Thm (deriv_rule_unconditional (Pt.strip_shyps_proof algebra present witnessed extra') der,
  1219          {thy_ref = Theory.check_thy thy, tags = tags, maxidx = maxidx,
  1220           shyps = shyps', hyps = hyps, tpairs = tpairs, prop = prop})
  1221       end;
  1222 
  1223 (*Internalize sort constraints of type variables*)
  1224 fun unconstrainT (thm as Thm (der, args)) =
  1225   let
  1226     val Deriv {promises, body} = der;
  1227     val {thy_ref, shyps, hyps, tpairs, prop, ...} = args;
  1228 
  1229     fun err msg = raise THM ("unconstrainT: " ^ msg, 0, [thm]);
  1230     val _ = null hyps orelse err "illegal hyps";
  1231     val _ = null tpairs orelse err "unsolved flex-flex constraints";
  1232     val tfrees = rev (Term.add_tfree_names prop []);
  1233     val _ = null tfrees orelse err ("illegal free type variables " ^ commas_quote tfrees);
  1234 
  1235     val ps = map (apsnd (Future.map proof_body_of)) promises;
  1236     val thy = Theory.deref thy_ref;
  1237     val (pthm as (_, (_, prop', _)), proof) = Pt.unconstrain_thm_proof thy shyps prop ps body;
  1238     val der' = make_deriv [] [] [pthm] proof;
  1239     val _ = Theory.check_thy thy;
  1240   in
  1241     Thm (der',
  1242      {thy_ref = thy_ref,
  1243       tags = [],
  1244       maxidx = maxidx_of_term prop',
  1245       shyps = [[]],  (*potentially redundant*)
  1246       hyps = [],
  1247       tpairs = [],
  1248       prop = prop'})
  1249   end;
  1250 
  1251 (* Replace all TFrees not fixed or in the hyps by new TVars *)
  1252 fun varifyT_global' fixed (Thm (der, {thy_ref, maxidx, shyps, hyps, tpairs, prop, ...})) =
  1253   let
  1254     val tfrees = fold Term.add_tfrees hyps fixed;
  1255     val prop1 = attach_tpairs tpairs prop;
  1256     val (al, prop2) = Type.varify_global tfrees prop1;
  1257     val (ts, prop3) = Logic.strip_prems (length tpairs, [], prop2);
  1258   in
  1259     (al, Thm (deriv_rule1 (Pt.varify_proof prop tfrees) der,
  1260      {thy_ref = thy_ref,
  1261       tags = [],
  1262       maxidx = Int.max (0, maxidx),
  1263       shyps = shyps,
  1264       hyps = hyps,
  1265       tpairs = rev (map Logic.dest_equals ts),
  1266       prop = prop3}))
  1267   end;
  1268 
  1269 val varifyT_global = #2 o varifyT_global' [];
  1270 
  1271 (* Replace all TVars by TFrees that are often new *)
  1272 fun legacy_freezeT (Thm (der, {thy_ref, shyps, hyps, tpairs, prop, ...})) =
  1273   let
  1274     val prop1 = attach_tpairs tpairs prop;
  1275     val prop2 = Type.legacy_freeze prop1;
  1276     val (ts, prop3) = Logic.strip_prems (length tpairs, [], prop2);
  1277   in
  1278     Thm (deriv_rule1 (Pt.legacy_freezeT prop1) der,
  1279      {thy_ref = thy_ref,
  1280       tags = [],
  1281       maxidx = maxidx_of_term prop2,
  1282       shyps = shyps,
  1283       hyps = hyps,
  1284       tpairs = rev (map Logic.dest_equals ts),
  1285       prop = prop3})
  1286   end;
  1287 
  1288 
  1289 (*** Inference rules for tactics ***)
  1290 
  1291 (*Destruct proof state into constraints, other goals, goal(i), rest *)
  1292 fun dest_state (state as Thm (_, {prop,tpairs,...}), i) =
  1293   (case  Logic.strip_prems(i, [], prop) of
  1294       (B::rBs, C) => (tpairs, rev rBs, B, C)
  1295     | _ => raise THM("dest_state", i, [state]))
  1296   handle TERM _ => raise THM("dest_state", i, [state]);
  1297 
  1298 (*Increment variables and parameters of orule as required for
  1299   resolution with a goal.*)
  1300 fun lift_rule goal orule =
  1301   let
  1302     val Cterm {t = gprop, T, maxidx = gmax, sorts, ...} = goal;
  1303     val inc = gmax + 1;
  1304     val lift_abs = Logic.lift_abs inc gprop;
  1305     val lift_all = Logic.lift_all inc gprop;
  1306     val Thm (der, {maxidx, shyps, hyps, tpairs, prop, ...}) = orule;
  1307     val (As, B) = Logic.strip_horn prop;
  1308   in
  1309     if T <> propT then raise THM ("lift_rule: the term must have type prop", 0, [])
  1310     else
  1311       Thm (deriv_rule1 (Pt.lift_proof gprop inc prop) der,
  1312        {thy_ref = merge_thys1 goal orule,
  1313         tags = [],
  1314         maxidx = maxidx + inc,
  1315         shyps = Sorts.union shyps sorts,  (*sic!*)
  1316         hyps = hyps,
  1317         tpairs = map (pairself lift_abs) tpairs,
  1318         prop = Logic.list_implies (map lift_all As, lift_all B)})
  1319   end;
  1320 
  1321 fun incr_indexes i (thm as Thm (der, {thy_ref, maxidx, shyps, hyps, tpairs, prop, ...})) =
  1322   if i < 0 then raise THM ("negative increment", 0, [thm])
  1323   else if i = 0 then thm
  1324   else
  1325     Thm (deriv_rule1 (Pt.incr_indexes i) der,
  1326      {thy_ref = thy_ref,
  1327       tags = [],
  1328       maxidx = maxidx + i,
  1329       shyps = shyps,
  1330       hyps = hyps,
  1331       tpairs = map (pairself (Logic.incr_indexes ([], i))) tpairs,
  1332       prop = Logic.incr_indexes ([], i) prop});
  1333 
  1334 (*Solve subgoal Bi of proof state B1...Bn/C by assumption. *)
  1335 fun assumption i state =
  1336   let
  1337     val Thm (der, {thy_ref, maxidx, shyps, hyps, ...}) = state;
  1338     val thy = Theory.deref thy_ref;
  1339     val (tpairs, Bs, Bi, C) = dest_state (state, i);
  1340     fun newth n (env, tpairs) =
  1341       Thm (deriv_rule1
  1342           ((if Envir.is_empty env then I else (Pt.norm_proof' env)) o
  1343             Pt.assumption_proof Bs Bi n) der,
  1344        {tags = [],
  1345         maxidx = Envir.maxidx_of env,
  1346         shyps = Envir.insert_sorts env shyps,
  1347         hyps = hyps,
  1348         tpairs =
  1349           if Envir.is_empty env then tpairs
  1350           else map (pairself (Envir.norm_term env)) tpairs,
  1351         prop =
  1352           if Envir.is_empty env then (*avoid wasted normalizations*)
  1353             Logic.list_implies (Bs, C)
  1354           else (*normalize the new rule fully*)
  1355             Envir.norm_term env (Logic.list_implies (Bs, C)),
  1356         thy_ref = Theory.check_thy thy});
  1357 
  1358     val (close, asms, concl) = Logic.assum_problems (~1, Bi);
  1359     val concl' = close concl;
  1360     fun addprfs [] _ = Seq.empty
  1361       | addprfs (asm :: rest) n = Seq.make (fn () => Seq.pull
  1362           (Seq.mapp (newth n)
  1363             (if Term.could_unify (asm, concl) then
  1364               (Unify.unifiers (thy, Envir.empty maxidx, (close asm, concl') :: tpairs))
  1365              else Seq.empty)
  1366             (addprfs rest (n + 1))))
  1367   in addprfs asms 1 end;
  1368 
  1369 (*Solve subgoal Bi of proof state B1...Bn/C by assumption.
  1370   Checks if Bi's conclusion is alpha-convertible to one of its assumptions*)
  1371 fun eq_assumption i state =
  1372   let
  1373     val Thm (der, {thy_ref, maxidx, shyps, hyps, ...}) = state;
  1374     val (tpairs, Bs, Bi, C) = dest_state (state, i);
  1375     val (_, asms, concl) = Logic.assum_problems (~1, Bi);
  1376   in
  1377     (case find_index (fn asm => Pattern.aeconv (asm, concl)) asms of
  1378       ~1 => raise THM ("eq_assumption", 0, [state])
  1379     | n =>
  1380         Thm (deriv_rule1 (Pt.assumption_proof Bs Bi (n + 1)) der,
  1381          {thy_ref = thy_ref,
  1382           tags = [],
  1383           maxidx = maxidx,
  1384           shyps = shyps,
  1385           hyps = hyps,
  1386           tpairs = tpairs,
  1387           prop = Logic.list_implies (Bs, C)}))
  1388   end;
  1389 
  1390 
  1391 (*For rotate_tac: fast rotation of assumptions of subgoal i*)
  1392 fun rotate_rule k i state =
  1393   let
  1394     val Thm (der, {thy_ref, maxidx, shyps, hyps, ...}) = state;
  1395     val (tpairs, Bs, Bi, C) = dest_state (state, i);
  1396     val params = Term.strip_all_vars Bi
  1397     and rest   = Term.strip_all_body Bi;
  1398     val asms   = Logic.strip_imp_prems rest
  1399     and concl  = Logic.strip_imp_concl rest;
  1400     val n = length asms;
  1401     val m = if k < 0 then n + k else k;
  1402     val Bi' =
  1403       if 0 = m orelse m = n then Bi
  1404       else if 0 < m andalso m < n then
  1405         let val (ps, qs) = chop m asms
  1406         in list_all (params, Logic.list_implies (qs @ ps, concl)) end
  1407       else raise THM ("rotate_rule", k, [state]);
  1408   in
  1409     Thm (deriv_rule1 (Pt.rotate_proof Bs Bi m) der,
  1410      {thy_ref = thy_ref,
  1411       tags = [],
  1412       maxidx = maxidx,
  1413       shyps = shyps,
  1414       hyps = hyps,
  1415       tpairs = tpairs,
  1416       prop = Logic.list_implies (Bs @ [Bi'], C)})
  1417   end;
  1418 
  1419 
  1420 (*Rotates a rule's premises to the left by k, leaving the first j premises
  1421   unchanged.  Does nothing if k=0 or if k equals n-j, where n is the
  1422   number of premises.  Useful with etac and underlies defer_tac*)
  1423 fun permute_prems j k rl =
  1424   let
  1425     val Thm (der, {thy_ref, maxidx, shyps, hyps, tpairs, prop, ...}) = rl;
  1426     val prems = Logic.strip_imp_prems prop
  1427     and concl = Logic.strip_imp_concl prop;
  1428     val moved_prems = List.drop (prems, j)
  1429     and fixed_prems = List.take (prems, j)
  1430       handle Subscript => raise THM ("permute_prems: j", j, [rl]);
  1431     val n_j = length moved_prems;
  1432     val m = if k < 0 then n_j + k else k;
  1433     val prop' =
  1434       if 0 = m orelse m = n_j then prop
  1435       else if 0 < m andalso m < n_j then
  1436         let val (ps, qs) = chop m moved_prems
  1437         in Logic.list_implies (fixed_prems @ qs @ ps, concl) end
  1438       else raise THM ("permute_prems: k", k, [rl]);
  1439   in
  1440     Thm (deriv_rule1 (Pt.permute_prems_proof prems j m) der,
  1441      {thy_ref = thy_ref,
  1442       tags = [],
  1443       maxidx = maxidx,
  1444       shyps = shyps,
  1445       hyps = hyps,
  1446       tpairs = tpairs,
  1447       prop = prop'})
  1448   end;
  1449 
  1450 
  1451 (** User renaming of parameters in a subgoal **)
  1452 
  1453 (*Calls error rather than raising an exception because it is intended
  1454   for top-level use -- exception handling would not make sense here.
  1455   The names in cs, if distinct, are used for the innermost parameters;
  1456   preceding parameters may be renamed to make all params distinct.*)
  1457 fun rename_params_rule (cs, i) state =
  1458   let
  1459     val Thm (der, {thy_ref, tags, maxidx, shyps, hyps, ...}) = state;
  1460     val (tpairs, Bs, Bi, C) = dest_state (state, i);
  1461     val iparams = map #1 (Logic.strip_params Bi);
  1462     val short = length iparams - length cs;
  1463     val newnames =
  1464       if short < 0 then error "More names than abstractions!"
  1465       else Name.variant_list cs (take short iparams) @ cs;
  1466     val freenames = Term.fold_aterms (fn Free (x, _) => insert (op =) x | _ => I) Bi [];
  1467     val newBi = Logic.list_rename_params (newnames, Bi);
  1468   in
  1469     (case duplicates (op =) cs of
  1470       a :: _ => (warning ("Can't rename.  Bound variables not distinct: " ^ a); state)
  1471     | [] =>
  1472       (case inter (op =) cs freenames of
  1473         a :: _ => (warning ("Can't rename.  Bound/Free variable clash: " ^ a); state)
  1474       | [] =>
  1475         Thm (der,
  1476          {thy_ref = thy_ref,
  1477           tags = tags,
  1478           maxidx = maxidx,
  1479           shyps = shyps,
  1480           hyps = hyps,
  1481           tpairs = tpairs,
  1482           prop = Logic.list_implies (Bs @ [newBi], C)})))
  1483   end;
  1484 
  1485 
  1486 (*** Preservation of bound variable names ***)
  1487 
  1488 fun rename_boundvars pat obj (thm as Thm (der, {thy_ref, tags, maxidx, shyps, hyps, tpairs, prop})) =
  1489   (case Term.rename_abs pat obj prop of
  1490     NONE => thm
  1491   | SOME prop' => Thm (der,
  1492       {thy_ref = thy_ref,
  1493        tags = tags,
  1494        maxidx = maxidx,
  1495        hyps = hyps,
  1496        shyps = shyps,
  1497        tpairs = tpairs,
  1498        prop = prop'}));
  1499 
  1500 
  1501 (* strip_apply f (A, B) strips off all assumptions/parameters from A
  1502    introduced by lifting over B, and applies f to remaining part of A*)
  1503 fun strip_apply f =
  1504   let fun strip(Const("==>",_)$ A1 $ B1,
  1505                 Const("==>",_)$ _  $ B2) = Logic.mk_implies (A1, strip(B1,B2))
  1506         | strip((c as Const("all",_)) $ Abs(a,T,t1),
  1507                       Const("all",_)  $ Abs(_,_,t2)) = c$Abs(a,T,strip(t1,t2))
  1508         | strip(A,_) = f A
  1509   in strip end;
  1510 
  1511 (*Use the alist to rename all bound variables and some unknowns in a term
  1512   dpairs = current disagreement pairs;  tpairs = permanent ones (flexflex);
  1513   Preserves unknowns in tpairs and on lhs of dpairs. *)
  1514 fun rename_bvs([],_,_,_) = I
  1515   | rename_bvs(al,dpairs,tpairs,B) =
  1516       let
  1517         val add_var = fold_aterms (fn Var ((x, _), _) => insert (op =) x | _ => I);
  1518         val vids = []
  1519           |> fold (add_var o fst) dpairs
  1520           |> fold (add_var o fst) tpairs
  1521           |> fold (add_var o snd) tpairs;
  1522         (*unknowns appearing elsewhere be preserved!*)
  1523         fun rename(t as Var((x,i),T)) =
  1524               (case AList.lookup (op =) al x of
  1525                 SOME y =>
  1526                   if member (op =) vids x orelse member (op =) vids y then t
  1527                   else Var((y,i),T)
  1528               | NONE=> t)
  1529           | rename(Abs(x,T,t)) =
  1530               Abs (the_default x (AList.lookup (op =) al x), T, rename t)
  1531           | rename(f$t) = rename f $ rename t
  1532           | rename(t) = t;
  1533         fun strip_ren Ai = strip_apply rename (Ai,B)
  1534       in strip_ren end;
  1535 
  1536 (*Function to rename bounds/unknowns in the argument, lifted over B*)
  1537 fun rename_bvars(dpairs, tpairs, B) =
  1538         rename_bvs(List.foldr Term.match_bvars [] dpairs, dpairs, tpairs, B);
  1539 
  1540 
  1541 (*** RESOLUTION ***)
  1542 
  1543 (** Lifting optimizations **)
  1544 
  1545 (*strip off pairs of assumptions/parameters in parallel -- they are
  1546   identical because of lifting*)
  1547 fun strip_assums2 (Const("==>", _) $ _ $ B1,
  1548                    Const("==>", _) $ _ $ B2) = strip_assums2 (B1,B2)
  1549   | strip_assums2 (Const("all",_)$Abs(a,T,t1),
  1550                    Const("all",_)$Abs(_,_,t2)) =
  1551       let val (B1,B2) = strip_assums2 (t1,t2)
  1552       in  (Abs(a,T,B1), Abs(a,T,B2))  end
  1553   | strip_assums2 BB = BB;
  1554 
  1555 
  1556 (*Faster normalization: skip assumptions that were lifted over*)
  1557 fun norm_term_skip env 0 t = Envir.norm_term env t
  1558   | norm_term_skip env n (Const ("all", _) $ Abs (a, T, t)) =
  1559       let
  1560         val T' = Envir.subst_type (Envir.type_env env) T
  1561         (*Must instantiate types of parameters because they are flattened;
  1562           this could be a NEW parameter*)
  1563       in Term.all T' $ Abs (a, T', norm_term_skip env n t) end
  1564   | norm_term_skip env n (Const ("==>", _) $ A $ B) =
  1565       Logic.mk_implies (A, norm_term_skip env (n - 1) B)
  1566   | norm_term_skip _ _ _ = error "norm_term_skip: too few assumptions??";
  1567 
  1568 
  1569 (*Composition of object rule r=(A1...Am/B) with proof state s=(B1...Bn/C)
  1570   Unifies B with Bi, replacing subgoal i    (1 <= i <= n)
  1571   If match then forbid instantiations in proof state
  1572   If lifted then shorten the dpair using strip_assums2.
  1573   If eres_flg then simultaneously proves A1 by assumption.
  1574   nsubgoal is the number of new subgoals (written m above).
  1575   Curried so that resolution calls dest_state only once.
  1576 *)
  1577 local exception COMPOSE
  1578 in
  1579 fun bicompose_aux flatten match (state, (stpairs, Bs, Bi, C), lifted)
  1580                         (eres_flg, orule, nsubgoal) =
  1581  let val Thm (sder, {maxidx=smax, shyps=sshyps, hyps=shyps, ...}) = state
  1582      and Thm (rder, {maxidx=rmax, shyps=rshyps, hyps=rhyps,
  1583              tpairs=rtpairs, prop=rprop,...}) = orule
  1584          (*How many hyps to skip over during normalization*)
  1585      and nlift = Logic.count_prems (strip_all_body Bi) + (if eres_flg then ~1 else 0)
  1586      val thy = Theory.deref (merge_thys2 state orule);
  1587      (** Add new theorem with prop = '[| Bs; As |] ==> C' to thq **)
  1588      fun addth A (As, oldAs, rder', n) ((env, tpairs), thq) =
  1589        let val normt = Envir.norm_term env;
  1590            (*perform minimal copying here by examining env*)
  1591            val (ntpairs, normp) =
  1592              if Envir.is_empty env then (tpairs, (Bs @ As, C))
  1593              else
  1594              let val ntps = map (pairself normt) tpairs
  1595              in if Envir.above env smax then
  1596                   (*no assignments in state; normalize the rule only*)
  1597                   if lifted
  1598                   then (ntps, (Bs @ map (norm_term_skip env nlift) As, C))
  1599                   else (ntps, (Bs @ map normt As, C))
  1600                 else if match then raise COMPOSE
  1601                 else (*normalize the new rule fully*)
  1602                   (ntps, (map normt (Bs @ As), normt C))
  1603              end
  1604            val th =
  1605              Thm (deriv_rule2
  1606                    ((if Envir.is_empty env then I
  1607                      else if Envir.above env smax then
  1608                        (fn f => fn der => f (Pt.norm_proof' env der))
  1609                      else
  1610                        curry op oo (Pt.norm_proof' env))
  1611                     (Pt.bicompose_proof flatten Bs oldAs As A n (nlift+1))) rder' sder,
  1612                 {tags = [],
  1613                  maxidx = Envir.maxidx_of env,
  1614                  shyps = Envir.insert_sorts env (Sorts.union rshyps sshyps),
  1615                  hyps = union_hyps rhyps shyps,
  1616                  tpairs = ntpairs,
  1617                  prop = Logic.list_implies normp,
  1618                  thy_ref = Theory.check_thy thy})
  1619         in  Seq.cons th thq  end  handle COMPOSE => thq;
  1620      val (rAs,B) = Logic.strip_prems(nsubgoal, [], rprop)
  1621        handle TERM _ => raise THM("bicompose: rule", 0, [orule,state]);
  1622      (*Modify assumptions, deleting n-th if n>0 for e-resolution*)
  1623      fun newAs(As0, n, dpairs, tpairs) =
  1624        let val (As1, rder') =
  1625          if not lifted then (As0, rder)
  1626          else (map (rename_bvars(dpairs,tpairs,B)) As0,
  1627            deriv_rule1 (Pt.map_proof_terms
  1628              (rename_bvars (dpairs, tpairs, Bound 0)) I) rder);
  1629        in (map (if flatten then (Logic.flatten_params n) else I) As1, As1, rder', n)
  1630           handle TERM _ =>
  1631           raise THM("bicompose: 1st premise", 0, [orule])
  1632        end;
  1633      val env = Envir.empty(Int.max(rmax,smax));
  1634      val BBi = if lifted then strip_assums2(B,Bi) else (B,Bi);
  1635      val dpairs = BBi :: (rtpairs@stpairs);
  1636 
  1637      (*elim-resolution: try each assumption in turn*)
  1638      fun eres [] = raise THM ("bicompose: no premises", 0, [orule, state])
  1639        | eres (A1 :: As) =
  1640            let
  1641              val A = SOME A1;
  1642              val (close, asms, concl) = Logic.assum_problems (nlift + 1, A1);
  1643              val concl' = close concl;
  1644              fun tryasms [] _ = Seq.empty
  1645                | tryasms (asm :: rest) n =
  1646                    if Term.could_unify (asm, concl) then
  1647                      let val asm' = close asm in
  1648                        (case Seq.pull (Unify.unifiers (thy, env, (asm', concl') :: dpairs)) of
  1649                          NONE => tryasms rest (n + 1)
  1650                        | cell as SOME ((_, tpairs), _) =>
  1651                            Seq.it_right (addth A (newAs (As, n, [BBi, (concl', asm')], tpairs)))
  1652                              (Seq.make (fn () => cell),
  1653                               Seq.make (fn () => Seq.pull (tryasms rest (n + 1)))))
  1654                      end
  1655                    else tryasms rest (n + 1);
  1656            in tryasms asms 1 end;
  1657 
  1658      (*ordinary resolution*)
  1659      fun res () =
  1660        (case Seq.pull (Unify.unifiers (thy, env, dpairs)) of
  1661          NONE => Seq.empty
  1662        | cell as SOME ((_, tpairs), _) =>
  1663            Seq.it_right (addth NONE (newAs (rev rAs, 0, [BBi], tpairs)))
  1664              (Seq.make (fn () => cell), Seq.empty));
  1665  in
  1666    if eres_flg then eres (rev rAs) else res ()
  1667  end;
  1668 end;
  1669 
  1670 fun compose_no_flatten match (orule, nsubgoal) i state =
  1671   bicompose_aux false match (state, dest_state (state, i), false) (false, orule, nsubgoal);
  1672 
  1673 fun bicompose match arg i state =
  1674   bicompose_aux true match (state, dest_state (state,i), false) arg;
  1675 
  1676 (*Quick test whether rule is resolvable with the subgoal with hyps Hs
  1677   and conclusion B.  If eres_flg then checks 1st premise of rule also*)
  1678 fun could_bires (Hs, B, eres_flg, rule) =
  1679     let fun could_reshyp (A1::_) = exists (fn H => Term.could_unify (A1, H)) Hs
  1680           | could_reshyp [] = false;  (*no premise -- illegal*)
  1681     in  Term.could_unify(concl_of rule, B) andalso
  1682         (not eres_flg  orelse  could_reshyp (prems_of rule))
  1683     end;
  1684 
  1685 (*Bi-resolution of a state with a list of (flag,rule) pairs.
  1686   Puts the rule above:  rule/state.  Renames vars in the rules. *)
  1687 fun biresolution match brules i state =
  1688     let val (stpairs, Bs, Bi, C) = dest_state(state,i);
  1689         val lift = lift_rule (cprem_of state i);
  1690         val B = Logic.strip_assums_concl Bi;
  1691         val Hs = Logic.strip_assums_hyp Bi;
  1692         val compose = bicompose_aux true match (state, (stpairs, Bs, Bi, C), true);
  1693         fun res [] = Seq.empty
  1694           | res ((eres_flg, rule)::brules) =
  1695               if !Pattern.trace_unify_fail orelse
  1696                  could_bires (Hs, B, eres_flg, rule)
  1697               then Seq.make (*delay processing remainder till needed*)
  1698                   (fn()=> SOME(compose (eres_flg, lift rule, nprems_of rule),
  1699                                res brules))
  1700               else res brules
  1701     in  Seq.flat (res brules)  end;
  1702 
  1703 
  1704 
  1705 (*** Oracles ***)
  1706 
  1707 (* oracle rule *)
  1708 
  1709 fun invoke_oracle thy_ref1 name oracle arg =
  1710   let val Cterm {thy_ref = thy_ref2, t = prop, T, maxidx, sorts} = oracle arg in
  1711     if T <> propT then
  1712       raise THM ("Oracle's result must have type prop: " ^ name, 0, [])
  1713     else
  1714       let val (ora, prf) = Pt.oracle_proof name prop in
  1715         Thm (make_deriv [] [ora] [] prf,
  1716          {thy_ref = Theory.merge_refs (thy_ref1, thy_ref2),
  1717           tags = [],
  1718           maxidx = maxidx,
  1719           shyps = sorts,
  1720           hyps = [],
  1721           tpairs = [],
  1722           prop = prop})
  1723       end
  1724   end;
  1725 
  1726 end;
  1727 end;
  1728 end;
  1729 
  1730 
  1731 (* authentic derivation names *)
  1732 
  1733 structure Oracles = Theory_Data
  1734 (
  1735   type T = unit Name_Space.table;
  1736   val empty : T = Name_Space.empty_table "oracle";
  1737   val extend = I;
  1738   fun merge data : T = Name_Space.merge_tables data;
  1739 );
  1740 
  1741 val extern_oracles = map #1 o Name_Space.extern_table o Oracles.get;
  1742 
  1743 fun add_oracle (b, oracle) thy =
  1744   let
  1745     val naming = Sign.naming_of thy;
  1746     val (name, tab') = Name_Space.define true naming (b, ()) (Oracles.get thy);
  1747     val thy' = Oracles.put tab' thy;
  1748   in ((name, invoke_oracle (Theory.check_thy thy') name oracle), thy') end;
  1749 
  1750 end;
  1751 
  1752 structure Basic_Thm: BASIC_THM = Thm;
  1753 open Basic_Thm;