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