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