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