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