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