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