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