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