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