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