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