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