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