src/Pure/thm.ML
author nipkow
Mon Nov 24 16:43:43 1997 +0100 (1997-11-24)
changeset 4281 6c6073b13600
parent 4270 957c887b89b5
child 4288 3f5e8c4aa84d
permissions -rw-r--r--
Added read_def_cterms for simultaneous reading/typing of terms under
defaults.
Redefined read_def_cterm in in terms of read_def_cterms.
Deleted obsolete read_cterms.

Cleaned up def of read_insts, which is not much shorter but much clearere are
correcter now.
     1 (*  Title:      Pure/thm.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1994  University of Cambridge
     5 
     6 The core of Isabelle's Meta Logic: certified types and terms, meta
     7 theorems, meta rules (including resolution and simplification).
     8 *)
     9 
    10 signature THM =
    11   sig
    12   (*certified types*)
    13   type ctyp
    14   val rep_ctyp          : ctyp -> {sign: Sign.sg, T: typ}
    15   val typ_of            : ctyp -> typ
    16   val ctyp_of           : Sign.sg -> typ -> ctyp
    17   val read_ctyp         : Sign.sg -> string -> ctyp
    18 
    19   (*certified terms*)
    20   type cterm
    21   exception CTERM of string
    22   val rep_cterm         : cterm -> {sign: Sign.sg, t: term, T: typ, maxidx: int}
    23   val term_of           : cterm -> term
    24   val cterm_of          : Sign.sg -> term -> cterm
    25   val ctyp_of_term      : cterm -> ctyp
    26   val read_cterm        : Sign.sg -> string * typ -> cterm
    27   val cterm_fun         : (term -> term) -> (cterm -> cterm)
    28   val dest_comb         : cterm -> cterm * cterm
    29   val dest_abs          : cterm -> cterm * cterm
    30   val adjust_maxidx     : cterm -> cterm
    31   val capply            : cterm -> cterm -> cterm
    32   val cabs              : cterm -> cterm -> cterm
    33   val read_def_cterm    :
    34     Sign.sg * (indexname -> typ option) * (indexname -> sort option) ->
    35     string list -> bool -> string * typ -> cterm * (indexname * typ) list
    36   val read_def_cterms   :
    37     Sign.sg * (indexname -> typ option) * (indexname -> sort option) ->
    38     string list -> bool -> (string * typ)list
    39     -> cterm list * (indexname * typ)list
    40 
    41   (*proof terms [must DUPLICATE declaration as a specification]*)
    42   datatype deriv_kind = MinDeriv | ThmDeriv | FullDeriv;
    43   val keep_derivs       : deriv_kind ref
    44   datatype rule = 
    45       MinProof                          
    46     | Oracle		  of string * Sign.sg * object
    47     | Axiom               of string
    48     | Theorem             of string       
    49     | Assume              of cterm
    50     | Implies_intr        of cterm
    51     | Implies_intr_shyps
    52     | Implies_intr_hyps
    53     | Implies_elim 
    54     | Forall_intr         of cterm
    55     | Forall_elim         of cterm
    56     | Reflexive           of cterm
    57     | Symmetric 
    58     | Transitive
    59     | Beta_conversion     of cterm
    60     | Extensional
    61     | Abstract_rule       of string * cterm
    62     | Combination
    63     | Equal_intr
    64     | Equal_elim
    65     | Trivial             of cterm
    66     | Lift_rule           of cterm * int 
    67     | Assumption          of int * Envir.env option
    68     | Rotate_rule         of int * int
    69     | Instantiate         of (indexname * ctyp) list * (cterm * cterm) list
    70     | Bicompose           of bool * bool * int * int * Envir.env
    71     | Flexflex_rule       of Envir.env            
    72     | Class_triv          of class       
    73     | VarifyT
    74     | FreezeT
    75     | RewriteC            of cterm
    76     | CongC               of cterm
    77     | Rewrite_cterm       of cterm
    78     | Rename_params_rule  of string list * int;
    79 
    80   type deriv   (* = rule mtree *)
    81 
    82   (*meta theorems*)
    83   type thm
    84   exception THM of string * int * thm list
    85   val rep_thm           : thm -> {sign: Sign.sg, der: deriv, maxidx: int,
    86                                   shyps: sort list, hyps: term list, 
    87                                   prop: term}
    88   val crep_thm          : thm -> {sign: Sign.sg, der: deriv, maxidx: int,
    89                                   shyps: sort list, hyps: cterm list, 
    90                                   prop: cterm}
    91   val eq_thm		: thm * thm -> bool
    92   val sign_of_thm       : thm -> Sign.sg
    93   val transfer_sg	: Sign.sg -> thm -> thm
    94   val transfer		: theory -> thm -> thm
    95   val tpairs_of         : thm -> (term * term) list
    96   val prems_of          : thm -> term list
    97   val nprems_of         : thm -> int
    98   val concl_of          : thm -> term
    99   val cprop_of          : thm -> cterm
   100   val extra_shyps       : thm -> sort list
   101   val force_strip_shyps : bool ref      (* FIXME tmp (since 1995/08/01) *)
   102   val strip_shyps       : thm -> thm
   103   val implies_intr_shyps: thm -> thm
   104   val get_axiom         : theory -> xstring -> thm
   105   val name_thm          : string * thm -> thm
   106   val name_of_thm	: thm -> string
   107   val axioms_of         : theory -> (string * thm) list
   108 
   109   (*meta rules*)
   110   val assume            : cterm -> thm
   111   val compress          : thm -> thm
   112   val implies_intr      : cterm -> thm -> thm
   113   val implies_elim      : thm -> thm -> thm
   114   val forall_intr       : cterm -> thm -> thm
   115   val forall_elim       : cterm -> thm -> thm
   116   val reflexive         : cterm -> thm
   117   val symmetric         : thm -> thm
   118   val transitive        : thm -> thm -> thm
   119   val beta_conversion   : cterm -> thm
   120   val extensional       : thm -> thm
   121   val abstract_rule     : string -> cterm -> thm -> thm
   122   val combination       : thm -> thm -> thm
   123   val equal_intr        : thm -> thm -> thm
   124   val equal_elim        : thm -> thm -> thm
   125   val implies_intr_hyps : thm -> thm
   126   val flexflex_rule     : thm -> thm Seq.seq
   127   val instantiate       :
   128     (indexname * ctyp) list * (cterm * cterm) list -> thm -> thm
   129   val trivial           : cterm -> thm
   130   val class_triv        : theory -> class -> thm
   131   val varifyT           : thm -> thm
   132   val freezeT           : thm -> thm
   133   val dest_state        : thm * int ->
   134     (term * term) list * term list * term * term
   135   val lift_rule         : (thm * int) -> thm -> thm
   136   val assumption        : int -> thm -> thm Seq.seq
   137   val eq_assumption     : int -> thm -> thm
   138   val rotate_rule       : int -> int -> thm -> thm
   139   val rename_params_rule: string list * int -> thm -> thm
   140   val bicompose         : bool -> bool * thm * int ->
   141     int -> thm -> thm Seq.seq
   142   val biresolution      : bool -> (bool * thm) list ->
   143     int -> thm -> thm Seq.seq
   144 
   145   (*meta simplification*)
   146   exception SIMPLIFIER of string * thm
   147   type meta_simpset
   148   val dest_mss		: meta_simpset ->
   149     {simps: thm list, congs: thm list, procs: (string * cterm list) list}
   150   val empty_mss         : meta_simpset
   151   val merge_mss		: meta_simpset * meta_simpset -> meta_simpset
   152   val add_simps         : meta_simpset * thm list -> meta_simpset
   153   val del_simps         : meta_simpset * thm list -> meta_simpset
   154   val mss_of            : thm list -> meta_simpset
   155   val add_congs         : meta_simpset * thm list -> meta_simpset
   156   val del_congs         : meta_simpset * thm list -> meta_simpset
   157   val add_simprocs	: meta_simpset *
   158     (string * cterm list * (Sign.sg -> thm list -> term -> thm option) * stamp) list
   159       -> meta_simpset
   160   val del_simprocs	: meta_simpset *
   161     (string * cterm list * (Sign.sg -> thm list -> term -> thm option) * stamp) list
   162       -> meta_simpset
   163   val add_prems         : meta_simpset * thm list -> meta_simpset
   164   val prems_of_mss      : meta_simpset -> thm list
   165   val set_mk_rews       : meta_simpset * (thm -> thm list) -> meta_simpset
   166   val mk_rews_of_mss    : meta_simpset -> thm -> thm list
   167   val set_termless      : meta_simpset * (term * term -> bool) -> meta_simpset
   168   val trace_simp        : bool ref
   169   val rewrite_cterm     : bool * bool -> meta_simpset ->
   170                           (meta_simpset -> thm -> thm option) -> cterm -> thm
   171 
   172   val invoke_oracle     : theory -> xstring -> Sign.sg * object -> thm
   173 end;
   174 
   175 structure Thm: THM =
   176 struct
   177 
   178 (*** Certified terms and types ***)
   179 
   180 (** certified types **)
   181 
   182 (*certified typs under a signature*)
   183 
   184 datatype ctyp = Ctyp of {sign_ref: Sign.sg_ref, T: typ};
   185 
   186 fun rep_ctyp (Ctyp {sign_ref, T}) = {sign = Sign.deref sign_ref, T = T};
   187 fun typ_of (Ctyp {T, ...}) = T;
   188 
   189 fun ctyp_of sign T =
   190   Ctyp {sign_ref = Sign.self_ref sign, T = Sign.certify_typ sign T};
   191 
   192 fun read_ctyp sign s =
   193   Ctyp {sign_ref = Sign.self_ref sign, T = Sign.read_typ (sign, K None) s};
   194 
   195 
   196 
   197 (** certified terms **)
   198 
   199 (*certified terms under a signature, with checked typ and maxidx of Vars*)
   200 
   201 datatype cterm = Cterm of {sign_ref: Sign.sg_ref, t: term, T: typ, maxidx: int};
   202 
   203 fun rep_cterm (Cterm {sign_ref, t, T, maxidx}) =
   204   {sign = Sign.deref sign_ref, t = t, T = T, maxidx = maxidx};
   205 
   206 fun term_of (Cterm {t, ...}) = t;
   207 
   208 fun ctyp_of_term (Cterm {sign_ref, T, ...}) = Ctyp {sign_ref = sign_ref, T = T};
   209 
   210 (*create a cterm by checking a "raw" term with respect to a signature*)
   211 fun cterm_of sign tm =
   212   let val (t, T, maxidx) = Sign.certify_term sign tm
   213   in  Cterm {sign_ref = Sign.self_ref sign, t = t, T = T, maxidx = maxidx}
   214   end;
   215 
   216 fun cterm_fun f (Cterm {sign_ref, t, ...}) = cterm_of (Sign.deref sign_ref) (f t);
   217 
   218 
   219 exception CTERM of string;
   220 
   221 (*Destruct application in cterms*)
   222 fun dest_comb (Cterm {sign_ref, T, maxidx, t = A $ B}) =
   223       let val typeA = fastype_of A;
   224           val typeB =
   225             case typeA of Type("fun",[S,T]) => S
   226                         | _ => error "Function type expected in dest_comb";
   227       in
   228       (Cterm {sign_ref=sign_ref, maxidx=maxidx, t=A, T=typeA},
   229        Cterm {sign_ref=sign_ref, maxidx=maxidx, t=B, T=typeB})
   230       end
   231   | dest_comb _ = raise CTERM "dest_comb";
   232 
   233 (*Destruct abstraction in cterms*)
   234 fun dest_abs (Cterm {sign_ref, T as Type("fun",[_,S]), maxidx, t=Abs(x,ty,M)}) = 
   235       let val (y,N) = variant_abs (x,ty,M)
   236       in (Cterm {sign_ref = sign_ref, T = ty, maxidx = 0, t = Free(y,ty)},
   237           Cterm {sign_ref = sign_ref, T = S, maxidx = maxidx, t = N})
   238       end
   239   | dest_abs _ = raise CTERM "dest_abs";
   240 
   241 (*Makes maxidx precise: it is often too big*)
   242 fun adjust_maxidx (ct as Cterm {sign_ref, T, t, maxidx, ...}) =
   243   if maxidx = ~1 then ct 
   244   else  Cterm {sign_ref = sign_ref, T = T, maxidx = maxidx_of_term t, t = t};
   245 
   246 (*Form cterm out of a function and an argument*)
   247 fun capply (Cterm {t=f, sign_ref=sign_ref1, T=Type("fun",[dty,rty]), maxidx=maxidx1})
   248            (Cterm {t=x, sign_ref=sign_ref2, T, maxidx=maxidx2}) =
   249       if T = dty then Cterm{t=f$x, sign_ref=Sign.merge_refs(sign_ref1,sign_ref2), T=rty,
   250                             maxidx=Int.max(maxidx1, maxidx2)}
   251       else raise CTERM "capply: types don't agree"
   252   | capply _ _ = raise CTERM "capply: first arg is not a function"
   253 
   254 fun cabs (Cterm {t=Free(a,ty), sign_ref=sign_ref1, T=T1, maxidx=maxidx1})
   255          (Cterm {t=t2, sign_ref=sign_ref2, T=T2, maxidx=maxidx2}) =
   256       Cterm {t=absfree(a,ty,t2), sign_ref=Sign.merge_refs(sign_ref1,sign_ref2),
   257              T = ty --> T2, maxidx=Int.max(maxidx1, maxidx2)}
   258   | cabs _ _ = raise CTERM "cabs: first arg is not a free variable";
   259 
   260 
   261 
   262 (** read cterms **)   (*exception ERROR*)
   263 
   264 (*read terms, infer types, certify terms*)
   265 fun read_def_cterms (sign, types, sorts) used freeze sTs =
   266   let
   267     val syn = #syn (Sign.rep_sg sign)
   268     fun read(s,T) =
   269       let val T' = Sign.certify_typ sign T
   270                    handle TYPE (msg, _, _) => error msg
   271       in (Syntax.read syn T' s, T') end
   272     val tsTs = map read sTs
   273     val (ts',tye) = Sign.infer_types_simult sign types sorts used freeze tsTs;
   274     val cts = map (cterm_of sign) ts'
   275       handle TYPE (msg, _, _) => error msg
   276            | TERM (msg, _) => error msg;
   277   in (cts, tye) end;
   278 
   279 (*read term, infer types, certify term*)
   280 fun read_def_cterm args used freeze aT =
   281   let val ([ct],tye) = read_def_cterms args used freeze [aT]
   282   in (ct,tye) end;
   283 
   284 fun read_cterm sign = #1 o read_def_cterm (sign, K None, K None) [] true;
   285 
   286 (*read a list of terms, matching them against a list of expected types.
   287   NO disambiguation of alternative parses via type-checking -- it is just
   288   not practical.
   289 
   290 Why not? In any case, this function is not used at all.
   291 
   292 fun read_cterms sg (bs, Ts) =
   293   let
   294     val {tsig, syn, ...} = Sign.rep_sg sg;
   295     fun read (b, T) =
   296       (case Syntax.read syn T b of
   297         [t] => t
   298       | _  => error ("Error or ambiguity in parsing of " ^ b));
   299 
   300     val prt = setmp Syntax.show_brackets true (Sign.pretty_term sg);
   301     val prT = Sign.pretty_typ sg;
   302     val (us, _) =
   303       (* FIXME Sign.infer_types!? *)
   304       Type.infer_types prt prT tsig (Sign.const_type sg) (K None) (K None)
   305         (Sign.intern_const sg) (Sign.intern_tycons sg) (Sign.intern_sort sg)
   306         [] true (map (Sign.certify_typ sg) Ts) (ListPair.map read (bs, Ts));
   307   in map (cterm_of sg) us end
   308   handle TYPE (msg, _, _) => error msg
   309        | TERM (msg, _) => error msg;
   310 *)
   311 
   312 
   313 (*** Derivations ***)
   314 
   315 (*Names of rules in derivations.  Includes logically trivial rules, if 
   316   executed in ML.*)
   317 datatype rule = 
   318     MinProof                            (*for building minimal proof terms*)
   319   | Oracle              of string * Sign.sg * object       (*oracles*)
   320 (*Axioms/theorems*)
   321   | Axiom               of string
   322   | Theorem             of string
   323 (*primitive inferences and compound versions of them*)
   324   | Assume              of cterm
   325   | Implies_intr        of cterm
   326   | Implies_intr_shyps
   327   | Implies_intr_hyps
   328   | Implies_elim 
   329   | Forall_intr         of cterm
   330   | Forall_elim         of cterm
   331   | Reflexive           of cterm
   332   | Symmetric 
   333   | Transitive
   334   | Beta_conversion     of cterm
   335   | Extensional
   336   | Abstract_rule       of string * cterm
   337   | Combination
   338   | Equal_intr
   339   | Equal_elim
   340 (*derived rules for tactical proof*)
   341   | Trivial             of cterm
   342         (*For lift_rule, the proof state is not a premise.
   343           Use cterm instead of thm to avoid mutual recursion.*)
   344   | Lift_rule           of cterm * int 
   345   | Assumption          of int * Envir.env option (*includes eq_assumption*)
   346   | Rotate_rule         of int * int
   347   | Instantiate         of (indexname * ctyp) list * (cterm * cterm) list
   348   | Bicompose           of bool * bool * int * int * Envir.env
   349   | Flexflex_rule       of Envir.env            (*identifies unifier chosen*)
   350 (*other derived rules*)
   351   | Class_triv          of class
   352   | VarifyT
   353   | FreezeT
   354 (*for the simplifier*)
   355   | RewriteC            of cterm
   356   | CongC               of cterm
   357   | Rewrite_cterm       of cterm
   358 (*Logical identities, recorded since they are part of the proof process*)
   359   | Rename_params_rule  of string list * int;
   360 
   361 
   362 type deriv = rule mtree;
   363 
   364 datatype deriv_kind = MinDeriv | ThmDeriv | FullDeriv;
   365 
   366 val keep_derivs = ref MinDeriv;
   367 
   368 
   369 (*Build a minimal derivation.  Keep oracles; suppress atomic inferences;
   370   retain Theorems or their underlying links; keep anything else*)
   371 fun squash_derivs [] = []
   372   | squash_derivs (der::ders) =
   373      (case der of
   374           Join (Oracle _, _) => der :: squash_derivs ders
   375         | Join (Theorem _, [der']) => if !keep_derivs=ThmDeriv 
   376                                       then der :: squash_derivs ders
   377                                       else squash_derivs (der'::ders)
   378         | Join (Axiom _, _) => if !keep_derivs=ThmDeriv 
   379                                then der :: squash_derivs ders
   380                                else squash_derivs ders
   381         | Join (_, [])      => squash_derivs ders
   382         | _                 => der :: squash_derivs ders);
   383 
   384 
   385 (*Ensure sharing of the most likely derivation, the empty one!*)
   386 val min_infer = Join (MinProof, []);
   387 
   388 (*Make a minimal inference*)
   389 fun make_min_infer []    = min_infer
   390   | make_min_infer [der] = der
   391   | make_min_infer ders  = Join (MinProof, ders);
   392 
   393 fun infer_derivs (rl, [])   = Join (rl, [])
   394   | infer_derivs (rl, ders) =
   395     if !keep_derivs=FullDeriv then Join (rl, ders)
   396     else make_min_infer (squash_derivs ders);
   397 
   398 
   399 
   400 (*** Meta theorems ***)
   401 
   402 datatype thm = Thm of
   403  {sign_ref: Sign.sg_ref,       (*mutable reference to signature*)
   404   der: deriv,                  (*derivation*)
   405   maxidx: int,                 (*maximum index of any Var or TVar*)
   406   shyps: sort list,            (*sort hypotheses*)
   407   hyps: term list,             (*hypotheses*)
   408   prop: term};                 (*conclusion*)
   409 
   410 fun rep_thm (Thm {sign_ref, der, maxidx, shyps, hyps, prop}) =
   411   {sign = Sign.deref sign_ref, der = der, maxidx = maxidx,
   412     shyps = shyps, hyps = hyps, prop = prop};
   413 
   414 (*Version of rep_thm returning cterms instead of terms*)
   415 fun crep_thm (Thm {sign_ref, der, maxidx, shyps, hyps, prop}) =
   416   let fun ctermf max t = Cterm{sign_ref=sign_ref, t=t, T=propT, maxidx=max};
   417   in {sign = Sign.deref sign_ref, der = der, maxidx = maxidx, shyps = shyps,
   418       hyps = map (ctermf ~1) hyps,
   419       prop = ctermf maxidx prop}
   420   end;
   421 
   422 (*errors involving theorems*)
   423 exception THM of string * int * thm list;
   424 
   425 (*equality of theorems uses equality of signatures and the
   426   a-convertible test for terms*)
   427 fun eq_thm (th1, th2) =
   428   let
   429     val {sign = sg1, shyps = shyps1, hyps = hyps1, prop = prop1, ...} = rep_thm th1;
   430     val {sign = sg2, shyps = shyps2, hyps = hyps2, prop = prop2, ...} = rep_thm th2;
   431   in
   432     Sign.eq_sg (sg1, sg2) andalso
   433     eq_set_sort (shyps1, shyps2) andalso
   434     aconvs (hyps1, hyps2) andalso
   435     prop1 aconv prop2
   436   end;
   437 
   438 fun sign_of_thm (Thm {sign_ref, ...}) = Sign.deref sign_ref;
   439 
   440 (*merge signatures of two theorems; raise exception if incompatible*)
   441 fun merge_thm_sgs
   442     (th1 as Thm {sign_ref = sgr1, ...}, th2 as Thm {sign_ref = sgr2, ...}) =
   443   Sign.merge_refs (sgr1, sgr2) handle TERM (msg, _) => raise THM (msg, 0, [th1, th2]);
   444 
   445 (*transfer thm to super theory (non-destructive)*)
   446 fun transfer_sg sign' thm =
   447   let
   448     val Thm {sign_ref, der, maxidx, shyps, hyps, prop} = thm;
   449     val sign = Sign.deref sign_ref;
   450   in
   451     if Sign.eq_sg (sign, sign') then thm
   452     else if Sign.subsig (sign, sign') then
   453       Thm {sign_ref = Sign.self_ref sign', der = der, maxidx = maxidx,
   454         shyps = shyps, hyps = hyps, prop = prop}
   455     else raise THM ("transfer: not a super theory", 0, [thm])
   456   end;
   457 
   458 val transfer = transfer_sg o sign_of;
   459 
   460 (*maps object-rule to tpairs*)
   461 fun tpairs_of (Thm {prop, ...}) = #1 (Logic.strip_flexpairs prop);
   462 
   463 (*maps object-rule to premises*)
   464 fun prems_of (Thm {prop, ...}) =
   465   Logic.strip_imp_prems (Logic.skip_flexpairs prop);
   466 
   467 (*counts premises in a rule*)
   468 fun nprems_of (Thm {prop, ...}) =
   469   Logic.count_prems (Logic.skip_flexpairs prop, 0);
   470 
   471 (*maps object-rule to conclusion*)
   472 fun concl_of (Thm {prop, ...}) = Logic.strip_imp_concl prop;
   473 
   474 (*the statement of any thm is a cterm*)
   475 fun cprop_of (Thm {sign_ref, maxidx, prop, ...}) =
   476   Cterm {sign_ref = sign_ref, maxidx = maxidx, T = propT, t = prop};
   477 
   478 
   479 
   480 (** sort contexts of theorems **)
   481 
   482 (* basic utils *)
   483 
   484 (*accumulate sorts suppressing duplicates; these are coded low levelly
   485   to improve efficiency a bit*)
   486 
   487 fun add_typ_sorts (Type (_, Ts), Ss) = add_typs_sorts (Ts, Ss)
   488   | add_typ_sorts (TFree (_, S), Ss) = ins_sort(S,Ss)
   489   | add_typ_sorts (TVar (_, S), Ss) = ins_sort(S,Ss)
   490 and add_typs_sorts ([], Ss) = Ss
   491   | add_typs_sorts (T :: Ts, Ss) = add_typs_sorts (Ts, add_typ_sorts (T, Ss));
   492 
   493 fun add_term_sorts (Const (_, T), Ss) = add_typ_sorts (T, Ss)
   494   | add_term_sorts (Free (_, T), Ss) = add_typ_sorts (T, Ss)
   495   | add_term_sorts (Var (_, T), Ss) = add_typ_sorts (T, Ss)
   496   | add_term_sorts (Bound _, Ss) = Ss
   497   | add_term_sorts (Abs (_,T,t), Ss) = add_term_sorts (t, add_typ_sorts (T,Ss))
   498   | add_term_sorts (t $ u, Ss) = add_term_sorts (t, add_term_sorts (u, Ss));
   499 
   500 fun add_terms_sorts ([], Ss) = Ss
   501   | add_terms_sorts (t::ts, Ss) = add_terms_sorts (ts, add_term_sorts (t,Ss));
   502 
   503 fun env_codT (Envir.Envir {iTs, ...}) = map snd iTs;
   504 
   505 fun add_env_sorts (env, Ss) =
   506   add_terms_sorts (map snd (Envir.alist_of env),
   507     add_typs_sorts (env_codT env, Ss));
   508 
   509 fun add_thm_sorts (Thm {hyps, prop, ...}, Ss) =
   510   add_terms_sorts (hyps, add_term_sorts (prop, Ss));
   511 
   512 fun add_thms_shyps ([], Ss) = Ss
   513   | add_thms_shyps (Thm {shyps, ...} :: ths, Ss) =
   514       add_thms_shyps (ths, union_sort(shyps,Ss));
   515 
   516 
   517 (*get 'dangling' sort constraints of a thm*)
   518 fun extra_shyps (th as Thm {shyps, ...}) =
   519   shyps \\ add_thm_sorts (th, []);
   520 
   521 
   522 (* fix_shyps *)
   523 
   524 (*preserve sort contexts of rule premises and substituted types*)
   525 fun fix_shyps thms Ts thm =
   526   let
   527     val Thm {sign_ref, der, maxidx, hyps, prop, ...} = thm;
   528     val shyps =
   529       add_thm_sorts (thm, add_typs_sorts (Ts, add_thms_shyps (thms, [])));
   530   in
   531     Thm {sign_ref = sign_ref,
   532          der = der,             (*No new derivation, as other rules call this*)
   533          maxidx = maxidx,
   534          shyps = shyps, hyps = hyps, prop = prop}
   535   end;
   536 
   537 
   538 (* strip_shyps *)       (* FIXME improve? (e.g. only minimal extra sorts) *)
   539 
   540 val force_strip_shyps = ref true;  (* FIXME tmp (since 1995/08/01) *)
   541 
   542 (*remove extra sorts that are known to be syntactically non-empty*)
   543 fun strip_shyps thm =
   544   let
   545     val Thm {sign_ref, der, maxidx, shyps, hyps, prop} = thm;
   546     val sorts = add_thm_sorts (thm, []);
   547     val maybe_empty = not o Sign.nonempty_sort (Sign.deref sign_ref) sorts;
   548     val shyps' = filter (fn S => mem_sort(S,sorts) orelse maybe_empty S) shyps;
   549   in
   550     Thm {sign_ref = sign_ref, der = der, maxidx = maxidx,
   551          shyps =
   552          (if eq_set_sort (shyps',sorts) orelse 
   553              not (!force_strip_shyps) then shyps'
   554           else    (* FIXME tmp (since 1995/08/01) *)
   555               (warning ("Removed sort hypotheses: " ^
   556                         commas (map Sorts.str_of_sort (shyps' \\ sorts)));
   557                warning "Let's hope these sorts are non-empty!";
   558            sorts)),
   559       hyps = hyps, 
   560       prop = prop}
   561   end;
   562 
   563 
   564 (* implies_intr_shyps *)
   565 
   566 (*discharge all extra sort hypotheses*)
   567 fun implies_intr_shyps thm =
   568   (case extra_shyps thm of
   569     [] => thm
   570   | xshyps =>
   571       let
   572         val Thm {sign_ref, der, maxidx, shyps, hyps, prop} = thm;
   573         val shyps' = ins_sort (logicS, shyps \\ xshyps);
   574         val used_names = foldr add_term_tfree_names (prop :: hyps, []);
   575         val names =
   576           tl (variantlist (replicate (length xshyps + 1) "'", used_names));
   577         val tfrees = map (TFree o rpair logicS) names;
   578 
   579         fun mk_insort (T, S) = map (Logic.mk_inclass o pair T) S;
   580         val sort_hyps = List.concat (map2 mk_insort (tfrees, xshyps));
   581       in
   582         Thm {sign_ref = sign_ref, 
   583              der = infer_derivs (Implies_intr_shyps, [der]), 
   584              maxidx = maxidx, 
   585              shyps = shyps',
   586              hyps = hyps, 
   587              prop = Logic.list_implies (sort_hyps, prop)}
   588       end);
   589 
   590 
   591 (** Axioms **)
   592 
   593 (*look up the named axiom in the theory*)
   594 fun get_axiom theory raw_name =
   595   let
   596     val name = Sign.intern (sign_of theory) Theory.axiomK raw_name;
   597     fun get_ax [] = raise Match
   598       | get_ax (thy :: thys) =
   599           let val {sign, axioms, parents, ...} = rep_theory thy
   600           in case Symtab.lookup (axioms, name) of
   601                 Some t => fix_shyps [] []
   602                            (Thm {sign_ref = Sign.self_ref sign,
   603                                  der = infer_derivs (Axiom name, []),
   604                                  maxidx = maxidx_of_term t,
   605                                  shyps = [], 
   606                                  hyps = [], 
   607                                  prop = t})
   608               | None => get_ax parents handle Match => get_ax thys
   609           end;
   610   in
   611     get_ax [theory] handle Match
   612       => raise THEORY ("No axiom " ^ quote name, [theory])
   613   end;
   614 
   615 
   616 (*return additional axioms of this theory node*)
   617 fun axioms_of thy =
   618   map (fn (s, _) => (s, get_axiom thy s))
   619     (Symtab.dest (#axioms (rep_theory thy)));
   620 
   621 (*Attach a label to a theorem to make proof objects more readable*)
   622 fun name_thm (name, th as Thm {sign_ref, der, maxidx, shyps, hyps, prop}) =
   623   (case der of
   624     Join (Theorem _, _) => th
   625   | Join (Axiom _, _) => th
   626   | _ => Thm {sign_ref = sign_ref, der = Join (Theorem name, [der]),
   627       maxidx = maxidx, shyps = shyps, hyps = hyps, prop = prop});
   628 
   629 fun name_of_thm (Thm {der, ...}) =
   630   (case der of
   631     Join (Theorem name, _) => name
   632   | Join (Axiom name, _) => name
   633   | _ => "");
   634 
   635 
   636 (*Compression of theorems -- a separate rule, not integrated with the others,
   637   as it could be slow.*)
   638 fun compress (Thm {sign_ref, der, maxidx, shyps, hyps, prop}) = 
   639     Thm {sign_ref = sign_ref, 
   640          der = der,     (*No derivation recorded!*)
   641          maxidx = maxidx,
   642          shyps = shyps, 
   643          hyps = map Term.compress_term hyps, 
   644          prop = Term.compress_term prop};
   645 
   646 
   647 
   648 (*** Meta rules ***)
   649 
   650 (*Check that term does not contain same var with different typing/sorting.
   651   If this check must be made, recalculate maxidx in hope of preventing its
   652   recurrence.*)
   653 fun nodup_Vars (thm as Thm{sign_ref, der, maxidx, shyps, hyps, prop}) s =
   654   (Sign.nodup_Vars prop; 
   655    Thm {sign_ref = sign_ref, 
   656          der = der,     
   657          maxidx = maxidx_of_term prop,
   658          shyps = shyps, 
   659          hyps = hyps, 
   660          prop = prop})
   661   handle TYPE(msg,Ts,ts) => raise TYPE(s^": "^msg,Ts,ts);
   662 
   663 (** 'primitive' rules **)
   664 
   665 (*discharge all assumptions t from ts*)
   666 val disch = gen_rem (op aconv);
   667 
   668 (*The assumption rule A|-A in a theory*)
   669 fun assume ct : thm =
   670   let val Cterm {sign_ref, t=prop, T, maxidx} = ct
   671   in  if T<>propT then
   672         raise THM("assume: assumptions must have type prop", 0, [])
   673       else if maxidx <> ~1 then
   674         raise THM("assume: assumptions may not contain scheme variables",
   675                   maxidx, [])
   676       else Thm{sign_ref   = sign_ref,
   677                der    = infer_derivs (Assume ct, []), 
   678                maxidx = ~1, 
   679                shyps  = add_term_sorts(prop,[]), 
   680                hyps   = [prop], 
   681                prop   = prop}
   682   end;
   683 
   684 (*Implication introduction
   685     [A]
   686      :
   687      B
   688   -------
   689   A ==> B
   690 *)
   691 fun implies_intr cA (thB as Thm{sign_ref,der,maxidx,hyps,prop,...}) : thm =
   692   let val Cterm {sign_ref=sign_refA, t=A, T, maxidx=maxidxA} = cA
   693   in  if T<>propT then
   694         raise THM("implies_intr: assumptions must have type prop", 0, [thB])
   695       else fix_shyps [thB] []
   696         (Thm{sign_ref = Sign.merge_refs (sign_ref,sign_refA),  
   697              der = infer_derivs (Implies_intr cA, [der]),
   698              maxidx = Int.max(maxidxA, maxidx),
   699              shyps = [],
   700              hyps = disch(hyps,A),
   701              prop = implies$A$prop})
   702       handle TERM _ =>
   703         raise THM("implies_intr: incompatible signatures", 0, [thB])
   704   end;
   705 
   706 
   707 (*Implication elimination
   708   A ==> B    A
   709   ------------
   710         B
   711 *)
   712 fun implies_elim thAB thA : thm =
   713     let val Thm{maxidx=maxA, der=derA, hyps=hypsA, prop=propA,...} = thA
   714         and Thm{sign_ref, der, maxidx, hyps, prop,...} = thAB;
   715         fun err(a) = raise THM("implies_elim: "^a, 0, [thAB,thA])
   716     in  case prop of
   717             imp$A$B =>
   718                 if imp=implies andalso  A aconv propA
   719                 then fix_shyps [thAB, thA] []
   720                        (Thm{sign_ref= merge_thm_sgs(thAB,thA),
   721                             der = infer_derivs (Implies_elim, [der,derA]),
   722                             maxidx = Int.max(maxA,maxidx),
   723                             shyps = [],
   724                             hyps = union_term(hypsA,hyps),  (*dups suppressed*)
   725                             prop = B})
   726                 else err("major premise")
   727           | _ => err("major premise")
   728     end;
   729 
   730 (*Forall introduction.  The Free or Var x must not be free in the hypotheses.
   731     A
   732   -----
   733   !!x.A
   734 *)
   735 fun forall_intr cx (th as Thm{sign_ref,der,maxidx,hyps,prop,...}) =
   736   let val x = term_of cx;
   737       fun result(a,T) = fix_shyps [th] []
   738         (Thm{sign_ref = sign_ref, 
   739              der = infer_derivs (Forall_intr cx, [der]),
   740              maxidx = maxidx,
   741              shyps = [],
   742              hyps = hyps,
   743              prop = all(T) $ Abs(a, T, abstract_over (x,prop))})
   744   in  case x of
   745         Free(a,T) =>
   746           if exists (apl(x, Logic.occs)) hyps
   747           then  raise THM("forall_intr: variable free in assumptions", 0, [th])
   748           else  result(a,T)
   749       | Var((a,_),T) => result(a,T)
   750       | _ => raise THM("forall_intr: not a variable", 0, [th])
   751   end;
   752 
   753 (*Forall elimination
   754   !!x.A
   755   ------
   756   A[t/x]
   757 *)
   758 fun forall_elim ct (th as Thm{sign_ref,der,maxidx,hyps,prop,...}) : thm =
   759   let val Cterm {sign_ref=sign_reft, t, T, maxidx=maxt} = ct
   760   in  case prop of
   761         Const("all",Type("fun",[Type("fun",[qary,_]),_])) $ A =>
   762           if T<>qary then
   763               raise THM("forall_elim: type mismatch", 0, [th])
   764           else let val thm = fix_shyps [th] []
   765                     (Thm{sign_ref= Sign.merge_refs(sign_ref,sign_reft),
   766                          der = infer_derivs (Forall_elim ct, [der]),
   767                          maxidx = Int.max(maxidx, maxt),
   768                          shyps = [],
   769                          hyps = hyps,  
   770                          prop = betapply(A,t)})
   771                in if maxt >= 0 andalso maxidx >= 0
   772                   then nodup_Vars thm "forall_elim" 
   773                   else thm (*no new Vars: no expensive check!*)
   774                end
   775       | _ => raise THM("forall_elim: not quantified", 0, [th])
   776   end
   777   handle TERM _ =>
   778          raise THM("forall_elim: incompatible signatures", 0, [th]);
   779 
   780 
   781 (* Equality *)
   782 
   783 (*The reflexivity rule: maps  t   to the theorem   t==t   *)
   784 fun reflexive ct =
   785   let val Cterm {sign_ref, t, T, maxidx} = ct
   786   in  fix_shyps [] []
   787        (Thm{sign_ref= sign_ref, 
   788             der = infer_derivs (Reflexive ct, []),
   789             shyps = [],
   790             hyps = [], 
   791             maxidx = maxidx,
   792             prop = Logic.mk_equals(t,t)})
   793   end;
   794 
   795 (*The symmetry rule
   796   t==u
   797   ----
   798   u==t
   799 *)
   800 fun symmetric (th as Thm{sign_ref,der,maxidx,shyps,hyps,prop}) =
   801   case prop of
   802       (eq as Const("==",_)) $ t $ u =>
   803         (*no fix_shyps*)
   804           Thm{sign_ref = sign_ref,
   805               der = infer_derivs (Symmetric, [der]),
   806               maxidx = maxidx,
   807               shyps = shyps,
   808               hyps = hyps,
   809               prop = eq$u$t}
   810     | _ => raise THM("symmetric", 0, [th]);
   811 
   812 (*The transitive rule
   813   t1==u    u==t2
   814   --------------
   815       t1==t2
   816 *)
   817 fun transitive th1 th2 =
   818   let val Thm{der=der1, maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
   819       and Thm{der=der2, maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
   820       fun err(msg) = raise THM("transitive: "^msg, 0, [th1,th2])
   821   in case (prop1,prop2) of
   822        ((eq as Const("==",_)) $ t1 $ u, Const("==",_) $ u' $ t2) =>
   823           if not (u aconv u') then err"middle term"
   824           else let val thm =      
   825               fix_shyps [th1, th2] []
   826                 (Thm{sign_ref= merge_thm_sgs(th1,th2), 
   827                      der = infer_derivs (Transitive, [der1, der2]),
   828                      maxidx = Int.max(max1,max2), 
   829                      shyps = [],
   830                      hyps = union_term(hyps1,hyps2),
   831                      prop = eq$t1$t2})
   832                  in if max1 >= 0 andalso max2 >= 0
   833                     then nodup_Vars thm "transitive" 
   834                     else thm (*no new Vars: no expensive check!*)
   835                  end
   836      | _ =>  err"premises"
   837   end;
   838 
   839 (*Beta-conversion: maps (%x.t)(u) to the theorem (%x.t)(u) == t[u/x] *)
   840 fun beta_conversion ct =
   841   let val Cterm {sign_ref, t, T, maxidx} = ct
   842   in  case t of
   843           Abs(_,_,bodt) $ u => fix_shyps [] []
   844             (Thm{sign_ref = sign_ref,  
   845                  der = infer_derivs (Beta_conversion ct, []),
   846                  maxidx = maxidx,
   847                  shyps = [],
   848                  hyps = [],
   849                  prop = Logic.mk_equals(t, subst_bound (u,bodt))})
   850         | _ =>  raise THM("beta_conversion: not a redex", 0, [])
   851   end;
   852 
   853 (*The extensionality rule   (proviso: x not free in f, g, or hypotheses)
   854   f(x) == g(x)
   855   ------------
   856      f == g
   857 *)
   858 fun extensional (th as Thm{sign_ref, der, maxidx,shyps,hyps,prop}) =
   859   case prop of
   860     (Const("==",_)) $ (f$x) $ (g$y) =>
   861       let fun err(msg) = raise THM("extensional: "^msg, 0, [th])
   862       in (if x<>y then err"different variables" else
   863           case y of
   864                 Free _ =>
   865                   if exists (apl(y, Logic.occs)) (f::g::hyps)
   866                   then err"variable free in hyps or functions"    else  ()
   867               | Var _ =>
   868                   if Logic.occs(y,f)  orelse  Logic.occs(y,g)
   869                   then err"variable free in functions"   else  ()
   870               | _ => err"not a variable");
   871           (*no fix_shyps*)
   872           Thm{sign_ref = sign_ref,
   873               der = infer_derivs (Extensional, [der]),
   874               maxidx = maxidx,
   875               shyps = shyps,
   876               hyps = hyps, 
   877               prop = Logic.mk_equals(f,g)}
   878       end
   879  | _ =>  raise THM("extensional: premise", 0, [th]);
   880 
   881 (*The abstraction rule.  The Free or Var x must not be free in the hypotheses.
   882   The bound variable will be named "a" (since x will be something like x320)
   883      t == u
   884   ------------
   885   %x.t == %x.u
   886 *)
   887 fun abstract_rule a cx (th as Thm{sign_ref,der,maxidx,hyps,prop,...}) =
   888   let val x = term_of cx;
   889       val (t,u) = Logic.dest_equals prop
   890             handle TERM _ =>
   891                 raise THM("abstract_rule: premise not an equality", 0, [th])
   892       fun result T = fix_shyps [th] []
   893           (Thm{sign_ref = sign_ref,
   894                der = infer_derivs (Abstract_rule (a,cx), [der]),
   895                maxidx = maxidx, 
   896                shyps = [], 
   897                hyps = hyps,
   898                prop = Logic.mk_equals(Abs(a, T, abstract_over (x,t)),
   899                                       Abs(a, T, abstract_over (x,u)))})
   900   in  case x of
   901         Free(_,T) =>
   902          if exists (apl(x, Logic.occs)) hyps
   903          then raise THM("abstract_rule: variable free in assumptions", 0, [th])
   904          else result T
   905       | Var(_,T) => result T
   906       | _ => raise THM("abstract_rule: not a variable", 0, [th])
   907   end;
   908 
   909 (*The combination rule
   910   f == g  t == u
   911   --------------
   912    f(t) == g(u)
   913 *)
   914 fun combination th1 th2 =
   915   let val Thm{der=der1, maxidx=max1, shyps=shyps1, hyps=hyps1, 
   916               prop=prop1,...} = th1
   917       and Thm{der=der2, maxidx=max2, shyps=shyps2, hyps=hyps2, 
   918               prop=prop2,...} = th2
   919       fun chktypes (f,t) =
   920             (case fastype_of f of
   921                 Type("fun",[T1,T2]) => 
   922                     if T1 <> fastype_of t then
   923                          raise THM("combination: types", 0, [th1,th2])
   924                     else ()
   925                 | _ => raise THM("combination: not function type", 0, 
   926                                  [th1,th2]))
   927   in case (prop1,prop2)  of
   928        (Const("==",_) $ f $ g, Const("==",_) $ t $ u) =>
   929           let val _   = chktypes (f,t)
   930               val thm = (*no fix_shyps*)
   931                         Thm{sign_ref = merge_thm_sgs(th1,th2), 
   932                             der = infer_derivs (Combination, [der1, der2]),
   933                             maxidx = Int.max(max1,max2), 
   934                             shyps = union_sort(shyps1,shyps2),
   935                             hyps = union_term(hyps1,hyps2),
   936                             prop = Logic.mk_equals(f$t, g$u)}
   937           in if max1 >= 0 andalso max2 >= 0
   938              then nodup_Vars thm "combination" 
   939              else thm (*no new Vars: no expensive check!*)  
   940           end
   941      | _ =>  raise THM("combination: premises", 0, [th1,th2])
   942   end;
   943 
   944 
   945 (* Equality introduction
   946   A ==> B  B ==> A
   947   ----------------
   948        A == B
   949 *)
   950 fun equal_intr th1 th2 =
   951   let val Thm{der=der1,maxidx=max1, shyps=shyps1, hyps=hyps1, 
   952               prop=prop1,...} = th1
   953       and Thm{der=der2, maxidx=max2, shyps=shyps2, hyps=hyps2, 
   954               prop=prop2,...} = th2;
   955       fun err(msg) = raise THM("equal_intr: "^msg, 0, [th1,th2])
   956   in case (prop1,prop2) of
   957        (Const("==>",_) $ A $ B, Const("==>",_) $ B' $ A')  =>
   958           if A aconv A' andalso B aconv B'
   959           then
   960             (*no fix_shyps*)
   961               Thm{sign_ref = merge_thm_sgs(th1,th2),
   962                   der = infer_derivs (Equal_intr, [der1, der2]),
   963                   maxidx = Int.max(max1,max2),
   964                   shyps = union_sort(shyps1,shyps2),
   965                   hyps = union_term(hyps1,hyps2),
   966                   prop = Logic.mk_equals(A,B)}
   967           else err"not equal"
   968      | _ =>  err"premises"
   969   end;
   970 
   971 
   972 (*The equal propositions rule
   973   A == B  A
   974   ---------
   975       B
   976 *)
   977 fun equal_elim th1 th2 =
   978   let val Thm{der=der1, maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
   979       and Thm{der=der2, maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
   980       fun err(msg) = raise THM("equal_elim: "^msg, 0, [th1,th2])
   981   in  case prop1  of
   982        Const("==",_) $ A $ B =>
   983           if not (prop2 aconv A) then err"not equal"  else
   984             fix_shyps [th1, th2] []
   985               (Thm{sign_ref= merge_thm_sgs(th1,th2), 
   986                    der = infer_derivs (Equal_elim, [der1, der2]),
   987                    maxidx = Int.max(max1,max2),
   988                    shyps = [],
   989                    hyps = union_term(hyps1,hyps2),
   990                    prop = B})
   991      | _ =>  err"major premise"
   992   end;
   993 
   994 
   995 
   996 (**** Derived rules ****)
   997 
   998 (*Discharge all hypotheses.  Need not verify cterms or call fix_shyps.
   999   Repeated hypotheses are discharged only once;  fold cannot do this*)
  1000 fun implies_intr_hyps (Thm{sign_ref, der, maxidx, shyps, hyps=A::As, prop}) =
  1001       implies_intr_hyps (*no fix_shyps*)
  1002             (Thm{sign_ref = sign_ref, 
  1003                  der = infer_derivs (Implies_intr_hyps, [der]), 
  1004                  maxidx = maxidx, 
  1005                  shyps = shyps,
  1006                  hyps = disch(As,A),  
  1007                  prop = implies$A$prop})
  1008   | implies_intr_hyps th = th;
  1009 
  1010 (*Smash" unifies the list of term pairs leaving no flex-flex pairs.
  1011   Instantiates the theorem and deletes trivial tpairs.
  1012   Resulting sequence may contain multiple elements if the tpairs are
  1013     not all flex-flex. *)
  1014 fun flexflex_rule (th as Thm{sign_ref, der, maxidx, hyps, prop,...}) =
  1015   let fun newthm env =
  1016           if Envir.is_empty env then th
  1017           else
  1018           let val (tpairs,horn) =
  1019                         Logic.strip_flexpairs (Envir.norm_term env prop)
  1020                 (*Remove trivial tpairs, of the form t=t*)
  1021               val distpairs = filter (not o op aconv) tpairs
  1022               val newprop = Logic.list_flexpairs(distpairs, horn)
  1023           in  fix_shyps [th] (env_codT env)
  1024                 (Thm{sign_ref = sign_ref, 
  1025                      der = infer_derivs (Flexflex_rule env, [der]), 
  1026                      maxidx = maxidx_of_term newprop, 
  1027                      shyps = [], 
  1028                      hyps = hyps,
  1029                      prop = newprop})
  1030           end;
  1031       val (tpairs,_) = Logic.strip_flexpairs prop
  1032   in Seq.map newthm
  1033             (Unify.smash_unifiers(Sign.deref sign_ref, Envir.empty maxidx, tpairs))
  1034   end;
  1035 
  1036 (*Instantiation of Vars
  1037            A
  1038   -------------------
  1039   A[t1/v1,....,tn/vn]
  1040 *)
  1041 
  1042 (*Check that all the terms are Vars and are distinct*)
  1043 fun instl_ok ts = forall is_Var ts andalso null(findrep ts);
  1044 
  1045 (*For instantiate: process pair of cterms, merge theories*)
  1046 fun add_ctpair ((ct,cu), (sign_ref,tpairs)) =
  1047   let val Cterm {sign_ref=sign_reft, t=t, T= T, ...} = ct
  1048       and Cterm {sign_ref=sign_refu, t=u, T= U, ...} = cu
  1049   in
  1050     if T=U then
  1051       (Sign.merge_refs (sign_ref, Sign.merge_refs (sign_reft, sign_refu)), (t,u)::tpairs)
  1052     else raise TYPE("add_ctpair", [T,U], [t,u])
  1053   end;
  1054 
  1055 fun add_ctyp ((v,ctyp), (sign_ref',vTs)) =
  1056   let val Ctyp {T,sign_ref} = ctyp
  1057   in (Sign.merge_refs(sign_ref,sign_ref'), (v,T)::vTs) end;
  1058 
  1059 (*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
  1060   Instantiates distinct Vars by terms of same type.
  1061   Normalizes the new theorem! *)
  1062 fun instantiate ([], []) th = th
  1063   | instantiate (vcTs,ctpairs)  (th as Thm{sign_ref,der,maxidx,hyps,prop,...}) =
  1064   let val (newsign_ref,tpairs) = foldr add_ctpair (ctpairs, (sign_ref,[]));
  1065       val (newsign_ref,vTs) = foldr add_ctyp (vcTs, (newsign_ref,[]));
  1066       val newprop =
  1067             Envir.norm_term (Envir.empty 0)
  1068               (subst_atomic tpairs
  1069                (Type.inst_term_tvars(Sign.tsig_of (Sign.deref newsign_ref),vTs) prop))
  1070       val newth =
  1071             fix_shyps [th] (map snd vTs)
  1072               (Thm{sign_ref = newsign_ref, 
  1073                    der = infer_derivs (Instantiate(vcTs,ctpairs), [der]), 
  1074                    maxidx = maxidx_of_term newprop, 
  1075                    shyps = [],
  1076                    hyps = hyps,
  1077                    prop = newprop})
  1078   in  if not(instl_ok(map #1 tpairs))
  1079       then raise THM("instantiate: variables not distinct", 0, [th])
  1080       else if not(null(findrep(map #1 vTs)))
  1081       then raise THM("instantiate: type variables not distinct", 0, [th])
  1082       else nodup_Vars newth "instantiate"
  1083   end
  1084   handle TERM _ =>
  1085            raise THM("instantiate: incompatible signatures",0,[th])
  1086        | TYPE (msg,_,_) => raise THM("instantiate: type conflict: " ^ msg, 
  1087 				     0, [th]);
  1088 
  1089 (*The trivial implication A==>A, justified by assume and forall rules.
  1090   A can contain Vars, not so for assume!   *)
  1091 fun trivial ct : thm =
  1092   let val Cterm {sign_ref, t=A, T, maxidx} = ct
  1093   in  if T<>propT then
  1094             raise THM("trivial: the term must have type prop", 0, [])
  1095       else fix_shyps [] []
  1096         (Thm{sign_ref = sign_ref, 
  1097              der = infer_derivs (Trivial ct, []), 
  1098              maxidx = maxidx, 
  1099              shyps = [], 
  1100              hyps = [],
  1101              prop = implies$A$A})
  1102   end;
  1103 
  1104 (*Axiom-scheme reflecting signature contents: "OFCLASS(?'a::c, c_class)" *)
  1105 fun class_triv thy c =
  1106   let val sign = sign_of thy;
  1107       val Cterm {sign_ref, t, maxidx, ...} =
  1108           cterm_of sign (Logic.mk_inclass (TVar (("'a", 0), [c]), c))
  1109             handle TERM (msg, _) => raise THM ("class_triv: " ^ msg, 0, []);
  1110   in
  1111     fix_shyps [] []
  1112       (Thm {sign_ref = sign_ref, 
  1113             der = infer_derivs (Class_triv c, []), 
  1114             maxidx = maxidx, 
  1115             shyps = [], 
  1116             hyps = [], 
  1117             prop = t})
  1118   end;
  1119 
  1120 
  1121 (* Replace all TFrees not in the hyps by new TVars *)
  1122 fun varifyT(Thm{sign_ref,der,maxidx,shyps,hyps,prop}) =
  1123   let val tfrees = foldr add_term_tfree_names (hyps,[])
  1124   in let val thm = (*no fix_shyps*)
  1125     Thm{sign_ref = sign_ref, 
  1126         der = infer_derivs (VarifyT, [der]), 
  1127         maxidx = Int.max(0,maxidx), 
  1128         shyps = shyps, 
  1129         hyps = hyps,
  1130         prop = Type.varify(prop,tfrees)}
  1131      in nodup_Vars thm "varifyT" end
  1132 (* this nodup_Vars check can be removed if thms are guaranteed not to contain
  1133 duplicate TVars with differnt sorts *)
  1134   end;
  1135 
  1136 (* Replace all TVars by new TFrees *)
  1137 fun freezeT(Thm{sign_ref,der,maxidx,shyps,hyps,prop}) =
  1138   let val (prop',_) = Type.freeze_thaw prop
  1139   in (*no fix_shyps*)
  1140     Thm{sign_ref = sign_ref, 
  1141         der = infer_derivs (FreezeT, [der]),
  1142         maxidx = maxidx_of_term prop',
  1143         shyps = shyps,
  1144         hyps = hyps,
  1145         prop = prop'}
  1146   end;
  1147 
  1148 
  1149 (*** Inference rules for tactics ***)
  1150 
  1151 (*Destruct proof state into constraints, other goals, goal(i), rest *)
  1152 fun dest_state (state as Thm{prop,...}, i) =
  1153   let val (tpairs,horn) = Logic.strip_flexpairs prop
  1154   in  case  Logic.strip_prems(i, [], horn) of
  1155           (B::rBs, C) => (tpairs, rev rBs, B, C)
  1156         | _ => raise THM("dest_state", i, [state])
  1157   end
  1158   handle TERM _ => raise THM("dest_state", i, [state]);
  1159 
  1160 (*Increment variables and parameters of orule as required for
  1161   resolution with goal i of state. *)
  1162 fun lift_rule (state, i) orule =
  1163   let val Thm{shyps=sshyps, prop=sprop, maxidx=smax, sign_ref=ssign_ref,...} = state
  1164       val (Bi::_, _) = Logic.strip_prems(i, [], Logic.skip_flexpairs sprop)
  1165         handle TERM _ => raise THM("lift_rule", i, [orule,state])
  1166       val ct_Bi = Cterm {sign_ref=ssign_ref, maxidx=smax, T=propT, t=Bi}
  1167       val (lift_abs,lift_all) = Logic.lift_fns(Bi,smax+1)
  1168       val (Thm{sign_ref, der, maxidx,shyps,hyps,prop}) = orule
  1169       val (tpairs,As,B) = Logic.strip_horn prop
  1170   in  (*no fix_shyps*)
  1171       Thm{sign_ref = merge_thm_sgs(state,orule),
  1172           der = infer_derivs (Lift_rule(ct_Bi, i), [der]),
  1173           maxidx = maxidx+smax+1,
  1174           shyps=union_sort(sshyps,shyps), 
  1175           hyps=hyps, 
  1176           prop = Logic.rule_of (map (pairself lift_abs) tpairs,
  1177                                 map lift_all As,    
  1178                                 lift_all B)}
  1179   end;
  1180 
  1181 (*Solve subgoal Bi of proof state B1...Bn/C by assumption. *)
  1182 fun assumption i state =
  1183   let val Thm{sign_ref,der,maxidx,hyps,prop,...} = state;
  1184       val (tpairs, Bs, Bi, C) = dest_state(state,i)
  1185       fun newth (env as Envir.Envir{maxidx, ...}, tpairs) =
  1186         fix_shyps [state] (env_codT env)
  1187           (Thm{sign_ref = sign_ref, 
  1188                der = infer_derivs (Assumption (i, Some env), [der]),
  1189                maxidx = maxidx,
  1190                shyps = [],
  1191                hyps = hyps,
  1192                prop = 
  1193                if Envir.is_empty env then (*avoid wasted normalizations*)
  1194                    Logic.rule_of (tpairs, Bs, C)
  1195                else (*normalize the new rule fully*)
  1196                    Envir.norm_term env (Logic.rule_of (tpairs, Bs, C))});
  1197       fun addprfs [] = Seq.empty
  1198         | addprfs ((t,u)::apairs) = Seq.make (fn()=> Seq.pull
  1199              (Seq.mapp newth
  1200                 (Unify.unifiers(Sign.deref sign_ref,Envir.empty maxidx, (t,u)::tpairs))
  1201                 (addprfs apairs)))
  1202   in  addprfs (Logic.assum_pairs Bi)  end;
  1203 
  1204 (*Solve subgoal Bi of proof state B1...Bn/C by assumption.
  1205   Checks if Bi's conclusion is alpha-convertible to one of its assumptions*)
  1206 fun eq_assumption i state =
  1207   let val Thm{sign_ref,der,maxidx,hyps,prop,...} = state;
  1208       val (tpairs, Bs, Bi, C) = dest_state(state,i)
  1209   in  if exists (op aconv) (Logic.assum_pairs Bi)
  1210       then fix_shyps [state] []
  1211              (Thm{sign_ref = sign_ref, 
  1212                   der = infer_derivs (Assumption (i,None), [der]),
  1213                   maxidx = maxidx,
  1214                   shyps = [],
  1215                   hyps = hyps,
  1216                   prop = Logic.rule_of(tpairs, Bs, C)})
  1217       else  raise THM("eq_assumption", 0, [state])
  1218   end;
  1219 
  1220 
  1221 (*For rotate_tac: fast rotation of assumptions of subgoal i*)
  1222 fun rotate_rule k i state =
  1223   let val Thm{sign_ref,der,maxidx,hyps,prop,shyps} = state;
  1224       val (tpairs, Bs, Bi, C) = dest_state(state,i)
  1225       val params = Logic.strip_params Bi
  1226       and asms   = Logic.strip_assums_hyp Bi
  1227       and concl  = Logic.strip_assums_concl Bi
  1228       val n      = length asms
  1229       fun rot m  = if 0=m orelse m=n then Bi
  1230 		   else if 0<m andalso m<n 
  1231 		   then list_all 
  1232 			   (params, 
  1233 			    Logic.list_implies(List.drop(asms, m) @ 
  1234 					       List.take(asms, m),
  1235 					       concl))
  1236 		   else raise THM("rotate_rule", m, [state])
  1237   in  Thm{sign_ref = sign_ref, 
  1238 	  der = infer_derivs (Rotate_rule (k,i), [der]),
  1239 	  maxidx = maxidx,
  1240 	  shyps = shyps,
  1241 	  hyps = hyps,
  1242 	  prop = Logic.rule_of(tpairs, Bs@[rot (if k<0 then n+k else k)], C)}
  1243   end;
  1244 
  1245 
  1246 (** User renaming of parameters in a subgoal **)
  1247 
  1248 (*Calls error rather than raising an exception because it is intended
  1249   for top-level use -- exception handling would not make sense here.
  1250   The names in cs, if distinct, are used for the innermost parameters;
  1251    preceding parameters may be renamed to make all params distinct.*)
  1252 fun rename_params_rule (cs, i) state =
  1253   let val Thm{sign_ref,der,maxidx,hyps,...} = state
  1254       val (tpairs, Bs, Bi, C) = dest_state(state,i)
  1255       val iparams = map #1 (Logic.strip_params Bi)
  1256       val short = length iparams - length cs
  1257       val newnames =
  1258             if short<0 then error"More names than abstractions!"
  1259             else variantlist(take (short,iparams), cs) @ cs
  1260       val freenames = map (#1 o dest_Free) (term_frees Bi)
  1261       val newBi = Logic.list_rename_params (newnames, Bi)
  1262   in
  1263   case findrep cs of
  1264      c::_ => (warning ("Can't rename.  Bound variables not distinct: " ^ c); 
  1265 	      state)
  1266    | [] => (case cs inter_string freenames of
  1267        a::_ => (warning ("Can't rename.  Bound/Free variable clash: " ^ a); 
  1268 		state)
  1269      | [] => fix_shyps [state] []
  1270                 (Thm{sign_ref = sign_ref,
  1271                      der = infer_derivs (Rename_params_rule(cs,i), [der]),
  1272                      maxidx = maxidx,
  1273                      shyps = [],
  1274                      hyps = hyps,
  1275                      prop = Logic.rule_of(tpairs, Bs@[newBi], C)}))
  1276   end;
  1277 
  1278 (*** Preservation of bound variable names ***)
  1279 
  1280 (*Scan a pair of terms; while they are similar,
  1281   accumulate corresponding bound vars in "al"*)
  1282 fun match_bvs(Abs(x,_,s),Abs(y,_,t), al) =
  1283       match_bvs(s, t, if x="" orelse y="" then al
  1284                                           else (x,y)::al)
  1285   | match_bvs(f$s, g$t, al) = match_bvs(f,g,match_bvs(s,t,al))
  1286   | match_bvs(_,_,al) = al;
  1287 
  1288 (* strip abstractions created by parameters *)
  1289 fun match_bvars((s,t),al) = match_bvs(strip_abs_body s, strip_abs_body t, al);
  1290 
  1291 
  1292 (* strip_apply f A(,B) strips off all assumptions/parameters from A
  1293    introduced by lifting over B, and applies f to remaining part of A*)
  1294 fun strip_apply f =
  1295   let fun strip(Const("==>",_)$ A1 $ B1,
  1296                 Const("==>",_)$ _  $ B2) = implies $ A1 $ strip(B1,B2)
  1297         | strip((c as Const("all",_)) $ Abs(a,T,t1),
  1298                       Const("all",_)  $ Abs(_,_,t2)) = c$Abs(a,T,strip(t1,t2))
  1299         | strip(A,_) = f A
  1300   in strip end;
  1301 
  1302 (*Use the alist to rename all bound variables and some unknowns in a term
  1303   dpairs = current disagreement pairs;  tpairs = permanent ones (flexflex);
  1304   Preserves unknowns in tpairs and on lhs of dpairs. *)
  1305 fun rename_bvs([],_,_,_) = I
  1306   | rename_bvs(al,dpairs,tpairs,B) =
  1307     let val vars = foldr add_term_vars
  1308                         (map fst dpairs @ map fst tpairs @ map snd tpairs, [])
  1309         (*unknowns appearing elsewhere be preserved!*)
  1310         val vids = map (#1 o #1 o dest_Var) vars;
  1311         fun rename(t as Var((x,i),T)) =
  1312                 (case assoc(al,x) of
  1313                    Some(y) => if x mem_string vids orelse y mem_string vids then t
  1314                               else Var((y,i),T)
  1315                  | None=> t)
  1316           | rename(Abs(x,T,t)) =
  1317               Abs(case assoc_string(al,x) of Some(y) => y | None => x,
  1318                   T, rename t)
  1319           | rename(f$t) = rename f $ rename t
  1320           | rename(t) = t;
  1321         fun strip_ren Ai = strip_apply rename (Ai,B)
  1322     in strip_ren end;
  1323 
  1324 (*Function to rename bounds/unknowns in the argument, lifted over B*)
  1325 fun rename_bvars(dpairs, tpairs, B) =
  1326         rename_bvs(foldr match_bvars (dpairs,[]), dpairs, tpairs, B);
  1327 
  1328 
  1329 (*** RESOLUTION ***)
  1330 
  1331 (** Lifting optimizations **)
  1332 
  1333 (*strip off pairs of assumptions/parameters in parallel -- they are
  1334   identical because of lifting*)
  1335 fun strip_assums2 (Const("==>", _) $ _ $ B1,
  1336                    Const("==>", _) $ _ $ B2) = strip_assums2 (B1,B2)
  1337   | strip_assums2 (Const("all",_)$Abs(a,T,t1),
  1338                    Const("all",_)$Abs(_,_,t2)) =
  1339       let val (B1,B2) = strip_assums2 (t1,t2)
  1340       in  (Abs(a,T,B1), Abs(a,T,B2))  end
  1341   | strip_assums2 BB = BB;
  1342 
  1343 
  1344 (*Faster normalization: skip assumptions that were lifted over*)
  1345 fun norm_term_skip env 0 t = Envir.norm_term env t
  1346   | norm_term_skip env n (Const("all",_)$Abs(a,T,t)) =
  1347         let val Envir.Envir{iTs, ...} = env
  1348             val T' = typ_subst_TVars iTs T
  1349             (*Must instantiate types of parameters because they are flattened;
  1350               this could be a NEW parameter*)
  1351         in  all T' $ Abs(a, T', norm_term_skip env n t)  end
  1352   | norm_term_skip env n (Const("==>", _) $ A $ B) =
  1353         implies $ A $ norm_term_skip env (n-1) B
  1354   | norm_term_skip env n t = error"norm_term_skip: too few assumptions??";
  1355 
  1356 
  1357 (*Composition of object rule r=(A1...Am/B) with proof state s=(B1...Bn/C)
  1358   Unifies B with Bi, replacing subgoal i    (1 <= i <= n)
  1359   If match then forbid instantiations in proof state
  1360   If lifted then shorten the dpair using strip_assums2.
  1361   If eres_flg then simultaneously proves A1 by assumption.
  1362   nsubgoal is the number of new subgoals (written m above).
  1363   Curried so that resolution calls dest_state only once.
  1364 *)
  1365 local exception COMPOSE
  1366 in
  1367 fun bicompose_aux match (state, (stpairs, Bs, Bi, C), lifted)
  1368                         (eres_flg, orule, nsubgoal) =
  1369  let val Thm{der=sder, maxidx=smax, shyps=sshyps, hyps=shyps, ...} = state
  1370      and Thm{der=rder, maxidx=rmax, shyps=rshyps, hyps=rhyps, 
  1371              prop=rprop,...} = orule
  1372          (*How many hyps to skip over during normalization*)
  1373      and nlift = Logic.count_prems(strip_all_body Bi,
  1374                                    if eres_flg then ~1 else 0)
  1375      val sign_ref = merge_thm_sgs(state,orule);
  1376      val sign = Sign.deref sign_ref;
  1377      (** Add new theorem with prop = '[| Bs; As |] ==> C' to thq **)
  1378      fun addth As ((env as Envir.Envir {maxidx, ...}, tpairs), thq) =
  1379        let val normt = Envir.norm_term env;
  1380            (*perform minimal copying here by examining env*)
  1381            val normp =
  1382              if Envir.is_empty env then (tpairs, Bs @ As, C)
  1383              else
  1384              let val ntps = map (pairself normt) tpairs
  1385              in if Envir.above (smax, env) then
  1386                   (*no assignments in state; normalize the rule only*)
  1387                   if lifted
  1388                   then (ntps, Bs @ map (norm_term_skip env nlift) As, C)
  1389                   else (ntps, Bs @ map normt As, C)
  1390                 else if match then raise COMPOSE
  1391                 else (*normalize the new rule fully*)
  1392                   (ntps, map normt (Bs @ As), normt C)
  1393              end
  1394            val th = (*tuned fix_shyps*)
  1395              Thm{sign_ref = sign_ref,
  1396                  der = infer_derivs (Bicompose(match, eres_flg,
  1397                                                1 + length Bs, nsubgoal, env),
  1398                                      [rder,sder]),
  1399                  maxidx = maxidx,
  1400                  shyps = add_env_sorts (env, union_sort(rshyps,sshyps)),
  1401                  hyps = union_term(rhyps,shyps),
  1402                  prop = Logic.rule_of normp}
  1403         in  Seq.cons(th, thq)  end  handle COMPOSE => thq
  1404      val (rtpairs,rhorn) = Logic.strip_flexpairs(rprop);
  1405      val (rAs,B) = Logic.strip_prems(nsubgoal, [], rhorn)
  1406        handle TERM _ => raise THM("bicompose: rule", 0, [orule,state]);
  1407      (*Modify assumptions, deleting n-th if n>0 for e-resolution*)
  1408      fun newAs(As0, n, dpairs, tpairs) =
  1409        let val As1 = if !Logic.auto_rename orelse not lifted then As0
  1410                      else map (rename_bvars(dpairs,tpairs,B)) As0
  1411        in (map (Logic.flatten_params n) As1)
  1412           handle TERM _ =>
  1413           raise THM("bicompose: 1st premise", 0, [orule])
  1414        end;
  1415      val env = Envir.empty(Int.max(rmax,smax));
  1416      val BBi = if lifted then strip_assums2(B,Bi) else (B,Bi);
  1417      val dpairs = BBi :: (rtpairs@stpairs);
  1418      (*elim-resolution: try each assumption in turn.  Initially n=1*)
  1419      fun tryasms (_, _, []) = Seq.empty
  1420        | tryasms (As, n, (t,u)::apairs) =
  1421           (case Seq.pull(Unify.unifiers(sign, env, (t,u)::dpairs))  of
  1422                None                   => tryasms (As, n+1, apairs)
  1423              | cell as Some((_,tpairs),_) =>
  1424                    Seq.it_right (addth (newAs(As, n, [BBi,(u,t)], tpairs)))
  1425                        (Seq.make (fn()=> cell),
  1426                         Seq.make (fn()=> Seq.pull (tryasms (As, n+1, apairs)))));
  1427      fun eres [] = raise THM("bicompose: no premises", 0, [orule,state])
  1428        | eres (A1::As) = tryasms (As, 1, Logic.assum_pairs A1);
  1429      (*ordinary resolution*)
  1430      fun res(None) = Seq.empty
  1431        | res(cell as Some((_,tpairs),_)) =
  1432              Seq.it_right (addth(newAs(rev rAs, 0, [BBi], tpairs)))
  1433                        (Seq.make (fn()=> cell), Seq.empty)
  1434  in  if eres_flg then eres(rev rAs)
  1435      else res(Seq.pull(Unify.unifiers(sign, env, dpairs)))
  1436  end;
  1437 end;  (*open Sequence*)
  1438 
  1439 
  1440 fun bicompose match arg i state =
  1441     bicompose_aux match (state, dest_state(state,i), false) arg;
  1442 
  1443 (*Quick test whether rule is resolvable with the subgoal with hyps Hs
  1444   and conclusion B.  If eres_flg then checks 1st premise of rule also*)
  1445 fun could_bires (Hs, B, eres_flg, rule) =
  1446     let fun could_reshyp (A1::_) = exists (apl(A1,could_unify)) Hs
  1447           | could_reshyp [] = false;  (*no premise -- illegal*)
  1448     in  could_unify(concl_of rule, B) andalso
  1449         (not eres_flg  orelse  could_reshyp (prems_of rule))
  1450     end;
  1451 
  1452 (*Bi-resolution of a state with a list of (flag,rule) pairs.
  1453   Puts the rule above:  rule/state.  Renames vars in the rules. *)
  1454 fun biresolution match brules i state =
  1455     let val lift = lift_rule(state, i);
  1456         val (stpairs, Bs, Bi, C) = dest_state(state,i)
  1457         val B = Logic.strip_assums_concl Bi;
  1458         val Hs = Logic.strip_assums_hyp Bi;
  1459         val comp = bicompose_aux match (state, (stpairs, Bs, Bi, C), true);
  1460         fun res [] = Seq.empty
  1461           | res ((eres_flg, rule)::brules) =
  1462               if could_bires (Hs, B, eres_flg, rule)
  1463               then Seq.make (*delay processing remainder till needed*)
  1464                   (fn()=> Some(comp (eres_flg, lift rule, nprems_of rule),
  1465                                res brules))
  1466               else res brules
  1467     in  Seq.flat (res brules)  end;
  1468 
  1469 
  1470 
  1471 (*** Meta Simplification ***)
  1472 
  1473 (** diagnostics **)
  1474 
  1475 exception SIMPLIFIER of string * thm;
  1476 
  1477 fun prnt warn a = if warn then warning a else writeln a;
  1478 
  1479 fun prtm warn a sign t =
  1480   (prnt warn a; prnt warn (Sign.string_of_term sign t));
  1481 
  1482 val trace_simp = ref false;
  1483 
  1484 fun trace warn a = if !trace_simp then prnt warn a else ();
  1485 
  1486 fun trace_term warn a sign t =
  1487   if !trace_simp then prtm warn a sign t else ();
  1488 
  1489 fun trace_thm warn a (thm as Thm{sign_ref, prop, ...}) =
  1490   (trace_term warn a (Sign.deref sign_ref) prop);
  1491 
  1492 
  1493 
  1494 (** meta simp sets **)
  1495 
  1496 (* basic components *)
  1497 
  1498 type rrule = {thm: thm, lhs: term, perm: bool};
  1499 type cong = {thm: thm, lhs: term};
  1500 type simproc =
  1501  {name: string, proc: Sign.sg -> thm list -> term -> thm option, lhs: cterm, id: stamp};
  1502 
  1503 fun eq_rrule ({thm = Thm {prop = p1, ...}, ...}: rrule,
  1504   {thm = Thm {prop = p2, ...}, ...}: rrule) = p1 aconv p2;
  1505 
  1506 fun eq_cong ({thm = Thm {prop = p1, ...}, ...}: cong,
  1507   {thm = Thm {prop = p2, ...}, ...}: cong) = p1 aconv p2;
  1508 
  1509 fun eq_prem (Thm {prop = p1, ...}, Thm {prop = p2, ...}) = p1 aconv p2;
  1510 
  1511 fun eq_simproc ({id = s1, ...}:simproc, {id = s2, ...}:simproc) = (s1 = s2);
  1512 
  1513 fun mk_simproc (name, proc, lhs, id) =
  1514   {name = name, proc = proc, lhs = lhs, id = id};
  1515 
  1516 
  1517 (* datatype mss *)
  1518 
  1519 (*
  1520   A "mss" contains data needed during conversion:
  1521     rules: discrimination net of rewrite rules;
  1522     congs: association list of congruence rules;
  1523     procs: discrimination net of simplification procedures
  1524       (functions that prove rewrite rules on the fly);
  1525     bounds: names of bound variables already used
  1526       (for generating new names when rewriting under lambda abstractions);
  1527     prems: current premises;
  1528     mk_rews: turns simplification thms into rewrite rules;
  1529     termless: relation for ordered rewriting;
  1530 *)
  1531 
  1532 datatype meta_simpset =
  1533   Mss of {
  1534     rules: rrule Net.net,
  1535     congs: (string * cong) list,
  1536     procs: simproc Net.net,
  1537     bounds: string list,
  1538     prems: thm list,
  1539     mk_rews: thm -> thm list,
  1540     termless: term * term -> bool};
  1541 
  1542 fun mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless) =
  1543   Mss {rules = rules, congs = congs, procs = procs, bounds = bounds,
  1544     prems = prems, mk_rews = mk_rews, termless = termless};
  1545 
  1546 val empty_mss =
  1547   mk_mss (Net.empty, [], Net.empty, [], [], K [], Logic.termless);
  1548 
  1549 
  1550 
  1551 (** simpset operations **)
  1552 
  1553 (* dest_mss *)
  1554 
  1555 fun dest_mss (Mss {rules, congs, procs, ...}) =
  1556   {simps = map (fn (_, {thm, ...}) => thm) (Net.dest rules),
  1557    congs = map (fn (_, {thm, ...}) => thm) congs,
  1558    procs =
  1559      map (fn (_, {name, lhs, id, ...}) => ((name, lhs), id)) (Net.dest procs)
  1560      |> partition_eq eq_snd
  1561      |> map (fn ps => (#1 (#1 (hd ps)), map (#2 o #1) ps))};
  1562 
  1563 
  1564 (* merge_mss *)		(*NOTE: ignores mk_rews and termless of 2nd mss*)
  1565 
  1566 fun merge_mss
  1567  (Mss {rules = rules1, congs = congs1, procs = procs1, bounds = bounds1,
  1568     prems = prems1, mk_rews, termless},
  1569   Mss {rules = rules2, congs = congs2, procs = procs2, bounds = bounds2,
  1570     prems = prems2, ...}) =
  1571       mk_mss
  1572        (Net.merge (rules1, rules2, eq_rrule),
  1573         generic_merge (eq_cong o pairself snd) I I congs1 congs2,
  1574         Net.merge (procs1, procs2, eq_simproc),
  1575         merge_lists bounds1 bounds2,
  1576         generic_merge eq_prem I I prems1 prems2,
  1577         mk_rews, termless);
  1578 
  1579 
  1580 (* mk_rrule *)
  1581 
  1582 fun mk_rrule (thm as Thm {sign_ref, prop, ...}) =
  1583   let
  1584     val sign = Sign.deref sign_ref;
  1585     val prems = Logic.strip_imp_prems prop;
  1586     val concl = Logic.strip_imp_concl prop;
  1587     val (lhs, rhs) = Logic.dest_equals concl handle TERM _ =>
  1588       raise SIMPLIFIER ("Rewrite rule not a meta-equality", thm);
  1589   in case Logic.rewrite_rule_ok sign prems lhs rhs of
  1590      (None,perm) => Some {thm = thm, lhs = lhs, perm = perm}
  1591    | (Some msg,_) =>
  1592         (prtm true ("ignoring rewrite rule ("^msg^")") sign prop; None)
  1593   end;
  1594 
  1595 
  1596 (* add_simps *)
  1597 
  1598 fun add_simp
  1599   (mss as Mss {rules, congs, procs, bounds, prems, mk_rews, termless},
  1600     thm as Thm {sign_ref, prop, ...}) =
  1601   (case mk_rrule thm of
  1602     None => mss
  1603   | Some (rrule as {lhs, ...}) =>
  1604       (trace_thm false "Adding rewrite rule:" thm;
  1605         mk_mss (Net.insert_term ((lhs, rrule), rules, eq_rrule) handle Net.INSERT =>
  1606           (prtm true "ignoring duplicate rewrite rule" (Sign.deref sign_ref) prop; rules),
  1607             congs, procs, bounds, prems, mk_rews, termless)));
  1608 
  1609 val add_simps = foldl add_simp;
  1610 
  1611 fun mss_of thms = add_simps (empty_mss, thms);
  1612 
  1613 
  1614 (* del_simps *)
  1615 
  1616 fun del_simp
  1617   (mss as Mss {rules, congs, procs, bounds, prems, mk_rews, termless},
  1618     thm as Thm {sign_ref, prop, ...}) =
  1619   (case mk_rrule thm of
  1620     None => mss
  1621   | Some (rrule as {lhs, ...}) =>
  1622       mk_mss (Net.delete_term ((lhs, rrule), rules, eq_rrule) handle Net.DELETE =>
  1623         (prtm true "rewrite rule not in simpset" (Sign.deref sign_ref) prop; rules),
  1624           congs, procs, bounds, prems, mk_rews, termless));
  1625 
  1626 val del_simps = foldl del_simp;
  1627 
  1628 
  1629 (* add_congs *)
  1630 
  1631 fun add_cong (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, thm) =
  1632   let
  1633     val (lhs, _) = Logic.dest_equals (concl_of thm) handle TERM _ =>
  1634       raise SIMPLIFIER ("Congruence not a meta-equality", thm);
  1635 (*   val lhs = Pattern.eta_contract lhs; *)
  1636     val (a, _) = dest_Const (head_of lhs) handle TERM _ =>
  1637       raise SIMPLIFIER ("Congruence must start with a constant", thm);
  1638   in
  1639     mk_mss (rules, (a, {lhs = lhs, thm = thm}) :: congs, procs, bounds,
  1640       prems, mk_rews, termless)
  1641   end;
  1642 
  1643 val (op add_congs) = foldl add_cong;
  1644 
  1645 
  1646 (* del_congs *)
  1647 
  1648 fun del_cong (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, thm) =
  1649   let
  1650     val (lhs, _) = Logic.dest_equals (concl_of thm) handle TERM _ =>
  1651       raise SIMPLIFIER ("Congruence not a meta-equality", thm);
  1652 (*   val lhs = Pattern.eta_contract lhs; *)
  1653     val (a, _) = dest_Const (head_of lhs) handle TERM _ =>
  1654       raise SIMPLIFIER ("Congruence must start with a constant", thm);
  1655   in
  1656     mk_mss (rules, filter (fn (x,_)=> x<>a) congs, procs, bounds,
  1657       prems, mk_rews, termless)
  1658   end;
  1659 
  1660 val (op del_congs) = foldl del_cong;
  1661 
  1662 
  1663 (* add_simprocs *)
  1664 
  1665 fun add_proc (mss as Mss {rules, congs, procs, bounds, prems, mk_rews, termless},
  1666     (name, lhs as Cterm {sign_ref, t, ...}, proc, id)) =
  1667   (trace_term false ("Adding simplification procedure " ^ quote name ^ " for:")
  1668       (Sign.deref sign_ref) t;
  1669     mk_mss (rules, congs,
  1670       Net.insert_term ((t, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
  1671         handle Net.INSERT => (trace true "ignored duplicate"; procs),
  1672         bounds, prems, mk_rews, termless));
  1673 
  1674 fun add_simproc (mss, (name, lhss, proc, id)) =
  1675   foldl add_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
  1676 
  1677 val add_simprocs = foldl add_simproc;
  1678 
  1679 
  1680 (* del_simprocs *)
  1681 
  1682 fun del_proc (mss as Mss {rules, congs, procs, bounds, prems, mk_rews, termless},
  1683     (name, lhs as Cterm {t, ...}, proc, id)) =
  1684   mk_mss (rules, congs,
  1685     Net.delete_term ((t, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
  1686       handle Net.DELETE => (trace true "simplification procedure not in simpset"; procs),
  1687       bounds, prems, mk_rews, termless);
  1688 
  1689 fun del_simproc (mss, (name, lhss, proc, id)) =
  1690   foldl del_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
  1691 
  1692 val del_simprocs = foldl del_simproc;
  1693 
  1694 
  1695 (* prems *)
  1696 
  1697 fun add_prems (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, thms) =
  1698   mk_mss (rules, congs, procs, bounds, thms @ prems, mk_rews, termless);
  1699 
  1700 fun prems_of_mss (Mss {prems, ...}) = prems;
  1701 
  1702 
  1703 (* mk_rews *)
  1704 
  1705 fun set_mk_rews
  1706   (Mss {rules, congs, procs, bounds, prems, mk_rews = _, termless}, mk_rews) =
  1707     mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless);
  1708 
  1709 fun mk_rews_of_mss (Mss {mk_rews, ...}) = mk_rews;
  1710 
  1711 
  1712 (* termless *)
  1713 
  1714 fun set_termless
  1715   (Mss {rules, congs, procs, bounds, prems, mk_rews, termless = _}, termless) =
  1716     mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless);
  1717 
  1718 
  1719 
  1720 (** rewriting **)
  1721 
  1722 (*
  1723   Uses conversions, omitting proofs for efficiency.  See:
  1724     L C Paulson, A higher-order implementation of rewriting,
  1725     Science of Computer Programming 3 (1983), pages 119-149.
  1726 *)
  1727 
  1728 type prover = meta_simpset -> thm -> thm option;
  1729 type termrec = (Sign.sg_ref * term list) * term;
  1730 type conv = meta_simpset -> termrec -> termrec;
  1731 
  1732 fun check_conv (thm as Thm{shyps,hyps,prop,sign_ref,der,...}, prop0, ders) =
  1733   let fun err() = (trace_thm false "Proved wrong thm (Check subgoaler?)" thm;
  1734                    trace_term false "Should have proved" (Sign.deref sign_ref) prop0;
  1735                    None)
  1736       val (lhs0,_) = Logic.dest_equals(Logic.strip_imp_concl prop0)
  1737   in case prop of
  1738        Const("==",_) $ lhs $ rhs =>
  1739          if (lhs = lhs0) orelse
  1740             (lhs aconv Envir.norm_term (Envir.empty 0) lhs0)
  1741          then (trace_thm false "SUCCEEDED" thm; 
  1742                Some(shyps, hyps, rhs, der::ders))
  1743          else err()
  1744      | _ => err()
  1745   end;
  1746 
  1747 fun ren_inst(insts,prop,pat,obj) =
  1748   let val ren = match_bvs(pat,obj,[])
  1749       fun renAbs(Abs(x,T,b)) =
  1750             Abs(case assoc_string(ren,x) of None => x | Some(y) => y, T, renAbs(b))
  1751         | renAbs(f$t) = renAbs(f) $ renAbs(t)
  1752         | renAbs(t) = t
  1753   in subst_vars insts (if null(ren) then prop else renAbs(prop)) end;
  1754 
  1755 fun add_insts_sorts ((iTs, is), Ss) =
  1756   add_typs_sorts (map snd iTs, add_terms_sorts (map snd is, Ss));
  1757 
  1758 
  1759 (* mk_procrule *)
  1760 
  1761 fun mk_procrule (thm as Thm {sign_ref, prop, ...}) =
  1762   let
  1763     val sign = Sign.deref sign_ref;
  1764     val prems = Logic.strip_imp_prems prop;
  1765     val concl = Logic.strip_imp_concl prop;
  1766     val (lhs, _) = Logic.dest_equals concl handle TERM _ =>
  1767       raise SIMPLIFIER ("Rewrite rule not a meta-equality", thm);
  1768     val econcl = Pattern.eta_contract concl;
  1769     val (elhs, erhs) = Logic.dest_equals econcl;
  1770   in case Logic.rewrite_rule_extra_vars prems elhs erhs of
  1771        Some msg => (prtm true msg sign prop; [])
  1772      | None => [{thm = thm, lhs = lhs, perm = false}]
  1773   end;
  1774 
  1775 
  1776 (* conversion to apply the meta simpset to a term *)
  1777 
  1778 (*
  1779   we try in order:
  1780     (1) beta reduction
  1781     (2) unconditional rewrite rules
  1782     (3) conditional rewrite rules
  1783     (4) simplification procedures
  1784 
  1785   IMPORTANT: rewrite rules must not introduce new Vars or TVars!
  1786 
  1787 *)
  1788 
  1789 fun rewritec (prover,sign_reft,maxt)
  1790              (mss as Mss{rules, procs, mk_rews, termless, prems, ...}) 
  1791              (shypst,hypst,t,ders) =
  1792   let
  1793       val signt = Sign.deref sign_reft;
  1794       val tsigt = Sign.tsig_of signt;
  1795       fun rew{thm as Thm{sign_ref,der,shyps,hyps,prop,maxidx,...}, lhs, perm} =
  1796         let
  1797             val _ =
  1798               if Sign.subsig (Sign.deref sign_ref, signt) then ()
  1799               else (trace_thm true "rewrite rule from different theory" thm;
  1800                 raise Pattern.MATCH);
  1801             val rprop = if maxt = ~1 then prop
  1802                         else Logic.incr_indexes([],maxt+1) prop;
  1803             val rlhs = if maxt = ~1 then lhs
  1804                        else fst(Logic.dest_equals(Logic.strip_imp_concl rprop))
  1805             val insts = Pattern.match tsigt (rlhs,t);
  1806             val prop' = ren_inst(insts,rprop,rlhs,t);
  1807             val hyps' = union_term(hyps,hypst);
  1808             val shyps' = add_insts_sorts (insts, union_sort(shyps,shypst));
  1809             val unconditional = (Logic.count_prems(prop',0) = 0);
  1810             val maxidx' = if unconditional then maxt else maxidx+maxt+1
  1811             val ct' = Cterm{sign_ref = sign_reft,       (*used for deriv only*)
  1812                             t = prop',
  1813                             T = propT,
  1814                             maxidx = maxidx'}
  1815             val der' = infer_derivs (RewriteC ct', [der]);
  1816             val thm' = Thm{sign_ref = sign_reft, 
  1817                            der = der',
  1818                            shyps = shyps',
  1819                            hyps = hyps',
  1820                            prop = prop',
  1821                            maxidx = maxidx'}
  1822             val (lhs',rhs') = Logic.dest_equals(Logic.strip_imp_concl prop')
  1823         in if perm andalso not(termless(rhs',lhs')) then None else
  1824            if unconditional
  1825            then (trace_thm false "Rewriting:" thm'; 
  1826                  Some(shyps', hyps', rhs', der'::ders))
  1827            else (trace_thm false "Trying to rewrite:" thm';
  1828                  case prover mss thm' of
  1829                    None       => (trace_thm false "FAILED" thm'; None)
  1830                  | Some(thm2) => check_conv(thm2,prop',ders))
  1831         end
  1832 
  1833       fun rews [] = None
  1834         | rews (rrule :: rrules) =
  1835             let val opt = rew rrule handle Pattern.MATCH => None
  1836             in case opt of None => rews rrules | some => some end;
  1837 
  1838       fun sort_rrules rrs = let
  1839         fun is_simple {thm as Thm{prop,...}, lhs, perm} = case prop of 
  1840                                         Const("==",_) $ _ $ _ => true
  1841                                         | _                   => false 
  1842         fun sort []        (re1,re2) = re1 @ re2
  1843         |   sort (rr::rrs) (re1,re2) = if is_simple rr 
  1844                                        then sort rrs (rr::re1,re2)
  1845                                        else sort rrs (re1,rr::re2)
  1846       in sort rrs ([],[]) 
  1847       end
  1848 
  1849       fun proc_rews _ ([]:simproc list) = None
  1850         | proc_rews eta_t ({name, proc, lhs = Cterm {t = plhs, ...}, ...} :: ps) =
  1851             if Pattern.matches tsigt (plhs, t) then
  1852              (trace_term false ("Trying procedure " ^ quote name ^ " on:") signt eta_t;
  1853               case proc signt prems eta_t of
  1854                 None => (trace false "FAILED"; proc_rews eta_t ps)
  1855               | Some raw_thm =>
  1856                  (trace_thm false ("Procedure " ^ quote name ^ " proved rewrite rule:") raw_thm;
  1857                    (case rews (mk_procrule raw_thm) of
  1858                      None => (trace false "IGNORED"; proc_rews eta_t ps)
  1859                    | some => some)))
  1860             else proc_rews eta_t ps;
  1861   in
  1862     (case t of
  1863       Abs (_, _, body) $ u =>
  1864         Some (shypst, hypst, subst_bound (u, body), ders)
  1865      | _ =>
  1866       (case rews (sort_rrules (Net.match_term rules t)) of
  1867         None => proc_rews (Pattern.eta_contract t) (Net.match_term procs t)
  1868       | some => some))
  1869   end;
  1870 
  1871 
  1872 (* conversion to apply a congruence rule to a term *)
  1873 
  1874 fun congc (prover,sign_reft,maxt) {thm=cong,lhs=lhs} (shypst,hypst,t,ders) =
  1875   let val signt = Sign.deref sign_reft;
  1876       val tsig = Sign.tsig_of signt;
  1877       val Thm{sign_ref,der,shyps,hyps,maxidx,prop,...} = cong
  1878       val _ = if Sign.subsig(Sign.deref sign_ref,signt) then ()
  1879                  else error("Congruence rule from different theory")
  1880       val rprop = if maxt = ~1 then prop
  1881                   else Logic.incr_indexes([],maxt+1) prop;
  1882       val rlhs = if maxt = ~1 then lhs
  1883                  else fst(Logic.dest_equals(Logic.strip_imp_concl rprop))
  1884       val insts = Pattern.match tsig (rlhs,t)
  1885       (* Pattern.match can raise Pattern.MATCH;
  1886          is handled when congc is called *)
  1887       val prop' = ren_inst(insts,rprop,rlhs,t);
  1888       val shyps' = add_insts_sorts (insts, union_sort(shyps,shypst))
  1889       val maxidx' = maxidx_of_term prop'
  1890       val ct' = Cterm{sign_ref = sign_reft,     (*used for deriv only*)
  1891                       t = prop',
  1892                       T = propT,
  1893                       maxidx = maxidx'}
  1894       val thm' = Thm{sign_ref = sign_reft, 
  1895                      der = infer_derivs (CongC ct', [der]),
  1896                      shyps = shyps',
  1897                      hyps = union_term(hyps,hypst),
  1898                      prop = prop',
  1899                      maxidx = maxidx'};
  1900       val unit = trace_thm false "Applying congruence rule" thm';
  1901       fun err() = error("Failed congruence proof!")
  1902 
  1903   in case prover thm' of
  1904        None => err()
  1905      | Some(thm2) => (case check_conv(thm2,prop',ders) of
  1906                         None => err() | some => some)
  1907   end;
  1908 
  1909 fun bottomc ((simprem,useprem),prover,sign_ref,maxidx) =
  1910  let fun botc fail mss trec =
  1911           (case subc mss trec of
  1912              some as Some(trec1) =>
  1913                (case rewritec (prover,sign_ref,maxidx) mss trec1 of
  1914                   Some(trec2) => botc false mss trec2
  1915                 | None => some)
  1916            | None =>
  1917                (case rewritec (prover,sign_ref,maxidx) mss trec of
  1918                   Some(trec2) => botc false mss trec2
  1919                 | None => if fail then None else Some(trec)))
  1920 
  1921      and try_botc mss trec = (case botc true mss trec of
  1922                                 Some(trec1) => trec1
  1923                               | None => trec)
  1924 
  1925      and subc (mss as Mss{rules,congs,procs,bounds,prems,mk_rews,termless})
  1926               (trec as (shyps,hyps,t0,ders)) =
  1927        (case t0 of
  1928            Abs(a,T,t) =>
  1929              let val b = variant bounds a
  1930                  val v = Free("." ^ b,T)
  1931                  val mss' = mk_mss (rules, congs, procs, b :: bounds, prems, mk_rews, termless)
  1932              in case botc true mss' 
  1933                        (shyps,hyps,subst_bound (v,t),ders) of
  1934                   Some(shyps',hyps',t',ders') =>
  1935                     Some(shyps', hyps', Abs(a, T, abstract_over(v,t')), ders')
  1936                 | None => None
  1937              end
  1938          | t$u => (case t of
  1939              Const("==>",_)$s  => Some(impc(shyps,hyps,s,u,mss,ders))
  1940            | Abs(_,_,body) =>
  1941                let val trec = (shyps,hyps,subst_bound (u,body),ders)
  1942                in case subc mss trec of
  1943                     None => Some(trec)
  1944                   | trec => trec
  1945                end
  1946            | _  =>
  1947                let fun appc() =
  1948                      (case botc true mss (shyps,hyps,t,ders) of
  1949                         Some(shyps1,hyps1,t1,ders1) =>
  1950                           (case botc true mss (shyps1,hyps1,u,ders1) of
  1951                              Some(shyps2,hyps2,u1,ders2) =>
  1952                                Some(shyps2, hyps2, t1$u1, ders2)
  1953                            | None => Some(shyps1, hyps1, t1$u, ders1))
  1954                       | None =>
  1955                           (case botc true mss (shyps,hyps,u,ders) of
  1956                              Some(shyps1,hyps1,u1,ders1) =>
  1957                                Some(shyps1, hyps1, t$u1, ders1)
  1958                            | None => None))
  1959                    val (h,ts) = strip_comb t
  1960                in case h of
  1961                     Const(a,_) =>
  1962                       (case assoc_string(congs,a) of
  1963                          None => appc()
  1964                        | Some(cong) =>
  1965                            (congc (prover mss,sign_ref,maxidx) cong trec
  1966                             handle Pattern.MATCH => appc() ) )
  1967                   | _ => appc()
  1968                end)
  1969          | _ => None)
  1970 
  1971      and impc(shyps, hyps, s, u, mss as Mss{mk_rews,...}, ders) =
  1972        let val (shyps1,hyps1,s1,ders1) =
  1973              if simprem then try_botc mss (shyps,hyps,s,ders)
  1974                         else (shyps,hyps,s,ders);
  1975            val maxidx1 = maxidx_of_term s1
  1976            val mss1 =
  1977              if not useprem then mss else
  1978              if maxidx1 <> ~1 then (trace_term true
  1979 "Cannot add premise as rewrite rule because it contains (type) unknowns:"
  1980                                                   (Sign.deref sign_ref) s1; mss)
  1981              else let val thm = assume (Cterm{sign_ref=sign_ref, t=s1, 
  1982                                               T=propT, maxidx= ~1})
  1983                   in add_simps(add_prems(mss,[thm]), mk_rews thm) end
  1984            val (shyps2,hyps2,u1,ders2) = try_botc mss1 (shyps1,hyps1,u,ders1)
  1985            val hyps3 = if gen_mem (op aconv) (s1, hyps1)
  1986                        then hyps2 else hyps2\s1
  1987        in (shyps2, hyps3, Logic.mk_implies(s1,u1), ders2) 
  1988        end
  1989 
  1990  in try_botc end;
  1991 
  1992 
  1993 (*** Meta-rewriting: rewrites t to u and returns the theorem t==u ***)
  1994 
  1995 (*
  1996   Parameters:
  1997     mode = (simplify A, use A in simplifying B) when simplifying A ==> B
  1998     mss: contains equality theorems of the form [|p1,...|] ==> t==u
  1999     prover: how to solve premises in conditional rewrites and congruences
  2000 *)
  2001 
  2002 (* FIXME: check that #bounds(mss) does not "occur" in ct alread *)
  2003 
  2004 fun rewrite_cterm mode mss prover ct =
  2005   let val Cterm {sign_ref, t, T, maxidx} = ct;
  2006       val (shyps,hyps,u,ders) =
  2007         bottomc (mode,prover, sign_ref, maxidx) mss 
  2008                 (add_term_sorts(t,[]), [], t, []);
  2009       val prop = Logic.mk_equals(t,u)
  2010   in
  2011       Thm{sign_ref = sign_ref, 
  2012           der = infer_derivs (Rewrite_cterm ct, ders),
  2013           maxidx = maxidx,
  2014           shyps = shyps, 
  2015           hyps = hyps, 
  2016           prop = prop}
  2017   end;
  2018 
  2019 
  2020 
  2021 (*** Oracles ***)
  2022 
  2023 fun invoke_oracle thy raw_name =
  2024   let
  2025     val {sign = sg, oracles, ...} = rep_theory thy;
  2026     val name = Sign.intern sg Theory.oracleK raw_name;
  2027     val oracle =
  2028       (case Symtab.lookup (oracles, name) of
  2029         None => raise THM ("Unknown oracle: " ^ name, 0, [])
  2030       | Some (f, _) => f);
  2031   in
  2032     fn (sign, exn) =>
  2033       let
  2034         val sign_ref' = Sign.merge_refs (Sign.self_ref sg, Sign.self_ref sign);
  2035         val sign' = Sign.deref sign_ref';
  2036         val (prop, T, maxidx) = Sign.certify_term sign' (oracle (sign', exn));
  2037       in
  2038         if T <> propT then
  2039           raise THM ("Oracle's result must have type prop: " ^ name, 0, [])
  2040         else fix_shyps [] []
  2041           (Thm {sign_ref = sign_ref', 
  2042             der = Join (Oracle (name, sign, exn), []),
  2043             maxidx = maxidx,
  2044             shyps = [], 
  2045             hyps = [], 
  2046             prop = prop})
  2047       end
  2048   end;
  2049 
  2050 
  2051 end;
  2052 
  2053 open Thm;