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