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