src/Pure/thm.ML
author nipkow
Sun Mar 27 12:33:14 1994 +0200 (1994-03-27)
changeset 305 4c2bbb5de471
parent 288 b00ce6a1fe27
child 309 3751567696bf
permissions -rw-r--r--
Changed term ordering for permutative rewrites to be AC-compatible.
wenzelm@250
     1
(*  Title:      Pure/thm.ML
clasohm@0
     2
    ID:         $Id$
wenzelm@250
     3
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
lcp@229
     4
    Copyright   1994  University of Cambridge
lcp@229
     5
wenzelm@250
     6
The abstract types "theory" and "thm".
wenzelm@250
     7
Also "cterm" / "ctyp" (certified terms / typs under a signature).
clasohm@0
     8
clasohm@0
     9
*)
clasohm@0
    10
wenzelm@250
    11
signature THM =
wenzelm@250
    12
sig
clasohm@0
    13
  structure Envir : ENVIR
clasohm@0
    14
  structure Sequence : SEQUENCE
clasohm@0
    15
  structure Sign : SIGN
lcp@229
    16
  type cterm
lcp@229
    17
  type ctyp
clasohm@0
    18
  type meta_simpset
clasohm@0
    19
  type theory
clasohm@0
    20
  type thm
clasohm@0
    21
  exception THM of string * int * thm list
clasohm@0
    22
  exception THEORY of string * theory list
clasohm@0
    23
  exception SIMPLIFIER of string * thm
lcp@229
    24
  (*Certified terms/types; previously in sign.ML*)
lcp@229
    25
  val cterm_of: Sign.sg -> term -> cterm
lcp@229
    26
  val ctyp_of: Sign.sg -> typ -> ctyp
wenzelm@250
    27
  val read_ctyp: Sign.sg -> string -> ctyp
lcp@229
    28
  val read_cterm: Sign.sg -> string * typ -> cterm
lcp@229
    29
  val rep_cterm: cterm -> {T: typ, t: term, sign: Sign.sg, maxidx: int}
lcp@229
    30
  val rep_ctyp: ctyp -> {T: typ, sign: Sign.sg}
lcp@229
    31
  val term_of: cterm -> term
lcp@229
    32
  val typ_of: ctyp -> typ
wenzelm@250
    33
  val cterm_fun: (term -> term) -> (cterm -> cterm)
wenzelm@250
    34
  (*End of cterm/ctyp functions*)
lcp@229
    35
  val abstract_rule: string -> cterm -> thm -> thm
clasohm@0
    36
  val add_congs: meta_simpset * thm list -> meta_simpset
clasohm@0
    37
  val add_prems: meta_simpset * thm list -> meta_simpset
clasohm@0
    38
  val add_simps: meta_simpset * thm list -> meta_simpset
lcp@229
    39
  val assume: cterm -> thm
wenzelm@250
    40
  val assumption: int -> thm -> thm Sequence.seq
clasohm@0
    41
  val axioms_of: theory -> (string * thm) list
wenzelm@250
    42
  val beta_conversion: cterm -> thm
wenzelm@250
    43
  val bicompose: bool -> bool * thm * int -> int -> thm -> thm Sequence.seq
wenzelm@250
    44
  val biresolution: bool -> (bool*thm)list -> int -> thm -> thm Sequence.seq
wenzelm@250
    45
  val combination: thm -> thm -> thm
wenzelm@250
    46
  val concl_of: thm -> term
lcp@229
    47
  val cprop_of: thm -> cterm
nipkow@87
    48
  val del_simps: meta_simpset * thm list -> meta_simpset
lcp@229
    49
  val dest_cimplies: cterm -> cterm*cterm
clasohm@0
    50
  val dest_state: thm * int -> (term*term)list * term list * term * term
clasohm@0
    51
  val empty_mss: meta_simpset
wenzelm@250
    52
  val eq_assumption: int -> thm -> thm
clasohm@0
    53
  val equal_intr: thm -> thm -> thm
clasohm@0
    54
  val equal_elim: thm -> thm -> thm
clasohm@0
    55
  val extend_theory: theory -> string
wenzelm@250
    56
        -> (class * class list) list * sort
wenzelm@250
    57
           * (string list * int)list
wenzelm@250
    58
           * (string * string list * string) list
wenzelm@250
    59
           * (string list * (sort list * class))list
wenzelm@250
    60
           * (string list * string)list * Sign.Syntax.sext option
wenzelm@250
    61
        -> (string*string)list -> theory
wenzelm@250
    62
  val extensional: thm -> thm
wenzelm@250
    63
  val flexflex_rule: thm -> thm Sequence.seq
wenzelm@250
    64
  val flexpair_def: thm
lcp@229
    65
  val forall_elim: cterm -> thm -> thm
lcp@229
    66
  val forall_intr: cterm -> thm -> thm
clasohm@0
    67
  val freezeT: thm -> thm
clasohm@0
    68
  val get_axiom: theory -> string -> thm
clasohm@0
    69
  val implies_elim: thm -> thm -> thm
lcp@229
    70
  val implies_intr: cterm -> thm -> thm
clasohm@0
    71
  val implies_intr_hyps: thm -> thm
wenzelm@250
    72
  val instantiate: (indexname*ctyp)list * (cterm*cterm)list
clasohm@0
    73
                   -> thm -> thm
clasohm@0
    74
  val lift_rule: (thm * int) -> thm -> thm
clasohm@0
    75
  val merge_theories: theory * theory -> theory
clasohm@0
    76
  val mk_rews_of_mss: meta_simpset -> thm -> thm list
clasohm@0
    77
  val mss_of: thm list -> meta_simpset
clasohm@0
    78
  val nprems_of: thm -> int
clasohm@0
    79
  val parents_of: theory -> theory list
clasohm@0
    80
  val prems_of: thm -> term list
clasohm@0
    81
  val prems_of_mss: meta_simpset -> thm list
clasohm@0
    82
  val pure_thy: theory
lcp@229
    83
  val read_def_cterm :
lcp@229
    84
         Sign.sg * (indexname -> typ option) * (indexname -> sort option) ->
lcp@229
    85
         string * typ -> cterm * (indexname * typ) list
wenzelm@250
    86
   val reflexive: cterm -> thm
clasohm@0
    87
  val rename_params_rule: string list * int -> thm -> thm
clasohm@0
    88
  val rep_thm: thm -> {prop: term, hyps: term list, maxidx: int, sign: Sign.sg}
nipkow@214
    89
  val rewrite_cterm:
nipkow@214
    90
         bool*bool -> meta_simpset -> (meta_simpset -> thm -> thm option)
lcp@229
    91
           -> cterm -> thm
clasohm@0
    92
  val set_mk_rews: meta_simpset * (thm -> thm list) -> meta_simpset
wenzelm@250
    93
  val sign_of: theory -> Sign.sg
clasohm@0
    94
  val syn_of: theory -> Sign.Syntax.syntax
clasohm@0
    95
  val stamps_of_thm: thm -> string ref list
clasohm@0
    96
  val stamps_of_thy: theory -> string ref list
wenzelm@250
    97
  val symmetric: thm -> thm
clasohm@0
    98
  val tpairs_of: thm -> (term*term)list
clasohm@0
    99
  val trace_simp: bool ref
clasohm@0
   100
  val transitive: thm -> thm -> thm
lcp@229
   101
  val trivial: cterm -> thm
clasohm@0
   102
  val varifyT: thm -> thm
wenzelm@250
   103
end;
clasohm@0
   104
wenzelm@250
   105
functor ThmFun (structure Logic: LOGIC and Unify: UNIFY and Pattern: PATTERN
wenzelm@250
   106
  and Net:NET sharing type Pattern.type_sig = Unify.Sign.Type.type_sig)(*: THM *) (* FIXME debug *) =
clasohm@0
   107
struct
wenzelm@250
   108
clasohm@0
   109
structure Sequence = Unify.Sequence;
clasohm@0
   110
structure Envir = Unify.Envir;
clasohm@0
   111
structure Sign = Unify.Sign;
clasohm@0
   112
structure Type = Sign.Type;
clasohm@0
   113
structure Syntax = Sign.Syntax;
clasohm@0
   114
structure Symtab = Sign.Symtab;
clasohm@0
   115
clasohm@0
   116
wenzelm@250
   117
(** certified types **)
wenzelm@250
   118
wenzelm@250
   119
(*certified typs under a signature*)
wenzelm@250
   120
wenzelm@250
   121
datatype ctyp = Ctyp of {sign: Sign.sg, T: typ};
wenzelm@250
   122
wenzelm@250
   123
fun rep_ctyp (Ctyp args) = args;
wenzelm@250
   124
fun typ_of (Ctyp {T, ...}) = T;
wenzelm@250
   125
wenzelm@250
   126
fun ctyp_of sign T =
wenzelm@250
   127
  Ctyp {sign = sign, T = Sign.certify_typ sign T};
wenzelm@250
   128
wenzelm@250
   129
fun read_ctyp sign s =
wenzelm@250
   130
  Ctyp {sign = sign, T = Sign.read_typ (sign, K None) s};
lcp@229
   131
lcp@229
   132
lcp@229
   133
wenzelm@250
   134
(** certified terms **)
lcp@229
   135
wenzelm@250
   136
(*certified terms under a signature, with checked typ and maxidx of Vars*)
lcp@229
   137
wenzelm@250
   138
datatype cterm = Cterm of {sign: Sign.sg, t: term, T: typ, maxidx: int};
lcp@229
   139
lcp@229
   140
fun rep_cterm (Cterm args) = args;
wenzelm@250
   141
fun term_of (Cterm {t, ...}) = t;
lcp@229
   142
wenzelm@250
   143
(*create a cterm by checking a "raw" term with respect to a signature*)
wenzelm@250
   144
fun cterm_of sign tm =
wenzelm@250
   145
  let val (t, T, maxidx) = Sign.certify_term sign tm
wenzelm@250
   146
  in Cterm {sign = sign, t = t, T = T, maxidx = maxidx}
wenzelm@250
   147
  end handle TYPE (msg, _, _)
wenzelm@250
   148
    => raise TERM ("Term not in signature\n" ^ msg, [tm]);
