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