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