src/Pure/meta_simplifier.ML
author skalberg
Wed Jun 30 00:42:59 2004 +0200 (2004-06-30)
changeset 15011 35be762f58f9
parent 15006 107e4dfd3b96
child 15023 0e4689f411d5
permissions -rw-r--r--
Made simplification procedures simpset-aware.
berghofe@10413
     1
(*  Title:      Pure/meta_simplifier.ML
berghofe@10413
     2
    ID:         $Id$
wenzelm@11672
     3
    Author:     Tobias Nipkow and Stefan Berghofer
berghofe@10413
     4
wenzelm@11672
     5
Meta-level Simplification.
berghofe@10413
     6
*)
berghofe@10413
     7
skalberg@15006
     8
infix 4
skalberg@15006
     9
  setsubgoaler setloop addloop delloop setSSolver addSSolver setSolver
skalberg@15006
    10
  addSolver addsimps delsimps addeqcongs deleqcongs addcongs delcongs
skalberg@15006
    11
  setmksimps setmkeqTrue setmkcong setmksym settermless addsimprocs delsimprocs;
skalberg@15006
    12
wenzelm@11672
    13
signature BASIC_META_SIMPLIFIER =
wenzelm@11672
    14
sig
wenzelm@11672
    15
  val trace_simp: bool ref
wenzelm@11672
    16
  val debug_simp: bool ref
nipkow@13828
    17
  val simp_depth_limit: int ref
wenzelm@11672
    18
end;
wenzelm@11672
    19
skalberg@15006
    20
signature AUX_SIMPLIFIER =
skalberg@15006
    21
sig
skalberg@15006
    22
  type meta_simpset
skalberg@15011
    23
  type simpset
skalberg@15006
    24
  type simproc
skalberg@15011
    25
  val full_mk_simproc: string -> cterm list
skalberg@15011
    26
    -> (simpset -> Sign.sg -> thm list -> term -> thm option) -> simproc
skalberg@15006
    27
  val mk_simproc: string -> cterm list
skalberg@15006
    28
    -> (Sign.sg -> thm list -> term -> thm option) -> simproc
skalberg@15006
    29
  type solver
skalberg@15006
    30
  val mk_solver: string -> (thm list -> int -> tactic) -> solver
skalberg@15006
    31
  val empty_ss: simpset
skalberg@15006
    32
  val rep_ss: simpset ->
skalberg@15006
    33
   {mss: meta_simpset,
skalberg@15006
    34
    mk_cong: thm -> thm,
skalberg@15006
    35
    subgoal_tac: simpset -> int -> tactic,
skalberg@15006
    36
    loop_tacs: (string * (int -> tactic)) list,
skalberg@15006
    37
    unsafe_solvers: solver list,
skalberg@15011
    38
    solvers: solver list}
skalberg@15011
    39
  val from_mss: meta_simpset -> simpset
skalberg@15011
    40
  val ss_of            : thm list -> simpset
skalberg@15006
    41
  val print_ss: simpset -> unit
skalberg@15006
    42
  val setsubgoaler: simpset *  (simpset -> int -> tactic) -> simpset
skalberg@15006
    43
  val setloop:      simpset *             (int -> tactic) -> simpset
skalberg@15006
    44
  val addloop:      simpset *  (string * (int -> tactic)) -> simpset
skalberg@15006
    45
  val delloop:      simpset *   string                    -> simpset
skalberg@15006
    46
  val setSSolver:   simpset * solver -> simpset
skalberg@15006
    47
  val addSSolver:   simpset * solver -> simpset
skalberg@15006
    48
  val setSolver:    simpset * solver -> simpset
skalberg@15006
    49
  val addSolver:    simpset * solver -> simpset
skalberg@15006
    50
  val setmksimps:   simpset * (thm -> thm list) -> simpset
skalberg@15006
    51
  val setmkeqTrue:  simpset * (thm -> thm option) -> simpset
skalberg@15006
    52
  val setmkcong:    simpset * (thm -> thm) -> simpset
skalberg@15006
    53
  val setmksym:     simpset * (thm -> thm option) -> simpset
skalberg@15006
    54
  val settermless:  simpset * (term * term -> bool) -> simpset
skalberg@15006
    55
  val addsimps:     simpset * thm list -> simpset
skalberg@15006
    56
  val delsimps:     simpset * thm list -> simpset
skalberg@15006
    57
  val addeqcongs:   simpset * thm list -> simpset
skalberg@15006
    58
  val deleqcongs:   simpset * thm list -> simpset
skalberg@15006
    59
  val addcongs:     simpset * thm list -> simpset
skalberg@15006
    60
  val delcongs:     simpset * thm list -> simpset
skalberg@15006
    61
  val addsimprocs:  simpset * simproc list -> simpset
skalberg@15006
    62
  val delsimprocs:  simpset * simproc list -> simpset
skalberg@15006
    63
  val merge_ss:     simpset * simpset -> simpset
skalberg@15006
    64
  val prems_of_ss:  simpset -> thm list
skalberg@15006
    65
  val generic_simp_tac: bool -> bool * bool * bool -> simpset -> int -> tactic
skalberg@15006
    66
  val simproc: Sign.sg -> string -> string list
skalberg@15006
    67
    -> (Sign.sg -> thm list -> term -> thm option) -> simproc
skalberg@15006
    68
  val simproc_i: Sign.sg -> string -> term list
skalberg@15006
    69
    -> (Sign.sg -> thm list -> term -> thm option) -> simproc
skalberg@15011
    70
  val full_simproc: Sign.sg -> string -> string list
skalberg@15011
    71
    -> (simpset -> Sign.sg -> thm list -> term -> thm option) -> simproc
skalberg@15011
    72
  val full_simproc_i: Sign.sg -> string -> term list
skalberg@15011
    73
    -> (simpset -> Sign.sg -> thm list -> term -> thm option) -> simproc
skalberg@15006
    74
  val clear_ss  : simpset -> simpset
skalberg@15006
    75
  val simp_thm  : bool * bool * bool -> simpset -> thm -> thm
skalberg@15006
    76
  val simp_cterm: bool * bool * bool -> simpset -> cterm -> thm
skalberg@15006
    77
end;
skalberg@15006
    78
berghofe@10413
    79
signature META_SIMPLIFIER =
berghofe@10413
    80
sig
wenzelm@11672
    81
  include BASIC_META_SIMPLIFIER
skalberg@15006
    82
  include AUX_SIMPLIFIER
berghofe@10413
    83
  exception SIMPLIFIER of string * thm
wenzelm@13486
    84
  exception SIMPROC_FAIL of string * exn
wenzelm@12603
    85
  val dest_mss          : meta_simpset ->
berghofe@10413
    86
    {simps: thm list, congs: thm list, procs: (string * cterm list) list}
berghofe@10413
    87
  val empty_mss         : meta_simpset
wenzelm@12603
    88
  val clear_mss         : meta_simpset -> meta_simpset
wenzelm@12603
    89
  val merge_mss         : meta_simpset * meta_simpset -> meta_simpset
berghofe@10413
    90
  val add_simps         : meta_simpset * thm list -> meta_simpset
berghofe@10413
    91
  val del_simps         : meta_simpset * thm list -> meta_simpset
berghofe@10413
    92
  val mss_of            : thm list -> meta_simpset
berghofe@10413
    93
  val add_congs         : meta_simpset * thm list -> meta_simpset
berghofe@10413
    94
  val del_congs         : meta_simpset * thm list -> meta_simpset
wenzelm@12603
    95
  val add_simprocs      : meta_simpset *
skalberg@15011
    96
    (string * cterm list * (simpset -> Sign.sg -> thm list -> term -> thm option) * stamp) list
berghofe@10413
    97
      -> meta_simpset
wenzelm@12603
    98
  val del_simprocs      : meta_simpset *
skalberg@15011
    99
    (string * cterm list * (simpset -> Sign.sg -> thm list -> term -> thm option) * stamp) list
berghofe@10413
   100
      -> meta_simpset
berghofe@10413
   101
  val add_prems         : meta_simpset * thm list -> meta_simpset
berghofe@10413
   102
  val prems_of_mss      : meta_simpset -> thm list
berghofe@10413
   103
  val set_mk_rews       : meta_simpset * (thm -> thm list) -> meta_simpset
berghofe@10413
   104
  val set_mk_sym        : meta_simpset * (thm -> thm option) -> meta_simpset
berghofe@10413
   105
  val set_mk_eq_True    : meta_simpset * (thm -> thm option) -> meta_simpset
skalberg@14242
   106
  val get_mk_rews       : meta_simpset -> thm -> thm list
skalberg@14242
   107
  val get_mk_sym        : meta_simpset -> thm -> thm option
skalberg@14242
   108
  val get_mk_eq_True    : meta_simpset -> thm -> thm option
berghofe@10413
   109
  val set_termless      : meta_simpset * (term * term -> bool) -> meta_simpset
wenzelm@11672
   110
  val rewrite_cterm: bool * bool * bool ->
skalberg@15011
   111
    (meta_simpset -> thm -> thm option) -> simpset -> cterm -> thm
wenzelm@11767
   112
  val rewrite_aux       : (meta_simpset -> thm -> thm option) -> bool -> thm list -> cterm -> thm
wenzelm@11767
   113
  val simplify_aux      : (meta_simpset -> thm -> thm option) -> bool -> thm list -> thm -> thm
berghofe@10413
   114
  val rewrite_thm       : bool * bool * bool
berghofe@10413
   115
                          -> (meta_simpset -> thm -> thm option)
skalberg@15011
   116
                          -> simpset -> thm -> thm
berghofe@10413
   117
  val rewrite_goals_rule_aux: (meta_simpset -> thm -> thm option) -> thm list -> thm -> thm
berghofe@10413
   118
  val rewrite_goal_rule : bool* bool * bool
berghofe@10413
   119
                          -> (meta_simpset -> thm -> thm option)
skalberg@15011
   120
                          -> simpset -> int -> thm -> thm
berghofe@13196
   121
  val rewrite_term: Sign.sg -> thm list -> (term -> term option) list -> term -> term
skalberg@15006
   122
  val asm_rewrite_goal_tac: bool*bool*bool ->
skalberg@15011
   123
    (meta_simpset -> tactic) -> simpset -> int -> tactic
skalberg@15006
   124
berghofe@10413
   125
end;
berghofe@10413
   126
berghofe@10413
   127
structure MetaSimplifier : META_SIMPLIFIER =
berghofe@10413
   128
struct
berghofe@10413
   129
berghofe@10413
   130
(** diagnostics **)
berghofe@10413
   131
berghofe@10413
   132
exception SIMPLIFIER of string * thm;
wenzelm@13486
   133
exception SIMPROC_FAIL of string * exn;
berghofe@10413
   134
nipkow@11505
   135
val simp_depth = ref 0;
nipkow@13828
   136
val simp_depth_limit = ref 1000;
nipkow@11505
   137
wenzelm@12603
   138
local
wenzelm@12603
   139
wenzelm@12603
   140
fun println a =
wenzelm@12603
   141
  tracing ((case ! simp_depth of 0 => "" | n => "[" ^ string_of_int n ^ "]") ^ a);
nipkow@11505
   142
nipkow@11505
   143
fun prnt warn a = if warn then warning a else println a;
wenzelm@12603
   144
