src/Pure/raw_simplifier.ML
author wenzelm
Wed Sep 02 20:14:19 2015 +0200 (2015-09-02)
changeset 61090 16f7f9aa4263
parent 61057 5f6a1e31f3ad
child 61095 50e793295ce1
permissions -rw-r--r--
more thorough transfer;
wenzelm@41228
     1
(*  Title:      Pure/raw_simplifier.ML
wenzelm@29269
     2
    Author:     Tobias Nipkow and Stefan Berghofer, TU Muenchen
berghofe@10413
     3
wenzelm@41228
     4
Higher-order Simplification.
berghofe@10413
     5
*)
berghofe@10413
     6
skalberg@15006
     7
infix 4
wenzelm@45620
     8
  addsimps delsimps addsimprocs delsimprocs
wenzelm@52037
     9
  setloop addloop delloop
wenzelm@45625
    10
  setSSolver addSSolver setSolver addSolver;
skalberg@15006
    11
wenzelm@41228
    12
signature BASIC_RAW_SIMPLIFIER =
wenzelm@11672
    13
sig
wenzelm@41227
    14
  val simp_depth_limit: int Config.T
wenzelm@41227
    15
  val simp_trace_depth_limit: int Config.T
wenzelm@40878
    16
  val simp_debug: bool Config.T
wenzelm@40878
    17
  val simp_trace: bool Config.T
wenzelm@51590
    18
  type cong_name = bool * string
wenzelm@15023
    19
  type rrule
lars@55316
    20
  val mk_rrules: Proof.context -> thm list -> rrule list
wenzelm@16807
    21
  val eq_rrule: rrule * rrule -> bool
wenzelm@15023
    22
  type proc
wenzelm@17614
    23
  type solver
wenzelm@51717
    24
  val mk_solver: string -> (Proof.context -> int -> tactic) -> solver
wenzelm@51717
    25
  type simpset
wenzelm@15023
    26
  val empty_ss: simpset
wenzelm@15023
    27
  val merge_ss: simpset * simpset -> simpset
wenzelm@30356
    28
  val dest_ss: simpset ->
wenzelm@30356
    29
   {simps: (string * thm) list,
wenzelm@30356
    30
    procs: (string * cterm list) list,
wenzelm@51590
    31
    congs: (cong_name * thm) list,
wenzelm@51590
    32
    weak_congs: cong_name list,
wenzelm@30356
    33
    loopers: string list,
wenzelm@30356
    34
    unsafe_solvers: string list,
wenzelm@30356
    35
    safe_solvers: string list}
wenzelm@15023
    36
  type simproc
wenzelm@22234
    37
  val eq_simproc: simproc * simproc -> bool
wenzelm@45290
    38
  val transform_simproc: morphism -> simproc -> simproc
wenzelm@22234
    39
  val make_simproc: {name: string, lhss: cterm list,
wenzelm@51717
    40
    proc: morphism -> Proof.context -> cterm -> thm option, identifier: thm list} -> simproc
wenzelm@51717
    41
  val mk_simproc: string -> cterm list -> (Proof.context -> term -> thm option) -> simproc
wenzelm@51717
    42
  val simpset_of: Proof.context -> simpset
wenzelm@51717
    43
  val put_simpset: simpset -> Proof.context -> Proof.context
wenzelm@51717
    44
  val simpset_map: Proof.context -> (Proof.context -> Proof.context) -> simpset -> simpset
wenzelm@51717
    45
  val map_theory_simpset: (Proof.context -> Proof.context) -> theory -> theory
wenzelm@51717
    46
  val empty_simpset: Proof.context -> Proof.context
wenzelm@51717
    47
  val clear_simpset: Proof.context -> Proof.context
wenzelm@51717
    48
  val addsimps: Proof.context * thm list -> Proof.context
wenzelm@51717
    49
  val delsimps: Proof.context * thm list -> Proof.context
wenzelm@51717
    50
  val addsimprocs: Proof.context * simproc list -> Proof.context
wenzelm@51717
    51
  val delsimprocs: Proof.context * simproc list -> Proof.context
wenzelm@52037
    52
  val setloop: Proof.context * (Proof.context -> int -> tactic) -> Proof.context
wenzelm@52037
    53
  val addloop: Proof.context * (string * (Proof.context -> int -> tactic)) -> Proof.context
wenzelm@51717
    54
  val delloop: Proof.context * string -> Proof.context
wenzelm@51717
    55
  val setSSolver: Proof.context * solver -> Proof.context
wenzelm@51717
    56
  val addSSolver: Proof.context * solver -> Proof.context
wenzelm@51717
    57
  val setSolver: Proof.context * solver -> Proof.context
wenzelm@51717
    58
  val addSolver: Proof.context * solver -> Proof.context
wenzelm@21708
    59
wenzelm@54742
    60
  val rewrite_rule: Proof.context -> thm list -> thm -> thm
wenzelm@54742
    61
  val rewrite_goals_rule: Proof.context -> thm list -> thm -> thm
wenzelm@54742
    62
  val rewrite_goals_tac: Proof.context -> thm list -> tactic
wenzelm@54742
    63
  val rewrite_goal_tac: Proof.context -> thm list -> int -> tactic
wenzelm@54742
    64
  val prune_params_tac: Proof.context -> tactic
wenzelm@54742
    65
  val fold_rule: Proof.context -> thm list -> thm -> thm
wenzelm@54742
    66
  val fold_goals_tac: Proof.context -> thm list -> tactic
wenzelm@54883
    67
  val norm_hhf: Proof.context -> thm -> thm
wenzelm@54883
    68
  val norm_hhf_protect: Proof.context -> thm -> thm
skalberg@15006
    69
end;
skalberg@15006
    70
wenzelm@41228
    71
signature RAW_SIMPLIFIER =
berghofe@10413
    72
sig
wenzelm@41228
    73
  include BASIC_RAW_SIMPLIFIER
wenzelm@54997
    74
  exception SIMPLIFIER of string * thm list
wenzelm@54729
    75
  type trace_ops
wenzelm@54731
    76
  val set_trace_ops: trace_ops -> theory -> theory
wenzelm@30336
    77
  val internal_ss: simpset ->
wenzelm@51590
    78
   {congs: (cong_name * thm) list * cong_name list,
wenzelm@30336
    79
    procs: proc Net.net,
wenzelm@30336
    80
    mk_rews:
wenzelm@51717
    81
     {mk: Proof.context -> thm -> thm list,
wenzelm@51717
    82
      mk_cong: Proof.context -> thm -> thm,
wenzelm@51717
    83
      mk_sym: Proof.context -> thm -> thm option,
wenzelm@51717
    84
      mk_eq_True: Proof.context -> thm -> thm option,
wenzelm@51717
    85
      reorient: Proof.context -> term list -> term -> term -> bool},
wenzelm@30336
    86
    termless: term * term -> bool,
wenzelm@51717
    87
    subgoal_tac: Proof.context -> int -> tactic,
wenzelm@51717
    88
    loop_tacs: (string * (Proof.context -> int -> tactic)) list,
wenzelm@54731
    89
    solvers: solver list * solver list}
wenzelm@51717
    90
  val map_ss: (Proof.context -> Proof.context) -> Context.generic -> Context.generic
wenzelm@51717
    91
  val prems_of: Proof.context -> thm list
wenzelm@51717
    92
  val add_simp: thm -> Proof.context -> Proof.context
wenzelm@51717
    93
  val del_simp: thm -> Proof.context -> Proof.context
wenzelm@51717
    94
  val add_eqcong: thm -> Proof.context -> Proof.context
wenzelm@51717
    95
  val del_eqcong: thm -> Proof.context -> Proof.context
wenzelm@51717
    96
  val add_cong: thm -> Proof.context -> Proof.context
wenzelm@51717
    97
  val del_cong: thm -> Proof.context -> Proof.context
wenzelm@51717
    98
  val mksimps: Proof.context -> thm -> thm list
wenzelm@51717
    99
  val set_mksimps: (Proof.context -> thm -> thm list) -> Proof.context -> Proof.context
wenzelm@51717
   100
  val set_mkcong: (Proof.context -> thm -> thm) -> Proof.context -> Proof.context
wenzelm@51717
   101
  val set_mksym: (Proof.context -> thm -> thm option) -> Proof.context -> Proof.context
wenzelm@51717
   102
  val set_mkeqTrue: (Proof.context -> thm -> thm option) -> Proof.context -> Proof.context
wenzelm@51717
   103
  val set_termless: (term * term -> bool) -> Proof.context -> Proof.context
wenzelm@51717
   104
  val set_subgoaler: (Proof.context -> int -> tactic) -> Proof.context -> Proof.context
wenzelm@51717
   105
  val solver: Proof.context -> solver -> int -> tactic
wenzelm@39163
   106
  val simp_depth_limit_raw: Config.raw
wenzelm@51717
   107
  val default_mk_sym: Proof.context -> thm -> thm option
wenzelm@51717
   108
  val simproc_global_i: theory -> string -> term list ->
wenzelm@51717
   109
    (Proof.context -> term -> thm option) -> simproc
wenzelm@51717
   110
  val simproc_global: theory -> string -> string list ->
wenzelm@51717
   111
    (Proof.context -> term -> thm option) -> simproc
wenzelm@41227
   112
  val simp_trace_depth_limit_raw: Config.raw
wenzelm@41227
   113
  val simp_trace_raw: Config.raw
wenzelm@41227
   114
  val simp_debug_raw: Config.raw
wenzelm@51717
   115
  val add_prems: thm list -> Proof.context -> Proof.context
wenzelm@51717
   116
  val set_reorient: (Proof.context -> term list -> term -> term -> bool) ->
wenzelm@51717
   117
    Proof.context -> Proof.context
wenzelm@51717
   118
  val set_solvers: solver list -> Proof.context -> Proof.context
wenzelm@51717
   119
  val rewrite_cterm: bool * bool * bool ->
wenzelm@51717
   120
    (Proof.context -> thm -> thm option) -> Proof.context -> conv
wenzelm@16458
   121
  val rewrite_term: theory -> thm list -> (term -> term option) list -> term -> term
wenzelm@15023
   122
  val rewrite_thm: bool * bool * bool ->
wenzelm@51717
   123
    (Proof.context -> thm -> thm option) -> Proof.context -> thm -> thm
wenzelm@46465
   124
  val generic_rewrite_goal_tac: bool * bool * bool ->
wenzelm@51717
   125
    (Proof.context -> tactic) -> Proof.context -> int -> tactic
wenzelm@54742
   126
  val rewrite: Proof.context -> bool -> thm list -> conv
berghofe@10413
   127
end;
berghofe@10413
   128
wenzelm@41228
   129
structure Raw_Simplifier: RAW_SIMPLIFIER =
berghofe@10413
   130
struct
berghofe@10413
   131
wenzelm@15023
   132
(** datatype simpset **)
wenzelm@15023
   133
wenzelm@51590
   134
(* congruence rules *)
wenzelm@51590
   135
wenzelm@51590
   136
type cong_name = bool * string;
wenzelm@51590
   137
wenzelm@51590
   138
fun cong_name (Const (a, _)) = SOME (true, a)
wenzelm@51590
   139
  | cong_name (Free (a, _)) = SOME (false, a)
wenzelm@51590
   140
  | cong_name _ = NONE;
wenzelm@51590
   141
wenzelm@51590
   142
wenzelm@15023
   143
(* rewrite rules *)
berghofe@10413
   144
wenzelm@20546
   145
type rrule =
wenzelm@20546
   146
 {thm: thm,         (*the rewrite rule*)
wenzelm@20546
   147
  name: string,     (*name of theorem from which rewrite rule was extracted*)
wenzelm@20546
   148
  lhs: term,        (*the left-hand side*)
wenzelm@58836
   149
  elhs: cterm,      (*the eta-contracted lhs*)
wenzelm@20546
   150
  extra: bool,      (*extra variables outside of elhs*)
wenzelm@20546
   151
  fo: bool,         (*use first-order matching*)
wenzelm@20546
   152
  perm: bool};      (*the rewrite rule is permutative*)
wenzelm@15023
   153
wenzelm@61057
   154
fun trim_context_rrule ({thm, name, lhs, elhs, extra, fo, perm}: rrule) =
wenzelm@61057
   155
  {thm = Thm.trim_context thm, name = name, lhs = lhs, elhs = Thm.trim_context_cterm elhs,
wenzelm@61057
   156
    extra = extra, fo = fo, perm = perm};
wenzelm@61057
   157
wenzelm@20546
   158
(*
wenzelm@12603
   159
Remarks:
berghofe@10413
   160
  - elhs is used for matching,
wenzelm@15023
   161
    lhs only for preservation of bound variable names;
berghofe@10413
   162
  - fo is set iff
berghofe@10413
   163
    either elhs is first-order (no Var is applied),
wenzelm@15023
   164
      in which case fo-matching is complete,
berghofe@10413
   165
    or elhs is not a pattern,
wenzelm@20546
   166
      in which case there is nothing better to do;
wenzelm@20546
   167
*)
berghofe@10413
   168
