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