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