lcp@229
   149
wenzelm@250
   150
fun cterm_fun f (Cterm {sign, t, ...}) = cterm_of sign (f t);
wenzelm@250
   151
lcp@229
   152
wenzelm@250
   153
(*dest_implies for cterms. Note T=prop below*)
wenzelm@250
   154
fun dest_cimplies (Cterm{sign, T, maxidx, t=Const("==>", _) $ A $ B}) =
lcp@229
   155
       (Cterm{sign=sign, T=T, maxidx=maxidx, t=A},
wenzelm@250
   156
        Cterm{sign=sign, T=T, maxidx=maxidx, t=B})
wenzelm@250
   157
  | dest_cimplies ct = raise TERM ("dest_cimplies", [term_of ct]);
lcp@229
   158
wenzelm@250
   159
lcp@229
   160
wenzelm@250
   161
(** read cterms **)
wenzelm@250
   162
wenzelm@250
   163
(*read term, infer types, certify term*)
wenzelm@250
   164
wenzelm@250
   165
fun read_def_cterm (sign, types, sorts) (a, T) =
wenzelm@250
   166
  let
wenzelm@250
   167
    val {tsig, const_tab, syn, ...} = Sign.rep_sg sign;
wenzelm@250
   168
    val showtyp = Sign.string_of_typ sign;
wenzelm@250
   169
    val showterm = Sign.string_of_term sign;
wenzelm@250
   170
wenzelm@250
   171
    fun termerr [] = ""
wenzelm@250
   172
      | termerr [t] = "\nInvolving this term:\n" ^ showterm t
wenzelm@250
   173
      | termerr ts = "\nInvolving these terms:\n" ^ cat_lines (map showterm ts);
wenzelm@250
   174
wenzelm@250
   175
    val T' = Sign.certify_typ sign T
wenzelm@250
   176
      handle TYPE (msg, _, _) => error msg;
wenzelm@250
   177
    val t = Syntax.read syn T' a;
wenzelm@250
   178
    val (t', tye) = Type.infer_types (tsig, const_tab, types, sorts, T', t)
wenzelm@250
   179
      handle TYPE (msg, Ts, ts) => error ("Type checking error: " ^ msg ^ "\n"
wenzelm@250
   180
        ^ cat_lines (map showtyp Ts) ^ termerr ts);
wenzelm@250
   181
    val ct = cterm_of sign t' handle TERM (msg, _) => error msg;
wenzelm@250
   182
  in (ct, tye) end;
lcp@229
   183
lcp@229
   184
fun read_cterm sign = #1 o (read_def_cterm (sign, K None, K None));
lcp@229
   185
wenzelm@250
   186
wenzelm@250
   187
lcp@229
   188
(**** META-THEOREMS ****)
lcp@229
   189
clasohm@0
   190
datatype thm = Thm of
wenzelm@250
   191
  {sign: Sign.sg, maxidx: int, hyps: term list, prop: term};
clasohm@0
   192
wenzelm@250
   193
fun rep_thm (Thm args) = args;
clasohm@0
   194
clasohm@0
   195
(*Errors involving theorems*)
clasohm@0
   196
exception THM of string * int * thm list;
clasohm@0
   197
clasohm@0
   198
(*maps object-rule to tpairs *)
clasohm@0
   199
fun tpairs_of (Thm{prop,...}) = #1 (Logic.strip_flexpairs prop);
clasohm@0
   200
clasohm@0
   201
(*maps object-rule to premises *)
clasohm@0
   202
fun prems_of (Thm{prop,...}) =
clasohm@0
   203
    Logic.strip_imp_prems (Logic.skip_flexpairs prop);
clasohm@0
   204
clasohm@0
   205
(*counts premises in a rule*)
clasohm@0
   206
fun nprems_of (Thm{prop,...}) =
clasohm@0
   207
    Logic.count_prems (Logic.skip_flexpairs prop, 0);
clasohm@0
   208
clasohm@0
   209
(*maps object-rule to conclusion *)
clasohm@0
   210
fun concl_of (Thm{prop,...}) = Logic.strip_imp_concl prop;
clasohm@0
   211
lcp@229
   212
(*The statement of any Thm is a Cterm*)
wenzelm@250
   213
fun cprop_of (Thm{sign,maxidx,hyps,prop}) =
wenzelm@250
   214
        Cterm{sign=sign, maxidx=maxidx, T=propT, t=prop};
lcp@229
   215
clasohm@0
   216
(*Stamps associated with a signature*)
clasohm@0
   217
val stamps_of_thm = #stamps o Sign.rep_sg o #sign o rep_thm;
clasohm@0
   218
clasohm@0
   219
(*Theories.  There is one pure theory.
clasohm@0
   220
  A theory can be extended.  Two theories can be merged.*)
clasohm@0
   221
datatype theory =
clasohm@0
   222
    Pure of {sign: Sign.sg}
clasohm@0
   223
  | Extend of {sign: Sign.sg,  axioms: thm Symtab.table,  thy: theory}
clasohm@0
   224
  | Merge of {sign: Sign.sg,  thy1: theory,  thy2: theory};
clasohm@0
   225
clasohm@0
   226
(*Errors involving theories*)
clasohm@0
   227
exception THEORY of string * theory list;
clasohm@0
   228
clasohm@0
   229
fun sign_of (Pure {sign}) = sign
clasohm@0
   230
  | sign_of (Extend {sign,...}) = sign
clasohm@0
   231
  | sign_of (Merge {sign,...}) = sign;
clasohm@0
   232
clasohm@0
   233
val syn_of = #syn o Sign.rep_sg o sign_of;
clasohm@0
   234
clasohm@0
   235
(*return the axioms of a theory and its ancestors*)
clasohm@0
   236
fun axioms_of (Pure _) = []
wenzelm@250
   237
  | axioms_of (Extend {axioms, thy, ...}) =
wenzelm@250
   238
      axioms_of thy @ Symtab.alist_of axioms
wenzelm@250
   239
  | axioms_of (Merge {thy1, thy2, ...}) = axioms_of thy1 @ axioms_of thy2;
clasohm@0
   240
clasohm@0
   241
(*return the immediate ancestors -- also distinguishes the kinds of theories*)
clasohm@0
   242
fun parents_of (Pure _) = []
clasohm@0
   243
  | parents_of (Extend{thy,...}) = [thy]
clasohm@0
   244
  | parents_of (Merge{thy1,thy2,...}) = [thy1,thy2];
clasohm@0
   245
clasohm@0
   246
clasohm@0
   247
(*Merge theories of two theorems.  Raise exception if incompatible.
clasohm@0
   248
  Prefers (via Sign.merge) the signature of th1.  *)
clasohm@0
   249
fun merge_theories(th1,th2) =
clasohm@0
   250
  let val Thm{sign=sign1,...} = th1 and Thm{sign=sign2,...} = th2
clasohm@0
   251
  in  Sign.merge (sign1,sign2)  end
clasohm@0
   252
  handle TERM _ => raise THM("incompatible signatures", 0, [th1,th2]);
clasohm@0
   253
clasohm@0
   254
(*Stamps associated with a theory*)
clasohm@0
   255
val stamps_of_thy = #stamps o Sign.rep_sg o sign_of;
clasohm@0
   256
clasohm@0
   257
clasohm@0
   258
(**** Primitive rules ****)
clasohm@0
   259
clasohm@0
   260
(* discharge all assumptions t from ts *)
clasohm@0
   261
val disch = gen_rem (op aconv);
clasohm@0
   262
clasohm@0
   263
(*The assumption rule A|-A in a theory  *)
wenzelm@250
   264
fun assume ct : thm =
lcp@229
   265
  let val {sign, t=prop, T, maxidx} = rep_cterm ct
wenzelm@250
   266
  in  if T<>propT then
wenzelm@250
   267
        raise THM("assume: assumptions must have type prop", 0, [])
clasohm@0
   268
      else if maxidx <> ~1 then
wenzelm@250
   269
        raise THM("assume: assumptions may not contain scheme variables",
wenzelm@250
   270
                  maxidx, [])
clasohm@0
   271
      else Thm{sign = sign, maxidx = ~1, hyps = [prop], prop = prop}
clasohm@0
   272
  end;
clasohm@0
   273
wenzelm@250
   274
(* Implication introduction
wenzelm@250
   275
              A |- B
wenzelm@250
   276
              -------
wenzelm@250
   277
              A ==> B    *)
clasohm@0
   278
fun implies_intr cA (thB as Thm{sign,maxidx,hyps,prop}) : thm =
lcp@229
   279
  let val {sign=signA, t=A, T, maxidx=maxidxA} = rep_cterm cA
clasohm@0
   280
  in  if T<>propT then
wenzelm@250
   281
        raise THM("implies_intr: assumptions must have type prop", 0, [thB])
wenzelm@250
   282
      else Thm{sign= Sign.merge (sign,signA),  maxidx= max[maxidxA, maxidx],
wenzelm@250
   283
             hyps= disch(hyps,A),  prop= implies$A$prop}
clasohm@0
   284
      handle TERM _ =>
clasohm@0
   285
        raise THM("implies_intr: incompatible signatures", 0, [thB])
clasohm@0
   286
  end;
clasohm@0
   287
clasohm@0
   288
(* Implication elimination
wenzelm@250
   289
        A ==> B       A
wenzelm@250
   290
        ---------------
wenzelm@250
   291
                B      *)
clasohm@0
   292
fun implies_elim thAB thA : thm =
clasohm@0
   293
    let val Thm{maxidx=maxA, hyps=hypsA, prop=propA,...} = thA
wenzelm@250
   294
        and Thm{sign, maxidx, hyps, prop,...} = thAB;
wenzelm@250
   295
        fun err(a) = raise THM("implies_elim: "^a, 0, [thAB,thA])
clasohm@0
   296
    in  case prop of
wenzelm@250
   297
            imp$A$B =>
wenzelm@250
   298
                if imp=implies andalso  A aconv propA
wenzelm@250
   299
                then  Thm{sign= merge_theories(thAB,thA),
wenzelm@250
   300
                          maxidx= max[maxA,maxidx],
wenzelm@250
   301
                          hyps= hypsA union hyps,  (*dups suppressed*)
wenzelm@250
   302
                          prop= B}
