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