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