wenzelm@250
   303
                else err("major premise")
wenzelm@250
   304
          | _ => err("major premise")
clasohm@0
   305
    end;
wenzelm@250
   306
clasohm@0
   307
(* Forall introduction.  The Free or Var x must not be free in the hypotheses.
clasohm@0
   308
     A
clasohm@0
   309
   ------
clasohm@0
   310
   !!x.A       *)
clasohm@0
   311
fun forall_intr cx (th as Thm{sign,maxidx,hyps,prop}) =
lcp@229
   312
  let val x = term_of cx;
clasohm@0
   313
      fun result(a,T) = Thm{sign= sign, maxidx= maxidx, hyps= hyps,
wenzelm@250
   314
                            prop= all(T) $ Abs(a, T, abstract_over (x,prop))}
clasohm@0
   315
  in  case x of
wenzelm@250
   316
        Free(a,T) =>
wenzelm@250
   317
          if exists (apl(x, Logic.occs)) hyps
wenzelm@250
   318
          then  raise THM("forall_intr: variable free in assumptions", 0, [th])
wenzelm@250
   319
          else  result(a,T)
clasohm@0
   320
      | Var((a,_),T) => result(a,T)
clasohm@0
   321
      | _ => raise THM("forall_intr: not a variable", 0, [th])
clasohm@0
   322
  end;
clasohm@0
   323
clasohm@0
   324
(* Forall elimination
wenzelm@250
   325
              !!x.A
wenzelm@250
   326
             --------
wenzelm@250
   327
              A[t/x]     *)
clasohm@0
   328
fun forall_elim ct (th as Thm{sign,maxidx,hyps,prop}) : thm =
lcp@229
   329
  let val {sign=signt, t, T, maxidx=maxt} = rep_cterm ct
clasohm@0
   330
  in  case prop of
wenzelm@250
   331
          Const("all",Type("fun",[Type("fun",[qary,_]),_])) $ A =>
wenzelm@250
   332
            if T<>qary then
wenzelm@250
   333
                raise THM("forall_elim: type mismatch", 0, [th])
wenzelm@250
   334
            else Thm{sign= Sign.merge(sign,signt),
wenzelm@250
   335
                     maxidx= max[maxidx, maxt],
wenzelm@250
   336
                     hyps= hyps,  prop= betapply(A,t)}
wenzelm@250
   337
        | _ => raise THM("forall_elim: not quantified", 0, [th])
clasohm@0
   338
  end
clasohm@0
   339
  handle TERM _ =>
wenzelm@250
   340
         raise THM("forall_elim: incompatible signatures", 0, [th]);
clasohm@0
   341
clasohm@0
   342
clasohm@0
   343
(*** Equality ***)
clasohm@0
   344
clasohm@0
   345
(*Definition of the relation =?= *)
clasohm@0
   346
val flexpair_def =
wenzelm@250
   347
  Thm{sign= Sign.pure, hyps= [], maxidx= 0,
wenzelm@250
   348
      prop= term_of
wenzelm@250
   349
              (read_cterm Sign.pure
wenzelm@250
   350
                 ("(?t =?= ?u) == (?t == ?u::?'a::{})", propT))};
clasohm@0
   351
clasohm@0
   352
(*The reflexivity rule: maps  t   to the theorem   t==t   *)
wenzelm@250
   353
fun reflexive ct =
lcp@229
   354
  let val {sign, t, T, maxidx} = rep_cterm ct
clasohm@0
   355
  in  Thm{sign= sign, hyps= [], maxidx= maxidx, prop= Logic.mk_equals(t,t)}
clasohm@0
   356
  end;
clasohm@0
   357
clasohm@0
   358
(*The symmetry rule
clasohm@0
   359
    t==u
clasohm@0
   360
    ----
clasohm@0
   361
    u==t         *)
clasohm@0
   362
fun symmetric (th as Thm{sign,hyps,prop,maxidx}) =
clasohm@0
   363
  case prop of
clasohm@0
   364
      (eq as Const("==",_)) $ t $ u =>
wenzelm@250
   365
          Thm{sign=sign, hyps=hyps, maxidx=maxidx, prop= eq$u$t}
clasohm@0
   366
    | _ => raise THM("symmetric", 0, [th]);
clasohm@0
   367
clasohm@0
   368
(*The transitive rule
clasohm@0
   369
    t1==u    u==t2
clasohm@0
   370
    ------------
clasohm@0
   371
        t1==t2      *)
clasohm@0
   372
