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