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