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