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