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