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