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