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