fun prtm warn a sign t = prnt warn (a ^ "\n" ^ Sign.string_of_term sign t);
wenzelm@12603
   145
fun prctm warn a t = prnt warn (a ^ "\n" ^ Display.string_of_cterm t);
berghofe@10413
   146
wenzelm@12603
   147
in
berghofe@10413
   148
wenzelm@12603
   149
fun prthm warn a = prctm warn a o Thm.cprop_of;
berghofe@10413
   150
berghofe@10413
   151
val trace_simp = ref false;
berghofe@10413
   152
val debug_simp = ref false;
berghofe@10413
   153
berghofe@10413
   154
fun trace warn a = if !trace_simp then prnt warn a else ();
berghofe@10413
   155
fun debug warn a = if !debug_simp then prnt warn a else ();
berghofe@10413
   156
berghofe@10413
   157
fun trace_term warn a sign t = if !trace_simp then prtm warn a sign t else ();
berghofe@10413
   158
fun trace_cterm warn a t = if !trace_simp then prctm warn a t else ();
berghofe@10413
   159
fun debug_term warn a sign t = if !debug_simp then prtm warn a sign t else ();
berghofe@10413
   160
nipkow@13569
   161
fun trace_thm a thm =
berghofe@10413
   162
  let val {sign, prop, ...} = rep_thm thm
nipkow@13569
   163
  in trace_term false a sign prop end;
nipkow@13569
   164
berghofe@13607
   165
fun trace_named_thm a (thm, name) =
berghofe@13607
   166
  trace_thm (a ^ (if name = "" then "" else " " ^ quote name) ^ ":") thm;
berghofe@10413
   167
wenzelm@12603
   168
end;
berghofe@10413
   169
berghofe@10413
   170
berghofe@10413
   171
(** meta simp sets **)
berghofe@10413
   172
berghofe@10413
   173
(* basic components *)
berghofe@10413
   174
berghofe@13607
   175
type rrule = {thm: thm, name: string, lhs: term, elhs: cterm, fo: bool, perm: bool};
berghofe@10413
   176
(* thm: the rewrite rule
berghofe@13607
   177
   name: name of theorem from which rewrite rule was extracted
berghofe@10413
   178
   lhs: the left-hand side
berghofe@10413
   179
   elhs: the etac-contracted lhs.
berghofe@10413
   180
   fo:  use first-order matching
berghofe@10413
   181
   perm: the rewrite rule is permutative
wenzelm@12603
   182
Remarks:
berghofe@10413
   183
  - elhs is used for matching,
berghofe@10413
   184
    lhs only for preservation of bound variable names.
berghofe@10413
   185
  - fo is set iff
berghofe@10413
   186
    either elhs is first-order (no Var is applied),
berghofe@10413
   187
           in which case fo-matching is complete,
berghofe@10413
   188
    or elhs is not a pattern,
berghofe@10413
   189
       in which case there is nothing better to do.
berghofe@10413
   190
*)
berghofe@10413
   191
type cong = {thm: thm, lhs: cterm};
berghofe@10413
   192
berghofe@10413
   193
fun eq_rrule ({thm = thm1, ...}: rrule, {thm = thm2, ...}: rrule) =
berghofe@10413
   194
  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
berghofe@10413
   195
wenzelm@12603
   196
fun eq_cong ({thm = thm1, ...}: cong, {thm = thm2, ...}: cong) =
berghofe@10413
   197
  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
berghofe@10413
   198
berghofe@10413
   199
fun eq_prem (thm1, thm2) =
berghofe@10413
   200
  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
berghofe@10413
   201
berghofe@10413
   202
berghofe@10413
   203
(* datatype mss *)
berghofe@10413
   204
berghofe@10413
   205
(*
berghofe@10413
   206
  A "mss" contains data needed during conversion:
berghofe@10413
   207
    rules: discrimination net of rewrite rules;
berghofe@10413
   208
    congs: association list of congruence rules and
berghofe@10413
   209
           a list of `weak' congruence constants.
berghofe@10413
   210
           A congruence is `weak' if it avoids normalization of some argument.
berghofe@10413
   211
    procs: discrimination net of simplification procedures
berghofe@10413
   212
      (functions that prove rewrite rules on the fly);
berghofe@10413
   213
    bounds: names of bound variables already used
berghofe@10413
   214
      (for generating new names when rewriting under lambda abstractions);
berghofe@10413
   215
    prems: current premises;
berghofe@10413
   216
    mk_rews: mk: turns simplification thms into rewrite rules;
berghofe@10413
   217
             mk_sym: turns == around; (needs Drule!)
berghofe@10413
   218
             mk_eq_True: turns P into P == True - logic specific;
berghofe@10413
   219
    termless: relation for ordered rewriting;
nipkow@11504
   220
    depth: depth of conditional rewriting;
berghofe@10413
   221
*)
berghofe@10413
   222
skalberg@15011
   223
datatype solver = Solver of string * (thm list -> int -> tactic) * stamp;
skalberg@15011
   224
berghofe@10413
   225
datatype meta_simpset =
berghofe@10413
   226
  Mss of {
berghofe@10413
   227
    rules: rrule Net.net,
berghofe@10413
   228
    congs: (string * cong) list * string list,
skalberg@15006
   229
    procs: meta_simproc Net.net,
berghofe@10413
   230
    bounds: string list,
berghofe@10413
   231
    prems: thm list,
berghofe@10413
   232
    mk_rews: {mk: thm -> thm list,
berghofe@10413
   233
              mk_sym: thm -> thm option,
berghofe@10413
   234
              mk_eq_True: thm -> thm option},
nipkow@11504
   235
    termless: term * term -> bool,
skalberg@15011
   236
    depth: int}
skalberg@15011
   237
and simpset =
skalberg@15011
   238
  Simpset of {
skalberg@15011
   239
    mss: meta_simpset,
skalberg@15011
   240
    mk_cong: thm -> thm,
skalberg@15011
   241
    subgoal_tac: simpset -> int -> tactic,
skalberg@15011
   242
    loop_tacs: (string * (int -> tactic)) list,
skalberg@15011
   243
    unsafe_solvers: solver list,
skalberg@15011
   244
    solvers: solver list}
skalberg@15011
   245
withtype meta_simproc =
skalberg@15011
   246
 {name: string, proc: simpset -> Sign.sg -> thm list -> term -> thm option, lhs: cterm, id: stamp};
berghofe@10413
   247
nipkow@11504
   248
fun mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless, depth) =
berghofe@10413
   249
  Mss {rules = rules, congs = congs, procs = procs, bounds = bounds,
nipkow@11504
   250
       prems=prems, mk_rews=mk_rews, termless=termless, depth=depth};
berghofe@10413
   251
nipkow@11504
   252
