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