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