berghofe@10413
   169
fun eq_rrule ({thm = thm1, ...}: rrule, {thm = thm2, ...}: rrule) =
wenzelm@22360
   170
  Thm.eq_thm_prop (thm1, thm2);
wenzelm@15023
   171
wenzelm@20546
   172
(* FIXME: it seems that the conditions on extra variables are too liberal if
wenzelm@20546
   173
prems are nonempty: does solving the prems really guarantee instantiation of
wenzelm@20546
   174
all its Vars? Better: a dynamic check each time a rule is applied.
wenzelm@20546
   175
*)
wenzelm@20546
   176
fun rewrite_rule_extra_vars prems elhs erhs =
wenzelm@20546
   177
  let
wenzelm@20546
   178
    val elhss = elhs :: prems;
wenzelm@20546
   179
    val tvars = fold Term.add_tvars elhss [];
wenzelm@20546
   180
    val vars = fold Term.add_vars elhss [];
wenzelm@20546
   181
  in
wenzelm@20546
   182
    erhs |> Term.exists_type (Term.exists_subtype
wenzelm@20546
   183
      (fn TVar v => not (member (op =) tvars v) | _ => false)) orelse
wenzelm@20546
   184
    erhs |> Term.exists_subterm
wenzelm@20546
   185
      (fn Var v => not (member (op =) vars v) | _ => false)
wenzelm@20546
   186
  end;
wenzelm@20546
   187
wenzelm@20546
   188
fun rrule_extra_vars elhs thm =
wenzelm@59582
   189
  rewrite_rule_extra_vars [] (Thm.term_of elhs) (Thm.full_prop_of thm);
wenzelm@20546
   190
wenzelm@15023
   191
fun mk_rrule2 {thm, name, lhs, elhs, perm} =
wenzelm@15023
   192
  let
wenzelm@59582
   193
    val t = Thm.term_of elhs;
wenzelm@20546
   194
    val fo = Pattern.first_order t orelse not (Pattern.pattern t);
wenzelm@20546
   195
    val extra = rrule_extra_vars elhs thm;
wenzelm@20546
   196
  in {thm = thm, name = name, lhs = lhs, elhs = elhs, extra = extra, fo = fo, perm = perm} end;
berghofe@10413
   197
wenzelm@15023
   198
(*simple test for looping rewrite rules and stupid orientations*)
wenzelm@51717
   199
fun default_reorient ctxt prems lhs rhs =
wenzelm@15023
   200
  rewrite_rule_extra_vars prems lhs rhs
wenzelm@15023
   201
    orelse
wenzelm@15023
   202
  is_Var (head_of lhs)
wenzelm@15023
   203
    orelse
nipkow@16305
   204