fun upd_rules(Mss{rules,congs,procs,bounds,prems,mk_rews,termless,depth}, rules') =
nipkow@11504
   253
  mk_mss(rules',congs,procs,bounds,prems,mk_rews,termless,depth);
berghofe@10413
   254
berghofe@10413
   255
val empty_mss =
berghofe@10413
   256
  let val mk_rews = {mk = K [], mk_sym = K None, mk_eq_True = K None}
nipkow@11504
   257
  in mk_mss (Net.empty, ([], []), Net.empty, [], [], mk_rews, Term.termless, 0) end;
berghofe@10413
   258
berghofe@10413
   259
fun clear_mss (Mss {mk_rews, termless, ...}) =
nipkow@11504
   260
  mk_mss (Net.empty, ([], []), Net.empty, [], [], mk_rews, termless,0);
berghofe@10413
   261
nipkow@11504
   262
fun incr_depth(Mss{rules,congs,procs,bounds,prems,mk_rews,termless,depth}) =
nipkow@13828
   263
  let val depth1 = depth+1
nipkow@13828
   264
  in if depth1 > !simp_depth_limit
nipkow@13828
   265
     then (warning "simp_depth_limit exceeded - giving up"; None)
kleing@14040
   266
     else (if depth1 mod 10 = 0
nipkow@13828
   267
           then warning("Simplification depth " ^ string_of_int depth1)
nipkow@13828
   268
           else ();
nipkow@13828
   269
           Some(mk_mss(rules,congs,procs,bounds,prems,mk_rews,termless,depth1))
nipkow@13828
   270
          )
nipkow@13828
   271
  end;
berghofe@10413
   272
skalberg@15011
   273
datatype simproc =
skalberg@15011
   274
  Simproc of string * cterm list * (simpset -> Sign.sg -> thm list -> term -> thm option) * stamp
skalberg@15011
   275
skalberg@15011
   276
fun eq_simproc ({id = s1, ...}:meta_simproc, {id = s2, ...}:meta_simproc) = (s1 = s2);
skalberg@15011
   277
skalberg@15011
   278
fun mk_simproc (name, proc, lhs, id) =
skalberg@15011
   279
  {name = name, proc = proc, lhs = lhs, id = id};
skalberg@15011
   280
berghofe@10413
   281
berghofe@10413
   282
(** simpset operations **)
berghofe@10413
   283
berghofe@10413
   284
(* term variables *)
berghofe@10413
   285
berghofe@10413
   286
val add_term_varnames = foldl_aterms (fn (xs, Var (x, _)) => ins_ix (x, xs) | (xs, _) => xs);
berghofe@10413
   287
fun term_varnames t = add_term_varnames ([], t);
berghofe@10413
   288
berghofe@10413
   289
berghofe@10413
   290
(* dest_mss *)
berghofe@10413
   291
berghofe@10413
   292
fun dest_mss (Mss {rules, congs, procs, ...}) =
berghofe@10413
   293
  {simps = map (fn (_, {thm, ...}) => thm) (Net.dest rules),
berghofe@10413
   294
   congs = map (fn (_, {thm, ...}) => thm) (fst congs),
berghofe@10413
   295
   procs =
berghofe@10413
   296
     map (fn (_, {name, lhs, id, ...}) => ((name, lhs), id)) (Net.dest procs)
berghofe@10413
   297
     |> partition_eq eq_snd
berghofe@10413
   298
     |> map (fn ps => (#1 (#1 (hd ps)), map (#2 o #1) ps))
berghofe@10413
   299
     |> Library.sort_wrt #1};
berghofe@10413
   300
berghofe@10413
   301
wenzelm@12603
   302
(* merge_mss *)       (*NOTE: ignores mk_rews, termless and depth of 2nd mss*)
berghofe@10413
   303
berghofe@10413
   304
fun merge_mss
berghofe@10413
   305
 (Mss {rules = rules1, congs = (congs1,weak1), procs = procs1,
nipkow@11504
   306
       bounds = bounds1, prems = prems1, mk_rews, termless, depth},
berghofe@10413
   307
  Mss {rules = rules2, congs = (congs2,weak2), procs = procs2,
berghofe@10413
   308
       bounds = bounds2, prems = prems2, ...}) =
berghofe@10413
   309
      mk_mss
berghofe@10413
   310
       (Net.merge (rules1, rules2, eq_rrule),
wenzelm@12285
   311
        (gen_merge_lists (eq_cong o pairself snd) congs1 congs2,
berghofe@10413
   312
        merge_lists weak1 weak2),
berghofe@10413
   313
        Net.merge (procs1, procs2, eq_simproc),
berghofe@10413
   314
        merge_lists bounds1 bounds2,
wenzelm@12285
   315
        gen_merge_lists eq_prem prems1 prems2,
nipkow@11504
   316
        mk_rews, termless, depth);
berghofe@10413
   317
berghofe@10413
   318
berghofe@10413
   319
(* add_simps *)
berghofe@10413
   320
berghofe@13607
   321
fun mk_rrule2{thm, name, lhs, elhs, perm} =
berghofe@10413
   322
  let val fo = Pattern.first_order (term_of elhs) orelse not(Pattern.pattern (term_of elhs))
berghofe@13607
   323
  in {thm=thm, name=name, lhs=lhs, elhs=elhs, fo=fo, perm=perm} end
berghofe@10413
   324
berghofe@13607
   325
fun insert_rrule quiet (mss as Mss {rules,...},
berghofe@13607
   326
                 rrule as {thm,name,lhs,elhs,perm}) =
berghofe@13607
   327
  (trace_named_thm "Adding rewrite rule" (thm, name);
berghofe@10413
   328
   let val rrule2 as {elhs,...} = mk_rrule2 rrule
berghofe@10413
   329
       val rules' = Net.insert_term ((term_of elhs, rrule2), rules, eq_rrule)
berghofe@10413
   330
   in upd_rules(mss,rules') end
berghofe@13607
   331
   handle Net.INSERT => if quiet then mss else
berghofe@10413
   332
     (prthm true "Ignoring duplicate rewrite rule:" thm; mss));
berghofe@10413
   333
berghofe@10413
   334
fun vperm (Var _, Var _) = true
berghofe@10413
   335
  | vperm (Abs (_, _, s), Abs (_, _, t)) = vperm (s, t)
berghofe@10413
   336
  | vperm (t1 $ t2, u1 $ u2) = vperm (t1, u1) andalso vperm (t2, u2)
berghofe@10413
   337
  | vperm (t, u) = (t = u);
berghofe@10413
   338
berghofe@10413
   339
fun var_perm (t, u) =
berghofe@10413
   340
  vperm (t, u) andalso eq_set (term_varnames t, term_varnames u);
berghofe@10413
   341
berghofe@10413
   342
(* FIXME: it seems that the conditions on extra variables are too liberal if
berghofe@10413
   343
prems are nonempty: does solving the prems really guarantee instantiation of
berghofe@10413
   344
all its Vars? Better: a dynamic check each time a rule is applied.
berghofe@10413
   345
*)
berghofe@10413
   346
fun rewrite_rule_extra_vars prems elhs erhs =
berghofe@10413
   347
  not (term_varnames erhs subset foldl add_term_varnames (term_varnames elhs, prems))
berghofe@10413
   348
  orelse
berghofe@10413
   349
  not ((term_tvars erhs) subset
berghofe@10413
   350
       (term_tvars elhs  union  List.concat(map term_tvars prems)));
berghofe@10413
   351
berghofe@10413
   352
(*Simple test for looping rewrite rules and stupid orientations*)
berghofe@10413
   353
fun reorient sign prems lhs rhs =
berghofe@10413
   354
   rewrite_rule_extra_vars prems lhs rhs
berghofe@10413
   355
  orelse
berghofe@10413
   356
   is_Var (head_of lhs)
berghofe@10413
   357
  orelse
berghofe@10413
   358
   (exists (apl (lhs, Logic.occs)) (rhs :: prems))
berghofe@10413
   359
  orelse
berghofe@10413
   360
   (null prems andalso
wenzelm@14643
   361
    Pattern.matches (Sign.tsig_of sign) (lhs, rhs))
berghofe@10413
   362
    (*the condition "null prems" is necessary because conditional rewrites
berghofe@10413
   363
      with extra variables in the conditions may terminate although
berghofe@10413
   364
      the rhs is an instance of the lhs. Example: ?m < ?n ==> f(?n) == f(?m)*)
berghofe@10413
   365
  orelse
berghofe@10413
   366
   (is_Const lhs andalso not(is_Const rhs))
berghofe@10413
   367
berghofe@10413
   368
fun decomp_simp thm =
berghofe@10413
   369
  let val {sign, prop, ...} = rep_thm thm;
berghofe@10413
   370
      val prems = Logic.strip_imp_prems prop;
berghofe@10413
   371
      val concl = Drule.strip_imp_concl (cprop_of thm);
berghofe@10413
   372
      val (lhs, rhs) = Drule.dest_equals concl handle TERM _ =>
berghofe@10413
   373
        raise SIMPLIFIER ("Rewrite rule not a meta-equality", thm)
berghofe@10413
   374
      val elhs = snd (Drule.dest_equals (cprop_of (Thm.eta_conversion lhs)));
berghofe@10413
   375
      val elhs = if elhs=lhs then lhs else elhs (* try to share *)
berghofe@10413
   376
      val erhs = Pattern.eta_contract (term_of rhs);
berghofe@10413
   377
      val perm = var_perm (term_of elhs, erhs) andalso not (term_of elhs aconv erhs)
berghofe@10413
   378
                 andalso not (is_Var (term_of elhs))
berghofe@10413
   379
  in (sign, prems, term_of lhs, elhs, term_of rhs, perm) end;
berghofe@10413
   380
wenzelm@12783
   381
fun decomp_simp' thm =
wenzelm@12979
   382
  let val (_, _, lhs, _, rhs, _) = decomp_simp thm in
wenzelm@12783
   383
    if Thm.nprems_of thm > 0 then raise SIMPLIFIER ("Bad conditional rewrite rule", thm)
wenzelm@12979
   384
    else (lhs, rhs)
wenzelm@12783
   385
  end;
wenzelm@12783
   386
berghofe@13607
   387
fun mk_eq_True (Mss{mk_rews={mk_eq_True,...},...}) (thm, name) =
berghofe@10413
   388
  case mk_eq_True thm of
berghofe@10413
   389
    None => []
berghofe@13607
   390
  | Some eq_True =>
berghofe@13607
   391
      let val (_,_,lhs,elhs,_,_) = decomp_simp eq_True
berghofe@13607
   392
      in [{thm=eq_True, name=name, lhs=lhs, elhs=elhs, perm=false}] end;
berghofe@10413
   393
berghofe@10413
   394
(* create the rewrite rule and possibly also the ==True variant,
berghofe@10413
   395
   in case there are extra vars on the rhs *)
berghofe@13607
   396
fun rrule_eq_True(thm,name,lhs,elhs,rhs,mss,thm2) =
berghofe@13607
   397
  let val rrule = {thm=thm, name=name, lhs=lhs, elhs=elhs, perm=false}
berghofe@10413
   398
  in if (term_varnames rhs)  subset (term_varnames lhs) andalso
berghofe@10413
   399
        (term_tvars rhs) subset (term_tvars lhs)
berghofe@10413
   400
     then [rrule]
berghofe@13607
   401
     else mk_eq_True mss (thm2, name) @ [rrule]
berghofe@10413
   402
  end;
berghofe@10413
   403
berghofe@13607
   404
fun mk_rrule mss (thm, name) =
berghofe@10413
   405
  let val (_,prems,lhs,elhs,rhs,perm) = decomp_simp thm
berghofe@13607
   406
  in if perm then [{thm=thm, name=name, lhs=lhs, elhs=elhs, perm=true}] else
berghofe@10413
   407
     (* weak test for loops: *)
berghofe@10413
   408
     if rewrite_rule_extra_vars prems lhs rhs orelse
berghofe@10413
   409
        is_Var (term_of elhs)
berghofe@13607
   410
     then mk_eq_True mss (thm, name)
berghofe@13607
   411
     else rrule_eq_True(thm,name,lhs,elhs,rhs,mss,thm)
berghofe@10413
   412
  end;
berghofe@10413
   413
berghofe@13607
   414
fun orient_rrule mss (thm, name) =
berghofe@10413
   415
  let val (sign,prems,lhs,elhs,rhs,perm) = decomp_simp thm
berghofe@13607
   416
  in if perm then [{thm=thm, name=name, lhs=lhs, elhs=elhs, perm=true}]
berghofe@10413
   417
     else if reorient sign prems lhs rhs
berghofe@10413
   418
          then if reorient sign prems rhs lhs
berghofe@13607
   419
               then mk_eq_True mss (thm, name)
berghofe@10413
   420
               else let val Mss{mk_rews={mk_sym,...},...} = mss
berghofe@10413
   421
                    in case mk_sym thm of
berghofe@10413
   422
                         None => []
berghofe@10413
   423
                       | Some thm' =>
berghofe@10413
   424
                           let val (_,_,lhs',elhs',rhs',_) = decomp_simp thm'
berghofe@13607
   425
                           in rrule_eq_True(thm',name,lhs',elhs',rhs',mss,thm) end
berghofe@10413
   426
                    end
berghofe@13607
   427
          else rrule_eq_True(thm,name,lhs,elhs,rhs,mss,thm)
berghofe@10413
   428
  end;
berghofe@10413
   429
berghofe@13607
   430
fun extract_rews(Mss{mk_rews = {mk,...},...},thms) =
berghofe@13607
   431
  flat (map (fn thm => map (rpair (Thm.name_of_thm thm)) (mk thm)) thms);
berghofe@10413
   432
berghofe@10413
   433
fun orient_comb_simps comb mk_rrule (mss,thms) =
berghofe@10413
   434
  let val rews = extract_rews(mss,thms)
berghofe@10413
   435
      val rrules = flat (map mk_rrule rews)
berghofe@10413
   436
  in foldl comb (mss,rrules) end
berghofe@10413
   437
berghofe@10413
   438
(* Add rewrite rules explicitly; do not reorient! *)
berghofe@10413
   439
fun add_simps(mss,thms) =
berghofe@13607
   440
  orient_comb_simps (insert_rrule false) (mk_rrule mss) (mss,thms);
berghofe@10413
   441
berghofe@13607
   442
fun mss_of thms = foldl (insert_rrule false) (empty_mss, flat
berghofe@13607
   443
  (map (fn thm => mk_rrule empty_mss (thm, Thm.name_of_thm thm)) thms));
berghofe@10413
   444
berghofe@10413
   445
fun extract_safe_rrules(mss,thm) =
berghofe@10413
   446
  flat (map (orient_rrule mss) (extract_rews(mss,[thm])));
berghofe@10413
   447
berghofe@10413
   448
(* del_simps *)
berghofe@10413
   449
berghofe@10413
   450
fun del_rrule(mss as Mss {rules,...},
berghofe@10413
   451
              rrule as {thm, elhs, ...}) =
berghofe@10413
   452
  (upd_rules(mss, Net.delete_term ((term_of elhs, rrule), rules, eq_rrule))
berghofe@10413
   453
   handle Net.DELETE =>
berghofe@10413
   454
     (prthm true "Rewrite rule not in simpset:" thm; mss));
berghofe@10413
   455
berghofe@10413
   456
fun del_simps(mss,thms) =
berghofe@10413
   457
  orient_comb_simps del_rrule (map mk_rrule2 o mk_rrule mss) (mss,thms);
berghofe@10413
   458
berghofe@10413
   459
berghofe@10413
   460
(* add_congs *)
berghofe@10413
   461
berghofe@10413
   462
fun is_full_cong_prems [] varpairs = null varpairs
berghofe@10413
   463
  | is_full_cong_prems (p::prems) varpairs =
berghofe@10413
   464
    (case Logic.strip_assums_concl p of
berghofe@10413
   465
       Const("==",_) $ lhs $ rhs =>
berghofe@10413
   466
         let val (x,xs) = strip_comb lhs and (y,ys) = strip_comb rhs
berghofe@10413
   467
         in is_Var x  andalso  forall is_Bound xs  andalso
berghofe@10413
   468
            null(findrep(xs))  andalso xs=ys andalso
berghofe@10413
   469
            (x,y) mem varpairs andalso
berghofe@10413
   470
            is_full_cong_prems prems (varpairs\(x,y))
berghofe@10413
   471
         end
berghofe@10413
   472
     | _ => false);
berghofe@10413
   473
berghofe@10413
   474
fun is_full_cong thm =
berghofe@10413
   475
let val prems = prems_of thm
berghofe@10413
   476
    and concl = concl_of thm
berghofe@10413
   477
    val (lhs,rhs) = Logic.dest_equals concl
berghofe@10413
   478
    val (f,xs) = strip_comb lhs
berghofe@10413
   479
    and (g,ys) = strip_comb rhs
berghofe@10413
   480
in
berghofe@10413
   481
  f=g andalso null(findrep(xs@ys)) andalso length xs = length ys andalso
berghofe@10413
   482
  is_full_cong_prems prems (xs ~~ ys)
berghofe@10413
   483
end
berghofe@10413
   484
ballarin@13835
   485
fun cong_name (Const (a, _)) = Some a
ballarin@13835
   486
  | cong_name (Free (a, _)) = Some ("Free: " ^ a)
ballarin@13835
   487
  | cong_name _ = None;
ballarin@13835
   488
nipkow@11504
   489
fun add_cong (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, thm) =
berghofe@10413
   490
  let
berghofe@10413
   491
    val (lhs, _) = Drule.dest_equals (Drule.strip_imp_concl (cprop_of thm)) handle TERM _ =>
berghofe@10413
   492
      raise SIMPLIFIER ("Congruence not a meta-equality", thm);
berghofe@10413
   493
(*   val lhs = Pattern.eta_contract lhs; *)
ballarin@13835
   494
    val a = (case cong_name (head_of (term_of lhs)) of
ballarin@13835
   495
        Some a => a
ballarin@13835
   496
      | None =>
ballarin@13835
   497
        raise SIMPLIFIER ("Congruence must start with a constant or free variable", thm));
berghofe@10413
   498
    val (alist,weak) = congs
berghofe@10413
   499
    val alist2 = overwrite_warn (alist, (a,{lhs=lhs, thm=thm}))
berghofe@10413
   500
           ("Overwriting congruence rule for " ^ quote a);
berghofe@10413
   501
    val weak2 = if is_full_cong thm then weak else a::weak
berghofe@10413
   502
  in
nipkow@11504
   503
    mk_mss (rules,(alist2,weak2),procs,bounds,prems,mk_rews,termless,depth)
berghofe@10413
   504
  end;
berghofe@10413
   505
berghofe@10413
   506
val (op add_congs) = foldl add_cong;
berghofe@10413
   507
berghofe@10413
   508
berghofe@10413
   509
(* del_congs *)
berghofe@10413
   510
nipkow@11504
   511
fun del_cong (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, thm) =
berghofe@10413
   512
  let
berghofe@10413
   513
    val (lhs, _) = Logic.dest_equals (concl_of thm) handle TERM _ =>
berghofe@10413
   514
      raise SIMPLIFIER ("Congruence not a meta-equality", thm);
berghofe@10413
   515
(*   val lhs = Pattern.eta_contract lhs; *)
ballarin@13835
   516
    val a = (case cong_name (head_of lhs) of
ballarin@13835
   517
        Some a => a
ballarin@13835
   518
      | None =>
ballarin@13835
   519
        raise SIMPLIFIER ("Congruence must start with a constant", thm));
berghofe@10413
   520
    val (alist,_) = congs
berghofe@10413
   521
    val alist2 = filter (fn (x,_)=> x<>a) alist
berghofe@10413
   522
    val weak2 = mapfilter (fn(a,{thm,...}) => if is_full_cong thm then None
berghofe@10413
   523
                                              else Some a)
berghofe@10413
   524
                   alist2
berghofe@10413
   525
  in
nipkow@11504
   526
    mk_mss (rules,(alist2,weak2),procs,bounds,prems,mk_rews,termless,depth)
berghofe@10413
   527
  end;
berghofe@10413
   528
berghofe@10413
   529
val (op del_congs) = foldl del_cong;
berghofe@10413
   530
berghofe@10413
   531
berghofe@10413
   532
(* add_simprocs *)
berghofe@10413
   533
nipkow@11504
   534
fun add_proc (mss as Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth},
berghofe@10413
   535
    (name, lhs, proc, id)) =
berghofe@10413
   536
  let val {sign, t, ...} = rep_cterm lhs
berghofe@10413
   537
  in (trace_term false ("Adding simplification procedure " ^ quote name ^ " for")
berghofe@10413
   538
      sign t;
berghofe@10413
   539
    mk_mss (rules, congs,
berghofe@10413
   540
      Net.insert_term ((t, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
wenzelm@12603
   541
        handle Net.INSERT =>
wenzelm@12603
   542
            (warning ("Ignoring duplicate simplification procedure \""
wenzelm@12603
   543
                      ^ name ^ "\"");
wenzelm@12603
   544
             procs),
nipkow@11504
   545
        bounds, prems, mk_rews, termless,depth))
berghofe@10413
   546
  end;
berghofe@10413
   547
berghofe@10413
   548
fun add_simproc (mss, (name, lhss, proc, id)) =
berghofe@10413
   549
  foldl add_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
berghofe@10413
   550
berghofe@10413
   551
val add_simprocs = foldl add_simproc;
berghofe@10413
   552
berghofe@10413
   553
berghofe@10413
   554
(* del_simprocs *)
berghofe@10413
   555
nipkow@11504
   556
fun del_proc (mss as Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth},
berghofe@10413
   557
    (name, lhs, proc, id)) =
berghofe@10413
   558
  mk_mss (rules, congs,
berghofe@10413
   559
    Net.delete_term ((term_of lhs, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
wenzelm@12603
   560
      handle Net.DELETE =>
wenzelm@12603
   561
          (warning ("Simplification procedure \"" ^ name ^
wenzelm@12603
   562
                       "\" not in simpset"); procs),
nipkow@11504
   563
      bounds, prems, mk_rews, termless, depth);
berghofe@10413
   564
berghofe@10413
   565
fun del_simproc (mss, (name, lhss, proc, id)) =
berghofe@10413
   566
  foldl del_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
berghofe@10413
   567
berghofe@10413
   568
val del_simprocs = foldl del_simproc;
berghofe@10413
   569
berghofe@10413
   570
berghofe@10413
   571
(* prems *)
berghofe@10413
   572
nipkow@11504
   573
fun add_prems (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, thms) =
nipkow@11504
   574
  mk_mss (rules, congs, procs, bounds, thms @ prems, mk_rews, termless, depth);
berghofe@10413
   575
berghofe@10413
   576
fun prems_of_mss (Mss {prems, ...}) = prems;
berghofe@10413
   577
berghofe@10413
   578
berghofe@10413
   579
(* mk_rews *)
berghofe@10413
   580
berghofe@10413
   581
fun set_mk_rews
nipkow@11504
   582
  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless, depth}, mk) =
berghofe@10413
   583
    mk_mss (rules, congs, procs, bounds, prems,
berghofe@10413
   584
            {mk=mk, mk_sym= #mk_sym mk_rews, mk_eq_True= #mk_eq_True mk_rews},
nipkow@11504
   585
            termless, depth);
berghofe@10413
   586
berghofe@10413
   587
fun set_mk_sym
nipkow@11504
   588
  (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, mk_sym) =
berghofe@10413
   589
    mk_mss (rules, congs, procs, bounds, prems,
berghofe@10413
   590
            {mk= #mk mk_rews, mk_sym= mk_sym, mk_eq_True= #mk_eq_True mk_rews},
nipkow@11504
   591
            termless,depth);
berghofe@10413
   592
berghofe@10413
   593
fun set_mk_eq_True
nipkow@11504
   594
  (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, mk_eq_True) =
berghofe@10413
   595
    mk_mss (rules, congs, procs, bounds, prems,
berghofe@10413
   596
            {mk= #mk mk_rews, mk_sym= #mk_sym mk_rews, mk_eq_True= mk_eq_True},
nipkow@11504
   597
            termless,depth);
berghofe@10413
   598
skalberg@14242
   599
fun get_mk_rews    (Mss {mk_rews,...}) = #mk         mk_rews
skalberg@14242
   600
fun get_mk_sym     (Mss {mk_rews,...}) = #mk_sym     mk_rews
skalberg@14242
   601
fun get_mk_eq_True (Mss {mk_rews,...}) = #mk_eq_True mk_rews
skalberg@14242
   602
berghofe@10413
   603
(* termless *)
berghofe@10413
   604
berghofe@10413
   605
fun set_termless
nipkow@11504
   606
  (Mss {rules, congs, procs, bounds, prems, mk_rews, depth, ...}, termless) =
nipkow@11504
   607
    mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless, depth);
berghofe@10413
   608
berghofe@10413
   609
berghofe@10413
   610
skalberg@15006
   611
(** simplification procedures **)
skalberg@15006
   612
skalberg@15006
   613
(* datatype simproc *)
skalberg@15006
   614
skalberg@15011
   615
fun full_mk_simproc name lhss proc =
skalberg@15011
   616
  Simproc (name, map (Thm.cterm_fun Logic.varify) lhss, proc, stamp ());
skalberg@15011
   617
skalberg@15011
   618
fun full_simproc sg name ss =
skalberg@15011
   619
  full_mk_simproc name (map (fn s => Thm.read_cterm sg (s, TypeInfer.logicT)) ss);
skalberg@15011
   620
fun full_simproc_i sg name = full_mk_simproc name o map (Thm.cterm_of sg);
skalberg@15006
   621
skalberg@15006
   622
fun mk_simproc name lhss proc =
skalberg@15011
   623
  Simproc (name, map (Thm.cterm_fun Logic.varify) lhss, K proc, stamp ());
skalberg@15006
   624
skalberg@15006
   625
fun simproc sg name ss =
skalberg@15006
   626
  mk_simproc name (map (fn s => Thm.read_cterm sg (s, TypeInfer.logicT)) ss);
skalberg@15006
   627
fun simproc_i sg name = mk_simproc name o map (Thm.cterm_of sg);
skalberg@15006
   628
skalberg@15006
   629
fun rep_simproc (Simproc args) = args;
skalberg@15006
   630
skalberg@15006
   631
skalberg@15006
   632
skalberg@15006
   633
(** solvers **)
skalberg@15006
   634
skalberg@15006
   635
fun mk_solver name solver = Solver (name, solver, stamp());
skalberg@15006
   636
fun eq_solver (Solver (_, _, s1), Solver(_, _, s2)) = s1 = s2;
skalberg@15006
   637
skalberg@15006
   638
val merge_solvers = gen_merge_lists eq_solver;
skalberg@15006
   639
skalberg@15006
   640
fun app_sols [] _ _ = no_tac
skalberg@15006
   641
  | app_sols (Solver(_,solver,_)::sols) thms i =
skalberg@15006
   642
       solver thms i ORELSE app_sols sols thms i;
skalberg@15006
   643
skalberg@15006
   644
skalberg@15006
   645
skalberg@15006
   646
(** simplification sets **)
skalberg@15006
   647
skalberg@15006
   648
(* type simpset *)
skalberg@15006
   649
skalberg@15006
   650
fun make_ss mss mk_cong subgoal_tac loop_tacs unsafe_solvers solvers =
skalberg@15006
   651
  Simpset {mss = mss, mk_cong = mk_cong, subgoal_tac = subgoal_tac,
skalberg@15006
   652
    loop_tacs = loop_tacs, unsafe_solvers = unsafe_solvers, solvers = solvers};
skalberg@15006
   653
skalberg@15011
   654
fun from_mss mss = make_ss mss I (K (K no_tac)) [] [] [];
skalberg@15011
   655
skalberg@15011
   656
val empty_ss = from_mss (set_mk_sym (empty_mss, Some o symmetric_fun));
skalberg@15006
   657
skalberg@15006
   658
fun rep_ss (Simpset args) = args;
skalberg@15006
   659
fun prems_of_ss (Simpset {mss, ...}) = prems_of_mss mss;
skalberg@15006
   660
skalberg@15006
   661
skalberg@15006
   662
(* print simpsets *)
skalberg@15006
   663
skalberg@15006
   664
fun print_ss ss =
skalberg@15006
   665
  let
skalberg@15006
   666
    val Simpset {mss, ...} = ss;
skalberg@15006
   667
    val {simps, procs, congs} = dest_mss mss;
skalberg@15006
   668
skalberg@15006
   669
    val pretty_thms = map Display.pretty_thm;
skalberg@15006
   670
    fun pretty_proc (name, lhss) =
skalberg@15006
   671
      Pretty.big_list (name ^ ":") (map Display.pretty_cterm lhss);
skalberg@15006
   672
  in
skalberg@15006
   673
    [Pretty.big_list "simplification rules:" (pretty_thms simps),
skalberg@15006
   674
      Pretty.big_list "simplification procedures:" (map pretty_proc procs),
skalberg@15006
   675
      Pretty.big_list "congruences:" (pretty_thms congs)]
skalberg@15006
   676
    |> Pretty.chunks |> Pretty.writeln
skalberg@15006
   677
  end;
skalberg@15006
   678
skalberg@15006
   679
skalberg@15006
   680
(* extend simpsets *)
skalberg@15006
   681
skalberg@15006
   682
fun (Simpset {mss, mk_cong, subgoal_tac = _, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   683
    setsubgoaler subgoal_tac =
skalberg@15006
   684
  make_ss mss mk_cong subgoal_tac loop_tacs unsafe_solvers solvers;
skalberg@15006
   685
skalberg@15006
   686
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs = _, unsafe_solvers, solvers})
skalberg@15006
   687
    setloop tac =
skalberg@15006
   688
  make_ss mss mk_cong subgoal_tac [("", tac)] unsafe_solvers solvers;
skalberg@15006
   689
skalberg@15006
   690
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   691
    addloop tac = make_ss mss mk_cong subgoal_tac
skalberg@15006
   692
      (case assoc_string (loop_tacs, (#1 tac)) of None => () | Some x =>
skalberg@15006
   693
        warning ("overwriting looper " ^ quote (#1 tac)); overwrite (loop_tacs, tac))
skalberg@15006
   694
      unsafe_solvers solvers;
skalberg@15006
   695
skalberg@15006
   696
fun (ss as Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   697
 delloop name =
skalberg@15006
   698
  let val (del, rest) = partition (fn (n, _) => n = name) loop_tacs in
skalberg@15006
   699
    if null del then (warning ("No such looper in simpset: " ^ name); ss)
skalberg@15006
   700
    else make_ss mss mk_cong subgoal_tac rest unsafe_solvers solvers
skalberg@15006
   701
  end;
skalberg@15006
   702
skalberg@15006
   703
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, ...})
skalberg@15006
   704
    setSSolver solver =
skalberg@15006
   705
  make_ss mss mk_cong subgoal_tac loop_tacs unsafe_solvers [solver];
skalberg@15006
   706
skalberg@15006
   707
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   708
    addSSolver sol =
skalberg@15006
   709
  make_ss mss mk_cong subgoal_tac loop_tacs unsafe_solvers (merge_solvers solvers [sol]);
skalberg@15006
   710
skalberg@15006
   711
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers = _, solvers})
skalberg@15006
   712
    setSolver unsafe_solver =
skalberg@15006
   713
  make_ss mss mk_cong subgoal_tac loop_tacs [unsafe_solver] solvers;
skalberg@15006
   714
skalberg@15006
   715
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   716
    addSolver sol =
skalberg@15006
   717
  make_ss mss mk_cong subgoal_tac loop_tacs (merge_solvers unsafe_solvers [sol]) solvers;
skalberg@15006
   718
skalberg@15006
   719
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   720
    setmksimps mk_simps =
skalberg@15006
   721
  make_ss (set_mk_rews (mss, mk_simps)) mk_cong subgoal_tac loop_tacs unsafe_solvers solvers;
skalberg@15006
   722
skalberg@15006
   723
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   724
    setmkeqTrue mk_eq_True =
skalberg@15006
   725
  make_ss (set_mk_eq_True (mss, mk_eq_True)) mk_cong subgoal_tac loop_tacs
skalberg@15006
   726
    unsafe_solvers solvers;
skalberg@15006
   727
skalberg@15006
   728
fun (Simpset {mss, mk_cong = _, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   729
    setmkcong mk_cong =
skalberg@15006
   730
  make_ss mss mk_cong subgoal_tac loop_tacs unsafe_solvers solvers;
skalberg@15006
   731
skalberg@15006
   732
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   733
    setmksym mksym =
skalberg@15006
   734
  make_ss (set_mk_sym (mss, mksym)) mk_cong subgoal_tac loop_tacs unsafe_solvers solvers;
skalberg@15006
   735
skalberg@15006
   736
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs,  unsafe_solvers, solvers})
skalberg@15006
   737
    settermless termless =
skalberg@15006
   738
  make_ss (set_termless (mss, termless)) mk_cong subgoal_tac loop_tacs
skalberg@15006
   739
    unsafe_solvers solvers;
skalberg@15006
   740
skalberg@15006
   741
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   742
    addsimps rews =
skalberg@15006
   743
  make_ss (add_simps (mss, rews)) mk_cong subgoal_tac loop_tacs unsafe_solvers solvers;
skalberg@15006
   744
skalberg@15006
   745
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   746
    delsimps rews =
skalberg@15006
   747
  make_ss (del_simps (mss, rews)) mk_cong subgoal_tac loop_tacs unsafe_solvers solvers;
skalberg@15006
   748
skalberg@15006
   749
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   750
    addeqcongs newcongs =
skalberg@15006
   751
  make_ss (add_congs (mss, newcongs)) mk_cong subgoal_tac loop_tacs unsafe_solvers solvers;
skalberg@15006
   752
skalberg@15006
   753
fun (Simpset {mss, subgoal_tac, mk_cong, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   754
    deleqcongs oldcongs =
skalberg@15006
   755
  make_ss (del_congs (mss, oldcongs)) mk_cong subgoal_tac loop_tacs unsafe_solvers solvers;
skalberg@15006
   756
skalberg@15006
   757
fun (ss as Simpset {mk_cong, ...}) addcongs newcongs =
skalberg@15006
   758
  ss addeqcongs map mk_cong newcongs;
skalberg@15006
   759
skalberg@15006
   760
fun (ss as Simpset {mk_cong, ...}) delcongs oldcongs =
skalberg@15006
   761
  ss deleqcongs map mk_cong oldcongs;
skalberg@15006
   762
skalberg@15006
   763
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   764
    addsimprocs simprocs =
skalberg@15006
   765
  make_ss (add_simprocs (mss, map rep_simproc simprocs)) mk_cong subgoal_tac loop_tacs
skalberg@15006
   766
    unsafe_solvers solvers;
skalberg@15006
   767
skalberg@15006
   768
fun (Simpset {mss, mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers})
skalberg@15006
   769
    delsimprocs simprocs =
skalberg@15006
   770
  make_ss (del_simprocs (mss, map rep_simproc simprocs)) mk_cong subgoal_tac
skalberg@15006
   771
    loop_tacs unsafe_solvers solvers;
skalberg@15006
   772
skalberg@15006
   773
fun clear_ss (Simpset {mss, mk_cong, subgoal_tac, loop_tacs = _, unsafe_solvers, solvers}) =
skalberg@15006
   774
  make_ss (clear_mss mss) mk_cong subgoal_tac [] unsafe_solvers solvers;
skalberg@15006
   775
skalberg@15006
   776
skalberg@15006
   777
(* merge simpsets *)
skalberg@15006
   778
skalberg@15006
   779
(*ignores subgoal_tac of 2nd simpset!*)
skalberg@15006
   780
skalberg@15006
   781
fun merge_ss
skalberg@15006
   782
   (Simpset {mss = mss1, mk_cong, loop_tacs = loop_tacs1, subgoal_tac,
skalberg@15006
   783
             unsafe_solvers = unsafe_solvers1, solvers = solvers1},
skalberg@15006
   784
    Simpset {mss = mss2, mk_cong = _, loop_tacs = loop_tacs2, subgoal_tac = _,
skalberg@15006
   785
             unsafe_solvers = unsafe_solvers2, solvers = solvers2}) =
skalberg@15006
   786
  make_ss (merge_mss (mss1, mss2)) mk_cong subgoal_tac
skalberg@15006
   787
    (merge_alists loop_tacs1 loop_tacs2)
skalberg@15006
   788
    (merge_solvers unsafe_solvers1 unsafe_solvers2)
skalberg@15006
   789
    (merge_solvers solvers1 solvers2);
skalberg@15006
   790
berghofe@10413
   791
(** rewriting **)
berghofe@10413
   792
berghofe@10413
   793
(*
berghofe@10413
   794
  Uses conversions, see:
berghofe@10413
   795
    L C Paulson, A higher-order implementation of rewriting,
berghofe@10413
   796
    Science of Computer Programming 3 (1983), pages 119-149.
berghofe@10413
   797
*)
berghofe@10413
   798
berghofe@10413
   799
val dest_eq = Drule.dest_equals o cprop_of;
berghofe@10413
   800
val lhs_of = fst o dest_eq;
berghofe@10413
   801
val rhs_of = snd o dest_eq;
berghofe@10413
   802
berghofe@10413
   803
fun check_conv msg thm thm' =
berghofe@10413
   804
  let
berghofe@10413
   805
    val thm'' = transitive thm (transitive
skalberg@15001
   806
      (symmetric (Drule.beta_eta_conversion (lhs_of thm'))) thm')
nipkow@13569
   807
  in (if msg then trace_thm "SUCCEEDED" thm' else (); Some thm'') end
berghofe@10413
   808
  handle THM _ =>
berghofe@10413
   809
    let val {sign, prop = _ $ _ $ prop0, ...} = rep_thm thm;
berghofe@10413
   810
    in
nipkow@13569
   811
      (trace_thm "Proved wrong thm (Check subgoaler?)" thm';
berghofe@10413
   812
       trace_term false "Should have proved:" sign prop0;
berghofe@10413
   813
       None)
berghofe@10413
   814
    end;
berghofe@10413
   815
berghofe@10413
   816
berghofe@10413
   817
(* mk_procrule *)
berghofe@10413
   818
berghofe@10413
   819
fun mk_procrule thm =
berghofe@10413
   820
  let val (_,prems,lhs,elhs,rhs,_) = decomp_simp thm
berghofe@10413
   821
  in if rewrite_rule_extra_vars prems lhs rhs
berghofe@10413
   822
     then (prthm true "Extra vars on rhs:" thm; [])
berghofe@13607
   823
     else [mk_rrule2{thm=thm, name="", lhs=lhs, elhs=elhs, perm=false}]
berghofe@10413
   824
  end;
berghofe@10413
   825
berghofe@10413
   826
berghofe@10413
   827
(* conversion to apply the meta simpset to a term *)
berghofe@10413
   828
berghofe@10413
   829
(* Since the rewriting strategy is bottom-up, we avoid re-normalizing already
berghofe@10413
   830
   normalized terms by carrying around the rhs of the rewrite rule just
berghofe@10413
   831
   applied. This is called the `skeleton'. It is decomposed in parallel
berghofe@10413
   832
   with the term. Once a Var is encountered, the corresponding term is
berghofe@10413
   833
   already in normal form.
berghofe@10413
   834
   skel0 is a dummy skeleton that is to enforce complete normalization.
berghofe@10413
   835
*)
berghofe@10413
   836
val skel0 = Bound 0;
berghofe@10413
   837
berghofe@10413
   838
(* Use rhs as skeleton only if the lhs does not contain unnormalized bits.
berghofe@10413
   839
   The latter may happen iff there are weak congruence rules for constants
berghofe@10413
   840
   in the lhs.
berghofe@10413
   841
*)
berghofe@10413
   842
fun uncond_skel((_,weak),(lhs,rhs)) =
berghofe@10413
   843
  if null weak then rhs (* optimization *)
berghofe@10413
   844
  else if exists_Const (fn (c,_) => c mem weak) lhs then skel0
berghofe@10413
   845
       else rhs;
berghofe@10413
   846
berghofe@10413
   847
(* Behaves like unconditional rule if rhs does not contain vars not in the lhs.
berghofe@10413
   848
   Otherwise those vars may become instantiated with unnormalized terms
berghofe@10413
   849
   while the premises are solved.
berghofe@10413
   850
*)
berghofe@10413
   851
fun cond_skel(args as (congs,(lhs,rhs))) =
berghofe@10413
   852
  if term_varnames rhs subset term_varnames lhs then uncond_skel(args)
berghofe@10413
   853
  else skel0;
berghofe@10413
   854
berghofe@10413
   855
(*
berghofe@10413
   856
  we try in order:
berghofe@10413
   857
    (1) beta reduction
berghofe@10413
   858
    (2) unconditional rewrite rules
berghofe@10413
   859
    (3) conditional rewrite rules
berghofe@10413
   860
    (4) simplification procedures
berghofe@10413
   861
berghofe@10413
   862
  IMPORTANT: rewrite rules must not introduce new Vars or TVars!
berghofe@10413
   863
berghofe@10413
   864
*)
berghofe@10413
   865
berghofe@10413
   866
fun rewritec (prover, signt, maxt)
skalberg@15011
   867
             (ss as Simpset{mss=mss as Mss{rules, procs, termless, prems, congs, depth,...},...}) t =
berghofe@10413
   868
  let
berghofe@10413
   869
    val eta_thm = Thm.eta_conversion t;
berghofe@10413
   870
    val eta_t' = rhs_of eta_thm;
berghofe@10413
   871
    val eta_t = term_of eta_t';
berghofe@10413
   872
    val tsigt = Sign.tsig_of signt;
berghofe@13607
   873
    fun rew {thm, name, lhs, elhs, fo, perm} =
berghofe@10413
   874
      let
berghofe@10413
   875
        val {sign, prop, maxidx, ...} = rep_thm thm;
berghofe@10413
   876
        val _ = if Sign.subsig (sign, signt) then ()
berghofe@10413
   877
                else (prthm true "Ignoring rewrite rule from different theory:" thm;
berghofe@10413
   878
                      raise Pattern.MATCH);
berghofe@10413
   879
        val (rthm, elhs') = if maxt = ~1 then (thm, elhs)
berghofe@10413
   880
          else (Thm.incr_indexes (maxt+1) thm, Thm.cterm_incr_indexes (maxt+1) elhs);
berghofe@10413
   881
        val insts = if fo then Thm.cterm_first_order_match (elhs', eta_t')
berghofe@10413
   882
                          else Thm.cterm_match (elhs', eta_t');
berghofe@10413
   883
        val thm' = Thm.instantiate insts (Thm.rename_boundvars lhs eta_t rthm);
wenzelm@14643
   884
        val prop' = Thm.prop_of thm';
berghofe@10413
   885
        val unconditional = (Logic.count_prems (prop',0) = 0);
berghofe@10413
   886
        val (lhs', rhs') = Logic.dest_equals (Logic.strip_imp_concl prop')
berghofe@10413
   887
      in
nipkow@11295
   888
        if perm andalso not (termless (rhs', lhs'))
berghofe@13607
   889
        then (trace_named_thm "Cannot apply permutative rewrite rule" (thm, name);
nipkow@13569
   890
              trace_thm "Term does not become smaller:" thm'; None)
berghofe@13607
   891
        else (trace_named_thm "Applying instance of rewrite rule" (thm, name);
berghofe@10413
   892
           if unconditional
berghofe@10413
   893
           then
nipkow@13569
   894
             (trace_thm "Rewriting:" thm';
berghofe@10413
   895
              let val lr = Logic.dest_equals prop;
berghofe@10413
   896
                  val Some thm'' = check_conv false eta_thm thm'
berghofe@10413
   897
              in Some (thm'', uncond_skel (congs, lr)) end)
berghofe@10413
   898
           else
nipkow@13569
   899
             (trace_thm "Trying to rewrite:" thm';
nipkow@13828
   900
              case incr_depth mss of
nipkow@13828
   901
                None => (trace_thm "FAILED - reached depth limit" thm'; None)
nipkow@13828
   902
              | Some mss =>
nipkow@13828
   903
              (case prover mss thm' of
nipkow@13569
   904
                None       => (trace_thm "FAILED" thm'; None)
berghofe@10413
   905
              | Some thm2 =>
berghofe@10413
   906
                  (case check_conv true eta_thm thm2 of
berghofe@10413
   907
                     None => None |
berghofe@10413
   908
                     Some thm2' =>
berghofe@10413
   909
                       let val concl = Logic.strip_imp_concl prop
berghofe@10413
   910
                           val lr = Logic.dest_equals concl
nipkow@13828
   911
                       in Some (thm2', cond_skel (congs, lr)) end))))
berghofe@10413
   912
      end
berghofe@10413
   913
berghofe@10413
   914
    fun rews [] = None
berghofe@10413
   915
      | rews (rrule :: rrules) =
berghofe@10413
   916
          let val opt = rew rrule handle Pattern.MATCH => None
berghofe@10413
   917
          in case opt of None => rews rrules | some => some end;
berghofe@10413
   918
berghofe@10413
   919
    fun sort_rrules rrs = let
wenzelm@14643
   920
      fun is_simple({thm, ...}:rrule) = case Thm.prop_of thm of
berghofe@10413
   921
                                      Const("==",_) $ _ $ _ => true
wenzelm@12603
   922
                                      | _                   => false
berghofe@10413
   923
      fun sort []        (re1,re2) = re1 @ re2
wenzelm@12603
   924
        | sort (rr::rrs) (re1,re2) = if is_simple rr
berghofe@10413
   925
                                     then sort rrs (rr::re1,re2)
berghofe@10413
   926
                                     else sort rrs (re1,rr::re2)
berghofe@10413
   927
    in sort rrs ([],[]) end
berghofe@10413
   928
skalberg@15006
   929
    fun proc_rews ([]:meta_simproc list) = None
berghofe@10413
   930
      | proc_rews ({name, proc, lhs, ...} :: ps) =
berghofe@10413
   931
          if Pattern.matches tsigt (term_of lhs, term_of t) then
berghofe@10413
   932
            (debug_term false ("Trying procedure " ^ quote name ^ " on:") signt eta_t;
wenzelm@13486
   933
             case transform_failure (curry SIMPROC_FAIL name)
skalberg@15011
   934
                 (fn () => proc ss signt prems eta_t) () of
wenzelm@13486
   935
               None => (debug false "FAILED"; proc_rews ps)
wenzelm@13486
   936
             | Some raw_thm =>
nipkow@13569
   937
                 (trace_thm ("Procedure " ^ quote name ^ " produced rewrite rule:") raw_thm;
berghofe@10413
   938
                  (case rews (mk_procrule raw_thm) of
wenzelm@13486
   939
                    None => (trace_cterm true ("IGNORED result of simproc " ^ quote name ^
wenzelm@13486
   940
                      " -- does not match") t; proc_rews ps)
berghofe@10413
   941
                  | some => some)))
berghofe@10413
   942
          else proc_rews ps;
berghofe@10413
   943
  in case eta_t of
berghofe@10413
   944
       Abs _ $ _ => Some (transitive eta_thm
berghofe@12155
   945
         (beta_conversion false eta_t'), skel0)
berghofe@10413
   946
     | _ => (case rews (sort_rrules (Net.match_term rules eta_t)) of
berghofe@10413
   947
               None => proc_rews (Net.match_term procs eta_t)
berghofe@10413
   948
             | some => some)
berghofe@10413
   949
  end;
berghofe@10413
   950
berghofe@10413
   951
berghofe@10413
   952
(* conversion to apply a congruence rule to a term *)
berghofe@10413
   953
berghofe@10413
   954
fun congc (prover,signt,maxt) {thm=cong,lhs=lhs} t =
wenzelm@14643
   955
  let val sign = Thm.sign_of_thm cong
berghofe@10413
   956
      val _ = if Sign.subsig (sign, signt) then ()
berghofe@10413
   957
                 else error("Congruence rule from different theory")
berghofe@10413
   958
      val rthm = if maxt = ~1 then cong else Thm.incr_indexes (maxt+1) cong;
berghofe@10413
   959
      val rlhs = fst (Drule.dest_equals (Drule.strip_imp_concl (cprop_of rthm)));
berghofe@10413
   960
      val insts = Thm.cterm_match (rlhs, t)
berghofe@10413
   961
      (* Pattern.match can raise Pattern.MATCH;
berghofe@10413
   962
         is handled when congc is called *)
berghofe@10413
   963
      val thm' = Thm.instantiate insts (Thm.rename_boundvars (term_of rlhs) (term_of t) rthm);
nipkow@13569
   964
      val unit = trace_thm "Applying congruence rule:" thm';
ballarin@13932
   965
      fun err (msg, thm) = (trace_thm msg thm; None)
berghofe@10413
   966
  in case prover thm' of
ballarin@13932
   967
       None => err ("Congruence proof failed.  Could not prove", thm')
skalberg@15001
   968
     | Some thm2 => (case check_conv true (Drule.beta_eta_conversion t) thm2 of
ballarin@13932
   969
          None => err ("Congruence proof failed.  Should not have proved", thm2)
berghofe@12155
   970
        | Some thm2' =>
berghofe@12155
   971
            if op aconv (pairself term_of (dest_equals (cprop_of thm2')))
berghofe@12155
   972
            then None else Some thm2')
berghofe@10413
   973
  end;
berghofe@10413
   974
berghofe@10413
   975
val (cA, (cB, cC)) =
berghofe@10413
   976
  apsnd dest_equals (dest_implies (hd (cprems_of Drule.imp_cong)));
berghofe@10413
   977
berghofe@13607
   978
fun transitive1 None None = None
berghofe@13607
   979
  | transitive1 (Some thm1) None = Some thm1
berghofe@13607
   980
  | transitive1 None (Some thm2) = Some thm2
berghofe@13607
   981
  | transitive1 (Some thm1) (Some thm2) = Some (transitive thm1 thm2)
berghofe@10413
   982
berghofe@13607
   983
fun transitive2 thm = transitive1 (Some thm);
berghofe@13607
   984
fun transitive3 thm = transitive1 thm o Some;
berghofe@13607
   985
skalberg@15011
   986
fun replace_mss (Simpset{mss=_,mk_cong,subgoal_tac,loop_tacs,unsafe_solvers,solvers}) mss_new =
skalberg@15011
   987
    Simpset{mss=mss_new,mk_cong=mk_cong,subgoal_tac=subgoal_tac,loop_tacs=loop_tacs,
skalberg@15011
   988
	    unsafe_solvers=unsafe_solvers,solvers=solvers};
skalberg@15011
   989
skalberg@15011
   990
fun bottomc ((simprem,useprem,mutsimp), prover, sign, maxidx) (ss as Simpset{mss,...}) =
berghofe@10413
   991
  let
berghofe@10413
   992
    fun botc skel mss t =
berghofe@10413
   993
          if is_Var skel then None
berghofe@10413
   994
          else
berghofe@10413
   995
          (case subc skel mss t of
berghofe@10413
   996
             some as Some thm1 =>
skalberg@15011
   997
               (case rewritec (prover, sign, maxidx) (replace_mss ss mss) (rhs_of thm1) of
berghofe@10413
   998
                  Some (thm2, skel2) =>
berghofe@13607
   999
                    transitive2 (transitive thm1 thm2)
berghofe@10413
  1000
                      (botc skel2 mss (rhs_of thm2))
berghofe@10413
  1001
                | None => some)
berghofe@10413
  1002
           | None =>
skalberg@15011
  1003
               (case rewritec (prover, sign, maxidx) (replace_mss ss mss) t of
berghofe@13607
  1004
                  Some (thm2, skel2) => transitive2 thm2
berghofe@10413
  1005
                    (botc skel2 mss (rhs_of thm2))
berghofe@10413
  1006
                | None => None))
berghofe@10413
  1007
berghofe@10413
  1008
    and try_botc mss t =
berghofe@10413
  1009
          (case botc skel0 mss t of
berghofe@10413
  1010
             Some trec1 => trec1 | None => (reflexive t))
berghofe@10413
  1011
berghofe@10413
  1012
    and subc skel
nipkow@11504
  1013
          (mss as Mss{rules,congs,procs,bounds,prems,mk_rews,termless,depth}) t0 =
berghofe@10413
  1014
       (case term_of t0 of
berghofe@10413
  1015
           Abs (a, T, t) =>
berghofe@10413
  1016
             let val b = variant bounds a
wenzelm@10767
  1017
                 val (v, t') = Thm.dest_abs (Some ("." ^ b)) t0
nipkow@11504
  1018
                 val mss' = mk_mss (rules, congs, procs, b :: bounds, prems, mk_rews, termless,depth)
berghofe@10413
  1019
                 val skel' = case skel of Abs (_, _, sk) => sk | _ => skel0
berghofe@10413
  1020
             in case botc skel' mss' t' of
berghofe@10413
  1021
                  Some thm => Some (abstract_rule a v thm)
berghofe@10413
  1022
                | None => None
berghofe@10413
  1023
             end
berghofe@10413
  1024
         | t $ _ => (case t of
berghofe@13614
  1025
             Const ("==>", _) $ _  => impc t0 mss
berghofe@10413
  1026
           | Abs _ =>
berghofe@10413
  1027
               let val thm = beta_conversion false t0
berghofe@10413
  1028
               in case subc skel0 mss (rhs_of thm) of
berghofe@10413
  1029
                    None => Some thm
berghofe@10413
  1030
                  | Some thm' => Some (transitive thm thm')
berghofe@10413
  1031
               end
berghofe@10413
  1032
           | _  =>
berghofe@10413
  1033
               let fun appc () =
berghofe@10413
  1034
                     let
berghofe@10413
  1035
                       val (tskel, uskel) = case skel of
berghofe@10413
  1036
                           tskel $ uskel => (tskel, uskel)
berghofe@10413
  1037
                         | _ => (skel0, skel0);
wenzelm@10767
  1038
                       val (ct, cu) = Thm.dest_comb t0
berghofe@10413
  1039
                     in
berghofe@10413
  1040
                     (case botc tskel mss ct of
berghofe@10413
  1041
                        Some thm1 =>
berghofe@10413
  1042
                          (case botc uskel mss cu of
berghofe@10413
  1043
                             Some thm2 => Some (combination thm1 thm2)
berghofe@10413
  1044
                           | None => Some (combination thm1 (reflexive cu)))
berghofe@10413
  1045
                      | None =>
berghofe@10413
  1046
                          (case botc uskel mss cu of
berghofe@10413
  1047
                             Some thm1 => Some (combination (reflexive ct) thm1)
berghofe@10413
  1048
                           | None => None))
berghofe@10413
  1049
                     end
berghofe@10413
  1050
                   val (h, ts) = strip_comb t
ballarin@13835
  1051
               in case cong_name h of
ballarin@13835
  1052
                    Some a =>
berghofe@10413
  1053
                      (case assoc_string (fst congs, a) of
berghofe@10413
  1054
                         None => appc ()
berghofe@10413
  1055
                       | Some cong =>
berghofe@10413
  1056
(* post processing: some partial applications h t1 ... tj, j <= length ts,
berghofe@10413
  1057
   may be a redex. Example: map (%x.x) = (%xs.xs) wrt map_cong *)
berghofe@10413
  1058
                          (let
berghofe@10413
  1059
                             val thm = congc (prover mss, sign, maxidx) cong t0;
berghofe@12155
  1060
                             val t = if_none (apsome rhs_of thm) t0;
wenzelm@10767
  1061
                             val (cl, cr) = Thm.dest_comb t
berghofe@10413
  1062
                             val dVar = Var(("", 0), dummyT)
berghofe@10413
  1063
                             val skel =
berghofe@10413
  1064
                               list_comb (h, replicate (length ts) dVar)
berghofe@10413
  1065
                           in case botc skel mss cl of
berghofe@12155
  1066
                                None => thm
berghofe@13607
  1067
                              | Some thm' => transitive3 thm
berghofe@12155
  1068
                                  (combination thm' (reflexive cr))
berghofe@10413
  1069
                           end handle TERM _ => error "congc result"
berghofe@10413
  1070
                                    | Pattern.MATCH => appc ()))
berghofe@10413
  1071
                  | _ => appc ()
berghofe@10413
  1072
               end)
berghofe@10413
  1073
         | _ => None)
berghofe@10413
  1074
berghofe@13607
  1075
    and impc ct mss =
berghofe@13607
  1076
      if mutsimp then mut_impc0 [] ct [] [] mss else nonmut_impc ct mss
berghofe@10413
  1077
berghofe@13607
  1078
    and rules_of_prem mss prem =
berghofe@13607
  1079
      if maxidx_of_term (term_of prem) <> ~1
berghofe@13607
  1080
      then (trace_cterm true
berghofe@13607
  1081
        "Cannot add premise as rewrite rule because it contains (type) unknowns:" prem; ([], None))
berghofe@13607
  1082
      else
berghofe@13607
  1083
        let val asm = assume prem
berghofe@13607
  1084
        in (extract_safe_rrules (mss, asm), Some asm) end
berghofe@10413
  1085
berghofe@13607
  1086
    and add_rrules (rrss, asms) mss =
berghofe@13607
  1087
      add_prems (foldl (insert_rrule true) (mss, flat rrss), mapfilter I asms)
berghofe@10413
  1088
berghofe@13607
  1089
    and disch r (prem, eq) =
berghofe@13607
  1090
      let
berghofe@13607
  1091
        val (lhs, rhs) = dest_eq eq;
berghofe@13607
  1092
        val eq' = implies_elim (Thm.instantiate
berghofe@13607
  1093
          ([], [(cA, prem), (cB, lhs), (cC, rhs)]) Drule.imp_cong)
berghofe@13607
  1094
          (implies_intr prem eq)
berghofe@13607
  1095
      in if not r then eq' else
berghofe@10413
  1096
        let
berghofe@13607
  1097
          val (prem', concl) = dest_implies lhs;
berghofe@13607
  1098
          val (prem'', _) = dest_implies rhs
berghofe@13607
  1099
        in transitive (transitive
berghofe@13607
  1100
          (Thm.instantiate ([], [(cA, prem'), (cB, prem), (cC, concl)])
berghofe@13607
  1101
             Drule.swap_prems_eq) eq')
berghofe@13607
  1102
          (Thm.instantiate ([], [(cA, prem), (cB, prem''), (cC, concl)])
berghofe@13607
  1103
             Drule.swap_prems_eq)
berghofe@10413
  1104
        end
berghofe@10413
  1105
      end
berghofe@10413
  1106
berghofe@13607
  1107
    and rebuild [] _ _ _ _ eq = eq
berghofe@13607
  1108
      | rebuild (prem :: prems) concl (rrs :: rrss) (asm :: asms) mss eq =
berghofe@13607
  1109
          let
berghofe@13607
  1110
            val mss' = add_rrules (rev rrss, rev asms) mss;
berghofe@13607
  1111
            val concl' =
berghofe@13607
  1112
              Drule.mk_implies (prem, if_none (apsome rhs_of eq) concl);
berghofe@13607
  1113
            val dprem = apsome (curry (disch false) prem)
skalberg@15011
  1114
          in case rewritec (prover, sign, maxidx) (replace_mss ss mss') concl' of
berghofe@13607
  1115
              None => rebuild prems concl' rrss asms mss (dprem eq)
berghofe@13607
  1116
            | Some (eq', _) => transitive2 (foldl (disch false o swap)
berghofe@13607
  1117
                  (the (transitive3 (dprem eq) eq'), prems))
berghofe@13607
  1118
                (mut_impc0 (rev prems) (rhs_of eq') (rev rrss) (rev asms) mss)
berghofe@13607
  1119
          end
berghofe@13607
  1120
          
berghofe@13607
  1121
    and mut_impc0 prems concl rrss asms mss =
berghofe@13607
  1122
      let
berghofe@13607
  1123
        val prems' = strip_imp_prems concl;
berghofe@13607
  1124
        val (rrss', asms') = split_list (map (rules_of_prem mss) prems')
berghofe@13607
  1125
      in mut_impc (prems @ prems') (strip_imp_concl concl) (rrss @ rrss')
berghofe@13607
  1126
        (asms @ asms') [] [] [] [] mss ~1 ~1
berghofe@13607
  1127
      end
berghofe@13607
  1128
 
berghofe@13607
  1129
    and mut_impc [] concl [] [] prems' rrss' asms' eqns mss changed k =
berghofe@13607
  1130
        transitive1 (foldl (fn (eq2, (eq1, prem)) => transitive1 eq1
berghofe@13607
  1131
            (apsome (curry (disch false) prem) eq2)) (None, eqns ~~ prems'))
berghofe@13607
  1132
          (if changed > 0 then
berghofe@13607
  1133
             mut_impc (rev prems') concl (rev rrss') (rev asms')
berghofe@13607
  1134
               [] [] [] [] mss ~1 changed
berghofe@13607
  1135
           else rebuild prems' concl rrss' asms' mss
berghofe@13607
  1136
             (botc skel0 (add_rrules (rev rrss', rev asms') mss) concl))
berghofe@13607
  1137
berghofe@13607
  1138
      | mut_impc (prem :: prems) concl (rrs :: rrss) (asm :: asms)
berghofe@13607
  1139
          prems' rrss' asms' eqns mss changed k =
berghofe@13607
  1140
        case (if k = 0 then None else botc skel0 (add_rrules
berghofe@13607
  1141
          (rev rrss' @ rrss, rev asms' @ asms) mss) prem) of
berghofe@13607
  1142
            None => mut_impc prems concl rrss asms (prem :: prems')
berghofe@13607
  1143
              (rrs :: rrss') (asm :: asms') (None :: eqns) mss changed
berghofe@13607
  1144
              (if k = 0 then 0 else k - 1)
berghofe@13607
  1145
          | Some eqn =>
berghofe@13607
  1146
            let
berghofe@13607
  1147
              val prem' = rhs_of eqn;
berghofe@13607
  1148
              val tprems = map term_of prems;
berghofe@13607
  1149
              val i = 1 + foldl Int.max (~1, map (fn p =>
berghofe@13607
  1150
                find_index_eq p tprems) (#hyps (rep_thm eqn)));
berghofe@13607
  1151
              val (rrs', asm') = rules_of_prem mss prem'
berghofe@13607
  1152
            in mut_impc prems concl rrss asms (prem' :: prems')
berghofe@13607
  1153
              (rrs' :: rrss') (asm' :: asms') (Some (foldr (disch true)
skalberg@15001
  1154
                (take (i, prems), Drule.imp_cong' eqn (reflexive (Drule.list_implies
berghofe@13607
  1155
                  (drop (i, prems), concl))))) :: eqns) mss (length prems') ~1
berghofe@13607
  1156
            end
berghofe@13607
  1157
berghofe@10413
  1158
     (* legacy code - only for backwards compatibility *)
berghofe@13607
  1159
     and nonmut_impc ct mss =
berghofe@13607
  1160
       let val (prem, conc) = dest_implies ct;
berghofe@13607
  1161
           val thm1 = if simprem then botc skel0 mss prem else None;
berghofe@10413
  1162
           val prem1 = if_none (apsome rhs_of thm1) prem;
berghofe@13607
  1163
           val mss1 = if not useprem then mss else add_rrules
berghofe@13607
  1164
             (apsnd single (apfst single (rules_of_prem mss prem1))) mss
berghofe@10413
  1165
       in (case botc skel0 mss1 conc of
berghofe@10413
  1166
           None => (case thm1 of
berghofe@10413
  1167
               None => None
skalberg@15001
  1168
             | Some thm1' => Some (Drule.imp_cong' thm1' (reflexive conc)))
berghofe@10413
  1169
         | Some thm2 =>
berghofe@13607
  1170
           let val thm2' = disch false (prem1, thm2)
berghofe@10413
  1171
           in (case thm1 of
berghofe@10413
  1172
               None => Some thm2'
berghofe@13607
  1173
             | Some thm1' =>
skalberg@15001
  1174
                 Some (transitive (Drule.imp_cong' thm1' (reflexive conc)) thm2'))
berghofe@10413
  1175
           end)
berghofe@10413
  1176
       end
berghofe@10413
  1177
skalberg@15011
  1178
 in try_botc mss end;
berghofe@10413
  1179
berghofe@10413
  1180
berghofe@10413
  1181
(*** Meta-rewriting: rewrites t to u and returns the theorem t==u ***)
berghofe@10413
  1182
berghofe@10413
  1183
(*
berghofe@10413
  1184
  Parameters:
berghofe@10413
  1185
    mode = (simplify A,
berghofe@10413
  1186
            use A in simplifying B,
berghofe@10413
  1187
            use prems of B (if B is again a meta-impl.) to simplify A)
berghofe@10413
  1188
           when simplifying A ==> B
berghofe@10413
  1189
    mss: contains equality theorems of the form [|p1,...|] ==> t==u
berghofe@10413
  1190
    prover: how to solve premises in conditional rewrites and congruences
berghofe@10413
  1191
*)
berghofe@10413
  1192
skalberg@15011
  1193
fun rewrite_cterm mode prover (ss as Simpset{mss,...}) ct =
berghofe@10413
  1194
  let val {sign, t, maxidx, ...} = rep_cterm ct
nipkow@11505
  1195
      val Mss{depth, ...} = mss
nipkow@14330
  1196
  in trace_cterm false "SIMPLIFIER INVOKED ON THE FOLLOWING TERM:" ct;
nipkow@14330
  1197
     simp_depth := depth;
skalberg@15011
  1198
     bottomc (mode, prover, sign, maxidx) ss ct
nipkow@11505
  1199
  end
berghofe@10413
  1200
  handle THM (s, _, thms) =>
berghofe@10413
  1201
    error ("Exception THM was raised in simplifier:\n" ^ s ^ "\n" ^
wenzelm@11886
  1202
      Pretty.string_of (Display.pretty_thms thms));
berghofe@10413
  1203
skalberg@15011
  1204
val ss_of = from_mss o mss_of
skalberg@15011
  1205
wenzelm@11760
  1206
(*Rewrite a cterm*)
wenzelm@11767
  1207
fun rewrite_aux _ _ [] = (fn ct => Thm.reflexive ct)
skalberg@15011
  1208
  | rewrite_aux prover full thms = rewrite_cterm (full, false, false) prover (ss_of thms);
wenzelm@11672
  1209
berghofe@10413
  1210
(*Rewrite a theorem*)
wenzelm@11767
  1211
fun simplify_aux _ _ [] = (fn th => th)
wenzelm@11767
  1212
  | simplify_aux prover full thms =
skalberg@15011
  1213
      Drule.fconv_rule (rewrite_cterm (full, false, false) prover (ss_of thms));
berghofe@10413
  1214
skalberg@15001
  1215
fun rewrite_thm mode prover mss = Drule.fconv_rule (rewrite_cterm mode prover mss);
berghofe@10413
  1216
berghofe@10413
  1217
(*Rewrite the subgoals of a proof state (represented by a theorem) *)
berghofe@10413
  1218
fun rewrite_goals_rule_aux _ []   th = th
berghofe@10413
  1219
  | rewrite_goals_rule_aux prover thms th =
skalberg@15001
  1220
      Drule.fconv_rule (Drule.goals_conv (K true) (rewrite_cterm (true, true, false) prover
skalberg@15011
  1221
        (ss_of thms))) th;
berghofe@10413
  1222
berghofe@10413
  1223
(*Rewrite the subgoal of a proof state (represented by a theorem) *)
skalberg@15011
  1224
fun rewrite_goal_rule mode prover ss i thm =
berghofe@10413
  1225
  if 0 < i  andalso  i <= nprems_of thm
skalberg@15011
  1226
  then Drule.fconv_rule (Drule.goals_conv (fn j => j=i) (rewrite_cterm mode prover ss)) thm
berghofe@10413
  1227
  else raise THM("rewrite_goal_rule",i,[thm]);
berghofe@10413
  1228
wenzelm@12783
  1229
wenzelm@12783
  1230
(*simple term rewriting -- without proofs*)
berghofe@13196
  1231
fun rewrite_term sg rules procs =
berghofe@13196
  1232
  Pattern.rewrite_term (Sign.tsig_of sg) (map decomp_simp' rules) procs;
wenzelm@12783
  1233
skalberg@15006
  1234
(*Rewrite subgoal i only.  SELECT_GOAL avoids inefficiencies in goals_conv.*)
skalberg@15006
  1235
fun asm_rewrite_goal_tac mode prover_tac mss =
skalberg@15006
  1236
  SELECT_GOAL
skalberg@15006
  1237
    (PRIMITIVE (rewrite_goal_rule mode (SINGLE o prover_tac) mss 1));
skalberg@15006
  1238
skalberg@15006
  1239
(** simplification tactics **)
skalberg@15006
  1240
skalberg@15006
  1241
fun solve_all_tac (mk_cong, subgoal_tac, loop_tacs, unsafe_solvers) mss =
skalberg@15006
  1242
  let
skalberg@15006
  1243
    val ss =
skalberg@15006
  1244
      make_ss mss mk_cong subgoal_tac loop_tacs unsafe_solvers unsafe_solvers;
skalberg@15006
  1245
    val solve1_tac = (subgoal_tac ss THEN_ALL_NEW (K no_tac)) 1
skalberg@15006
  1246
  in DEPTH_SOLVE solve1_tac end;
skalberg@15006
  1247
skalberg@15006
  1248
fun loop_tac loop_tacs = FIRST'(map snd loop_tacs);
skalberg@15006
  1249
skalberg@15006
  1250
(*note: may instantiate unknowns that appear also in other subgoals*)
skalberg@15006
  1251
fun generic_simp_tac safe mode =
skalberg@15011
  1252
  fn (ss as Simpset {mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, solvers, ...}) =>
skalberg@15006
  1253
    let
skalberg@15006
  1254
      val solvs = app_sols (if safe then solvers else unsafe_solvers);
skalberg@15006
  1255
      fun simp_loop_tac i =
skalberg@15006
  1256
        asm_rewrite_goal_tac mode
skalberg@15006
  1257
          (solve_all_tac (mk_cong, subgoal_tac, loop_tacs, unsafe_solvers))
skalberg@15011
  1258
          ss i
skalberg@15011
  1259
        THEN (solvs (prems_of_ss ss) i ORELSE
skalberg@15006
  1260
              TRY ((loop_tac loop_tacs THEN_ALL_NEW simp_loop_tac) i))
skalberg@15006
  1261
    in simp_loop_tac end;
skalberg@15006
  1262
skalberg@15006
  1263
(** simplification rules and conversions **)
skalberg@15006
  1264
skalberg@15006
  1265
fun simp rew mode
skalberg@15011
  1266
     (ss as Simpset {mk_cong, subgoal_tac, loop_tacs, unsafe_solvers, ...}) thm =
skalberg@15006
  1267
  let
skalberg@15006
  1268
    val tacf = solve_all_tac (mk_cong, subgoal_tac, loop_tacs, unsafe_solvers);
skalberg@15006
  1269
    fun prover m th = apsome fst (Seq.pull (tacf m th));
skalberg@15011
  1270
  in rew mode prover ss thm end;
skalberg@15006
  1271
skalberg@15006
  1272
val simp_thm = simp rewrite_thm;
skalberg@15006
  1273
val simp_cterm = simp rewrite_cterm;
skalberg@15006
  1274
berghofe@10413
  1275
end;
berghofe@10413
  1276
wenzelm@11672
  1277
structure BasicMetaSimplifier: BASIC_META_SIMPLIFIER = MetaSimplifier;
wenzelm@11672
  1278
open BasicMetaSimplifier;