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