(* turns t = x around, which causes a headache if x is a local variable -
nipkow@16305
   205
   usually it is very useful :-(
nipkow@16305
   206
  is_Free rhs andalso not(is_Free lhs) andalso not(Logic.occs(rhs,lhs))
nipkow@16305
   207
  andalso not(exists_subterm is_Var lhs)
nipkow@16305
   208
    orelse
nipkow@16305
   209
*)
wenzelm@16842
   210
  exists (fn t => Logic.occs (lhs, t)) (rhs :: prems)
wenzelm@15023
   211
    orelse
wenzelm@51717
   212
  null prems andalso Pattern.matches (Proof_Context.theory_of ctxt) (lhs, rhs)
berghofe@10413
   213
    (*the condition "null prems" is necessary because conditional rewrites
berghofe@10413
   214
      with extra variables in the conditions may terminate although
wenzelm@15023
   215
      the rhs is an instance of the lhs; example: ?m < ?n ==> f(?n) == f(?m)*)
wenzelm@15023
   216
    orelse
wenzelm@15023
   217
  is_Const lhs andalso not (is_Const rhs);
berghofe@10413
   218
wenzelm@51717
   219
wenzelm@51717
   220
(* simplification procedures *)
wenzelm@51717
   221
wenzelm@51717
   222
datatype proc =
wenzelm@51717
   223
  Proc of
wenzelm@51717
   224
   {name: string,
wenzelm@51717
   225
    lhs: cterm,
wenzelm@51717
   226
    proc: Proof.context -> cterm -> thm option,
wenzelm@51717
   227
    id: stamp * thm list};
wenzelm@51717
   228
wenzelm@51717
   229
fun eq_procid ((s1: stamp, ths1: thm list), (s2, ths2)) =
wenzelm@51717
   230
  s1 = s2 andalso eq_list Thm.eq_thm (ths1, ths2);
wenzelm@51717
   231
wenzelm@51717
   232
fun eq_proc (Proc {id = id1, ...}, Proc {id = id2, ...}) = eq_procid (id1, id2);
wenzelm@51717
   233
wenzelm@51717
   234
wenzelm@51717
   235
(* solvers *)
wenzelm@51717
   236
wenzelm@51717
   237
datatype solver =
wenzelm@51717
   238
  Solver of
wenzelm@51717
   239
   {name: string,
wenzelm@51717
   240
    solver: Proof.context -> int -> tactic,
wenzelm@51717
   241
    id: stamp};
wenzelm@51717
   242
wenzelm@51717
   243
fun mk_solver name solver = Solver {name = name, solver = solver, id = stamp ()};
wenzelm@51717
   244
wenzelm@51717
   245
fun solver_name (Solver {name, ...}) = name;
wenzelm@51717
   246
fun solver ctxt (Solver {solver = tac, ...}) = tac ctxt;
wenzelm@51717
   247
fun eq_solver (Solver {id = id1, ...}, Solver {id = id2, ...}) = (id1 = id2);
wenzelm@51717
   248
wenzelm@51717
   249
wenzelm@51717
   250
(* simplification sets *)
wenzelm@51717
   251
wenzelm@51717
   252
(*A simpset contains data required during conversion:
wenzelm@51717
   253
    rules: discrimination net of rewrite rules;
wenzelm@51717
   254
    prems: current premises;
wenzelm@51717
   255
    depth: simp_depth and exceeded flag;
wenzelm@51717
   256
    congs: association list of congruence rules and
wenzelm@51717
   257
           a list of `weak' congruence constants.
wenzelm@51717
   258
           A congruence is `weak' if it avoids normalization of some argument.
wenzelm@51717
   259
    procs: discrimination net of simplification procedures
wenzelm@51717
   260
      (functions that prove rewrite rules on the fly);
wenzelm@51717
   261
    mk_rews:
wenzelm@51717
   262
      mk: turn simplification thms into rewrite rules;
wenzelm@51717
   263
      mk_cong: prepare congruence rules;
wenzelm@51717
   264
      mk_sym: turn == around;
wenzelm@51717
   265
      mk_eq_True: turn P into P == True;
wenzelm@51717
   266
    termless: relation for ordered rewriting;*)
wenzelm@51717
   267
wenzelm@51717
   268
datatype simpset =
wenzelm@51717
   269
  Simpset of
wenzelm@51717
   270
   {rules: rrule Net.net,
wenzelm@51717
   271
    prems: thm list,
wenzelm@51717
   272
    depth: int * bool Unsynchronized.ref} *
wenzelm@51717
   273
   {congs: (cong_name * thm) list * cong_name list,
wenzelm@51717
   274
    procs: proc Net.net,
wenzelm@51717
   275
    mk_rews:
wenzelm@51717
   276
     {mk: Proof.context -> thm -> thm list,
wenzelm@51717
   277
      mk_cong: Proof.context -> thm -> thm,
wenzelm@51717
   278
      mk_sym: Proof.context -> thm -> thm option,
wenzelm@51717
   279
      mk_eq_True: Proof.context -> thm -> thm option,
wenzelm@51717
   280
      reorient: Proof.context -> term list -> term -> term -> bool},
wenzelm@51717
   281
    termless: term * term -> bool,
wenzelm@51717
   282
    subgoal_tac: Proof.context -> int -> tactic,
wenzelm@51717
   283
    loop_tacs: (string * (Proof.context -> int -> tactic)) list,
wenzelm@54731
   284
    solvers: solver list * solver list};
wenzelm@51717
   285
wenzelm@54728
   286
fun internal_ss (Simpset (_, ss2)) = ss2;
wenzelm@51717
   287
wenzelm@55014
   288
fun make_ss1 (rules, prems, depth) = {rules = rules, prems = prems, depth = depth};
wenzelm@51717
   289
wenzelm@55014
   290
fun map_ss1 f {rules, prems, depth} = make_ss1 (f (rules, prems, depth));
wenzelm@51717
   291
wenzelm@54731
   292
fun make_ss2 (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =
wenzelm@51717
   293
  {congs = congs, procs = procs, mk_rews = mk_rews, termless = termless,
wenzelm@54731
   294
    subgoal_tac = subgoal_tac, loop_tacs = loop_tacs, solvers = solvers};
wenzelm@51717
   295
wenzelm@54731
   296
fun map_ss2 f {congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers} =
wenzelm@54731
   297
  make_ss2 (f (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers));
wenzelm@51717
   298
wenzelm@51717
   299
fun make_simpset (args1, args2) = Simpset (make_ss1 args1, make_ss2 args2);
wenzelm@51717
   300
wenzelm@51717
   301
fun dest_ss (Simpset ({rules, ...}, {congs, procs, loop_tacs, solvers, ...})) =
wenzelm@51717
   302
 {simps = Net.entries rules
wenzelm@51717
   303
    |> map (fn {name, thm, ...} => (name, thm)),
wenzelm@51717
   304
  procs = Net.entries procs
wenzelm@51717
   305
    |> map (fn Proc {name, lhs, id, ...} => ((name, lhs), id))
wenzelm@51717
   306
    |> partition_eq (eq_snd eq_procid)
wenzelm@51717
   307
    |> map (fn ps => (fst (fst (hd ps)), map (snd o fst) ps)),
wenzelm@51717
   308
  congs = #1 congs,
wenzelm@51717
   309
  weak_congs = #2 congs,
wenzelm@51717
   310
  loopers = map fst loop_tacs,
wenzelm@51717
   311
  unsafe_solvers = map solver_name (#1 solvers),
wenzelm@51717
   312
  safe_solvers = map solver_name (#2 solvers)};
wenzelm@51717
   313
wenzelm@51717
   314
wenzelm@51717
   315
(* empty *)
wenzelm@51717
   316
wenzelm@55014
   317
fun init_ss depth mk_rews termless subgoal_tac solvers =
wenzelm@55014
   318
  make_simpset ((Net.empty, [], depth),
wenzelm@54731
   319
    (([], []), Net.empty, mk_rews, termless, subgoal_tac, [], solvers));
wenzelm@51717
   320
wenzelm@51717
   321
fun default_mk_sym _ th = SOME (th RS Drule.symmetric_thm);
wenzelm@51717
   322
wenzelm@51717
   323
val empty_ss =
wenzelm@55014
   324
  init_ss (0, Unsynchronized.ref false)
wenzelm@51717
   325
    {mk = fn _ => fn th => if can Logic.dest_equals (Thm.concl_of th) then [th] else [],
wenzelm@51717
   326
      mk_cong = K I,
wenzelm@51717
   327
      mk_sym = default_mk_sym,
wenzelm@51717
   328
      mk_eq_True = K (K NONE),
wenzelm@51717
   329
      reorient = default_reorient}
wenzelm@54731
   330
    Term_Ord.termless (K (K no_tac)) ([], []);
wenzelm@51717
   331
wenzelm@51717
   332
wenzelm@51717
   333
(* merge *)  (*NOTE: ignores some fields of 2nd simpset*)
wenzelm@51717
   334
wenzelm@51717
   335
fun merge_ss (ss1, ss2) =
wenzelm@51717
   336
  if pointer_eq (ss1, ss2) then ss1
wenzelm@51717
   337
  else
wenzelm@51717
   338
    let
wenzelm@55014
   339
      val Simpset ({rules = rules1, prems = prems1, depth = depth1},
wenzelm@51717
   340
       {congs = (congs1, weak1), procs = procs1, mk_rews, termless, subgoal_tac,
wenzelm@54731
   341
        loop_tacs = loop_tacs1, solvers = (unsafe_solvers1, solvers1)}) = ss1;
wenzelm@55014
   342
      val Simpset ({rules = rules2, prems = prems2, depth = depth2},
wenzelm@51717
   343
       {congs = (congs2, weak2), procs = procs2, mk_rews = _, termless = _, subgoal_tac = _,
wenzelm@54731
   344
        loop_tacs = loop_tacs2, solvers = (unsafe_solvers2, solvers2)}) = ss2;
wenzelm@51717
   345
wenzelm@51717
   346
      val rules' = Net.merge eq_rrule (rules1, rules2);
wenzelm@51717
   347
      val prems' = Thm.merge_thms (prems1, prems2);
wenzelm@51717
   348
      val depth' = if #1 depth1 < #1 depth2 then depth2 else depth1;
wenzelm@59058
   349
      val congs' = merge (Thm.eq_thm_prop o apply2 #2) (congs1, congs2);
wenzelm@51717
   350
      val weak' = merge (op =) (weak1, weak2);
wenzelm@51717
   351
      val procs' = Net.merge eq_proc (procs1, procs2);
wenzelm@51717
   352
      val loop_tacs' = AList.merge (op =) (K true) (loop_tacs1, loop_tacs2);
wenzelm@51717
   353
      val unsafe_solvers' = merge eq_solver (unsafe_solvers1, unsafe_solvers2);
wenzelm@51717
   354
      val solvers' = merge eq_solver (solvers1, solvers2);
wenzelm@51717
   355
    in
wenzelm@55014
   356
      make_simpset ((rules', prems', depth'), ((congs', weak'), procs',
wenzelm@54731
   357
        mk_rews, termless, subgoal_tac, loop_tacs', (unsafe_solvers', solvers')))
wenzelm@51717
   358
    end;
wenzelm@51717
   359
wenzelm@51717
   360
wenzelm@51717
   361
wenzelm@51717
   362
(** context data **)
wenzelm@51717
   363
wenzelm@51717
   364
structure Simpset = Generic_Data
wenzelm@51717
   365
(
wenzelm@51717
   366
  type T = simpset;
wenzelm@51717
   367
  val empty = empty_ss;
wenzelm@51717
   368
  val extend = I;
wenzelm@51717
   369
  val merge = merge_ss;
wenzelm@51717
   370
);
wenzelm@51717
   371
wenzelm@51717
   372
val simpset_of = Simpset.get o Context.Proof;
wenzelm@51717
   373
wenzelm@51717
   374
fun map_simpset f = Context.proof_map (Simpset.map f);
wenzelm@51717
   375
fun map_simpset1 f = map_simpset (fn Simpset (ss1, ss2) => Simpset (map_ss1 f ss1, ss2));
wenzelm@51717
   376
fun map_simpset2 f = map_simpset (fn Simpset (ss1, ss2) => Simpset (ss1, map_ss2 f ss2));
wenzelm@51717
   377
wenzelm@51717
   378
fun simpset_map ctxt f ss = ctxt |> map_simpset (K ss) |> f |> Context.Proof |> Simpset.get;
wenzelm@51717
   379
wenzelm@55377
   380
fun put_simpset ss = map_simpset (K ss);
wenzelm@51717
   381
wenzelm@51717
   382
val empty_simpset = put_simpset empty_ss;
wenzelm@51717
   383
wenzelm@51717
   384
fun map_theory_simpset f thy =
wenzelm@51717
   385
  let
wenzelm@51717
   386
    val ctxt' = f (Proof_Context.init_global thy);
wenzelm@51717
   387
    val thy' = Proof_Context.theory_of ctxt';
wenzelm@51717
   388
  in Context.theory_map (Simpset.map (K (simpset_of ctxt'))) thy' end;
wenzelm@51717
   389
wenzelm@57859
   390
fun map_ss f = Context.mapping (map_theory_simpset (f o Context_Position.not_really)) f;
wenzelm@51717
   391
wenzelm@51717
   392
val clear_simpset =
wenzelm@55014
   393
  map_simpset (fn Simpset ({depth, ...}, {mk_rews, termless, subgoal_tac, solvers, ...}) =>
wenzelm@55014
   394
    init_ss depth mk_rews termless subgoal_tac solvers);
wenzelm@51717
   395
wenzelm@51717
   396
wenzelm@51717
   397
(* simp depth *)
wenzelm@51717
   398
wenzelm@56438
   399
val simp_depth_limit_raw = Config.declare ("simp_depth_limit", @{here}) (K (Config.Int 100));
wenzelm@51717
   400
val simp_depth_limit = Config.int simp_depth_limit_raw;
wenzelm@51717
   401
wenzelm@56438
   402
val simp_trace_depth_limit_raw =
wenzelm@58859
   403
  Config.declare ("simp_trace_depth_limit", @{here}) (fn _ => Config.Int 1);
wenzelm@51717
   404
val simp_trace_depth_limit = Config.int simp_trace_depth_limit_raw;
wenzelm@51717
   405
wenzelm@51717
   406
fun inc_simp_depth ctxt =
wenzelm@55014
   407
  ctxt |> map_simpset1 (fn (rules, prems, (depth, exceeded)) =>
wenzelm@55014
   408
    (rules, prems,
wenzelm@51717
   409
      (depth + 1,
wenzelm@51717
   410
        if depth = Config.get ctxt simp_trace_depth_limit
wenzelm@51717
   411
        then Unsynchronized.ref false else exceeded)));
wenzelm@51717
   412
wenzelm@51717
   413
fun simp_depth ctxt =
wenzelm@51717
   414
  let val Simpset ({depth = (depth, _), ...}, _) = simpset_of ctxt
wenzelm@51717
   415
  in depth end;
wenzelm@51717
   416
wenzelm@51717
   417
wenzelm@51717
   418
(* diagnostics *)
wenzelm@51717
   419
wenzelm@54997
   420
exception SIMPLIFIER of string * thm list;
wenzelm@51717
   421
wenzelm@56438
   422
val simp_debug_raw = Config.declare ("simp_debug", @{here}) (K (Config.Bool false));
wenzelm@51717
   423
val simp_debug = Config.bool simp_debug_raw;
wenzelm@51717
   424
wenzelm@58859
   425
val simp_trace_raw = Config.declare ("simp_trace", @{here}) (fn _ => Config.Bool false);
wenzelm@51717
   426
val simp_trace = Config.bool simp_trace_raw;
wenzelm@51717
   427
wenzelm@55028
   428
fun cond_warning ctxt msg =
wenzelm@57859
   429
  if Context_Position.is_really_visible ctxt then warning (msg ()) else ();
wenzelm@51717
   430
wenzelm@55031
   431
fun cond_tracing' ctxt flag msg =
wenzelm@55028
   432
  if Config.get ctxt flag then
wenzelm@55028
   433
    let
wenzelm@55028
   434
      val Simpset ({depth = (depth, exceeded), ...}, _) = simpset_of ctxt;
wenzelm@55028
   435
      val depth_limit = Config.get ctxt simp_trace_depth_limit;
wenzelm@55028
   436
    in
wenzelm@55028
   437
      if depth > depth_limit then
wenzelm@55028
   438
        if ! exceeded then () else (tracing "simp_trace_depth_limit exceeded!"; exceeded := true)
wenzelm@55028
   439
      else (tracing (enclose "[" "]" (string_of_int depth) ^ msg ()); exceeded := false)
wenzelm@55028
   440
    end
wenzelm@55028
   441
  else ();
wenzelm@51717
   442
wenzelm@55031
   443
fun cond_tracing ctxt = cond_tracing' ctxt simp_trace;
wenzelm@55031
   444
wenzelm@55028
   445
fun print_term ctxt s t =
wenzelm@55028
   446
  s ^ "\n" ^ Syntax.string_of_term ctxt t;
wenzelm@51717
   447
wenzelm@55028
   448
fun print_thm ctxt s (name, th) =
wenzelm@55028
   449
  print_term ctxt (if name = "" then s else s ^ " " ^ quote name ^ ":") (Thm.full_prop_of th);
wenzelm@51717
   450
wenzelm@51717
   451
wenzelm@51717
   452
wenzelm@51717
   453
(** simpset operations **)
wenzelm@51717
   454
wenzelm@55014
   455
(* prems *)
wenzelm@51717
   456
wenzelm@51717
   457
fun prems_of ctxt =
wenzelm@51717
   458
  let val Simpset ({prems, ...}, _) = simpset_of ctxt in prems end;
wenzelm@51717
   459
wenzelm@51717
   460
fun add_prems ths =
wenzelm@55014
   461
  map_simpset1 (fn (rules, prems, depth) => (rules, ths @ prems, depth));
wenzelm@51717
   462
wenzelm@51717
   463
wenzelm@51717
   464
(* maintain simp rules *)
wenzelm@51717
   465
wenzelm@51717
   466
fun del_rrule (rrule as {thm, elhs, ...}) ctxt =
wenzelm@55014
   467
  ctxt |> map_simpset1 (fn (rules, prems, depth) =>
wenzelm@59582
   468
    (Net.delete_term eq_rrule (Thm.term_of elhs, rrule) rules, prems, depth))
wenzelm@55028
   469
  handle Net.DELETE =>
wenzelm@55028
   470
    (cond_warning ctxt (fn () => print_thm ctxt "Rewrite rule not in simpset:" ("", thm)); ctxt);
wenzelm@51717
   471
wenzelm@51717
   472
fun insert_rrule (rrule as {thm, name, ...}) ctxt =
wenzelm@55031
   473
 (cond_tracing ctxt (fn () => print_thm ctxt "Adding rewrite rule" (name, thm));
wenzelm@55014
   474
  ctxt |> map_simpset1 (fn (rules, prems, depth) =>
wenzelm@51717
   475
    let
wenzelm@51717
   476
      val rrule2 as {elhs, ...} = mk_rrule2 rrule;
wenzelm@61057
   477
      val rules' = Net.insert_term eq_rrule (Thm.term_of elhs, trim_context_rrule rrule2) rules;
wenzelm@55014
   478
    in (rules', prems, depth) end)
wenzelm@55028
   479
  handle Net.INSERT =>
wenzelm@55028
   480
    (cond_warning ctxt (fn () => print_thm ctxt "Ignoring duplicate rewrite rule:" ("", thm));
wenzelm@55028
   481
      ctxt));
wenzelm@51717
   482
wenzelm@51717
   483
local
wenzelm@51717
   484
wenzelm@51717
   485
fun vperm (Var _, Var _) = true
wenzelm@51717
   486
  | vperm (Abs (_, _, s), Abs (_, _, t)) = vperm (s, t)
wenzelm@51717
   487
  | vperm (t1 $ t2, u1 $ u2) = vperm (t1, u1) andalso vperm (t2, u2)
wenzelm@51717
   488
  | vperm (t, u) = (t = u);
wenzelm@51717
   489
wenzelm@51717
   490
fun var_perm (t, u) =
wenzelm@51717
   491
  vperm (t, u) andalso eq_set (op =) (Term.add_vars t [], Term.add_vars u []);
wenzelm@51717
   492
wenzelm@51717
   493
in
wenzelm@51717
   494
berghofe@10413
   495
fun decomp_simp thm =
wenzelm@15023
   496
  let
wenzelm@26626
   497
    val prop = Thm.prop_of thm;
wenzelm@15023
   498
    val prems = Logic.strip_imp_prems prop;
wenzelm@15023
   499
    val concl = Drule.strip_imp_concl (Thm.cprop_of thm);
wenzelm@22902
   500
    val (lhs, rhs) = Thm.dest_equals concl handle TERM _ =>
wenzelm@54997
   501
      raise SIMPLIFIER ("Rewrite rule not a meta-equality", [thm]);
wenzelm@20579
   502
    val elhs = Thm.dest_arg (Thm.cprop_of (Thm.eta_conversion lhs));
wenzelm@59582
   503
    val erhs = Envir.eta_contract (Thm.term_of rhs);
wenzelm@15023
   504
    val perm =
wenzelm@59582
   505
      var_perm (Thm.term_of elhs, erhs) andalso
wenzelm@59582
   506
      not (Thm.term_of elhs aconv erhs) andalso
wenzelm@59582
   507
      not (is_Var (Thm.term_of elhs));
wenzelm@59582
   508
  in (prems, Thm.term_of lhs, elhs, Thm.term_of rhs, perm) end;
berghofe@10413
   509
wenzelm@51717
   510
end;
wenzelm@51717
   511
wenzelm@12783
   512
fun decomp_simp' thm =
wenzelm@52091
   513
  let val (_, lhs, _, rhs, _) = decomp_simp thm in
wenzelm@54997
   514
    if Thm.nprems_of thm > 0 then raise SIMPLIFIER ("Bad conditional rewrite rule", [thm])
wenzelm@12979
   515
    else (lhs, rhs)
wenzelm@12783
   516
  end;
wenzelm@12783
   517
wenzelm@51717
   518
fun mk_eq_True ctxt (thm, name) =
wenzelm@51717
   519
  let val Simpset (_, {mk_rews = {mk_eq_True, ...}, ...}) = simpset_of ctxt in
wenzelm@51717
   520
    (case mk_eq_True ctxt thm of
wenzelm@51717
   521
      NONE => []
wenzelm@51717
   522
    | SOME eq_True =>
wenzelm@52091
   523
        let val (_, lhs, elhs, _, _) = decomp_simp eq_True;
wenzelm@51717
   524
        in [{thm = eq_True, name = name, lhs = lhs, elhs = elhs, perm = false}] end)
wenzelm@51717
   525
  end;
berghofe@10413
   526
wenzelm@15023
   527
(*create the rewrite rule and possibly also the eq_True variant,
wenzelm@15023
   528
  in case there are extra vars on the rhs*)
wenzelm@52082
   529
fun rrule_eq_True ctxt thm name lhs elhs rhs thm2 =
wenzelm@15023
   530
  let val rrule = {thm = thm, name = name, lhs = lhs, elhs = elhs, perm = false} in
wenzelm@20546
   531
    if rewrite_rule_extra_vars [] lhs rhs then
wenzelm@51717
   532
      mk_eq_True ctxt (thm2, name) @ [rrule]
wenzelm@20546
   533
    else [rrule]
berghofe@10413
   534
  end;
berghofe@10413
   535
wenzelm@51717
   536
fun mk_rrule ctxt (thm, name) =
wenzelm@52091
   537
  let val (prems, lhs, elhs, rhs, perm) = decomp_simp thm in
wenzelm@15023
   538
    if perm then [{thm = thm, name = name, lhs = lhs, elhs = elhs, perm = true}]
wenzelm@15023
   539
    else
wenzelm@15023
   540
      (*weak test for loops*)
wenzelm@59582
   541
      if rewrite_rule_extra_vars prems lhs rhs orelse is_Var (Thm.term_of elhs)
wenzelm@51717
   542
      then mk_eq_True ctxt (thm, name)
wenzelm@52082
   543
      else rrule_eq_True ctxt thm name lhs elhs rhs thm
berghofe@10413
   544
  end;
berghofe@10413
   545
wenzelm@51717
   546
fun orient_rrule ctxt (thm, name) =
wenzelm@18208
   547
  let
wenzelm@52091
   548
    val (prems, lhs, elhs, rhs, perm) = decomp_simp thm;
wenzelm@51717
   549
    val Simpset (_, {mk_rews = {reorient, mk_sym, ...}, ...}) = simpset_of ctxt;
wenzelm@18208
   550
  in
wenzelm@15023
   551
    if perm then [{thm = thm, name = name, lhs = lhs, elhs = elhs, perm = true}]
wenzelm@51717
   552
    else if reorient ctxt prems lhs rhs then
wenzelm@51717
   553
      if reorient ctxt prems rhs lhs
wenzelm@51717
   554
      then mk_eq_True ctxt (thm, name)
wenzelm@15023
   555
      else
wenzelm@51717
   556
        (case mk_sym ctxt thm of
wenzelm@18208
   557
          NONE => []
wenzelm@18208
   558
        | SOME thm' =>
wenzelm@52091
   559
            let val (_, lhs', elhs', rhs', _) = decomp_simp thm'
wenzelm@52082
   560
            in rrule_eq_True ctxt thm' name lhs' elhs' rhs' thm end)
wenzelm@52082
   561
    else rrule_eq_True ctxt thm name lhs elhs rhs thm
berghofe@10413
   562
  end;
berghofe@10413
   563
wenzelm@54982
   564
fun extract_rews ctxt thms =
wenzelm@51717
   565
  let val Simpset (_, {mk_rews = {mk, ...}, ...}) = simpset_of ctxt
wenzelm@51717
   566
  in maps (fn thm => map (rpair (Thm.get_name_hint thm)) (mk ctxt thm)) thms end;
berghofe@10413
   567
wenzelm@54982
   568
fun extract_safe_rrules ctxt thm =
wenzelm@54982
   569
  maps (orient_rrule ctxt) (extract_rews ctxt [thm]);
berghofe@10413
   570
lars@55316
   571
fun mk_rrules ctxt thms =
lars@55316
   572
  let
lars@55316
   573
    val rews = extract_rews ctxt thms
lars@55316
   574
    val raw_rrules = flat (map (mk_rrule ctxt) rews)
lars@55316
   575
  in map mk_rrule2 raw_rrules end
lars@55316
   576
berghofe@10413
   577
wenzelm@20028
   578
(* add/del rules explicitly *)
berghofe@10413
   579
wenzelm@61090
   580
local
wenzelm@61090
   581
wenzelm@54982
   582
fun comb_simps ctxt comb mk_rrule thms =
wenzelm@20028
   583
  let
wenzelm@61090
   584
    val rews = extract_rews ctxt (map (Thm.transfer (Proof_Context.theory_of ctxt)) thms);
wenzelm@51717
   585
  in fold (fold comb o mk_rrule) rews ctxt end;
berghofe@10413
   586
wenzelm@61090
   587
in
wenzelm@61090
   588
wenzelm@51717
   589
fun ctxt addsimps thms =
wenzelm@54982
   590
  comb_simps ctxt insert_rrule (mk_rrule ctxt) thms;
berghofe@10413
   591
wenzelm@51717
   592
fun ctxt delsimps thms =
wenzelm@54982
   593
  comb_simps ctxt del_rrule (map mk_rrule2 o mk_rrule ctxt) thms;
wenzelm@15023
   594
wenzelm@51717
   595
fun add_simp thm ctxt = ctxt addsimps [thm];
wenzelm@51717
   596
fun del_simp thm ctxt = ctxt delsimps [thm];
wenzelm@15023
   597
wenzelm@61090
   598
end;
wenzelm@61090
   599
wenzelm@57859
   600
wenzelm@15023
   601
(* congs *)
berghofe@10413
   602
wenzelm@15023
   603
local
wenzelm@15023
   604
wenzelm@15023
   605
fun is_full_cong_prems [] [] = true
wenzelm@15023
   606
  | is_full_cong_prems [] _ = false
wenzelm@15023
   607
  | is_full_cong_prems (p :: prems) varpairs =
wenzelm@15023
   608
      (case Logic.strip_assums_concl p of
wenzelm@56245
   609
        Const ("Pure.eq", _) $ lhs $ rhs =>
wenzelm@15023
   610
          let val (x, xs) = strip_comb lhs and (y, ys) = strip_comb rhs in
wenzelm@15023
   611
            is_Var x andalso forall is_Bound xs andalso
haftmann@20972
   612
            not (has_duplicates (op =) xs) andalso xs = ys andalso
wenzelm@20671
   613
            member (op =) varpairs (x, y) andalso
wenzelm@19303
   614
            is_full_cong_prems prems (remove (op =) (x, y) varpairs)
wenzelm@15023
   615
          end
wenzelm@15023
   616
      | _ => false);
wenzelm@15023
   617
wenzelm@15023
   618
fun is_full_cong thm =
berghofe@10413
   619
  let
wenzelm@43597
   620
    val prems = Thm.prems_of thm and concl = Thm.concl_of thm;
wenzelm@15023
   621
    val (lhs, rhs) = Logic.dest_equals concl;
wenzelm@15023
   622
    val (f, xs) = strip_comb lhs and (g, ys) = strip_comb rhs;
berghofe@10413
   623
  in
haftmann@20972
   624
    f = g andalso not (has_duplicates (op =) (xs @ ys)) andalso length xs = length ys andalso
wenzelm@15023
   625
    is_full_cong_prems prems (xs ~~ ys)
berghofe@10413
   626
  end;
berghofe@10413
   627
wenzelm@51717
   628
fun mk_cong ctxt =
wenzelm@51717
   629
  let val Simpset (_, {mk_rews = {mk_cong = f, ...}, ...}) = simpset_of ctxt
wenzelm@51717
   630
  in f ctxt end;
wenzelm@45620
   631
wenzelm@45620
   632
in
wenzelm@45620
   633
wenzelm@54729
   634
fun add_eqcong thm ctxt = ctxt |> map_simpset2
wenzelm@54731
   635
  (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
wenzelm@15023
   636
    let
wenzelm@45621
   637
      val (lhs, _) = Logic.dest_equals (Thm.concl_of thm)
wenzelm@54997
   638
        handle TERM _ => raise SIMPLIFIER ("Congruence not a meta-equality", [thm]);
wenzelm@18929
   639
    (*val lhs = Envir.eta_contract lhs;*)
wenzelm@45621
   640
      val a = the (cong_name (head_of lhs)) handle Option.Option =>
wenzelm@54997
   641
        raise SIMPLIFIER ("Congruence must start with a constant or free variable", [thm]);
haftmann@22221
   642
      val (xs, weak) = congs;
krauss@30908
   643
      val xs' = AList.update (op =) (a, thm) xs;
haftmann@22221
   644
      val weak' = if is_full_cong thm then weak else a :: weak;
wenzelm@54731
   645
    in ((xs', weak'), procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) end);
berghofe@10413
   646
wenzelm@54729
   647
fun del_eqcong thm ctxt = ctxt |> map_simpset2
wenzelm@54731
   648
  (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
wenzelm@15023
   649
    let
wenzelm@45621
   650
      val (lhs, _) = Logic.dest_equals (Thm.concl_of thm)
wenzelm@54997
   651
        handle TERM _ => raise SIMPLIFIER ("Congruence not a meta-equality", [thm]);
wenzelm@18929
   652
    (*val lhs = Envir.eta_contract lhs;*)
wenzelm@20057
   653
      val a = the (cong_name (head_of lhs)) handle Option.Option =>
wenzelm@54997
   654
        raise SIMPLIFIER ("Congruence must start with a constant", [thm]);
haftmann@22221
   655
      val (xs, _) = congs;
wenzelm@51590
   656
      val xs' = filter_out (fn (x : cong_name, _) => x = a) xs;
krauss@30908
   657
      val weak' = xs' |> map_filter (fn (a, thm) =>
skalberg@15531
   658
        if is_full_cong thm then NONE else SOME a);
wenzelm@54731
   659
    in ((xs', weak'), procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) end);
berghofe@10413
   660
wenzelm@51717
   661
fun add_cong thm ctxt = add_eqcong (mk_cong ctxt thm) ctxt;
wenzelm@51717
   662
fun del_cong thm ctxt = del_eqcong (mk_cong ctxt thm) ctxt;
wenzelm@15023
   663
wenzelm@15023
   664
end;
berghofe@10413
   665
berghofe@10413
   666
wenzelm@15023
   667
(* simprocs *)
wenzelm@15023
   668
wenzelm@22234
   669
datatype simproc =
wenzelm@22234
   670
  Simproc of
wenzelm@22234
   671
    {name: string,
wenzelm@22234
   672
     lhss: cterm list,
wenzelm@51717
   673
     proc: morphism -> Proof.context -> cterm -> thm option,
wenzelm@22234
   674
     id: stamp * thm list};
wenzelm@22234
   675
wenzelm@22234
   676
fun eq_simproc (Simproc {id = id1, ...}, Simproc {id = id2, ...}) = eq_procid (id1, id2);
wenzelm@22008
   677
wenzelm@45290
   678
fun transform_simproc phi (Simproc {name, lhss, proc, id = (s, ths)}) =
wenzelm@22234
   679
  Simproc
wenzelm@22234
   680
   {name = name,
wenzelm@22234
   681
    lhss = map (Morphism.cterm phi) lhss,
wenzelm@22669
   682
    proc = Morphism.transform phi proc,
wenzelm@22234
   683
    id = (s, Morphism.fact phi ths)};
wenzelm@22234
   684
wenzelm@22234
   685
fun make_simproc {name, lhss, proc, identifier} =
wenzelm@22234
   686
  Simproc {name = name, lhss = lhss, proc = proc, id = (stamp (), identifier)};
wenzelm@22008
   687
wenzelm@22008
   688
fun mk_simproc name lhss proc =
wenzelm@51717
   689
  make_simproc {name = name, lhss = lhss, proc = fn _ => fn ctxt => fn ct =>
wenzelm@59582
   690
    proc ctxt (Thm.term_of ct), identifier = []};
wenzelm@22008
   691
wenzelm@35845
   692
(* FIXME avoid global thy and Logic.varify_global *)
wenzelm@59621
   693
fun simproc_global_i thy name = mk_simproc name o map (Thm.global_cterm_of thy o Logic.varify_global);
wenzelm@38715
   694
fun simproc_global thy name = simproc_global_i thy name o map (Syntax.read_term_global thy);
wenzelm@22008
   695
wenzelm@22008
   696
wenzelm@15023
   697
local
berghofe@10413
   698
wenzelm@51717
   699
fun add_proc (proc as Proc {name, lhs, ...}) ctxt =
wenzelm@55031
   700
 (cond_tracing ctxt (fn () =>
wenzelm@59582
   701
    print_term ctxt ("Adding simplification procedure " ^ quote name ^ " for") (Thm.term_of lhs));
wenzelm@54729
   702
  ctxt |> map_simpset2
wenzelm@54731
   703
    (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
wenzelm@59582
   704
      (congs, Net.insert_term eq_proc (Thm.term_of lhs, proc) procs,
wenzelm@54731
   705
        mk_rews, termless, subgoal_tac, loop_tacs, solvers))
wenzelm@15023
   706
  handle Net.INSERT =>
wenzelm@55028
   707
    (cond_warning ctxt (fn () => "Ignoring duplicate simplification procedure " ^ quote name);
wenzelm@55028
   708
      ctxt));
berghofe@10413
   709
wenzelm@51717
   710
fun del_proc (proc as Proc {name, lhs, ...}) ctxt =
wenzelm@54729
   711
  ctxt |> map_simpset2
wenzelm@54731
   712
    (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
wenzelm@59582
   713
      (congs, Net.delete_term eq_proc (Thm.term_of lhs, proc) procs,
wenzelm@54731
   714
        mk_rews, termless, subgoal_tac, loop_tacs, solvers))
wenzelm@15023
   715
  handle Net.DELETE =>
wenzelm@55028
   716
    (cond_warning ctxt (fn () => "Simplification procedure " ^ quote name ^ " not in simpset");
wenzelm@55028
   717
      ctxt);
berghofe@10413
   718
wenzelm@22234
   719
fun prep_procs (Simproc {name, lhss, proc, id}) =
wenzelm@22669
   720
  lhss |> map (fn lhs => Proc {name = name, lhs = lhs, proc = Morphism.form proc, id = id});
wenzelm@22234
   721
wenzelm@15023
   722
in
berghofe@10413
   723
wenzelm@51717
   724
fun ctxt addsimprocs ps = fold (fold add_proc o prep_procs) ps ctxt;
wenzelm@51717
   725
fun ctxt delsimprocs ps = fold (fold del_proc o prep_procs) ps ctxt;
berghofe@10413
   726
wenzelm@15023
   727
end;
berghofe@10413
   728
berghofe@10413
   729
berghofe@10413
   730
(* mk_rews *)
berghofe@10413
   731
wenzelm@15023
   732
local
wenzelm@15023
   733
wenzelm@54729
   734
fun map_mk_rews f =
wenzelm@54731
   735
  map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
wenzelm@54729
   736
    let
wenzelm@54729
   737
      val {mk, mk_cong, mk_sym, mk_eq_True, reorient} = mk_rews;
wenzelm@54729
   738
      val (mk', mk_cong', mk_sym', mk_eq_True', reorient') =
wenzelm@54729
   739
        f (mk, mk_cong, mk_sym, mk_eq_True, reorient);
wenzelm@54729
   740
      val mk_rews' = {mk = mk', mk_cong = mk_cong', mk_sym = mk_sym', mk_eq_True = mk_eq_True',
wenzelm@54729
   741
        reorient = reorient'};
wenzelm@54731
   742
    in (congs, procs, mk_rews', termless, subgoal_tac, loop_tacs, solvers) end);
wenzelm@15023
   743
wenzelm@15023
   744
in
berghofe@10413
   745
wenzelm@51717
   746
fun mksimps ctxt =
wenzelm@51717
   747
  let val Simpset (_, {mk_rews = {mk, ...}, ...}) = simpset_of ctxt
wenzelm@51717
   748
  in mk ctxt end;
wenzelm@30318
   749
wenzelm@45625
   750
fun set_mksimps mk = map_mk_rews (fn (_, mk_cong, mk_sym, mk_eq_True, reorient) =>
wenzelm@18208
   751
  (mk, mk_cong, mk_sym, mk_eq_True, reorient));
wenzelm@15023
   752
wenzelm@45625
   753
fun set_mkcong mk_cong = map_mk_rews (fn (mk, _, mk_sym, mk_eq_True, reorient) =>
wenzelm@18208
   754
  (mk, mk_cong, mk_sym, mk_eq_True, reorient));
berghofe@10413
   755
wenzelm@45625
   756
fun set_mksym mk_sym = map_mk_rews (fn (mk, mk_cong, _, mk_eq_True, reorient) =>
wenzelm@18208
   757
  (mk, mk_cong, mk_sym, mk_eq_True, reorient));
berghofe@10413
   758
wenzelm@45625
   759
fun set_mkeqTrue mk_eq_True = map_mk_rews (fn (mk, mk_cong, mk_sym, _, reorient) =>
wenzelm@18208
   760
  (mk, mk_cong, mk_sym, mk_eq_True, reorient));
wenzelm@18208
   761
wenzelm@18208
   762
fun set_reorient reorient = map_mk_rews (fn (mk, mk_cong, mk_sym, mk_eq_True, _) =>
wenzelm@18208
   763
  (mk, mk_cong, mk_sym, mk_eq_True, reorient));
wenzelm@15023
   764
wenzelm@15023
   765
end;
wenzelm@15023
   766
skalberg@14242
   767
berghofe@10413
   768
(* termless *)
berghofe@10413
   769
wenzelm@45625
   770
fun set_termless termless =
wenzelm@54731
   771
  map_simpset2 (fn (congs, procs, mk_rews, _, subgoal_tac, loop_tacs, solvers) =>
wenzelm@54731
   772
   (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers));
skalberg@15006
   773
skalberg@15006
   774
wenzelm@15023
   775
(* tactics *)
skalberg@15006
   776
wenzelm@45625
   777
fun set_subgoaler subgoal_tac =
wenzelm@54731
   778
  map_simpset2 (fn (congs, procs, mk_rews, termless, _, loop_tacs, solvers) =>
wenzelm@54731
   779
   (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers));
skalberg@15006
   780
wenzelm@52037
   781
fun ctxt setloop tac = ctxt |>
wenzelm@54731
   782
  map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, _, solvers) =>
wenzelm@54731
   783
   (congs, procs, mk_rews, termless, subgoal_tac, [("", tac)], solvers));
skalberg@15006
   784
wenzelm@52037
   785
fun ctxt addloop (name, tac) = ctxt |>
wenzelm@54731
   786
  map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
wenzelm@15023
   787
    (congs, procs, mk_rews, termless, subgoal_tac,
wenzelm@54731
   788
     AList.update (op =) (name, tac) loop_tacs, solvers));
skalberg@15006
   789
wenzelm@51717
   790
fun ctxt delloop name = ctxt |>
wenzelm@54731
   791
  map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
haftmann@21286
   792
    (congs, procs, mk_rews, termless, subgoal_tac,
wenzelm@38834
   793
     (if AList.defined (op =) loop_tacs name then ()
wenzelm@55028
   794
      else cond_warning ctxt (fn () => "No such looper in simpset: " ^ quote name);
wenzelm@55028
   795
      AList.delete (op =) name loop_tacs), solvers));
skalberg@15006
   796
wenzelm@54729
   797
fun ctxt setSSolver solver = ctxt |> map_simpset2
wenzelm@54731
   798
  (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, (unsafe_solvers, _)) =>
wenzelm@54731
   799
    (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, (unsafe_solvers, [solver])));
skalberg@15006
   800
wenzelm@51717
   801
fun ctxt addSSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
wenzelm@54731
   802
  subgoal_tac, loop_tacs, (unsafe_solvers, solvers)) => (congs, procs, mk_rews, termless,
wenzelm@54731
   803
    subgoal_tac, loop_tacs, (unsafe_solvers, insert eq_solver solver solvers)));
skalberg@15006
   804
wenzelm@51717
   805
fun ctxt setSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
wenzelm@54731
   806
  subgoal_tac, loop_tacs, (_, solvers)) => (congs, procs, mk_rews, termless,
wenzelm@54731
   807
    subgoal_tac, loop_tacs, ([solver], solvers)));
skalberg@15006
   808
wenzelm@51717
   809
fun ctxt addSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
wenzelm@54731
   810
  subgoal_tac, loop_tacs, (unsafe_solvers, solvers)) => (congs, procs, mk_rews, termless,
wenzelm@54731
   811
    subgoal_tac, loop_tacs, (insert eq_solver solver unsafe_solvers, solvers)));
skalberg@15006
   812
wenzelm@15023
   813
fun set_solvers solvers = map_simpset2 (fn (congs, procs, mk_rews, termless,
wenzelm@54731
   814
  subgoal_tac, loop_tacs, _) => (congs, procs, mk_rews, termless,
wenzelm@54731
   815
  subgoal_tac, loop_tacs, (solvers, solvers)));
wenzelm@54729
   816
wenzelm@54729
   817
wenzelm@54729
   818
(* trace operations *)
wenzelm@54729
   819
wenzelm@54731
   820
type trace_ops =
wenzelm@54731
   821
 {trace_invoke: {depth: int, term: term} -> Proof.context -> Proof.context,
lars@55316
   822
  trace_apply: {unconditional: bool, term: term, thm: thm, rrule: rrule} ->
wenzelm@54731
   823
    Proof.context -> (Proof.context -> (thm * term) option) -> (thm * term) option};
wenzelm@54729
   824
wenzelm@54731
   825
structure Trace_Ops = Theory_Data
wenzelm@54731
   826
(
wenzelm@54731
   827
  type T = trace_ops;
wenzelm@54731
   828
  val empty: T =
wenzelm@54731
   829
   {trace_invoke = fn _ => fn ctxt => ctxt,
wenzelm@54731
   830
    trace_apply = fn _ => fn ctxt => fn cont => cont ctxt};
wenzelm@54731
   831
  val extend = I;
wenzelm@54731
   832
  fun merge (trace_ops, _) = trace_ops;
wenzelm@54731
   833
);
wenzelm@54731
   834
wenzelm@54731
   835
val set_trace_ops = Trace_Ops.put;
wenzelm@54731
   836
wenzelm@54731
   837
val trace_ops = Trace_Ops.get o Proof_Context.theory_of;
wenzelm@54729
   838
fun trace_invoke args ctxt = #trace_invoke (trace_ops ctxt) args ctxt;
wenzelm@54729
   839
fun trace_apply args ctxt = #trace_apply (trace_ops ctxt) args ctxt;
skalberg@15006
   840
skalberg@15006
   841
skalberg@15006
   842
berghofe@10413
   843
(** rewriting **)
berghofe@10413
   844
berghofe@10413
   845
(*
berghofe@10413
   846
  Uses conversions, see:
berghofe@10413
   847
    L C Paulson, A higher-order implementation of rewriting,
berghofe@10413
   848
    Science of Computer Programming 3 (1983), pages 119-149.
berghofe@10413
   849
*)
berghofe@10413
   850
wenzelm@51717
   851
fun check_conv ctxt msg thm thm' =
berghofe@10413
   852
  let
wenzelm@36944
   853
    val thm'' = Thm.transitive thm thm' handle THM _ =>
nipkow@59690
   854
      let
nipkow@59690
   855
        val nthm' =
nipkow@59690
   856
          Thm.transitive (Thm.symmetric (Drule.beta_eta_conversion (Thm.lhs_of thm'))) thm'
nipkow@59690
   857
      in Thm.transitive thm nthm' handle THM _ =>
nipkow@59690
   858
           let
nipkow@59690
   859
             val nthm =
nipkow@59690
   860
               Thm.transitive thm (Drule.beta_eta_conversion (Thm.rhs_of thm))
nipkow@59690
   861
           in Thm.transitive nthm nthm' end
nipkow@59690
   862
      end
wenzelm@55028
   863
    val _ =
wenzelm@55031
   864
      if msg then cond_tracing ctxt (fn () => print_thm ctxt "SUCCEEDED" ("", thm'))
wenzelm@55028
   865
      else ();
wenzelm@55028
   866
  in SOME thm'' end
berghofe@10413
   867
  handle THM _ =>
wenzelm@26626
   868
    let
wenzelm@26626
   869
      val _ $ _ $ prop0 = Thm.prop_of thm;
wenzelm@55028
   870
      val _ =
wenzelm@55032
   871
        cond_tracing ctxt (fn () =>
wenzelm@55032
   872
          print_thm ctxt "Proved wrong theorem (bad subgoaler?)" ("", thm') ^ "\n" ^
wenzelm@55028
   873
          print_term ctxt "Should have proved:" prop0);
wenzelm@55028
   874
    in NONE end;
berghofe@10413
   875
berghofe@10413
   876
berghofe@10413
   877
(* mk_procrule *)
berghofe@10413
   878
wenzelm@51717
   879
fun mk_procrule ctxt thm =
wenzelm@52091
   880
  let val (prems, lhs, elhs, rhs, _) = decomp_simp thm in
wenzelm@15023
   881
    if rewrite_rule_extra_vars prems lhs rhs
wenzelm@55028
   882
    then (cond_warning ctxt (fn () => print_thm ctxt "Extra vars on rhs:" ("", thm)); [])
wenzelm@15023
   883
    else [mk_rrule2 {thm = thm, name = "", lhs = lhs, elhs = elhs, perm = false}]
berghofe@10413
   884
  end;
berghofe@10413
   885
berghofe@10413
   886
wenzelm@15023
   887
(* rewritec: conversion to apply the meta simpset to a term *)
berghofe@10413
   888
wenzelm@15023
   889
(*Since the rewriting strategy is bottom-up, we avoid re-normalizing already
wenzelm@15023
   890
  normalized terms by carrying around the rhs of the rewrite rule just
wenzelm@15023
   891
  applied. This is called the `skeleton'. It is decomposed in parallel
wenzelm@15023
   892
  with the term. Once a Var is encountered, the corresponding term is
wenzelm@15023
   893
  already in normal form.
wenzelm@15023
   894
  skel0 is a dummy skeleton that is to enforce complete normalization.*)
wenzelm@15023
   895
berghofe@10413
   896
val skel0 = Bound 0;
berghofe@10413
   897
wenzelm@15023
   898
(*Use rhs as skeleton only if the lhs does not contain unnormalized bits.
wenzelm@15023
   899
  The latter may happen iff there are weak congruence rules for constants
wenzelm@15023
   900
  in the lhs.*)
berghofe@10413
   901
wenzelm@15023
   902
fun uncond_skel ((_, weak), (lhs, rhs)) =
wenzelm@15023
   903
  if null weak then rhs  (*optimization*)
wenzelm@51591
   904
  else if exists_subterm
wenzelm@51591
   905
    (fn Const (a, _) => member (op =) weak (true, a)
wenzelm@51591
   906
      | Free (a, _) => member (op =) weak (false, a)
wenzelm@51591
   907
      | _ => false) lhs then skel0
wenzelm@15023
   908
  else rhs;
wenzelm@15023
   909
wenzelm@15023
   910
(*Behaves like unconditional rule if rhs does not contain vars not in the lhs.
wenzelm@15023
   911
  Otherwise those vars may become instantiated with unnormalized terms
wenzelm@15023
   912
  while the premises are solved.*)
wenzelm@15023
   913
wenzelm@32797
   914
fun cond_skel (args as (_, (lhs, rhs))) =
haftmann@33038
   915
  if subset (op =) (Term.add_vars rhs [], Term.add_vars lhs []) then uncond_skel args
berghofe@10413
   916
  else skel0;
berghofe@10413
   917
berghofe@10413
   918
(*
wenzelm@15023
   919
  Rewriting -- we try in order:
berghofe@10413
   920
    (1) beta reduction
berghofe@10413
   921
    (2) unconditional rewrite rules
berghofe@10413
   922
    (3) conditional rewrite rules
berghofe@10413
   923
    (4) simplification procedures
berghofe@10413
   924
berghofe@10413
   925
  IMPORTANT: rewrite rules must not introduce new Vars or TVars!
berghofe@10413
   926
*)
berghofe@10413
   927
wenzelm@52091
   928
fun rewritec (prover, maxt) ctxt t =
berghofe@10413
   929
  let
wenzelm@61057
   930
    val thy = Proof_Context.theory_of ctxt;
wenzelm@51717
   931
    val Simpset ({rules, ...}, {congs, procs, termless, ...}) = simpset_of ctxt;
berghofe@10413
   932
    val eta_thm = Thm.eta_conversion t;
wenzelm@22902
   933
    val eta_t' = Thm.rhs_of eta_thm;
wenzelm@59582
   934
    val eta_t = Thm.term_of eta_t';
lars@55316
   935
    fun rew rrule =
berghofe@10413
   936
      let
wenzelm@61057
   937
        val {thm = thm0, name, lhs, elhs = elhs0, extra, fo, perm} = rrule;
wenzelm@61057
   938
        val thm = Thm.transfer thy thm0;
wenzelm@61057
   939
        val elhs = Thm.transfer_cterm thy elhs0;
wenzelm@32797
   940
        val prop = Thm.prop_of thm;
wenzelm@20546
   941
        val (rthm, elhs') =
wenzelm@20546
   942
          if maxt = ~1 orelse not extra then (thm, elhs)
wenzelm@22902
   943
          else (Thm.incr_indexes (maxt + 1) thm, Thm.incr_indexes_cterm (maxt + 1) elhs);
wenzelm@61057
   944
wenzelm@22902
   945
        val insts =
wenzelm@22902
   946
          if fo then Thm.first_order_match (elhs', eta_t')
wenzelm@22902
   947
          else Thm.match (elhs', eta_t');
berghofe@10413
   948
        val thm' = Thm.instantiate insts (Thm.rename_boundvars lhs eta_t rthm);
wenzelm@14643
   949
        val prop' = Thm.prop_of thm';
wenzelm@21576
   950
        val unconditional = (Logic.count_prems prop' = 0);
wenzelm@54725
   951
        val (lhs', rhs') = Logic.dest_equals (Logic.strip_imp_concl prop');
lars@55316
   952
        val trace_args = {unconditional = unconditional, term = eta_t, thm = thm', rrule = rrule};
berghofe@10413
   953
      in
nipkow@11295
   954
        if perm andalso not (termless (rhs', lhs'))
wenzelm@54725
   955
        then
wenzelm@55031
   956
         (cond_tracing ctxt (fn () =>
wenzelm@55028
   957
            print_thm ctxt "Cannot apply permutative rewrite rule" (name, thm) ^ "\n" ^
wenzelm@55028
   958
            print_thm ctxt "Term does not become smaller:" ("", thm'));
wenzelm@54725
   959
          NONE)
wenzelm@54725
   960
        else
wenzelm@55031
   961
         (cond_tracing ctxt (fn () =>
wenzelm@55028
   962
            print_thm ctxt "Applying instance of rewrite rule" (name, thm));
wenzelm@54725
   963
          if unconditional
wenzelm@54725
   964
          then
wenzelm@55031
   965
           (cond_tracing ctxt (fn () => print_thm ctxt "Rewriting:" ("", thm'));
wenzelm@54729
   966
            trace_apply trace_args ctxt (fn ctxt' =>
wenzelm@54729
   967
              let
wenzelm@54729
   968
                val lr = Logic.dest_equals prop;
wenzelm@54729
   969
                val SOME thm'' = check_conv ctxt' false eta_thm thm';
wenzelm@54729
   970
              in SOME (thm'', uncond_skel (congs, lr)) end))
wenzelm@54725
   971
          else
wenzelm@55031
   972
           (cond_tracing ctxt (fn () => print_thm ctxt "Trying to rewrite:" ("", thm'));
wenzelm@54725
   973
            if simp_depth ctxt > Config.get ctxt simp_depth_limit
wenzelm@55031
   974
            then (cond_tracing ctxt (fn () => "simp_depth_limit exceeded - giving up"); NONE)
wenzelm@54725
   975
            else
wenzelm@54729
   976
              trace_apply trace_args ctxt (fn ctxt' =>
wenzelm@54729
   977
                (case prover ctxt' thm' of
wenzelm@55031
   978
                  NONE => (cond_tracing ctxt' (fn () => print_thm ctxt' "FAILED" ("", thm')); NONE)
wenzelm@54729
   979
                | SOME thm2 =>
wenzelm@54729
   980
                    (case check_conv ctxt' true eta_thm thm2 of
wenzelm@54729
   981
                      NONE => NONE
wenzelm@54729
   982
                    | SOME thm2' =>
wenzelm@54729
   983
                        let
wenzelm@54729
   984
                          val concl = Logic.strip_imp_concl prop;
wenzelm@54729
   985
                          val lr = Logic.dest_equals concl;
wenzelm@54729
   986
                        in SOME (thm2', cond_skel (congs, lr)) end)))))
wenzelm@51717
   987
      end;
berghofe@10413
   988
skalberg@15531
   989
    fun rews [] = NONE
berghofe@10413
   990
      | rews (rrule :: rrules) =
skalberg@15531
   991
          let val opt = rew rrule handle Pattern.MATCH => NONE
wenzelm@54725
   992
          in (case opt of NONE => rews rrules | some => some) end;
berghofe@10413
   993
wenzelm@38834
   994
    fun sort_rrules rrs =
wenzelm@38834
   995
      let
wenzelm@38834
   996
        fun is_simple ({thm, ...}: rrule) =
wenzelm@38834
   997
          (case Thm.prop_of thm of
wenzelm@56245
   998
            Const ("Pure.eq", _) $ _ $ _ => true
wenzelm@38834
   999
          | _ => false);
wenzelm@38834
  1000
        fun sort [] (re1, re2) = re1 @ re2
wenzelm@38834
  1001
          | sort (rr :: rrs) (re1, re2) =
wenzelm@38834
  1002
              if is_simple rr
wenzelm@38834
  1003
              then sort rrs (rr :: re1, re2)
wenzelm@38834
  1004
              else sort rrs (re1, rr :: re2);
wenzelm@38834
  1005
      in sort rrs ([], []) end;
berghofe@10413
  1006
skalberg@15531
  1007
    fun proc_rews [] = NONE
wenzelm@15023
  1008
      | proc_rews (Proc {name, proc, lhs, ...} :: ps) =
wenzelm@59582
  1009
          if Pattern.matches (Proof_Context.theory_of ctxt) (Thm.term_of lhs, Thm.term_of t) then
wenzelm@55031
  1010
            (cond_tracing' ctxt simp_debug (fn () =>
wenzelm@55028
  1011
              print_term ctxt ("Trying procedure " ^ quote name ^ " on:") eta_t);
wenzelm@54725
  1012
             (case proc ctxt eta_t' of
wenzelm@55031
  1013
               NONE => (cond_tracing' ctxt simp_debug (fn () => "FAILED"); proc_rews ps)
skalberg@15531
  1014
             | SOME raw_thm =>
wenzelm@55031
  1015
                 (cond_tracing ctxt (fn () =>
wenzelm@55028
  1016
                    print_thm ctxt ("Procedure " ^ quote name ^ " produced rewrite rule:")
wenzelm@55028
  1017
                      ("", raw_thm));
wenzelm@51717
  1018
                  (case rews (mk_procrule ctxt raw_thm) of
wenzelm@55028
  1019
                    NONE =>
wenzelm@55031
  1020
                     (cond_tracing ctxt (fn () =>
wenzelm@55028
  1021
                        print_term ctxt ("IGNORED result of simproc " ^ quote name ^
wenzelm@55028
  1022
                            " -- does not match") (Thm.term_of t));
wenzelm@55028
  1023
                      proc_rews ps)
wenzelm@54725
  1024
                  | some => some))))
berghofe@10413
  1025
          else proc_rews ps;
wenzelm@38834
  1026
  in
wenzelm@38834
  1027
    (case eta_t of
wenzelm@38834
  1028
      Abs _ $ _ => SOME (Thm.transitive eta_thm (Thm.beta_conversion false eta_t'), skel0)
wenzelm@38834
  1029
    | _ =>
wenzelm@38834
  1030
      (case rews (sort_rrules (Net.match_term rules eta_t)) of
wenzelm@38834
  1031
        NONE => proc_rews (Net.match_term procs eta_t)
wenzelm@38834
  1032
      | some => some))
berghofe@10413
  1033
  end;
berghofe@10413
  1034
berghofe@10413
  1035
berghofe@10413
  1036
(* conversion to apply a congruence rule to a term *)
berghofe@10413
  1037
wenzelm@51717
  1038
fun congc prover ctxt maxt cong t =
wenzelm@51717
  1039
  let
wenzelm@51717
  1040
    val rthm = Thm.incr_indexes (maxt + 1) cong;
wenzelm@59582
  1041
    val rlhs = fst (Thm.dest_equals (Drule.strip_imp_concl (Thm.cprop_of rthm)));
wenzelm@51717
  1042
    val insts = Thm.match (rlhs, t)
wenzelm@51717
  1043
    (* Thm.match can raise Pattern.MATCH;
wenzelm@51717
  1044
       is handled when congc is called *)
wenzelm@59582
  1045
    val thm' =
wenzelm@59582
  1046
      Thm.instantiate insts (Thm.rename_boundvars (Thm.term_of rlhs) (Thm.term_of t) rthm);
wenzelm@55028
  1047
    val _ =
wenzelm@55031
  1048
      cond_tracing ctxt (fn () => print_thm ctxt "Applying congruence rule:" ("", thm'));
wenzelm@55031
  1049
    fun err (msg, thm) = (cond_tracing ctxt (fn () => print_thm ctxt msg ("", thm)); NONE);
wenzelm@38834
  1050
  in
wenzelm@38834
  1051
    (case prover thm' of
wenzelm@38834
  1052
      NONE => err ("Congruence proof failed.  Could not prove", thm')
wenzelm@38834
  1053
    | SOME thm2 =>
wenzelm@51717
  1054
        (case check_conv ctxt true (Drule.beta_eta_conversion t) thm2 of
skalberg@15531
  1055
          NONE => err ("Congruence proof failed.  Should not have proved", thm2)
skalberg@15531
  1056
        | SOME thm2' =>
wenzelm@59582
  1057
            if op aconv (apply2 Thm.term_of (Thm.dest_equals (Thm.cprop_of thm2')))
wenzelm@38834
  1058
            then NONE else SOME thm2'))
berghofe@10413
  1059
  end;
berghofe@10413
  1060
wenzelm@60642
  1061
val vA = (("A", 0), propT);
wenzelm@60642
  1062
val vB = (("B", 0), propT);
wenzelm@60642
  1063
val vC = (("C", 0), propT);
berghofe@10413
  1064
skalberg@15531
  1065
fun transitive1 NONE NONE = NONE
skalberg@15531
  1066
  | transitive1 (SOME thm1) NONE = SOME thm1
skalberg@15531
  1067
  | transitive1 NONE (SOME thm2) = SOME thm2
wenzelm@54725
  1068
  | transitive1 (SOME thm1) (SOME thm2) = SOME (Thm.transitive thm1 thm2);
berghofe@10413
  1069
skalberg@15531
  1070
fun transitive2 thm = transitive1 (SOME thm);
skalberg@15531
  1071
fun transitive3 thm = transitive1 thm o SOME;
berghofe@13607
  1072
wenzelm@52091
  1073
fun bottomc ((simprem, useprem, mutsimp), prover, maxidx) =
berghofe@10413
  1074
  let
wenzelm@51717
  1075
    fun botc skel ctxt t =
wenzelm@54725
  1076
      if is_Var skel then NONE
wenzelm@54725
  1077
      else
wenzelm@54725
  1078
        (case subc skel ctxt t of
wenzelm@54725
  1079
           some as SOME thm1 =>
wenzelm@54725
  1080
             (case rewritec (prover, maxidx) ctxt (Thm.rhs_of thm1) of
wenzelm@54725
  1081
                SOME (thm2, skel2) =>
wenzelm@54725
  1082
                  transitive2 (Thm.transitive thm1 thm2)
wenzelm@51717
  1083
                    (botc skel2 ctxt (Thm.rhs_of thm2))
wenzelm@54725
  1084
              | NONE => some)
wenzelm@54725
  1085
         | NONE =>
wenzelm@54725
  1086
             (case rewritec (prover, maxidx) ctxt t of
wenzelm@54725
  1087
                SOME (thm2, skel2) => transitive2 thm2
wenzelm@54725
  1088
                  (botc skel2 ctxt (Thm.rhs_of thm2))
wenzelm@54725
  1089
              | NONE => NONE))
berghofe@10413
  1090
wenzelm@51717
  1091
    and try_botc ctxt t =
wenzelm@54725
  1092
      (case botc skel0 ctxt t of
wenzelm@54725
  1093
        SOME trec1 => trec1
wenzelm@54725
  1094
      | NONE => Thm.reflexive t)
berghofe@10413
  1095
wenzelm@51717
  1096
    and subc skel ctxt t0 =
wenzelm@55014
  1097
        let val Simpset (_, {congs, ...}) = simpset_of ctxt in
wenzelm@59582
  1098
          (case Thm.term_of t0 of
wenzelm@51717
  1099
              Abs (a, T, _) =>
wenzelm@51717
  1100
                let
wenzelm@55635
  1101
                    val (v, ctxt') = Variable.next_bound (a, T) ctxt;
wenzelm@55635
  1102
                    val b = #1 (Term.dest_Free v);
wenzelm@55635
  1103
                    val (v', t') = Thm.dest_abs (SOME b) t0;
wenzelm@59582
  1104
                    val b' = #1 (Term.dest_Free (Thm.term_of v'));
wenzelm@51717
  1105
                    val _ =
wenzelm@51717
  1106
                      if b <> b' then
wenzelm@55635
  1107
                        warning ("Bad Simplifier context: renamed bound variable " ^
wenzelm@51717
  1108
                          quote b ^ " to " ^ quote b' ^ Position.here (Position.thread_data ()))
wenzelm@51717
  1109
                      else ();
wenzelm@54725
  1110
                    val skel' = (case skel of Abs (_, _, sk) => sk | _ => skel0);
wenzelm@51717
  1111
                in
wenzelm@51717
  1112
                  (case botc skel' ctxt' t' of
wenzelm@55635
  1113
                    SOME thm => SOME (Thm.abstract_rule a v' thm)
wenzelm@51717
  1114
                  | NONE => NONE)
wenzelm@51717
  1115
                end
wenzelm@54725
  1116
            | t $ _ =>
wenzelm@54725
  1117
              (case t of
wenzelm@56245
  1118
                Const ("Pure.imp", _) $ _  => impc t0 ctxt
wenzelm@51717
  1119
              | Abs _ =>
wenzelm@51717
  1120
                  let val thm = Thm.beta_conversion false t0
wenzelm@54725
  1121
                  in
wenzelm@54725
  1122
                    (case subc skel0 ctxt (Thm.rhs_of thm) of
wenzelm@54725
  1123
                      NONE => SOME thm
wenzelm@54725
  1124
                    | SOME thm' => SOME (Thm.transitive thm thm'))
wenzelm@51717
  1125
                  end
wenzelm@51717
  1126
              | _  =>
wenzelm@54727
  1127
                  let
wenzelm@54727
  1128
                    fun appc () =
wenzelm@54727
  1129
                      let
wenzelm@54727
  1130
                        val (tskel, uskel) =
wenzelm@54727
  1131
                          (case skel of
wenzelm@54727
  1132
                            tskel $ uskel => (tskel, uskel)
wenzelm@54727
  1133
                          | _ => (skel0, skel0));
wenzelm@54727
  1134
                        val (ct, cu) = Thm.dest_comb t0;
wenzelm@54727
  1135
                      in
wenzelm@54727
  1136
                        (case botc tskel ctxt ct of
wenzelm@54727
  1137
                          SOME thm1 =>
wenzelm@54727
  1138
                            (case botc uskel ctxt cu of
wenzelm@54727
  1139
                              SOME thm2 => SOME (Thm.combination thm1 thm2)
wenzelm@54727
  1140
                            | NONE => SOME (Thm.combination thm1 (Thm.reflexive cu)))
wenzelm@54727
  1141
                        | NONE =>
wenzelm@54727
  1142
                            (case botc uskel ctxt cu of
wenzelm@54727
  1143
                              SOME thm1 => SOME (Thm.combination (Thm.reflexive ct) thm1)
wenzelm@54727
  1144
                            | NONE => NONE))
wenzelm@54727
  1145
                      end;
wenzelm@54727
  1146
                    val (h, ts) = strip_comb t;
wenzelm@54725
  1147
                  in
wenzelm@54725
  1148
                    (case cong_name h of
wenzelm@54725
  1149
                      SOME a =>
wenzelm@54725
  1150
                        (case AList.lookup (op =) (fst congs) a of
wenzelm@54725
  1151
                           NONE => appc ()
wenzelm@54725
  1152
                        | SOME cong =>
wenzelm@51717
  1153
     (*post processing: some partial applications h t1 ... tj, j <= length ts,
wenzelm@51717
  1154
       may be a redex. Example: map (%x. x) = (%xs. xs) wrt map_cong*)
wenzelm@54725
  1155
                           (let
wenzelm@54725
  1156
                              val thm = congc (prover ctxt) ctxt maxidx cong t0;
wenzelm@54725
  1157
                              val t = the_default t0 (Option.map Thm.rhs_of thm);
wenzelm@54725
  1158
                              val (cl, cr) = Thm.dest_comb t
wenzelm@54725
  1159
                              val dVar = Var(("", 0), dummyT)
wenzelm@54725
  1160
                              val skel =
wenzelm@54725
  1161
                                list_comb (h, replicate (length ts) dVar)
wenzelm@54725
  1162
                            in
wenzelm@54725
  1163
                              (case botc skel ctxt cl of
wenzelm@54725
  1164
                                NONE => thm
wenzelm@54725
  1165
                              | SOME thm' =>
wenzelm@54725
  1166
                                  transitive3 thm (Thm.combination thm' (Thm.reflexive cr)))
wenzelm@54725
  1167
                            end handle Pattern.MATCH => appc ()))
wenzelm@54725
  1168
                     | _ => appc ())
wenzelm@51717
  1169
                  end)
wenzelm@51717
  1170
            | _ => NONE)
wenzelm@51717
  1171
        end
wenzelm@51717
  1172
    and impc ct ctxt =
wenzelm@54725
  1173
      if mutsimp then mut_impc0 [] ct [] [] ctxt
wenzelm@54725
  1174
      else nonmut_impc ct ctxt
berghofe@10413
  1175
wenzelm@54984
  1176
    and rules_of_prem prem ctxt =
wenzelm@59582
  1177
      if maxidx_of_term (Thm.term_of prem) <> ~1
wenzelm@55028
  1178
      then
wenzelm@55031
  1179
       (cond_tracing ctxt (fn () =>
wenzelm@55028
  1180
          print_term ctxt "Cannot add premise as rewrite rule because it contains (type) unknowns:"
wenzelm@59582
  1181
            (Thm.term_of prem));
wenzelm@55028
  1182
        (([], NONE), ctxt))
berghofe@13607
  1183
      else
wenzelm@54984
  1184
        let val (asm, ctxt') = Thm.assume_hyps prem ctxt
wenzelm@54984
  1185
        in ((extract_safe_rrules ctxt' asm, SOME asm), ctxt') end
berghofe@10413
  1186
wenzelm@51717
  1187
    and add_rrules (rrss, asms) ctxt =
wenzelm@51717
  1188
      (fold o fold) insert_rrule rrss ctxt |> add_prems (map_filter I asms)
berghofe@10413
  1189
wenzelm@23178
  1190
    and disch r prem eq =
berghofe@13607
  1191
      let
wenzelm@22902
  1192
        val (lhs, rhs) = Thm.dest_equals (Thm.cprop_of eq);
wenzelm@54727
  1193
        val eq' =
wenzelm@54727
  1194
          Thm.implies_elim
wenzelm@60642
  1195
            (Thm.instantiate ([], [(vA, prem), (vB, lhs), (vC, rhs)]) Drule.imp_cong)
wenzelm@54727
  1196
            (Thm.implies_intr prem eq);
wenzelm@54725
  1197
      in
wenzelm@54725
  1198
        if not r then eq'
wenzelm@54725
  1199
        else
wenzelm@54725
  1200
          let
wenzelm@54725
  1201
            val (prem', concl) = Thm.dest_implies lhs;
wenzelm@54727
  1202
            val (prem'', _) = Thm.dest_implies rhs;
wenzelm@54727
  1203
          in
wenzelm@54727
  1204
            Thm.transitive
wenzelm@54727
  1205
              (Thm.transitive
wenzelm@60642
  1206
                (Thm.instantiate ([], [(vA, prem'), (vB, prem), (vC, concl)]) Drule.swap_prems_eq)
wenzelm@54727
  1207
                eq')
wenzelm@60642
  1208
              (Thm.instantiate ([], [(vA, prem), (vB, prem''), (vC, concl)]) Drule.swap_prems_eq)
wenzelm@54725
  1209
          end
berghofe@10413
  1210
      end
berghofe@10413
  1211
berghofe@13607
  1212
    and rebuild [] _ _ _ _ eq = eq
wenzelm@51717
  1213
      | rebuild (prem :: prems) concl (_ :: rrss) (_ :: asms) ctxt eq =
berghofe@13607
  1214
          let
wenzelm@51717
  1215
            val ctxt' = add_rrules (rev rrss, rev asms) ctxt;
berghofe@13607
  1216
            val concl' =
wenzelm@22902
  1217
              Drule.mk_implies (prem, the_default concl (Option.map Thm.rhs_of eq));
wenzelm@54727
  1218
            val dprem = Option.map (disch false prem);
wenzelm@38834
  1219
          in
wenzelm@52091
  1220
            (case rewritec (prover, maxidx) ctxt' concl' of
wenzelm@51717
  1221
              NONE => rebuild prems concl' rrss asms ctxt (dprem eq)
wenzelm@54727
  1222
            | SOME (eq', _) =>
wenzelm@54727
  1223
                transitive2 (fold (disch false) prems (the (transitive3 (dprem eq) eq')))
wenzelm@54727
  1224
                  (mut_impc0 (rev prems) (Thm.rhs_of eq') (rev rrss) (rev asms) ctxt))
berghofe@13607
  1225
          end
wenzelm@15023
  1226
wenzelm@51717
  1227
    and mut_impc0 prems concl rrss asms ctxt =
berghofe@13607
  1228
      let
berghofe@13607
  1229
        val prems' = strip_imp_prems concl;
wenzelm@54984
  1230
        val ((rrss', asms'), ctxt') = fold_map rules_of_prem prems' ctxt |>> split_list;
wenzelm@38834
  1231
      in
wenzelm@38834
  1232
        mut_impc (prems @ prems') (strip_imp_concl concl) (rrss @ rrss')
wenzelm@54984
  1233
          (asms @ asms') [] [] [] [] ctxt' ~1 ~1
berghofe@13607
  1234
      end
wenzelm@15023
  1235
wenzelm@51717
  1236
    and mut_impc [] concl [] [] prems' rrss' asms' eqns ctxt changed k =
wenzelm@33245
  1237
        transitive1 (fold (fn (eq1, prem) => fn eq2 => transitive1 eq1
wenzelm@33245
  1238
            (Option.map (disch false prem) eq2)) (eqns ~~ prems') NONE)
berghofe@13607
  1239
          (if changed > 0 then
berghofe@13607
  1240
             mut_impc (rev prems') concl (rev rrss') (rev asms')
wenzelm@51717
  1241
               [] [] [] [] ctxt ~1 changed
wenzelm@51717
  1242
           else rebuild prems' concl rrss' asms' ctxt
wenzelm@51717
  1243
             (botc skel0 (add_rrules (rev rrss', rev asms') ctxt) concl))
berghofe@13607
  1244
berghofe@13607
  1245
      | mut_impc (prem :: prems) concl (rrs :: rrss) (asm :: asms)
wenzelm@51717
  1246
          prems' rrss' asms' eqns ctxt changed k =
wenzelm@54725
  1247
        (case (if k = 0 then NONE else botc skel0 (add_rrules
wenzelm@51717
  1248
          (rev rrss' @ rrss, rev asms' @ asms) ctxt) prem) of
skalberg@15531
  1249
            NONE => mut_impc prems concl rrss asms (prem :: prems')
wenzelm@51717
  1250
              (rrs :: rrss') (asm :: asms') (NONE :: eqns) ctxt changed
berghofe@13607
  1251
              (if k = 0 then 0 else k - 1)
wenzelm@54725
  1252
        | SOME eqn =>
berghofe@13607
  1253
            let
wenzelm@22902
  1254
              val prem' = Thm.rhs_of eqn;
wenzelm@59582
  1255
              val tprems = map Thm.term_of prems;
wenzelm@33029
  1256
              val i = 1 + fold Integer.max (map (fn p =>
wenzelm@44058
  1257
                find_index (fn q => q aconv p) tprems) (Thm.hyps_of eqn)) ~1;
wenzelm@54984
  1258
              val ((rrs', asm'), ctxt') = rules_of_prem prem' ctxt;
wenzelm@54725
  1259
            in
wenzelm@54725
  1260
              mut_impc prems concl rrss asms (prem' :: prems')
wenzelm@54725
  1261
                (rrs' :: rrss') (asm' :: asms')
wenzelm@54725
  1262
                (SOME (fold_rev (disch true)
wenzelm@54725
  1263
                  (take i prems)
wenzelm@54725
  1264
                  (Drule.imp_cong_rule eqn (Thm.reflexive (Drule.list_implies
wenzelm@54725
  1265
                    (drop i prems, concl))))) :: eqns)
wenzelm@54984
  1266
                ctxt' (length prems') ~1
wenzelm@54725
  1267
            end)
berghofe@13607
  1268
wenzelm@54725
  1269
    (*legacy code -- only for backwards compatibility*)
wenzelm@51717
  1270
    and nonmut_impc ct ctxt =
wenzelm@38834
  1271
      let
wenzelm@38834
  1272
        val (prem, conc) = Thm.dest_implies ct;
wenzelm@51717
  1273
        val thm1 = if simprem then botc skel0 ctxt prem else NONE;
wenzelm@38834
  1274
        val prem1 = the_default prem (Option.map Thm.rhs_of thm1);
wenzelm@51717
  1275
        val ctxt1 =
wenzelm@51717
  1276
          if not useprem then ctxt
wenzelm@54984
  1277
          else
wenzelm@54984
  1278
            let val ((rrs, asm), ctxt') = rules_of_prem prem1 ctxt
wenzelm@54984
  1279
            in add_rrules ([rrs], [asm]) ctxt' end;
wenzelm@38834
  1280
      in
wenzelm@51717
  1281
        (case botc skel0 ctxt1 conc of
wenzelm@38834
  1282
          NONE =>
wenzelm@38834
  1283
            (case thm1 of
wenzelm@38834
  1284
              NONE => NONE
wenzelm@38834
  1285
            | SOME thm1' => SOME (Drule.imp_cong_rule thm1' (Thm.reflexive conc)))
wenzelm@38834
  1286
        | SOME thm2 =>
wenzelm@38834
  1287
            let val thm2' = disch false prem1 thm2 in
wenzelm@38834
  1288
              (case thm1 of
wenzelm@38834
  1289
                NONE => SOME thm2'
wenzelm@38834
  1290
              | SOME thm1' =>
wenzelm@36944
  1291
                 SOME (Thm.transitive (Drule.imp_cong_rule thm1' (Thm.reflexive conc)) thm2'))
wenzelm@38834
  1292
            end)
wenzelm@54725
  1293
      end;
berghofe@10413
  1294
wenzelm@54725
  1295
  in try_botc end;
berghofe@10413
  1296
berghofe@10413
  1297
wenzelm@15023
  1298
(* Meta-rewriting: rewrites t to u and returns the theorem t==u *)
berghofe@10413
  1299
berghofe@10413
  1300
(*
berghofe@10413
  1301
  Parameters:
berghofe@10413
  1302
    mode = (simplify A,
berghofe@10413
  1303
            use A in simplifying B,
berghofe@10413
  1304
            use prems of B (if B is again a meta-impl.) to simplify A)
berghofe@10413
  1305
           when simplifying A ==> B
berghofe@10413
  1306
    prover: how to solve premises in conditional rewrites and congruences
berghofe@10413
  1307
*)
berghofe@10413
  1308
wenzelm@51717
  1309
fun rewrite_cterm mode prover raw_ctxt raw_ct =
wenzelm@17882
  1310
  let
wenzelm@54729
  1311
    val thy = Proof_Context.theory_of raw_ctxt;
wenzelm@52091
  1312
wenzelm@60324
  1313
    val ct = raw_ct
wenzelm@60324
  1314
      |> Thm.transfer_cterm thy
wenzelm@60324
  1315
      |> Thm.adjust_maxidx_cterm ~1;
wenzelm@59586
  1316
    val maxidx = Thm.maxidx_of_cterm ct;
wenzelm@52091
  1317
wenzelm@54729
  1318
    val ctxt =
wenzelm@54729
  1319
      raw_ctxt
wenzelm@54729
  1320
      |> Context_Position.set_visible false
wenzelm@54729
  1321
      |> inc_simp_depth
wenzelm@59582
  1322
      |> (fn ctxt => trace_invoke {depth = simp_depth ctxt, term = Thm.term_of ct} ctxt);
wenzelm@54729
  1323
wenzelm@55028
  1324
    val _ =
wenzelm@55031
  1325
      cond_tracing ctxt (fn () =>
wenzelm@59582
  1326
        print_term ctxt "SIMPLIFIER INVOKED ON THE FOLLOWING TERM:" (Thm.term_of ct));
wenzelm@58950
  1327
  in bottomc (mode, Option.map (Drule.flexflex_unique (SOME ctxt)) oo prover, maxidx) ctxt ct end;
berghofe@10413
  1328
wenzelm@21708
  1329
val simple_prover =
wenzelm@59498
  1330
  SINGLE o (fn ctxt => ALLGOALS (resolve_tac ctxt (prems_of ctxt)));
wenzelm@21708
  1331
wenzelm@54742
  1332
fun rewrite _ _ [] = Thm.reflexive
wenzelm@54742
  1333
  | rewrite ctxt full thms =
wenzelm@51717
  1334
      rewrite_cterm (full, false, false) simple_prover
wenzelm@54742
  1335
        (empty_simpset ctxt addsimps thms);
wenzelm@11672
  1336
wenzelm@54742
  1337
fun rewrite_rule ctxt = Conv.fconv_rule o rewrite ctxt true;
wenzelm@21708
  1338
wenzelm@15023
  1339
(*simple term rewriting -- no proof*)
wenzelm@16458
  1340
fun rewrite_term thy rules procs =
wenzelm@17203
  1341
  Pattern.rewrite_term thy (map decomp_simp' rules) procs;
wenzelm@15023
  1342
wenzelm@51717
  1343
fun rewrite_thm mode prover ctxt = Conv.fconv_rule (rewrite_cterm mode prover ctxt);
berghofe@10413
  1344
wenzelm@23536
  1345
(*Rewrite the subgoals of a proof state (represented by a theorem)*)
wenzelm@54742
  1346
fun rewrite_goals_rule ctxt thms th =
wenzelm@23584
  1347
  Conv.fconv_rule (Conv.prems_conv ~1 (rewrite_cterm (true, true, true) simple_prover
wenzelm@54742
  1348
    (empty_simpset ctxt addsimps thms))) th;
berghofe@10413
  1349
wenzelm@20228
  1350
wenzelm@21708
  1351
(** meta-rewriting tactics **)
wenzelm@21708
  1352
wenzelm@28839
  1353
(*Rewrite all subgoals*)
wenzelm@54742
  1354
fun rewrite_goals_tac ctxt defs = PRIMITIVE (rewrite_goals_rule ctxt defs);
wenzelm@21708
  1355
wenzelm@28839
  1356
(*Rewrite one subgoal*)
wenzelm@51717
  1357
fun generic_rewrite_goal_tac mode prover_tac ctxt i thm =
wenzelm@25203
  1358
  if 0 < i andalso i <= Thm.nprems_of thm then
wenzelm@51717
  1359
    Seq.single (Conv.gconv_rule (rewrite_cterm mode (SINGLE o prover_tac) ctxt) i thm)
wenzelm@25203
  1360
  else Seq.empty;
wenzelm@23536
  1361
wenzelm@54742
  1362
fun rewrite_goal_tac ctxt rews =
wenzelm@51717
  1363
  generic_rewrite_goal_tac (true, false, false) (K no_tac)
wenzelm@54742
  1364
    (empty_simpset ctxt addsimps rews);
wenzelm@23536
  1365
wenzelm@46707
  1366
(*Prunes all redundant parameters from the proof state by rewriting.*)
wenzelm@54742
  1367
fun prune_params_tac ctxt = rewrite_goals_tac ctxt [Drule.triv_forall_equality];
wenzelm@21708
  1368
wenzelm@21708
  1369
wenzelm@21708
  1370
(* for folding definitions, handling critical pairs *)
wenzelm@21708
  1371
wenzelm@21708
  1372
(*The depth of nesting in a term*)
wenzelm@32797
  1373
fun term_depth (Abs (_, _, t)) = 1 + term_depth t
wenzelm@32797
  1374
  | term_depth (f $ t) = 1 + Int.max (term_depth f, term_depth t)
wenzelm@21708
  1375
  | term_depth _ = 0;
wenzelm@21708
  1376
wenzelm@59582
  1377
val lhs_of_thm = #1 o Logic.dest_equals o Thm.prop_of;
wenzelm@21708
  1378
wenzelm@21708
  1379
(*folding should handle critical pairs!  E.g. K == Inl(0),  S == Inr(Inl(0))
wenzelm@21708
  1380
  Returns longest lhs first to avoid folding its subexpressions.*)
wenzelm@21708
  1381
fun sort_lhs_depths defs =
wenzelm@21708
  1382
  let val keylist = AList.make (term_depth o lhs_of_thm) defs
wenzelm@21708
  1383
      val keys = sort_distinct (rev_order o int_ord) (map #2 keylist)
wenzelm@21708
  1384
  in map (AList.find (op =) keylist) keys end;
wenzelm@21708
  1385
wenzelm@36944
  1386
val rev_defs = sort_lhs_depths o map Thm.symmetric;
wenzelm@21708
  1387
wenzelm@54742
  1388
fun fold_rule ctxt defs = fold (rewrite_rule ctxt) (rev_defs defs);
wenzelm@54742
  1389
fun fold_goals_tac ctxt defs = EVERY (map (rewrite_goals_tac ctxt) (rev_defs defs));
wenzelm@21708
  1390
wenzelm@21708
  1391
wenzelm@20228
  1392
(* HHF normal form: !! before ==>, outermost !! generalized *)
wenzelm@20228
  1393
wenzelm@20228
  1394
local
wenzelm@20228
  1395
wenzelm@54883
  1396
fun gen_norm_hhf ss ctxt th =
wenzelm@21565
  1397
  (if Drule.is_norm_hhf (Thm.prop_of th) then th
wenzelm@51717
  1398
   else
wenzelm@51717
  1399
    Conv.fconv_rule
wenzelm@54883
  1400
      (rewrite_cterm (true, false, false) (K (K NONE)) (put_simpset ss ctxt)) th)
wenzelm@21565
  1401
  |> Thm.adjust_maxidx_thm ~1
wenzelm@60822
  1402
  |> Variable.gen_all ctxt;
wenzelm@20228
  1403
wenzelm@51717
  1404
val hhf_ss =
wenzelm@51717
  1405
  simpset_of (empty_simpset (Context.proof_of (Context.the_thread_data ()))
wenzelm@51717
  1406
    addsimps Drule.norm_hhf_eqs);
wenzelm@51717
  1407
wenzelm@51717
  1408
val hhf_protect_ss =
wenzelm@51717
  1409
  simpset_of (empty_simpset (Context.proof_of (Context.the_thread_data ()))
wenzelm@51717
  1410
    addsimps Drule.norm_hhf_eqs |> add_eqcong Drule.protect_cong);
wenzelm@20228
  1411
wenzelm@20228
  1412
in
wenzelm@20228
  1413
wenzelm@26424
  1414
val norm_hhf = gen_norm_hhf hhf_ss;
wenzelm@51717
  1415
val norm_hhf_protect = gen_norm_hhf hhf_protect_ss;
wenzelm@20228
  1416
wenzelm@20228
  1417
end;
wenzelm@20228
  1418
berghofe@10413
  1419
end;
berghofe@10413
  1420
wenzelm@41228
  1421
structure Basic_Meta_Simplifier: BASIC_RAW_SIMPLIFIER = Raw_Simplifier;
wenzelm@32738
  1422
open Basic_Meta_Simplifier;