fun transitive th1 th2 =
clasohm@0
   373
  let val Thm{maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
clasohm@0
   374
      and Thm{maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
clasohm@0
   375
      fun err(msg) = raise THM("transitive: "^msg, 0, [th1,th2])
clasohm@0
   376
  in case (prop1,prop2) of
clasohm@0
   377
       ((eq as Const("==",_)) $ t1 $ u, Const("==",_) $ u' $ t2) =>
wenzelm@250
   378
          if not (u aconv u') then err"middle term"  else
wenzelm@250
   379
              Thm{sign= merge_theories(th1,th2), hyps= hyps1 union hyps2,
wenzelm@250
   380
                  maxidx= max[max1,max2], prop= eq$t1$t2}
clasohm@0
   381
     | _ =>  err"premises"
clasohm@0
   382
  end;
clasohm@0
   383
clasohm@0
   384
(*Beta-conversion: maps (%(x)t)(u) to the theorem  (%(x)t)(u) == t[u/x]   *)
wenzelm@250
   385
fun beta_conversion ct =
lcp@229
   386
  let val {sign, t, T, maxidx} = rep_cterm ct
clasohm@0
   387
  in  case t of
wenzelm@250
   388
          Abs(_,_,bodt) $ u =>
wenzelm@250
   389
            Thm{sign= sign,  hyps= [],
wenzelm@250
   390
                maxidx= maxidx_of_term t,
wenzelm@250
   391
                prop= Logic.mk_equals(t, subst_bounds([u],bodt))}
wenzelm@250
   392
        | _ =>  raise THM("beta_conversion: not a redex", 0, [])
clasohm@0
   393
  end;
clasohm@0
   394
clasohm@0
   395
(*The extensionality rule   (proviso: x not free in f, g, or hypotheses)
clasohm@0
   396
    f(x) == g(x)
clasohm@0
   397
    ------------
clasohm@0
   398
       f == g    *)
clasohm@0
   399
fun extensional (th as Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   400
  case prop of
clasohm@0
   401
    (Const("==",_)) $ (f$x) $ (g$y) =>
wenzelm@250
   402
      let fun err(msg) = raise THM("extensional: "^msg, 0, [th])
clasohm@0
   403
      in (if x<>y then err"different variables" else
clasohm@0
   404
          case y of
wenzelm@250
   405
                Free _ =>
wenzelm@250
   406
                  if exists (apl(y, Logic.occs)) (f::g::hyps)
wenzelm@250
   407
                  then err"variable free in hyps or functions"    else  ()
wenzelm@250
   408
              | Var _ =>
wenzelm@250
   409
                  if Logic.occs(y,f)  orelse  Logic.occs(y,g)
wenzelm@250
   410
                  then err"variable free in functions"   else  ()
wenzelm@250
   411
              | _ => err"not a variable");
wenzelm@250
   412
          Thm{sign=sign, hyps=hyps, maxidx=maxidx,
wenzelm@250
   413
              prop= Logic.mk_equals(f,g)}
clasohm@0
   414
      end
clasohm@0
   415
 | _ =>  raise THM("extensional: premise", 0, [th]);
clasohm@0
   416
clasohm@0
   417
(*The abstraction rule.  The Free or Var x must not be free in the hypotheses.
clasohm@0
   418
  The bound variable will be named "a" (since x will be something like x320)
clasohm@0
   419
          t == u
clasohm@0
   420
    ----------------
clasohm@0
   421
      %(x)t == %(x)u     *)
clasohm@0
   422
fun abstract_rule a cx (th as Thm{sign,maxidx,hyps,prop}) =
lcp@229
   423
  let val x = term_of cx;
wenzelm@250
   424
      val (t,u) = Logic.dest_equals prop
wenzelm@250
   425
            handle TERM _ =>
wenzelm@250
   426
                raise THM("abstract_rule: premise not an equality", 0, [th])
clasohm@0
   427
      fun result T =
clasohm@0
   428
            Thm{sign= sign, maxidx= maxidx, hyps= hyps,
wenzelm@250
   429
                prop= Logic.mk_equals(Abs(a, T, abstract_over (x,t)),
wenzelm@250
   430
                                      Abs(a, T, abstract_over (x,u)))}
clasohm@0
   431
  in  case x of
wenzelm@250
   432
        Free(_,T) =>
wenzelm@250
   433
         if exists (apl(x, Logic.occs)) hyps
wenzelm@250
   434
         then raise THM("abstract_rule: variable free in assumptions", 0, [th])
wenzelm@250
   435
         else result T
clasohm@0
   436
      | Var(_,T) => result T
clasohm@0
   437
      | _ => raise THM("abstract_rule: not a variable", 0, [th])
clasohm@0
   438
  end;
clasohm@0
   439
clasohm@0
   440
(*The combination rule
clasohm@0
   441
    f==g    t==u
clasohm@0
   442
    ------------
clasohm@0
   443
     f(t)==g(u)      *)
clasohm@0
   444
fun combination th1 th2 =
clasohm@0
   445
  let val Thm{maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
clasohm@0
   446
      and Thm{maxidx=max2, hyps=hyps2, prop=prop2,...} = th2
clasohm@0
   447
  in  case (prop1,prop2)  of
clasohm@0
   448
       (Const("==",_) $ f $ g, Const("==",_) $ t $ u) =>
wenzelm@250
   449
              Thm{sign= merge_theories(th1,th2), hyps= hyps1 union hyps2,
wenzelm@250
   450
                  maxidx= max[max1,max2], prop= Logic.mk_equals(f$t, g$u)}
clasohm@0
   451
     | _ =>  raise THM("combination: premises", 0, [th1,th2])
clasohm@0
   452
  end;
clasohm@0
   453
clasohm@0
   454
clasohm@0
   455
(*The equal propositions rule
clasohm@0
   456
    A==B    A
clasohm@0
   457
    ---------
clasohm@0
   458
        B          *)
clasohm@0
   459
fun equal_elim th1 th2 =
clasohm@0
   460
  let val Thm{maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
clasohm@0
   461
      and Thm{maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
clasohm@0
   462
      fun err(msg) = raise THM("equal_elim: "^msg, 0, [th1,th2])
clasohm@0
   463
  in  case prop1  of
clasohm@0
   464
       Const("==",_) $ A $ B =>
wenzelm@250
   465
          if not (prop2 aconv A) then err"not equal"  else
wenzelm@250
   466
              Thm{sign= merge_theories(th1,th2), hyps= hyps1 union hyps2,
wenzelm@250
   467
                  maxidx= max[max1,max2], prop= B}
clasohm@0
   468
     | _ =>  err"major premise"
clasohm@0
   469
  end;
clasohm@0
   470
clasohm@0
   471
clasohm@0
   472
(* Equality introduction
clasohm@0
   473
    A==>B    B==>A
clasohm@0
   474
    -------------
clasohm@0
   475
         A==B            *)
clasohm@0
   476
fun equal_intr th1 th2 =
clasohm@0
   477
let val Thm{maxidx=max1, hyps=hyps1, prop=prop1,...} = th1
clasohm@0
   478
    and Thm{maxidx=max2, hyps=hyps2, prop=prop2,...} = th2;
clasohm@0
   479
    fun err(msg) = raise THM("equal_intr: "^msg, 0, [th1,th2])
clasohm@0
   480
in case (prop1,prop2) of
clasohm@0
   481
     (Const("==>",_) $ A $ B, Const("==>",_) $ B' $ A')  =>
wenzelm@250
   482
        if A aconv A' andalso B aconv B'
wenzelm@250
   483
        then Thm{sign= merge_theories(th1,th2), hyps= hyps1 union hyps2,
wenzelm@250
   484
                 maxidx= max[max1,max2], prop= Logic.mk_equals(A,B)}
wenzelm@250
   485
        else err"not equal"
clasohm@0
   486
   | _ =>  err"premises"
clasohm@0
   487
end;
clasohm@0
   488
clasohm@0
   489
(**** Derived rules ****)
clasohm@0
   490
clasohm@0
   491
(*Discharge all hypotheses (need not verify cterms)
clasohm@0
   492
  Repeated hypotheses are discharged only once;  fold cannot do this*)
clasohm@0
   493
fun implies_intr_hyps (Thm{sign, maxidx, hyps=A::As, prop}) =
clasohm@0
   494
      implies_intr_hyps
wenzelm@250
   495
            (Thm{sign=sign,  maxidx=maxidx,
wenzelm@250
   496
                 hyps= disch(As,A),  prop= implies$A$prop})
clasohm@0
   497
  | implies_intr_hyps th = th;
clasohm@0
   498
clasohm@0
   499
(*Smash" unifies the list of term pairs leaving no flex-flex pairs.
wenzelm@250
   500
  Instantiates the theorem and deletes trivial tpairs.
clasohm@0
   501
  Resulting sequence may contain multiple elements if the tpairs are
clasohm@0
   502
    not all flex-flex. *)
clasohm@0
   503
fun flexflex_rule (Thm{sign,maxidx,hyps,prop}) =
wenzelm@250
   504
  let fun newthm env =
wenzelm@250
   505
          let val (tpairs,horn) =
wenzelm@250
   506
                        Logic.strip_flexpairs (Envir.norm_term env prop)
wenzelm@250
   507
                (*Remove trivial tpairs, of the form t=t*)
wenzelm@250
   508
              val distpairs = filter (not o op aconv) tpairs
wenzelm@250
   509
              val newprop = Logic.list_flexpairs(distpairs, horn)
wenzelm@250
   510
          in  Thm{sign= sign, hyps= hyps,
wenzelm@250
   511
                  maxidx= maxidx_of_term newprop, prop= newprop}
wenzelm@250
   512
          end;
clasohm@0
   513
      val (tpairs,_) = Logic.strip_flexpairs prop
clasohm@0
   514
  in Sequence.maps newthm
wenzelm@250
   515
            (Unify.smash_unifiers(sign, Envir.empty maxidx, tpairs))
clasohm@0
   516
  end;
clasohm@0
   517
clasohm@0
   518
(*Instantiation of Vars
wenzelm@250
   519
                      A
wenzelm@250
   520
             --------------------
wenzelm@250
   521
              A[t1/v1,....,tn/vn]     *)
clasohm@0
   522
clasohm@0
   523
(*Check that all the terms are Vars and are distinct*)
clasohm@0
   524
fun instl_ok ts = forall is_Var ts andalso null(findrep ts);
clasohm@0
   525
clasohm@0
   526
(*For instantiate: process pair of cterms, merge theories*)
clasohm@0
   527
fun add_ctpair ((ct,cu), (sign,tpairs)) =
lcp@229
   528
  let val {sign=signt, t=t, T= T, ...} = rep_cterm ct
lcp@229
   529
      and {sign=signu, t=u, T= U, ...} = rep_cterm cu
clasohm@0
   530
  in  if T=U  then (Sign.merge(sign, Sign.merge(signt, signu)), (t,u)::tpairs)
clasohm@0
   531
      else raise TYPE("add_ctpair", [T,U], [t,u])
clasohm@0
   532
  end;
clasohm@0
   533
clasohm@0
   534
fun add_ctyp ((v,ctyp), (sign',vTs)) =
lcp@229
   535
  let val {T,sign} = rep_ctyp ctyp
clasohm@0
   536
  in (Sign.merge(sign,sign'), (v,T)::vTs) end;
clasohm@0
   537
clasohm@0
   538
(*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
clasohm@0
   539
  Instantiates distinct Vars by terms of same type.
clasohm@0
   540
  Normalizes the new theorem! *)
wenzelm@250
   541
fun instantiate (vcTs,ctpairs)  (th as Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   542
  let val (newsign,tpairs) = foldr add_ctpair (ctpairs, (sign,[]));
clasohm@0
   543
      val (newsign,vTs) = foldr add_ctyp (vcTs, (newsign,[]));
wenzelm@250
   544
      val newprop =
wenzelm@250
   545
            Envir.norm_term (Envir.empty 0)
wenzelm@250
   546
              (subst_atomic tpairs
wenzelm@250
   547
               (Type.inst_term_tvars(#tsig(Sign.rep_sg newsign),vTs) prop))
clasohm@0
   548
      val newth = Thm{sign= newsign, hyps= hyps,
wenzelm@250
   549
                      maxidx= maxidx_of_term newprop, prop= newprop}
wenzelm@250
   550
  in  if not(instl_ok(map #1 tpairs))
nipkow@193
   551
      then raise THM("instantiate: variables not distinct", 0, [th])
nipkow@193
   552
      else if not(null(findrep(map #1 vTs)))
nipkow@193
   553
      then raise THM("instantiate: type variables not distinct", 0, [th])
nipkow@193
   554
      else (*Check types of Vars for agreement*)
nipkow@193
   555
      case findrep (map (#1 o dest_Var) (term_vars newprop)) of
wenzelm@250
   556
          ix::_ => raise THM("instantiate: conflicting types for variable " ^
wenzelm@250
   557
                             Syntax.string_of_vname ix ^ "\n", 0, [newth])
wenzelm@250
   558
        | [] =>
wenzelm@250
   559
             case findrep (map #1 (term_tvars newprop)) of
wenzelm@250
   560
             ix::_ => raise THM
wenzelm@250
   561
                    ("instantiate: conflicting sorts for type variable " ^
wenzelm@250
   562
                     Syntax.string_of_vname ix ^ "\n", 0, [newth])
nipkow@193
   563
        | [] => newth
clasohm@0
   564
  end
wenzelm@250
   565
  handle TERM _ =>
clasohm@0
   566
           raise THM("instantiate: incompatible signatures",0,[th])
nipkow@193
   567
       | TYPE _ => raise THM("instantiate: type conflict", 0, [th]);
clasohm@0
   568
clasohm@0
   569
(*The trivial implication A==>A, justified by assume and forall rules.
clasohm@0
   570
  A can contain Vars, not so for assume!   *)
wenzelm@250
   571
fun trivial ct : thm =
lcp@229
   572
  let val {sign, t=A, T, maxidx} = rep_cterm ct
wenzelm@250
   573
  in  if T<>propT then
wenzelm@250
   574
            raise THM("trivial: the term must have type prop", 0, [])
clasohm@0
   575
      else Thm{sign= sign, maxidx= maxidx, hyps= [], prop= implies$A$A}
clasohm@0
   576
  end;
clasohm@0
   577
clasohm@0
   578
(* Replace all TFrees not in the hyps by new TVars *)
clasohm@0
   579
fun varifyT(Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   580
  let val tfrees = foldr add_term_tfree_names (hyps,[])
clasohm@0
   581
  in Thm{sign=sign, maxidx=max[0,maxidx], hyps=hyps,
wenzelm@250
   582
         prop= Type.varify(prop,tfrees)}
clasohm@0
   583
  end;
clasohm@0
   584
clasohm@0
   585
(* Replace all TVars by new TFrees *)
clasohm@0
   586
fun freezeT(Thm{sign,maxidx,hyps,prop}) =
clasohm@0
   587
  let val prop' = Type.freeze (K true) prop
clasohm@0
   588
  in Thm{sign=sign, maxidx=maxidx_of_term prop', hyps=hyps, prop=prop'} end;
clasohm@0
   589
clasohm@0
   590
clasohm@0
   591
(*** Inference rules for tactics ***)
clasohm@0
   592
clasohm@0
   593
(*Destruct proof state into constraints, other goals, goal(i), rest *)
clasohm@0
   594
fun dest_state (state as Thm{prop,...}, i) =
clasohm@0
   595
  let val (tpairs,horn) = Logic.strip_flexpairs prop
clasohm@0
   596
  in  case  Logic.strip_prems(i, [], horn) of
clasohm@0
   597
          (B::rBs, C) => (tpairs, rev rBs, B, C)
clasohm@0
   598
        | _ => raise THM("dest_state", i, [state])
clasohm@0
   599
  end
clasohm@0
   600
  handle TERM _ => raise THM("dest_state", i, [state]);
clasohm@0
   601
clasohm@0
   602
(*Increment variables and parameters of rule as required for
clasohm@0
   603
  resolution with goal i of state. *)
clasohm@0
   604
fun lift_rule (state, i) orule =
clasohm@0
   605
  let val Thm{prop=sprop,maxidx=smax,...} = state;
clasohm@0
   606
      val (Bi::_, _) = Logic.strip_prems(i, [], Logic.skip_flexpairs sprop)
wenzelm@250
   607
        handle TERM _ => raise THM("lift_rule", i, [orule,state]);
clasohm@0
   608
      val (lift_abs,lift_all) = Logic.lift_fns(Bi,smax+1);
clasohm@0
   609
      val (Thm{sign,maxidx,hyps,prop}) = orule
clasohm@0
   610
      val (tpairs,As,B) = Logic.strip_horn prop
clasohm@0
   611
  in  Thm{hyps=hyps, sign= merge_theories(state,orule),
wenzelm@250
   612
          maxidx= maxidx+smax+1,
wenzelm@250
   613
          prop= Logic.rule_of(map (pairself lift_abs) tpairs,
wenzelm@250
   614
                              map lift_all As,    lift_all B)}
clasohm@0
   615
  end;
clasohm@0
   616
clasohm@0
   617
(*Solve subgoal Bi of proof state B1...Bn/C by assumption. *)
clasohm@0
   618
fun assumption i state =
clasohm@0
   619
  let val Thm{sign,maxidx,hyps,prop} = state;
clasohm@0
   620
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
wenzelm@250
   621
      fun newth (env as Envir.Envir{maxidx, ...}, tpairs) =
wenzelm@250
   622
          Thm{sign=sign, hyps=hyps, maxidx=maxidx, prop=
wenzelm@250
   623
            if Envir.is_empty env then (*avoid wasted normalizations*)
wenzelm@250
   624
              Logic.rule_of (tpairs, Bs, C)
wenzelm@250
   625
            else (*normalize the new rule fully*)
wenzelm@250
   626
              Envir.norm_term env (Logic.rule_of (tpairs, Bs, C))};
clasohm@0
   627
      fun addprfs [] = Sequence.null
clasohm@0
   628
        | addprfs ((t,u)::apairs) = Sequence.seqof (fn()=> Sequence.pull
clasohm@0
   629
             (Sequence.mapp newth
wenzelm@250
   630
                (Unify.unifiers(sign,Envir.empty maxidx, (t,u)::tpairs))
wenzelm@250
   631
                (addprfs apairs)))
clasohm@0
   632
  in  addprfs (Logic.assum_pairs Bi)  end;
clasohm@0
   633
wenzelm@250
   634
(*Solve subgoal Bi of proof state B1...Bn/C by assumption.
clasohm@0
   635
  Checks if Bi's conclusion is alpha-convertible to one of its assumptions*)
clasohm@0
   636
fun eq_assumption i state =
clasohm@0
   637
  let val Thm{sign,maxidx,hyps,prop} = state;
clasohm@0
   638
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
   639
  in  if exists (op aconv) (Logic.assum_pairs Bi)
wenzelm@250
   640
      then Thm{sign=sign, hyps=hyps, maxidx=maxidx,
wenzelm@250
   641
               prop=Logic.rule_of(tpairs, Bs, C)}
clasohm@0
   642
      else  raise THM("eq_assumption", 0, [state])
clasohm@0
   643
  end;
clasohm@0
   644
clasohm@0
   645
clasohm@0
   646
(** User renaming of parameters in a subgoal **)
clasohm@0
   647
clasohm@0
   648
(*Calls error rather than raising an exception because it is intended
clasohm@0
   649
  for top-level use -- exception handling would not make sense here.
clasohm@0
   650
  The names in cs, if distinct, are used for the innermost parameters;
clasohm@0
   651
   preceding parameters may be renamed to make all params distinct.*)
clasohm@0
   652
fun rename_params_rule (cs, i) state =
clasohm@0
   653
  let val Thm{sign,maxidx,hyps,prop} = state
clasohm@0
   654
      val (tpairs, Bs, Bi, C) = dest_state(state,i)
clasohm@0
   655
      val iparams = map #1 (Logic.strip_params Bi)
clasohm@0
   656
      val short = length iparams - length cs
wenzelm@250
   657
      val newnames =
wenzelm@250
   658
            if short<0 then error"More names than abstractions!"
wenzelm@250
   659
            else variantlist(take (short,iparams), cs) @ cs
clasohm@0
   660
      val freenames = map (#1 o dest_Free) (term_frees prop)
clasohm@0
   661
      val newBi = Logic.list_rename_params (newnames, Bi)
wenzelm@250
   662
  in
clasohm@0
   663
  case findrep cs of
clasohm@0
   664
     c::_ => error ("Bound variables not distinct: " ^ c)
clasohm@0
   665
   | [] => (case cs inter freenames of
clasohm@0
   666
       a::_ => error ("Bound/Free variable clash: " ^ a)
clasohm@0
   667
     | [] => Thm{sign=sign, hyps=hyps, maxidx=maxidx, prop=
wenzelm@250
   668
                    Logic.rule_of(tpairs, Bs@[newBi], C)})
clasohm@0
   669
  end;
clasohm@0
   670
clasohm@0
   671
(*** Preservation of bound variable names ***)
clasohm@0
   672
wenzelm@250
   673
(*Scan a pair of terms; while they are similar,
clasohm@0
   674
  accumulate corresponding bound vars in "al"*)
clasohm@0
   675
fun match_bvs(Abs(x,_,s),Abs(y,_,t), al) = match_bvs(s,t,(x,y)::al)
clasohm@0
   676
  | match_bvs(f$s, g$t, al) = match_bvs(f,g,match_bvs(s,t,al))
clasohm@0
   677
  | match_bvs(_,_,al) = al;
clasohm@0
   678
clasohm@0
   679
(* strip abstractions created by parameters *)
clasohm@0
   680
fun match_bvars((s,t),al) = match_bvs(strip_abs_body s, strip_abs_body t, al);
clasohm@0
   681
clasohm@0
   682
wenzelm@250
   683
(* strip_apply f A(,B) strips off all assumptions/parameters from A
clasohm@0
   684
   introduced by lifting over B, and applies f to remaining part of A*)
clasohm@0
   685
fun strip_apply f =
clasohm@0
   686
  let fun strip(Const("==>",_)$ A1 $ B1,
wenzelm@250
   687
                Const("==>",_)$ _  $ B2) = implies $ A1 $ strip(B1,B2)
wenzelm@250
   688
        | strip((c as Const("all",_)) $ Abs(a,T,t1),
wenzelm@250
   689
                      Const("all",_)  $ Abs(_,_,t2)) = c$Abs(a,T,strip(t1,t2))
wenzelm@250
   690
        | strip(A,_) = f A
clasohm@0
   691
  in strip end;
clasohm@0
   692
clasohm@0
   693
(*Use the alist to rename all bound variables and some unknowns in a term
clasohm@0
   694
  dpairs = current disagreement pairs;  tpairs = permanent ones (flexflex);
clasohm@0
   695
  Preserves unknowns in tpairs and on lhs of dpairs. *)
clasohm@0
   696
fun rename_bvs([],_,_,_) = I
clasohm@0
   697
  | rename_bvs(al,dpairs,tpairs,B) =
wenzelm@250
   698
    let val vars = foldr add_term_vars
wenzelm@250
   699
                        (map fst dpairs @ map fst tpairs @ map snd tpairs, [])
wenzelm@250
   700
        (*unknowns appearing elsewhere be preserved!*)
wenzelm@250
   701
        val vids = map (#1 o #1 o dest_Var) vars;
wenzelm@250
   702
        fun rename(t as Var((x,i),T)) =
wenzelm@250
   703
                (case assoc(al,x) of
wenzelm@250
   704
                   Some(y) => if x mem vids orelse y mem vids then t
wenzelm@250
   705
                              else Var((y,i),T)
wenzelm@250
   706
                 | None=> t)
clasohm@0
   707
          | rename(Abs(x,T,t)) =
wenzelm@250
   708
              Abs(case assoc(al,x) of Some(y) => y | None => x,
wenzelm@250
   709
                  T, rename t)
clasohm@0
   710
          | rename(f$t) = rename f $ rename t
clasohm@0
   711
          | rename(t) = t;
wenzelm@250
   712
        fun strip_ren Ai = strip_apply rename (Ai,B)
clasohm@0
   713
    in strip_ren end;
clasohm@0
   714
clasohm@0
   715
(*Function to rename bounds/unknowns in the argument, lifted over B*)
clasohm@0
   716
fun rename_bvars(dpairs, tpairs, B) =
wenzelm@250
   717
        rename_bvs(foldr match_bvars (dpairs,[]), dpairs, tpairs, B);
clasohm@0
   718
clasohm@0
   719
clasohm@0
   720
(*** RESOLUTION ***)
clasohm@0
   721
clasohm@0
   722
(*strip off pairs of assumptions/parameters in parallel -- they are
clasohm@0
   723
  identical because of lifting*)
wenzelm@250
   724
fun strip_assums2 (Const("==>", _) $ _ $ B1,
wenzelm@250
   725
                   Const("==>", _) $ _ $ B2) = strip_assums2 (B1,B2)
clasohm@0
   726
  | strip_assums2 (Const("all",_)$Abs(a,T,t1),
wenzelm@250
   727
                   Const("all",_)$Abs(_,_,t2)) =
clasohm@0
   728
      let val (B1,B2) = strip_assums2 (t1,t2)
clasohm@0
   729
      in  (Abs(a,T,B1), Abs(a,T,B2))  end
clasohm@0
   730
  | strip_assums2 BB = BB;
clasohm@0
   731
clasohm@0
   732
clasohm@0
   733
(*Composition of object rule r=(A1...Am/B) with proof state s=(B1...Bn/C)
wenzelm@250
   734
  Unifies B with Bi, replacing subgoal i    (1 <= i <= n)
clasohm@0
   735
  If match then forbid instantiations in proof state
clasohm@0
   736
  If lifted then shorten the dpair using strip_assums2.
clasohm@0
   737
  If eres_flg then simultaneously proves A1 by assumption.
wenzelm@250
   738
  nsubgoal is the number of new subgoals (written m above).
clasohm@0
   739
  Curried so that resolution calls dest_state only once.
clasohm@0
   740
*)
clasohm@0
   741
local open Sequence; exception Bicompose
clasohm@0
   742
in
wenzelm@250
   743
fun bicompose_aux match (state, (stpairs, Bs, Bi, C), lifted)
clasohm@0
   744
                        (eres_flg, orule, nsubgoal) =
clasohm@0
   745
 let val Thm{maxidx=smax, hyps=shyps, ...} = state
clasohm@0
   746
     and Thm{maxidx=rmax, hyps=rhyps, prop=rprop,...} = orule;
clasohm@0
   747
     val sign = merge_theories(state,orule);
clasohm@0
   748
     (** Add new theorem with prop = '[| Bs; As |] ==> C' to thq **)
wenzelm@250
   749
     fun addth As ((env as Envir.Envir {maxidx, ...}, tpairs), thq) =
wenzelm@250
   750
       let val normt = Envir.norm_term env;
wenzelm@250
   751
           (*perform minimal copying here by examining env*)
wenzelm@250
   752
           val normp =
wenzelm@250
   753
             if Envir.is_empty env then (tpairs, Bs @ As, C)
wenzelm@250
   754
             else
wenzelm@250
   755
             let val ntps = map (pairself normt) tpairs
wenzelm@250
   756
             in if the (Envir.minidx env) > smax then (*no assignments in state*)
wenzelm@250
   757
                  (ntps, Bs @ map normt As, C)
wenzelm@250
   758
                else if match then raise Bicompose
wenzelm@250
   759
                else (*normalize the new rule fully*)
wenzelm@250
   760
                  (ntps, map normt (Bs @ As), normt C)
wenzelm@250
   761
             end
wenzelm@250
   762
           val th = Thm{sign=sign, hyps=rhyps union shyps, maxidx=maxidx,
wenzelm@250
   763
                        prop= Logic.rule_of normp}
clasohm@0
   764
        in  cons(th, thq)  end  handle Bicompose => thq
clasohm@0
   765
     val (rtpairs,rhorn) = Logic.strip_flexpairs(rprop);
clasohm@0
   766
     val (rAs,B) = Logic.strip_prems(nsubgoal, [], rhorn)
clasohm@0
   767
       handle TERM _ => raise THM("bicompose: rule", 0, [orule,state]);
clasohm@0
   768
     (*Modify assumptions, deleting n-th if n>0 for e-resolution*)
clasohm@0
   769
     fun newAs(As0, n, dpairs, tpairs) =
clasohm@0
   770
       let val As1 = if !Logic.auto_rename orelse not lifted then As0
wenzelm@250
   771
                     else map (rename_bvars(dpairs,tpairs,B)) As0
clasohm@0
   772
       in (map (Logic.flatten_params n) As1)
wenzelm@250
   773
          handle TERM _ =>
wenzelm@250
   774
          raise THM("bicompose: 1st premise", 0, [orule])
clasohm@0
   775
       end;
clasohm@0
   776
     val env = Envir.empty(max[rmax,smax]);
clasohm@0
   777
     val BBi = if lifted then strip_assums2(B,Bi) else (B,Bi);
clasohm@0
   778
     val dpairs = BBi :: (rtpairs@stpairs);
clasohm@0
   779
     (*elim-resolution: try each assumption in turn.  Initially n=1*)
clasohm@0
   780
     fun tryasms (_, _, []) = null
clasohm@0
   781
       | tryasms (As, n, (t,u)::apairs) =
wenzelm@250
   782
          (case pull(Unify.unifiers(sign, env, (t,u)::dpairs))  of
wenzelm@250
   783
               None                   => tryasms (As, n+1, apairs)
wenzelm@250
   784
             | cell as Some((_,tpairs),_) =>
wenzelm@250
   785
                   its_right (addth (newAs(As, n, [BBi,(u,t)], tpairs)))
wenzelm@250
   786
                       (seqof (fn()=> cell),
wenzelm@250
   787
                        seqof (fn()=> pull (tryasms (As, n+1, apairs)))));
clasohm@0
   788
     fun eres [] = raise THM("bicompose: no premises", 0, [orule,state])
clasohm@0
   789
       | eres (A1::As) = tryasms (As, 1, Logic.assum_pairs A1);
clasohm@0
   790
     (*ordinary resolution*)
clasohm@0
   791
     fun res(None) = null
wenzelm@250
   792
       | res(cell as Some((_,tpairs),_)) =
wenzelm@250
   793
             its_right (addth(newAs(rev rAs, 0, [BBi], tpairs)))
wenzelm@250
   794
                       (seqof (fn()=> cell), null)
clasohm@0
   795
 in  if eres_flg then eres(rev rAs)
clasohm@0
   796
     else res(pull(Unify.unifiers(sign, env, dpairs)))
clasohm@0
   797
 end;
clasohm@0
   798
end;  (*open Sequence*)
clasohm@0
   799
clasohm@0
   800
clasohm@0
   801
fun bicompose match arg i state =
clasohm@0
   802
    bicompose_aux match (state, dest_state(state,i), false) arg;
clasohm@0
   803
clasohm@0
   804
(*Quick test whether rule is resolvable with the subgoal with hyps Hs
clasohm@0
   805
  and conclusion B.  If eres_flg then checks 1st premise of rule also*)
clasohm@0
   806
fun could_bires (Hs, B, eres_flg, rule) =
clasohm@0
   807
    let fun could_reshyp (A1::_) = exists (apl(A1,could_unify)) Hs
wenzelm@250
   808
          | could_reshyp [] = false;  (*no premise -- illegal*)
wenzelm@250
   809
    in  could_unify(concl_of rule, B) andalso
wenzelm@250
   810
        (not eres_flg  orelse  could_reshyp (prems_of rule))
clasohm@0
   811
    end;
clasohm@0
   812
clasohm@0
   813
(*Bi-resolution of a state with a list of (flag,rule) pairs.
clasohm@0
   814
  Puts the rule above:  rule/state.  Renames vars in the rules. *)
wenzelm@250
   815
fun biresolution match brules i state =
clasohm@0
   816
    let val lift = lift_rule(state, i);
wenzelm@250
   817
        val (stpairs, Bs, Bi, C) = dest_state(state,i)
wenzelm@250
   818
        val B = Logic.strip_assums_concl Bi;
wenzelm@250
   819
        val Hs = Logic.strip_assums_hyp Bi;
wenzelm@250
   820
        val comp = bicompose_aux match (state, (stpairs, Bs, Bi, C), true);
wenzelm@250
   821
        fun res [] = Sequence.null
wenzelm@250
   822
          | res ((eres_flg, rule)::brules) =
wenzelm@250
   823
              if could_bires (Hs, B, eres_flg, rule)
wenzelm@250
   824
              then Sequence.seqof (*delay processing remainder til needed*)
wenzelm@250
   825
                  (fn()=> Some(comp (eres_flg, lift rule, nprems_of rule),
wenzelm@250
   826
                               res brules))
wenzelm@250
   827
              else res brules
clasohm@0
   828
    in  Sequence.flats (res brules)  end;
clasohm@0
   829
clasohm@0
   830
clasohm@0
   831
(**** THEORIES ****)
clasohm@0
   832
clasohm@0
   833
val pure_thy = Pure{sign = Sign.pure};
clasohm@0
   834
clasohm@0
   835
(*Look up the named axiom in the theory*)
clasohm@0
   836
fun get_axiom thy axname =
clasohm@0
   837
    let fun get (Pure _) = raise Match
wenzelm@250
   838
          | get (Extend{axioms,thy,...}) =
wenzelm@250
   839
             (case Symtab.lookup(axioms,axname) of
wenzelm@250
   840
                  Some th => th
wenzelm@250
   841
                | None => get thy)
wenzelm@250
   842
         | get (Merge{thy1,thy2,...}) =
wenzelm@250
   843
                get thy1  handle Match => get thy2
clasohm@0
   844
    in  get thy
wenzelm@250
   845
        handle Match => raise THEORY("get_axiom: No axiom "^axname, [thy])
clasohm@0
   846
    end;
clasohm@0
   847
clasohm@0
   848
(*Converts Frees to Vars: axioms can be written without question marks*)
clasohm@0
   849
fun prepare_axiom sign sP =
lcp@229
   850
    Logic.varify (term_of (read_cterm sign (sP,propT)));
clasohm@0
   851
clasohm@0
   852
(*Read an axiom for a new theory*)
clasohm@0
   853
fun read_ax sign (a, sP) : string*thm =
clasohm@0
   854
  let val prop = prepare_axiom sign sP
wenzelm@250
   855
  in  (a, Thm{sign=sign, hyps=[], maxidx= maxidx_of_term prop, prop= prop})
clasohm@0
   856
  end
clasohm@0
   857
  handle ERROR =>
wenzelm@250
   858
        error("extend_theory: The error above occurred in axiom " ^ a);
clasohm@0
   859
clasohm@0
   860
fun mk_axioms sign axpairs =
wenzelm@250
   861
        Symtab.st_of_alist(map (read_ax sign) axpairs, Symtab.null)
wenzelm@250
   862
        handle Symtab.DUPLICATE(a) => error("Two axioms named " ^ a);
clasohm@0
   863
clasohm@0
   864
(*Extension of a theory with given classes, types, constants and syntax.
clasohm@0
   865
  Reads the axioms from strings: axpairs have the form (axname, axiom). *)
clasohm@0
   866
fun extend_theory thy thyname ext axpairs =
clasohm@0
   867
  let val sign = Sign.extend (sign_of thy) thyname ext;
clasohm@0
   868
      val axioms= mk_axioms sign axpairs
clasohm@0
   869
  in  Extend{sign=sign, axioms= axioms, thy = thy}  end;
clasohm@0
   870
clasohm@0
   871
(*The union of two theories*)
wenzelm@250
   872
fun merge_theories (thy1, thy2) =
wenzelm@250
   873
  Merge {sign = Sign.merge (sign_of thy1, sign_of thy2),
wenzelm@250
   874
         thy1 = thy1, thy2 = thy2} handle TERM (msg, _) => error msg;
clasohm@0
   875
clasohm@0
   876
clasohm@0
   877
(*** Meta simp sets ***)
clasohm@0
   878
nipkow@288
   879
type rrule = {thm:thm, lhs:term, perm:bool};
nipkow@288
   880
type cong = {thm:thm, lhs:term};
clasohm@0
   881
datatype meta_simpset =
nipkow@288
   882
  Mss of {net:rrule Net.net, congs:(string * cong)list, primes:string,
clasohm@0
   883
          prems: thm list, mk_rews: thm -> thm list};
clasohm@0
   884
clasohm@0
   885
(*A "mss" contains data needed during conversion:
clasohm@0
   886
  net: discrimination net of rewrite rules
clasohm@0
   887
  congs: association list of congruence rules
clasohm@0
   888
  primes: offset for generating unique new names
clasohm@0
   889
          for rewriting under lambda abstractions
clasohm@0
   890
  mk_rews: used when local assumptions are added
clasohm@0
   891
*)
clasohm@0
   892
clasohm@0
   893
val empty_mss = Mss{net= Net.empty, congs= [], primes="", prems= [],
clasohm@0
   894
                    mk_rews = K[]};
clasohm@0
   895
clasohm@0
   896
exception SIMPLIFIER of string * thm;
clasohm@0
   897
lcp@229
   898
fun prtm a sign t = (writeln a; writeln(Sign.string_of_term sign t));
clasohm@0
   899
nipkow@209
   900
val trace_simp = ref false;
nipkow@209
   901
lcp@229
   902
fun trace_term a sign t = if !trace_simp then prtm a sign t else ();
nipkow@209
   903
nipkow@209
   904
fun trace_thm a (Thm{sign,prop,...}) = trace_term a sign prop;
nipkow@209
   905
nipkow@288
   906
fun var_perm(Var _, Var _) = true
nipkow@288
   907
  | var_perm(Abs(_,_,s), Abs(_,_,t)) = var_perm(s,t)
nipkow@288
   908
  | var_perm(t1$t2, u1$u2) = var_perm(t1,u1) andalso var_perm(t2,u2)
nipkow@288
   909
  | var_perm(t,u) = (t=u);
nipkow@288
   910
nipkow@288
   911
clasohm@0
   912
(*simple test for looping rewrite*)
clasohm@0
   913
fun loops sign prems (lhs,rhs) =
clasohm@0
   914
  null(prems) andalso
clasohm@0
   915
  Pattern.eta_matches (#tsig(Sign.rep_sg sign)) (lhs,rhs);
clasohm@0
   916
clasohm@0
   917
fun mk_rrule (thm as Thm{hyps,sign,prop,maxidx,...}) =
clasohm@0
   918
  let val prems = Logic.strip_imp_prems prop
clasohm@0
   919
      val concl = Pattern.eta_contract (Logic.strip_imp_concl prop)
clasohm@0
   920
      val (lhs,rhs) = Logic.dest_equals concl handle TERM _ =>
clasohm@0
   921
                      raise SIMPLIFIER("Rewrite rule not a meta-equality",thm)
nipkow@288
   922
      val perm = var_perm(lhs,rhs) andalso not(lhs=rhs)
nipkow@288
   923
  in if not perm andalso loops sign prems (lhs,rhs)
clasohm@0
   924
     then (prtm "Warning: ignoring looping rewrite rule" sign prop; None)
nipkow@288
   925
     else Some{thm=thm,lhs=lhs,perm=perm}
clasohm@0
   926
  end;
clasohm@0
   927
nipkow@87
   928
local
nipkow@87
   929
 fun eq({thm=Thm{prop=p1,...},...}:rrule,
nipkow@87
   930
        {thm=Thm{prop=p2,...},...}:rrule) = p1 aconv p2
nipkow@87
   931
in
nipkow@87
   932
clasohm@0
   933
fun add_simp(mss as Mss{net,congs,primes,prems,mk_rews},
clasohm@0
   934
             thm as Thm{sign,prop,...}) =
nipkow@87
   935
  case mk_rrule thm of
nipkow@87
   936
    None => mss
nipkow@87
   937
  | Some(rrule as {lhs,...}) =>
nipkow@209
   938
      (trace_thm "Adding rewrite rule:" thm;
nipkow@209
   939
       Mss{net= (Net.insert_term((lhs,rrule),net,eq)
nipkow@209
   940
                 handle Net.INSERT =>
nipkow@87
   941
                  (prtm "Warning: ignoring duplicate rewrite rule" sign prop;
nipkow@87
   942
                   net)),
nipkow@209
   943
           congs=congs, primes=primes, prems=prems,mk_rews=mk_rews});
nipkow@87
   944
nipkow@87
   945
fun del_simp(mss as Mss{net,congs,primes,prems,mk_rews},
nipkow@87
   946
             thm as Thm{sign,prop,...}) =
nipkow@87
   947
  case mk_rrule thm of
nipkow@87
   948
    None => mss
nipkow@87
   949
  | Some(rrule as {lhs,...}) =>
nipkow@87
   950
      Mss{net= (Net.delete_term((lhs,rrule),net,eq)
nipkow@87
   951
                handle Net.INSERT =>
nipkow@87
   952
                 (prtm "Warning: rewrite rule not in simpset" sign prop;
nipkow@87
   953
                  net)),
clasohm@0
   954
             congs=congs, primes=primes, prems=prems,mk_rews=mk_rews}
nipkow@87
   955
nipkow@87
   956
end;
clasohm@0
   957
clasohm@0
   958
val add_simps = foldl add_simp;
nipkow@87
   959
val del_simps = foldl del_simp;
clasohm@0
   960
clasohm@0
   961
fun mss_of thms = add_simps(empty_mss,thms);
clasohm@0
   962
clasohm@0
   963
fun add_cong(Mss{net,congs,primes,prems,mk_rews},thm) =
clasohm@0
   964
  let val (lhs,_) = Logic.dest_equals(concl_of thm) handle TERM _ =>
clasohm@0
   965
                    raise SIMPLIFIER("Congruence not a meta-equality",thm)
clasohm@0
   966
      val lhs = Pattern.eta_contract lhs
clasohm@0
   967
      val (a,_) = dest_Const (head_of lhs) handle TERM _ =>
clasohm@0
   968
                  raise SIMPLIFIER("Congruence must start with a constant",thm)
clasohm@0
   969
  in Mss{net=net, congs=(a,{lhs=lhs,thm=thm})::congs, primes=primes,
clasohm@0
   970
         prems=prems, mk_rews=mk_rews}
clasohm@0
   971
  end;
clasohm@0
   972
clasohm@0
   973
val (op add_congs) = foldl add_cong;
clasohm@0
   974
clasohm@0
   975
fun add_prems(Mss{net,congs,primes,prems,mk_rews},thms) =
clasohm@0
   976
  Mss{net=net, congs=congs, primes=primes, prems=thms@prems, mk_rews=mk_rews};
clasohm@0
   977
clasohm@0
   978
fun prems_of_mss(Mss{prems,...}) = prems;
clasohm@0
   979
clasohm@0
   980
fun set_mk_rews(Mss{net,congs,primes,prems,...},mk_rews) =
clasohm@0
   981
  Mss{net=net, congs=congs, primes=primes, prems=prems, mk_rews=mk_rews};
clasohm@0
   982
fun mk_rews_of_mss(Mss{mk_rews,...}) = mk_rews;
clasohm@0
   983
clasohm@0
   984
wenzelm@250
   985
(*** Meta-level rewriting
clasohm@0
   986
     uses conversions, omitting proofs for efficiency.  See
wenzelm@250
   987
        L C Paulson, A higher-order implementation of rewriting,
wenzelm@250
   988
        Science of Computer Programming 3 (1983), pages 119-149. ***)
clasohm@0
   989
clasohm@0
   990
type prover = meta_simpset -> thm -> thm option;
clasohm@0
   991
type termrec = (Sign.sg * term list) * term;
clasohm@0
   992
type conv = meta_simpset -> termrec -> termrec;
clasohm@0
   993
nipkow@305
   994
datatype order = LESS | EQUAL | GREATER;
nipkow@288
   995
nipkow@305
   996
fun stringord(a,b:string) = if a<b then LESS  else
nipkow@305
   997
                            if a=b then EQUAL else GREATER;
nipkow@305
   998
nipkow@305
   999
fun intord(i,j:int) = if i<j then LESS  else
nipkow@305
  1000
                      if i=j then EQUAL else GREATER;
nipkow@288
  1001
nipkow@305
  1002
(* FIXME: "***ABSTRACTION***" is a hack and makes the ordering non-linear *)
nipkow@305
  1003
fun string_of_hd(Const(a,_)) = a
nipkow@305
  1004
  | string_of_hd(Free(a,_))  = a
nipkow@305
  1005
  | string_of_hd(Var(v,_))   = Syntax.string_of_vname v
nipkow@305
  1006
  | string_of_hd(Bound i)    = string_of_int i
nipkow@305
  1007
  | string_of_hd(Abs _)      = "***ABSTRACTION***";
nipkow@288
  1008
nipkow@305
  1009
(* a strict (not reflexive) linear well-founded AC-compatible ordering
nipkow@305
  1010
 * for terms:
nipkow@305
  1011
 * s < t <=> 1. size(s) < size(t) or
nipkow@305
  1012
             2. size(s) = size(t) and s=f(...) and t = g(...) and f<g or
nipkow@305
  1013
             3. size(s) = size(t) and s=f(s1..sn) and t=f(t1..tn) and
nipkow@305
  1014
                (s1..sn) < (t1..tn) (lexicographically)
nipkow@305
  1015
 *)
nipkow@288
  1016
nipkow@288
  1017
(* FIXME: should really take types into account as well.
nipkow@305
  1018
 * Otherwise not linear *)
nipkow@305
  1019
fun termord(t,u) =
nipkow@305
  1020
      (case intord(size_of_term t,size_of_term u) of
nipkow@305
  1021
         EQUAL => let val (f,ts) = strip_comb t and (g,us) = strip_comb u
nipkow@305
  1022
                  in case stringord(string_of_hd f, string_of_hd g) of
nipkow@305
  1023
                       EQUAL => lextermord(ts,us)
nipkow@305
  1024
                     | ord   => ord
nipkow@305
  1025
                  end
nipkow@305
  1026
       | ord => ord)
nipkow@305
  1027
and lextermord(t::ts,u::us) =
nipkow@305
  1028
      (case termord(t,u) of
nipkow@305
  1029
         EQUAL => lextermord(ts,us)
nipkow@305
  1030
       | ord   => ord)
nipkow@305
  1031
  | lextermord([],[]) = EQUAL
nipkow@305
  1032
  | lextermord _ = error("lextermord");
nipkow@288
  1033
nipkow@305
  1034
fun termless tu = (termord tu = LESS);
nipkow@288
  1035
nipkow@208
  1036
fun check_conv(thm as Thm{hyps,prop,...}, prop0) =
nipkow@112
  1037
  let fun err() = (trace_thm "Proved wrong thm (Check subgoaler?)" thm; None)
clasohm@0
  1038
      val (lhs0,_) = Logic.dest_equals(Logic.strip_imp_concl prop0)
clasohm@0
  1039
  in case prop of
clasohm@0
  1040
       Const("==",_) $ lhs $ rhs =>
clasohm@0
  1041
         if (lhs = lhs0) orelse
clasohm@0
  1042
            (lhs aconv (Envir.norm_term (Envir.empty 0) lhs0))
nipkow@208
  1043
         then (trace_thm "SUCCEEDED" thm; Some(hyps,rhs))
clasohm@0
  1044
         else err()
clasohm@0
  1045
     | _ => err()
clasohm@0
  1046
  end;
clasohm@0
  1047
clasohm@0
  1048
(*Conversion to apply the meta simpset to a term*)
nipkow@208
  1049
fun rewritec (prover,signt) (mss as Mss{net,...}) (hypst,t) =
nipkow@225
  1050
  let val t = Pattern.eta_contract t;
nipkow@288
  1051
      fun rew {thm as Thm{sign,hyps,maxidx,prop,...}, lhs, perm} =
wenzelm@250
  1052
        let val unit = if Sign.subsig(sign,signt) then ()
nipkow@208
  1053
                  else (writeln"Warning: rewrite rule from different theory";
nipkow@208
  1054
                        raise Pattern.MATCH)
nipkow@208
  1055
            val insts = Pattern.match (#tsig(Sign.rep_sg signt)) (lhs,t)
clasohm@0
  1056
            val prop' = subst_vars insts prop;
clasohm@0
  1057
            val hyps' = hyps union hypst;
nipkow@208
  1058
            val thm' = Thm{sign=signt, hyps=hyps', prop=prop', maxidx=maxidx}
clasohm@0
  1059
        in if nprems_of thm' = 0
clasohm@0
  1060
           then let val (_,rhs) = Logic.dest_equals prop'
nipkow@288
  1061
                in if perm andalso not(termless(rhs,t)) then None
nipkow@288
  1062
                   else (trace_thm "Rewriting:" thm'; Some(hyps',rhs)) end
clasohm@0
  1063
           else (trace_thm "Trying to rewrite:" thm';
clasohm@0
  1064
                 case prover mss thm' of
clasohm@0
  1065
                   None       => (trace_thm "FAILED" thm'; None)
nipkow@112
  1066
                 | Some(thm2) => check_conv(thm2,prop'))
clasohm@0
  1067
        end
clasohm@0
  1068
nipkow@225
  1069
      fun rews [] = None
nipkow@225
  1070
        | rews (rrule::rrules) =
nipkow@225
  1071
            let val opt = rew rrule handle Pattern.MATCH => None
nipkow@225
  1072
            in case opt of None => rews rrules | some => some end;
clasohm@0
  1073
clasohm@0
  1074
  in case t of
nipkow@208
  1075
       Abs(_,_,body) $ u => Some(hypst,subst_bounds([u], body))
nipkow@225
  1076
     | _                 => rews(Net.match_term net t)
clasohm@0
  1077
  end;
clasohm@0
  1078
clasohm@0
  1079
(*Conversion to apply a congruence rule to a term*)
nipkow@208
  1080
fun congc (prover,signt) {thm=cong,lhs=lhs} (hypst,t) =
clasohm@0
  1081
  let val Thm{sign,hyps,maxidx,prop,...} = cong
nipkow@208
  1082
      val unit = if Sign.subsig(sign,signt) then ()
nipkow@208
  1083
                 else error("Congruence rule from different theory")
nipkow@208
  1084
      val tsig = #tsig(Sign.rep_sg signt)
clasohm@0
  1085
      val insts = Pattern.match tsig (lhs,t) handle Pattern.MATCH =>
clasohm@0
  1086
                  error("Congruence rule did not match")
clasohm@0
  1087
      val prop' = subst_vars insts prop;
nipkow@208
  1088
      val thm' = Thm{sign=signt, hyps=hyps union hypst,
clasohm@0
  1089
                     prop=prop', maxidx=maxidx}
clasohm@0
  1090
      val unit = trace_thm "Applying congruence rule" thm';
nipkow@112
  1091
      fun err() = error("Failed congruence proof!")
clasohm@0
  1092
clasohm@0
  1093
  in case prover thm' of
nipkow@112
  1094
       None => err()
nipkow@112
  1095
     | Some(thm2) => (case check_conv(thm2,prop') of
nipkow@112
  1096
                        None => err() | Some(x) => x)
clasohm@0
  1097
  end;
clasohm@0
  1098
clasohm@0
  1099
nipkow@214
  1100
fun bottomc ((simprem,useprem),prover,sign) =
clasohm@0
  1101
  let fun botc mss trec = let val trec1 = subc mss trec
nipkow@208
  1102
                          in case rewritec (prover,sign) mss trec1 of
clasohm@0
  1103
                               None => trec1
clasohm@0
  1104
                             | Some(trec2) => botc mss trec2
clasohm@0
  1105
                          end
clasohm@0
  1106
clasohm@0
  1107
      and subc (mss as Mss{net,congs,primes,prems,mk_rews})
nipkow@208
  1108
               (trec as (hyps,t)) =
clasohm@0
  1109
        (case t of
clasohm@0
  1110
            Abs(a,T,t) =>
clasohm@0
  1111
              let val v = Free(".subc." ^ primes,T)
clasohm@0
  1112
                  val mss' = Mss{net=net, congs=congs, primes=primes^"'",
clasohm@0
  1113
                                 prems=prems,mk_rews=mk_rews}
nipkow@208
  1114
                  val (hyps',t') = botc mss' (hyps,subst_bounds([v],t))
nipkow@208
  1115
              in  (hyps', Abs(a, T, abstract_over(v,t')))  end
clasohm@0
  1116
          | t$u => (case t of
nipkow@208
  1117
              Const("==>",_)$s  => impc(hyps,s,u,mss)
nipkow@208
  1118
            | Abs(_,_,body)     => subc mss (hyps,subst_bounds([u], body))
clasohm@0
  1119
            | _                 =>
nipkow@208
  1120
                let fun appc() = let val (hyps1,t1) = botc mss (hyps,t)
nipkow@208
  1121
                                     val (hyps2,u1) = botc mss (hyps1,u)
nipkow@208
  1122
                                 in (hyps2,t1$u1) end
clasohm@0
  1123
                    val (h,ts) = strip_comb t
clasohm@0
  1124
                in case h of
clasohm@0
  1125
                     Const(a,_) =>
clasohm@0
  1126
                       (case assoc(congs,a) of
clasohm@0
  1127
                          None => appc()
nipkow@208
  1128
                        | Some(cong) => congc (prover mss,sign) cong trec)
clasohm@0
  1129
                   | _ => appc()
clasohm@0
  1130
                end)
clasohm@0
  1131
          | _ => trec)
clasohm@0
  1132
nipkow@208
  1133
      and impc(hyps,s,u,mss as Mss{mk_rews,...}) =
nipkow@214
  1134
        let val (hyps1,s') = if simprem then botc mss (hyps,s) else (hyps,s)
nipkow@214
  1135
            val mss' =
nipkow@214
  1136
              if not useprem orelse maxidx_of_term s' <> ~1 then mss
nipkow@208
  1137
              else let val thm = Thm{sign=sign,hyps=[s'],prop=s',maxidx= ~1}
nipkow@214
  1138
                   in add_simps(add_prems(mss,[thm]), mk_rews thm) end
nipkow@208
  1139
            val (hyps2,u') = botc mss' (hyps1,u)
nipkow@134
  1140
            val hyps2' = if s' mem hyps1 then hyps2 else hyps2\s'
nipkow@208
  1141
        in (hyps2', Logic.mk_implies(s',u')) end
clasohm@0
  1142
clasohm@0
  1143
  in botc end;
clasohm@0
  1144
clasohm@0
  1145
clasohm@0
  1146
(*** Meta-rewriting: rewrites t to u and returns the theorem t==u ***)
clasohm@0
  1147
(* Parameters:
wenzelm@250
  1148
   mode = (simplify A, use A in simplifying B) when simplifying A ==> B
clasohm@0
  1149
   mss: contains equality theorems of the form [|p1,...|] ==> t==u
clasohm@0
  1150
   prover: how to solve premises in conditional rewrites and congruences
clasohm@0
  1151
*)
clasohm@0
  1152
clasohm@0
  1153
(*** FIXME: check that #primes(mss) does not "occur" in ct alread ***)
nipkow@214
  1154
fun rewrite_cterm mode mss prover ct =
lcp@229
  1155
  let val {sign, t, T, maxidx} = rep_cterm ct;
nipkow@214
  1156
      val (hyps,u) = bottomc (mode,prover,sign) mss ([],t);
clasohm@0
  1157
      val prop = Logic.mk_equals(t,u)
nipkow@208
  1158
  in  Thm{sign= sign, hyps= hyps, maxidx= maxidx_of_term prop, prop= prop}
clasohm@0
  1159
  end
clasohm@0
  1160
clasohm@0
  1161
end;
wenzelm@250
  1162