src/Pure/meta_simplifier.ML
author ballarin
Thu Feb 27 15:12:29 2003 +0100 (2003-02-27)
changeset 13835 12b2ffbe543a
parent 13828 fb6ec40dd291
child 13932 0eb3d91b519a
permissions -rw-r--r--
Change to meta simplifier: congruence rules may now have frees as head of term.
berghofe@10413
     1
(*  Title:      Pure/meta_simplifier.ML
berghofe@10413
     2
    ID:         $Id$
wenzelm@11672
     3
    Author:     Tobias Nipkow and Stefan Berghofer
wenzelm@12783
     4
    License:    GPL (GNU GENERAL PUBLIC LICENSE)
berghofe@10413
     5
wenzelm@11672
     6
Meta-level Simplification.
berghofe@10413
     7
*)
berghofe@10413
     8
wenzelm@11672
     9
signature BASIC_META_SIMPLIFIER =
wenzelm@11672
    10
sig
wenzelm@11672
    11
  val trace_simp: bool ref
wenzelm@11672
    12
  val debug_simp: bool ref
nipkow@13828
    13
  val simp_depth_limit: int ref
wenzelm@11672
    14
end;
wenzelm@11672
    15
berghofe@10413
    16
signature META_SIMPLIFIER =
berghofe@10413
    17
sig
wenzelm@11672
    18
  include BASIC_META_SIMPLIFIER
berghofe@10413
    19
  exception SIMPLIFIER of string * thm
wenzelm@13486
    20
  exception SIMPROC_FAIL of string * exn
berghofe@10413
    21
  type meta_simpset
wenzelm@12603
    22
  val dest_mss          : meta_simpset ->
berghofe@10413
    23
    {simps: thm list, congs: thm list, procs: (string * cterm list) list}
berghofe@10413
    24
  val empty_mss         : meta_simpset
wenzelm@12603
    25
  val clear_mss         : meta_simpset -> meta_simpset
wenzelm@12603
    26
  val merge_mss         : meta_simpset * meta_simpset -> meta_simpset
berghofe@10413
    27
  val add_simps         : meta_simpset * thm list -> meta_simpset
berghofe@10413
    28
  val del_simps         : meta_simpset * thm list -> meta_simpset
berghofe@10413
    29
  val mss_of            : thm list -> meta_simpset
berghofe@10413
    30
  val add_congs         : meta_simpset * thm list -> meta_simpset
berghofe@10413
    31
  val del_congs         : meta_simpset * thm list -> meta_simpset
wenzelm@12603
    32
  val add_simprocs      : meta_simpset *
berghofe@10413
    33
    (string * cterm list * (Sign.sg -> thm list -> term -> thm option) * stamp) list
berghofe@10413
    34
      -> meta_simpset
wenzelm@12603
    35
  val del_simprocs      : meta_simpset *
berghofe@10413
    36
    (string * cterm list * (Sign.sg -> thm list -> term -> thm option) * stamp) list
berghofe@10413
    37
      -> meta_simpset
berghofe@10413
    38
  val add_prems         : meta_simpset * thm list -> meta_simpset
berghofe@10413
    39
  val prems_of_mss      : meta_simpset -> thm list
berghofe@10413
    40
  val set_mk_rews       : meta_simpset * (thm -> thm list) -> meta_simpset
berghofe@10413
    41
  val set_mk_sym        : meta_simpset * (thm -> thm option) -> meta_simpset
berghofe@10413
    42
  val set_mk_eq_True    : meta_simpset * (thm -> thm option) -> meta_simpset
berghofe@10413
    43
  val set_termless      : meta_simpset * (term * term -> bool) -> meta_simpset
wenzelm@12779
    44
  val beta_eta_conversion: cterm -> thm
wenzelm@11672
    45
  val rewrite_cterm: bool * bool * bool ->
wenzelm@11672
    46
    (meta_simpset -> thm -> thm option) -> meta_simpset -> cterm -> thm
berghofe@11736
    47
  val goals_conv        : (int -> bool) -> (cterm -> thm) -> cterm -> thm
berghofe@11736
    48
  val forall_conv       : (cterm -> thm) -> cterm -> thm
berghofe@11736
    49
  val fconv_rule        : (cterm -> thm) -> thm -> thm
wenzelm@11767
    50
  val rewrite_aux       : (meta_simpset -> thm -> thm option) -> bool -> thm list -> cterm -> thm
wenzelm@11767
    51
  val simplify_aux      : (meta_simpset -> thm -> thm option) -> bool -> thm list -> thm -> thm
berghofe@10413
    52
  val rewrite_thm       : bool * bool * bool
berghofe@10413
    53
                          -> (meta_simpset -> thm -> thm option)
berghofe@10413
    54
                          -> meta_simpset -> thm -> thm
berghofe@10413
    55
  val rewrite_goals_rule_aux: (meta_simpset -> thm -> thm option) -> thm list -> thm -> thm
berghofe@10413
    56
  val rewrite_goal_rule : bool* bool * bool
berghofe@10413
    57
                          -> (meta_simpset -> thm -> thm option)
berghofe@10413
    58
                          -> meta_simpset -> int -> thm -> thm
berghofe@13196
    59
  val rewrite_term: Sign.sg -> thm list -> (term -> term option) list -> term -> term
berghofe@10413
    60
end;
berghofe@10413
    61
berghofe@10413
    62
structure MetaSimplifier : META_SIMPLIFIER =
berghofe@10413
    63
struct
berghofe@10413
    64
berghofe@10413
    65
(** diagnostics **)
berghofe@10413
    66
berghofe@10413
    67
exception SIMPLIFIER of string * thm;
wenzelm@13486
    68
exception SIMPROC_FAIL of string * exn;
berghofe@10413
    69
nipkow@11505
    70
val simp_depth = ref 0;
nipkow@13828
    71
val simp_depth_limit = ref 1000;
nipkow@11505
    72
wenzelm@12603
    73
local
wenzelm@12603
    74
wenzelm@12603
    75
fun println a =
wenzelm@12603
    76
  tracing ((case ! simp_depth of 0 => "" | n => "[" ^ string_of_int n ^ "]") ^ a);
nipkow@11505
    77
nipkow@11505
    78
fun prnt warn a = if warn then warning a else println a;
wenzelm@12603
    79
fun prtm warn a sign t = prnt warn (a ^ "\n" ^ Sign.string_of_term sign t);
wenzelm@12603
    80
fun prctm warn a t = prnt warn (a ^ "\n" ^ Display.string_of_cterm t);
berghofe@10413
    81
wenzelm@12603
    82
in
berghofe@10413
    83
wenzelm@12603
    84
fun prthm warn a = prctm warn a o Thm.cprop_of;
berghofe@10413
    85
berghofe@10413
    86
val trace_simp = ref false;
berghofe@10413
    87
val debug_simp = ref false;
berghofe@10413
    88
berghofe@10413
    89
fun trace warn a = if !trace_simp then prnt warn a else ();
berghofe@10413
    90
fun debug warn a = if !debug_simp then prnt warn a else ();
berghofe@10413
    91
berghofe@10413
    92
fun trace_term warn a sign t = if !trace_simp then prtm warn a sign t else ();
berghofe@10413
    93
fun trace_cterm warn a t = if !trace_simp then prctm warn a t else ();
berghofe@10413
    94
fun debug_term warn a sign t = if !debug_simp then prtm warn a sign t else ();
berghofe@10413
    95
nipkow@13569
    96
fun trace_thm a thm =
berghofe@10413
    97
  let val {sign, prop, ...} = rep_thm thm
nipkow@13569
    98
  in trace_term false a sign prop end;
nipkow@13569
    99
berghofe@13607
   100
fun trace_named_thm a (thm, name) =
berghofe@13607
   101
  trace_thm (a ^ (if name = "" then "" else " " ^ quote name) ^ ":") thm;
berghofe@10413
   102
wenzelm@12603
   103
end;
berghofe@10413
   104
berghofe@10413
   105
berghofe@10413
   106
(** meta simp sets **)
berghofe@10413
   107
berghofe@10413
   108
(* basic components *)
berghofe@10413
   109
berghofe@13607
   110
type rrule = {thm: thm, name: string, lhs: term, elhs: cterm, fo: bool, perm: bool};
berghofe@10413
   111
(* thm: the rewrite rule
berghofe@13607
   112
   name: name of theorem from which rewrite rule was extracted
berghofe@10413
   113
   lhs: the left-hand side
berghofe@10413
   114
   elhs: the etac-contracted lhs.
berghofe@10413
   115
   fo:  use first-order matching
berghofe@10413
   116
   perm: the rewrite rule is permutative
wenzelm@12603
   117
Remarks:
berghofe@10413
   118
  - elhs is used for matching,
berghofe@10413
   119
    lhs only for preservation of bound variable names.
berghofe@10413
   120
  - fo is set iff
berghofe@10413
   121
    either elhs is first-order (no Var is applied),
berghofe@10413
   122
           in which case fo-matching is complete,
berghofe@10413
   123
    or elhs is not a pattern,
berghofe@10413
   124
       in which case there is nothing better to do.
berghofe@10413
   125
*)
berghofe@10413
   126
type cong = {thm: thm, lhs: cterm};
berghofe@10413
   127
type simproc =
berghofe@10413
   128
 {name: string, proc: Sign.sg -> thm list -> term -> thm option, lhs: cterm, id: stamp};
berghofe@10413
   129
berghofe@10413
   130
fun eq_rrule ({thm = thm1, ...}: rrule, {thm = thm2, ...}: rrule) =
berghofe@10413
   131
  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
berghofe@10413
   132
wenzelm@12603
   133
fun eq_cong ({thm = thm1, ...}: cong, {thm = thm2, ...}: cong) =
berghofe@10413
   134
  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
berghofe@10413
   135
berghofe@10413
   136
fun eq_prem (thm1, thm2) =
berghofe@10413
   137
  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
berghofe@10413
   138
berghofe@10413
   139
fun eq_simproc ({id = s1, ...}:simproc, {id = s2, ...}:simproc) = (s1 = s2);
berghofe@10413
   140
berghofe@10413
   141
fun mk_simproc (name, proc, lhs, id) =
berghofe@10413
   142
  {name = name, proc = proc, lhs = lhs, id = id};
berghofe@10413
   143
berghofe@10413
   144
berghofe@10413
   145
(* datatype mss *)
berghofe@10413
   146
berghofe@10413
   147
(*
berghofe@10413
   148
  A "mss" contains data needed during conversion:
berghofe@10413
   149
    rules: discrimination net of rewrite rules;
berghofe@10413
   150
    congs: association list of congruence rules and
berghofe@10413
   151
           a list of `weak' congruence constants.
berghofe@10413
   152
           A congruence is `weak' if it avoids normalization of some argument.
berghofe@10413
   153
    procs: discrimination net of simplification procedures
berghofe@10413
   154
      (functions that prove rewrite rules on the fly);
berghofe@10413
   155
    bounds: names of bound variables already used
berghofe@10413
   156
      (for generating new names when rewriting under lambda abstractions);
berghofe@10413
   157
    prems: current premises;
berghofe@10413
   158
    mk_rews: mk: turns simplification thms into rewrite rules;
berghofe@10413
   159
             mk_sym: turns == around; (needs Drule!)
berghofe@10413
   160
             mk_eq_True: turns P into P == True - logic specific;
berghofe@10413
   161
    termless: relation for ordered rewriting;
nipkow@11504
   162
    depth: depth of conditional rewriting;
berghofe@10413
   163
*)
berghofe@10413
   164
berghofe@10413
   165
datatype meta_simpset =
berghofe@10413
   166
  Mss of {
berghofe@10413
   167
    rules: rrule Net.net,
berghofe@10413
   168
    congs: (string * cong) list * string list,
berghofe@10413
   169
    procs: simproc Net.net,
berghofe@10413
   170
    bounds: string list,
berghofe@10413
   171
    prems: thm list,
berghofe@10413
   172
    mk_rews: {mk: thm -> thm list,
berghofe@10413
   173
              mk_sym: thm -> thm option,
berghofe@10413
   174
              mk_eq_True: thm -> thm option},
nipkow@11504
   175
    termless: term * term -> bool,
nipkow@11504
   176
    depth: int};
berghofe@10413
   177
nipkow@11504
   178
fun mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless, depth) =
berghofe@10413
   179
  Mss {rules = rules, congs = congs, procs = procs, bounds = bounds,
nipkow@11504
   180
       prems=prems, mk_rews=mk_rews, termless=termless, depth=depth};
berghofe@10413
   181
nipkow@11504
   182
fun upd_rules(Mss{rules,congs,procs,bounds,prems,mk_rews,termless,depth}, rules') =
nipkow@11504
   183
  mk_mss(rules',congs,procs,bounds,prems,mk_rews,termless,depth);
berghofe@10413
   184
berghofe@10413
   185
val empty_mss =
berghofe@10413
   186
  let val mk_rews = {mk = K [], mk_sym = K None, mk_eq_True = K None}
nipkow@11504
   187
  in mk_mss (Net.empty, ([], []), Net.empty, [], [], mk_rews, Term.termless, 0) end;
berghofe@10413
   188
berghofe@10413
   189
fun clear_mss (Mss {mk_rews, termless, ...}) =
nipkow@11504
   190
  mk_mss (Net.empty, ([], []), Net.empty, [], [], mk_rews, termless,0);
berghofe@10413
   191
nipkow@11504
   192
fun incr_depth(Mss{rules,congs,procs,bounds,prems,mk_rews,termless,depth}) =
nipkow@13828
   193
  let val depth1 = depth+1
nipkow@13828
   194
  in if depth1 > !simp_depth_limit
nipkow@13828
   195
     then (warning "simp_depth_limit exceeded - giving up"; None)
nipkow@13828
   196
     else (if depth1 mod 5 = 0
nipkow@13828
   197
           then warning("Simplification depth " ^ string_of_int depth1)
nipkow@13828
   198
           else ();
nipkow@13828
   199
           Some(mk_mss(rules,congs,procs,bounds,prems,mk_rews,termless,depth1))
nipkow@13828
   200
          )
nipkow@13828
   201
  end;
berghofe@10413
   202
berghofe@10413
   203
berghofe@10413
   204
(** simpset operations **)
berghofe@10413
   205
berghofe@10413
   206
(* term variables *)
berghofe@10413
   207
berghofe@10413
   208
val add_term_varnames = foldl_aterms (fn (xs, Var (x, _)) => ins_ix (x, xs) | (xs, _) => xs);
berghofe@10413
   209
fun term_varnames t = add_term_varnames ([], t);
berghofe@10413
   210
berghofe@10413
   211
berghofe@10413
   212
(* dest_mss *)
berghofe@10413
   213
berghofe@10413
   214
fun dest_mss (Mss {rules, congs, procs, ...}) =
berghofe@10413
   215
  {simps = map (fn (_, {thm, ...}) => thm) (Net.dest rules),
berghofe@10413
   216
   congs = map (fn (_, {thm, ...}) => thm) (fst congs),
berghofe@10413
   217
   procs =
berghofe@10413
   218
     map (fn (_, {name, lhs, id, ...}) => ((name, lhs), id)) (Net.dest procs)
berghofe@10413
   219
     |> partition_eq eq_snd
berghofe@10413
   220
     |> map (fn ps => (#1 (#1 (hd ps)), map (#2 o #1) ps))
berghofe@10413
   221
     |> Library.sort_wrt #1};
berghofe@10413
   222
berghofe@10413
   223
wenzelm@12603
   224
(* merge_mss *)       (*NOTE: ignores mk_rews, termless and depth of 2nd mss*)
berghofe@10413
   225
berghofe@10413
   226
fun merge_mss
berghofe@10413
   227
 (Mss {rules = rules1, congs = (congs1,weak1), procs = procs1,
nipkow@11504
   228
       bounds = bounds1, prems = prems1, mk_rews, termless, depth},
berghofe@10413
   229
  Mss {rules = rules2, congs = (congs2,weak2), procs = procs2,
berghofe@10413
   230
       bounds = bounds2, prems = prems2, ...}) =
berghofe@10413
   231
      mk_mss
berghofe@10413
   232
       (Net.merge (rules1, rules2, eq_rrule),
wenzelm@12285
   233
        (gen_merge_lists (eq_cong o pairself snd) congs1 congs2,
berghofe@10413
   234
        merge_lists weak1 weak2),
berghofe@10413
   235
        Net.merge (procs1, procs2, eq_simproc),
berghofe@10413
   236
        merge_lists bounds1 bounds2,
wenzelm@12285
   237
        gen_merge_lists eq_prem prems1 prems2,
nipkow@11504
   238
        mk_rews, termless, depth);
berghofe@10413
   239
berghofe@10413
   240
berghofe@10413
   241
(* add_simps *)
berghofe@10413
   242
berghofe@13607
   243
fun mk_rrule2{thm, name, lhs, elhs, perm} =
berghofe@10413
   244
  let val fo = Pattern.first_order (term_of elhs) orelse not(Pattern.pattern (term_of elhs))
berghofe@13607
   245
  in {thm=thm, name=name, lhs=lhs, elhs=elhs, fo=fo, perm=perm} end
berghofe@10413
   246
berghofe@13607
   247
fun insert_rrule quiet (mss as Mss {rules,...},
berghofe@13607
   248
                 rrule as {thm,name,lhs,elhs,perm}) =
berghofe@13607
   249
  (trace_named_thm "Adding rewrite rule" (thm, name);
berghofe@10413
   250
   let val rrule2 as {elhs,...} = mk_rrule2 rrule
berghofe@10413
   251
       val rules' = Net.insert_term ((term_of elhs, rrule2), rules, eq_rrule)
berghofe@10413
   252
   in upd_rules(mss,rules') end
berghofe@13607
   253
   handle Net.INSERT => if quiet then mss else
berghofe@10413
   254
     (prthm true "Ignoring duplicate rewrite rule:" thm; mss));
berghofe@10413
   255
berghofe@10413
   256
fun vperm (Var _, Var _) = true
berghofe@10413
   257
  | vperm (Abs (_, _, s), Abs (_, _, t)) = vperm (s, t)
berghofe@10413
   258
  | vperm (t1 $ t2, u1 $ u2) = vperm (t1, u1) andalso vperm (t2, u2)
berghofe@10413
   259
  | vperm (t, u) = (t = u);
berghofe@10413
   260
berghofe@10413
   261
fun var_perm (t, u) =
berghofe@10413
   262
  vperm (t, u) andalso eq_set (term_varnames t, term_varnames u);
berghofe@10413
   263
berghofe@10413
   264
(* FIXME: it seems that the conditions on extra variables are too liberal if
berghofe@10413
   265
prems are nonempty: does solving the prems really guarantee instantiation of
berghofe@10413
   266
all its Vars? Better: a dynamic check each time a rule is applied.
berghofe@10413
   267
*)
berghofe@10413
   268
fun rewrite_rule_extra_vars prems elhs erhs =
berghofe@10413
   269
  not (term_varnames erhs subset foldl add_term_varnames (term_varnames elhs, prems))
berghofe@10413
   270
  orelse
berghofe@10413
   271
  not ((term_tvars erhs) subset
berghofe@10413
   272
       (term_tvars elhs  union  List.concat(map term_tvars prems)));
berghofe@10413
   273
berghofe@10413
   274
(*Simple test for looping rewrite rules and stupid orientations*)
berghofe@10413
   275
fun reorient sign prems lhs rhs =
berghofe@10413
   276
   rewrite_rule_extra_vars prems lhs rhs
berghofe@10413
   277
  orelse
berghofe@10413
   278
   is_Var (head_of lhs)
berghofe@10413
   279
  orelse
berghofe@10413
   280
   (exists (apl (lhs, Logic.occs)) (rhs :: prems))
berghofe@10413
   281
  orelse
berghofe@10413
   282
   (null prems andalso
berghofe@10413
   283
    Pattern.matches (#tsig (Sign.rep_sg sign)) (lhs, rhs))
berghofe@10413
   284
    (*the condition "null prems" is necessary because conditional rewrites
berghofe@10413
   285
      with extra variables in the conditions may terminate although
berghofe@10413
   286
      the rhs is an instance of the lhs. Example: ?m < ?n ==> f(?n) == f(?m)*)
berghofe@10413
   287
  orelse
berghofe@10413
   288
   (is_Const lhs andalso not(is_Const rhs))
berghofe@10413
   289
berghofe@10413
   290
fun decomp_simp thm =
berghofe@10413
   291
  let val {sign, prop, ...} = rep_thm thm;
berghofe@10413
   292
      val prems = Logic.strip_imp_prems prop;
berghofe@10413
   293
      val concl = Drule.strip_imp_concl (cprop_of thm);
berghofe@10413
   294
      val (lhs, rhs) = Drule.dest_equals concl handle TERM _ =>
berghofe@10413
   295
        raise SIMPLIFIER ("Rewrite rule not a meta-equality", thm)
berghofe@10413
   296
      val elhs = snd (Drule.dest_equals (cprop_of (Thm.eta_conversion lhs)));
berghofe@10413
   297
      val elhs = if elhs=lhs then lhs else elhs (* try to share *)
berghofe@10413
   298
      val erhs = Pattern.eta_contract (term_of rhs);
berghofe@10413
   299
      val perm = var_perm (term_of elhs, erhs) andalso not (term_of elhs aconv erhs)
berghofe@10413
   300
                 andalso not (is_Var (term_of elhs))
berghofe@10413
   301
  in (sign, prems, term_of lhs, elhs, term_of rhs, perm) end;
berghofe@10413
   302
wenzelm@12783
   303
fun decomp_simp' thm =
wenzelm@12979
   304
  let val (_, _, lhs, _, rhs, _) = decomp_simp thm in
wenzelm@12783
   305
    if Thm.nprems_of thm > 0 then raise SIMPLIFIER ("Bad conditional rewrite rule", thm)
wenzelm@12979
   306
    else (lhs, rhs)
wenzelm@12783
   307
  end;
wenzelm@12783
   308
berghofe@13607
   309
fun mk_eq_True (Mss{mk_rews={mk_eq_True,...},...}) (thm, name) =
berghofe@10413
   310
  case mk_eq_True thm of
berghofe@10413
   311
    None => []
berghofe@13607
   312
  | Some eq_True =>
berghofe@13607
   313
      let val (_,_,lhs,elhs,_,_) = decomp_simp eq_True
berghofe@13607
   314
      in [{thm=eq_True, name=name, lhs=lhs, elhs=elhs, perm=false}] end;
berghofe@10413
   315
berghofe@10413
   316
(* create the rewrite rule and possibly also the ==True variant,
berghofe@10413
   317
   in case there are extra vars on the rhs *)
berghofe@13607
   318
fun rrule_eq_True(thm,name,lhs,elhs,rhs,mss,thm2) =
berghofe@13607
   319
  let val rrule = {thm=thm, name=name, lhs=lhs, elhs=elhs, perm=false}
berghofe@10413
   320
  in if (term_varnames rhs)  subset (term_varnames lhs) andalso
berghofe@10413
   321
        (term_tvars rhs) subset (term_tvars lhs)
berghofe@10413
   322
     then [rrule]
berghofe@13607
   323
     else mk_eq_True mss (thm2, name) @ [rrule]
berghofe@10413
   324
  end;
berghofe@10413
   325
berghofe@13607
   326
fun mk_rrule mss (thm, name) =
berghofe@10413
   327
  let val (_,prems,lhs,elhs,rhs,perm) = decomp_simp thm
berghofe@13607
   328
  in if perm then [{thm=thm, name=name, lhs=lhs, elhs=elhs, perm=true}] else
berghofe@10413
   329
     (* weak test for loops: *)
berghofe@10413
   330
     if rewrite_rule_extra_vars prems lhs rhs orelse
berghofe@10413
   331
        is_Var (term_of elhs)
berghofe@13607
   332
     then mk_eq_True mss (thm, name)
berghofe@13607
   333
     else rrule_eq_True(thm,name,lhs,elhs,rhs,mss,thm)
berghofe@10413
   334
  end;
berghofe@10413
   335
berghofe@13607
   336
fun orient_rrule mss (thm, name) =
berghofe@10413
   337
  let val (sign,prems,lhs,elhs,rhs,perm) = decomp_simp thm
berghofe@13607
   338
  in if perm then [{thm=thm, name=name, lhs=lhs, elhs=elhs, perm=true}]
berghofe@10413
   339
     else if reorient sign prems lhs rhs
berghofe@10413
   340
          then if reorient sign prems rhs lhs
berghofe@13607
   341
               then mk_eq_True mss (thm, name)
berghofe@10413
   342
               else let val Mss{mk_rews={mk_sym,...},...} = mss
berghofe@10413
   343
                    in case mk_sym thm of
berghofe@10413
   344
                         None => []
berghofe@10413
   345
                       | Some thm' =>
berghofe@10413
   346
                           let val (_,_,lhs',elhs',rhs',_) = decomp_simp thm'
berghofe@13607
   347
                           in rrule_eq_True(thm',name,lhs',elhs',rhs',mss,thm) end
berghofe@10413
   348
                    end
berghofe@13607
   349
          else rrule_eq_True(thm,name,lhs,elhs,rhs,mss,thm)
berghofe@10413
   350
  end;
berghofe@10413
   351
berghofe@13607
   352
fun extract_rews(Mss{mk_rews = {mk,...},...},thms) =
berghofe@13607
   353
  flat (map (fn thm => map (rpair (Thm.name_of_thm thm)) (mk thm)) thms);
berghofe@10413
   354
berghofe@10413
   355
fun orient_comb_simps comb mk_rrule (mss,thms) =
berghofe@10413
   356
  let val rews = extract_rews(mss,thms)
berghofe@10413
   357
      val rrules = flat (map mk_rrule rews)
berghofe@10413
   358
  in foldl comb (mss,rrules) end
berghofe@10413
   359
berghofe@10413
   360
(* Add rewrite rules explicitly; do not reorient! *)
berghofe@10413
   361
fun add_simps(mss,thms) =
berghofe@13607
   362
  orient_comb_simps (insert_rrule false) (mk_rrule mss) (mss,thms);
berghofe@10413
   363
berghofe@13607
   364
fun mss_of thms = foldl (insert_rrule false) (empty_mss, flat
berghofe@13607
   365
  (map (fn thm => mk_rrule empty_mss (thm, Thm.name_of_thm thm)) thms));
berghofe@10413
   366
berghofe@10413
   367
fun extract_safe_rrules(mss,thm) =
berghofe@10413
   368
  flat (map (orient_rrule mss) (extract_rews(mss,[thm])));
berghofe@10413
   369
berghofe@10413
   370
(* del_simps *)
berghofe@10413
   371
berghofe@10413
   372
fun del_rrule(mss as Mss {rules,...},
berghofe@10413
   373
              rrule as {thm, elhs, ...}) =
berghofe@10413
   374
  (upd_rules(mss, Net.delete_term ((term_of elhs, rrule), rules, eq_rrule))
berghofe@10413
   375
   handle Net.DELETE =>
berghofe@10413
   376
     (prthm true "Rewrite rule not in simpset:" thm; mss));
berghofe@10413
   377
berghofe@10413
   378
fun del_simps(mss,thms) =
berghofe@10413
   379
  orient_comb_simps del_rrule (map mk_rrule2 o mk_rrule mss) (mss,thms);
berghofe@10413
   380
berghofe@10413
   381
berghofe@10413
   382
(* add_congs *)
berghofe@10413
   383
berghofe@10413
   384
fun is_full_cong_prems [] varpairs = null varpairs
berghofe@10413
   385
  | is_full_cong_prems (p::prems) varpairs =
berghofe@10413
   386
    (case Logic.strip_assums_concl p of
berghofe@10413
   387
       Const("==",_) $ lhs $ rhs =>
berghofe@10413
   388
         let val (x,xs) = strip_comb lhs and (y,ys) = strip_comb rhs
berghofe@10413
   389
         in is_Var x  andalso  forall is_Bound xs  andalso
berghofe@10413
   390
            null(findrep(xs))  andalso xs=ys andalso
berghofe@10413
   391
            (x,y) mem varpairs andalso
berghofe@10413
   392
            is_full_cong_prems prems (varpairs\(x,y))
berghofe@10413
   393
         end
berghofe@10413
   394
     | _ => false);
berghofe@10413
   395
berghofe@10413
   396
fun is_full_cong thm =
berghofe@10413
   397
let val prems = prems_of thm
berghofe@10413
   398
    and concl = concl_of thm
berghofe@10413
   399
    val (lhs,rhs) = Logic.dest_equals concl
berghofe@10413
   400
    val (f,xs) = strip_comb lhs
berghofe@10413
   401
    and (g,ys) = strip_comb rhs
berghofe@10413
   402
in
berghofe@10413
   403
  f=g andalso null(findrep(xs@ys)) andalso length xs = length ys andalso
berghofe@10413
   404
  is_full_cong_prems prems (xs ~~ ys)
berghofe@10413
   405
end
berghofe@10413
   406
ballarin@13835
   407
fun cong_name (Const (a, _)) = Some a
ballarin@13835
   408
  | cong_name (Free (a, _)) = Some ("Free: " ^ a)
ballarin@13835
   409
  | cong_name _ = None;
ballarin@13835
   410
nipkow@11504
   411
fun add_cong (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, thm) =
berghofe@10413
   412
  let
berghofe@10413
   413
    val (lhs, _) = Drule.dest_equals (Drule.strip_imp_concl (cprop_of thm)) handle TERM _ =>
berghofe@10413
   414
      raise SIMPLIFIER ("Congruence not a meta-equality", thm);
berghofe@10413
   415
(*   val lhs = Pattern.eta_contract lhs; *)
ballarin@13835
   416
    val a = (case cong_name (head_of (term_of lhs)) of
ballarin@13835
   417
        Some a => a
ballarin@13835
   418
      | None =>
ballarin@13835
   419
        raise SIMPLIFIER ("Congruence must start with a constant or free variable", thm));
berghofe@10413
   420
    val (alist,weak) = congs
berghofe@10413
   421
    val alist2 = overwrite_warn (alist, (a,{lhs=lhs, thm=thm}))
berghofe@10413
   422
           ("Overwriting congruence rule for " ^ quote a);
berghofe@10413
   423
    val weak2 = if is_full_cong thm then weak else a::weak
berghofe@10413
   424
  in
nipkow@11504
   425
    mk_mss (rules,(alist2,weak2),procs,bounds,prems,mk_rews,termless,depth)
berghofe@10413
   426
  end;
berghofe@10413
   427
berghofe@10413
   428
val (op add_congs) = foldl add_cong;
berghofe@10413
   429
berghofe@10413
   430
berghofe@10413
   431
(* del_congs *)
berghofe@10413
   432
nipkow@11504
   433
fun del_cong (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, thm) =
berghofe@10413
   434
  let
berghofe@10413
   435
    val (lhs, _) = Logic.dest_equals (concl_of thm) handle TERM _ =>
berghofe@10413
   436
      raise SIMPLIFIER ("Congruence not a meta-equality", thm);
berghofe@10413
   437
(*   val lhs = Pattern.eta_contract lhs; *)
ballarin@13835
   438
    val a = (case cong_name (head_of lhs) of
ballarin@13835
   439
        Some a => a
ballarin@13835
   440
      | None =>
ballarin@13835
   441
        raise SIMPLIFIER ("Congruence must start with a constant", thm));
berghofe@10413
   442
    val (alist,_) = congs
berghofe@10413
   443
    val alist2 = filter (fn (x,_)=> x<>a) alist
berghofe@10413
   444
    val weak2 = mapfilter (fn(a,{thm,...}) => if is_full_cong thm then None
berghofe@10413
   445
                                              else Some a)
berghofe@10413
   446
                   alist2
berghofe@10413
   447
  in
nipkow@11504
   448
    mk_mss (rules,(alist2,weak2),procs,bounds,prems,mk_rews,termless,depth)
berghofe@10413
   449
  end;
berghofe@10413
   450
berghofe@10413
   451
val (op del_congs) = foldl del_cong;
berghofe@10413
   452
berghofe@10413
   453
berghofe@10413
   454
(* add_simprocs *)
berghofe@10413
   455
nipkow@11504
   456
fun add_proc (mss as Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth},
berghofe@10413
   457
    (name, lhs, proc, id)) =
berghofe@10413
   458
  let val {sign, t, ...} = rep_cterm lhs
berghofe@10413
   459
  in (trace_term false ("Adding simplification procedure " ^ quote name ^ " for")
berghofe@10413
   460
      sign t;
berghofe@10413
   461
    mk_mss (rules, congs,
berghofe@10413
   462
      Net.insert_term ((t, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
wenzelm@12603
   463
        handle Net.INSERT =>
wenzelm@12603
   464
            (warning ("Ignoring duplicate simplification procedure \""
wenzelm@12603
   465
                      ^ name ^ "\"");
wenzelm@12603
   466
             procs),
nipkow@11504
   467
        bounds, prems, mk_rews, termless,depth))
berghofe@10413
   468
  end;
berghofe@10413
   469
berghofe@10413
   470
fun add_simproc (mss, (name, lhss, proc, id)) =
berghofe@10413
   471
  foldl add_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
berghofe@10413
   472
berghofe@10413
   473
val add_simprocs = foldl add_simproc;
berghofe@10413
   474
berghofe@10413
   475
berghofe@10413
   476
(* del_simprocs *)
berghofe@10413
   477
nipkow@11504
   478
fun del_proc (mss as Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth},
berghofe@10413
   479
    (name, lhs, proc, id)) =
berghofe@10413
   480
  mk_mss (rules, congs,
berghofe@10413
   481
    Net.delete_term ((term_of lhs, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
wenzelm@12603
   482
      handle Net.DELETE =>
wenzelm@12603
   483
          (warning ("Simplification procedure \"" ^ name ^
wenzelm@12603
   484
                       "\" not in simpset"); procs),
nipkow@11504
   485
      bounds, prems, mk_rews, termless, depth);
berghofe@10413
   486
berghofe@10413
   487
fun del_simproc (mss, (name, lhss, proc, id)) =
berghofe@10413
   488
  foldl del_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
berghofe@10413
   489
berghofe@10413
   490
val del_simprocs = foldl del_simproc;
berghofe@10413
   491
berghofe@10413
   492
berghofe@10413
   493
(* prems *)
berghofe@10413
   494
nipkow@11504
   495
fun add_prems (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, thms) =
nipkow@11504
   496
  mk_mss (rules, congs, procs, bounds, thms @ prems, mk_rews, termless, depth);
berghofe@10413
   497
berghofe@10413
   498
fun prems_of_mss (Mss {prems, ...}) = prems;
berghofe@10413
   499
berghofe@10413
   500
berghofe@10413
   501
(* mk_rews *)
berghofe@10413
   502
berghofe@10413
   503
fun set_mk_rews
nipkow@11504
   504
  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless, depth}, mk) =
berghofe@10413
   505
    mk_mss (rules, congs, procs, bounds, prems,
berghofe@10413
   506
            {mk=mk, mk_sym= #mk_sym mk_rews, mk_eq_True= #mk_eq_True mk_rews},
nipkow@11504
   507
            termless, depth);
berghofe@10413
   508
berghofe@10413
   509
fun set_mk_sym
nipkow@11504
   510
  (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, mk_sym) =
berghofe@10413
   511
    mk_mss (rules, congs, procs, bounds, prems,
berghofe@10413
   512
            {mk= #mk mk_rews, mk_sym= mk_sym, mk_eq_True= #mk_eq_True mk_rews},
nipkow@11504
   513
            termless,depth);
berghofe@10413
   514
berghofe@10413
   515
fun set_mk_eq_True
nipkow@11504
   516
  (Mss {rules,congs,procs,bounds,prems,mk_rews,termless,depth}, mk_eq_True) =
berghofe@10413
   517
    mk_mss (rules, congs, procs, bounds, prems,
berghofe@10413
   518
            {mk= #mk mk_rews, mk_sym= #mk_sym mk_rews, mk_eq_True= mk_eq_True},
nipkow@11504
   519
            termless,depth);
berghofe@10413
   520
berghofe@10413
   521
(* termless *)
berghofe@10413
   522
berghofe@10413
   523
fun set_termless
nipkow@11504
   524
  (Mss {rules, congs, procs, bounds, prems, mk_rews, depth, ...}, termless) =
nipkow@11504
   525
    mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless, depth);
berghofe@10413
   526
berghofe@10413
   527
berghofe@10413
   528
berghofe@10413
   529
(** rewriting **)
berghofe@10413
   530
berghofe@10413
   531
(*
berghofe@10413
   532
  Uses conversions, see:
berghofe@10413
   533
    L C Paulson, A higher-order implementation of rewriting,
berghofe@10413
   534
    Science of Computer Programming 3 (1983), pages 119-149.
berghofe@10413
   535
*)
berghofe@10413
   536
berghofe@10413
   537
val dest_eq = Drule.dest_equals o cprop_of;
berghofe@10413
   538
val lhs_of = fst o dest_eq;
berghofe@10413
   539
val rhs_of = snd o dest_eq;
berghofe@10413
   540
berghofe@10413
   541
fun beta_eta_conversion t =
berghofe@10413
   542
  let val thm = beta_conversion true t;
berghofe@10413
   543
  in transitive thm (eta_conversion (rhs_of thm)) end;
berghofe@10413
   544
berghofe@10413
   545
fun check_conv msg thm thm' =
berghofe@10413
   546
  let
berghofe@10413
   547
    val thm'' = transitive thm (transitive
berghofe@10413
   548
      (symmetric (beta_eta_conversion (lhs_of thm'))) thm')
nipkow@13569
   549
  in (if msg then trace_thm "SUCCEEDED" thm' else (); Some thm'') end
berghofe@10413
   550
  handle THM _ =>
berghofe@10413
   551
    let val {sign, prop = _ $ _ $ prop0, ...} = rep_thm thm;
berghofe@10413
   552
    in
nipkow@13569
   553
      (trace_thm "Proved wrong thm (Check subgoaler?)" thm';
berghofe@10413
   554
       trace_term false "Should have proved:" sign prop0;
berghofe@10413
   555
       None)
berghofe@10413
   556
    end;
berghofe@10413
   557
berghofe@10413
   558
berghofe@10413
   559
(* mk_procrule *)
berghofe@10413
   560
berghofe@10413
   561
fun mk_procrule thm =
berghofe@10413
   562
  let val (_,prems,lhs,elhs,rhs,_) = decomp_simp thm
berghofe@10413
   563
  in if rewrite_rule_extra_vars prems lhs rhs
berghofe@10413
   564
     then (prthm true "Extra vars on rhs:" thm; [])
berghofe@13607
   565
     else [mk_rrule2{thm=thm, name="", lhs=lhs, elhs=elhs, perm=false}]
berghofe@10413
   566
  end;
berghofe@10413
   567
berghofe@10413
   568
berghofe@10413
   569
(* conversion to apply the meta simpset to a term *)
berghofe@10413
   570
berghofe@10413
   571
(* Since the rewriting strategy is bottom-up, we avoid re-normalizing already
berghofe@10413
   572
   normalized terms by carrying around the rhs of the rewrite rule just
berghofe@10413
   573
   applied. This is called the `skeleton'. It is decomposed in parallel
berghofe@10413
   574
   with the term. Once a Var is encountered, the corresponding term is
berghofe@10413
   575
   already in normal form.
berghofe@10413
   576
   skel0 is a dummy skeleton that is to enforce complete normalization.
berghofe@10413
   577
*)
berghofe@10413
   578
val skel0 = Bound 0;
berghofe@10413
   579
berghofe@10413
   580
(* Use rhs as skeleton only if the lhs does not contain unnormalized bits.
berghofe@10413
   581
   The latter may happen iff there are weak congruence rules for constants
berghofe@10413
   582
   in the lhs.
berghofe@10413
   583
*)
berghofe@10413
   584
fun uncond_skel((_,weak),(lhs,rhs)) =
berghofe@10413
   585
  if null weak then rhs (* optimization *)
berghofe@10413
   586
  else if exists_Const (fn (c,_) => c mem weak) lhs then skel0
berghofe@10413
   587
       else rhs;
berghofe@10413
   588
berghofe@10413
   589
(* Behaves like unconditional rule if rhs does not contain vars not in the lhs.
berghofe@10413
   590
   Otherwise those vars may become instantiated with unnormalized terms
berghofe@10413
   591
   while the premises are solved.
berghofe@10413
   592
*)
berghofe@10413
   593
fun cond_skel(args as (congs,(lhs,rhs))) =
berghofe@10413
   594
  if term_varnames rhs subset term_varnames lhs then uncond_skel(args)
berghofe@10413
   595
  else skel0;
berghofe@10413
   596
berghofe@10413
   597
(*
berghofe@10413
   598
  we try in order:
berghofe@10413
   599
    (1) beta reduction
berghofe@10413
   600
    (2) unconditional rewrite rules
berghofe@10413
   601
    (3) conditional rewrite rules
berghofe@10413
   602
    (4) simplification procedures
berghofe@10413
   603
berghofe@10413
   604
  IMPORTANT: rewrite rules must not introduce new Vars or TVars!
berghofe@10413
   605
berghofe@10413
   606
*)
berghofe@10413
   607
berghofe@10413
   608
fun rewritec (prover, signt, maxt)
nipkow@11504
   609
             (mss as Mss{rules, procs, termless, prems, congs, depth,...}) t =
berghofe@10413
   610
  let
berghofe@10413
   611
    val eta_thm = Thm.eta_conversion t;
berghofe@10413
   612
    val eta_t' = rhs_of eta_thm;
berghofe@10413
   613
    val eta_t = term_of eta_t';
berghofe@10413
   614
    val tsigt = Sign.tsig_of signt;
berghofe@13607
   615
    fun rew {thm, name, lhs, elhs, fo, perm} =
berghofe@10413
   616
      let
berghofe@10413
   617
        val {sign, prop, maxidx, ...} = rep_thm thm;
berghofe@10413
   618
        val _ = if Sign.subsig (sign, signt) then ()
berghofe@10413
   619
                else (prthm true "Ignoring rewrite rule from different theory:" thm;
berghofe@10413
   620
                      raise Pattern.MATCH);
berghofe@10413
   621
        val (rthm, elhs') = if maxt = ~1 then (thm, elhs)
berghofe@10413
   622
          else (Thm.incr_indexes (maxt+1) thm, Thm.cterm_incr_indexes (maxt+1) elhs);
berghofe@10413
   623
        val insts = if fo then Thm.cterm_first_order_match (elhs', eta_t')
berghofe@10413
   624
                          else Thm.cterm_match (elhs', eta_t');
berghofe@10413
   625
        val thm' = Thm.instantiate insts (Thm.rename_boundvars lhs eta_t rthm);
berghofe@10413
   626
        val prop' = #prop (rep_thm thm');
berghofe@10413
   627
        val unconditional = (Logic.count_prems (prop',0) = 0);
berghofe@10413
   628
        val (lhs', rhs') = Logic.dest_equals (Logic.strip_imp_concl prop')
berghofe@10413
   629
      in
nipkow@11295
   630
        if perm andalso not (termless (rhs', lhs'))
berghofe@13607
   631
        then (trace_named_thm "Cannot apply permutative rewrite rule" (thm, name);
nipkow@13569
   632
              trace_thm "Term does not become smaller:" thm'; None)
berghofe@13607
   633
        else (trace_named_thm "Applying instance of rewrite rule" (thm, name);
berghofe@10413
   634
           if unconditional
berghofe@10413
   635
           then
nipkow@13569
   636
             (trace_thm "Rewriting:" thm';
berghofe@10413
   637
              let val lr = Logic.dest_equals prop;
berghofe@10413
   638
                  val Some thm'' = check_conv false eta_thm thm'
berghofe@10413
   639
              in Some (thm'', uncond_skel (congs, lr)) end)
berghofe@10413
   640
           else
nipkow@13569
   641
             (trace_thm "Trying to rewrite:" thm';
nipkow@13828
   642
              case incr_depth mss of
nipkow@13828
   643
                None => (trace_thm "FAILED - reached depth limit" thm'; None)
nipkow@13828
   644
              | Some mss =>
nipkow@13828
   645
              (case prover mss thm' of
nipkow@13569
   646
                None       => (trace_thm "FAILED" thm'; None)
berghofe@10413
   647
              | Some thm2 =>
berghofe@10413
   648
                  (case check_conv true eta_thm thm2 of
berghofe@10413
   649
                     None => None |
berghofe@10413
   650
                     Some thm2' =>
berghofe@10413
   651
                       let val concl = Logic.strip_imp_concl prop
berghofe@10413
   652
                           val lr = Logic.dest_equals concl
nipkow@13828
   653
                       in Some (thm2', cond_skel (congs, lr)) end))))
berghofe@10413
   654
      end
berghofe@10413
   655
berghofe@10413
   656
    fun rews [] = None
berghofe@10413
   657
      | rews (rrule :: rrules) =
berghofe@10413
   658
          let val opt = rew rrule handle Pattern.MATCH => None
berghofe@10413
   659
          in case opt of None => rews rrules | some => some end;
berghofe@10413
   660
berghofe@10413
   661
    fun sort_rrules rrs = let
wenzelm@12603
   662
      fun is_simple({thm, ...}:rrule) = case #prop (rep_thm thm) of
berghofe@10413
   663
                                      Const("==",_) $ _ $ _ => true
wenzelm@12603
   664
                                      | _                   => false
berghofe@10413
   665
      fun sort []        (re1,re2) = re1 @ re2
wenzelm@12603
   666
        | sort (rr::rrs) (re1,re2) = if is_simple rr
berghofe@10413
   667
                                     then sort rrs (rr::re1,re2)
berghofe@10413
   668
                                     else sort rrs (re1,rr::re2)
berghofe@10413
   669
    in sort rrs ([],[]) end
berghofe@10413
   670
berghofe@10413
   671
    fun proc_rews ([]:simproc list) = None
berghofe@10413
   672
      | proc_rews ({name, proc, lhs, ...} :: ps) =
berghofe@10413
   673
          if Pattern.matches tsigt (term_of lhs, term_of t) then
berghofe@10413
   674
            (debug_term false ("Trying procedure " ^ quote name ^ " on:") signt eta_t;
wenzelm@13486
   675
             case transform_failure (curry SIMPROC_FAIL name)
wenzelm@13486
   676
                 (fn () => proc signt prems eta_t) () of
wenzelm@13486
   677
               None => (debug false "FAILED"; proc_rews ps)
wenzelm@13486
   678
             | Some raw_thm =>
nipkow@13569
   679
                 (trace_thm ("Procedure " ^ quote name ^ " produced rewrite rule:") raw_thm;
berghofe@10413
   680
                  (case rews (mk_procrule raw_thm) of
wenzelm@13486
   681
                    None => (trace_cterm true ("IGNORED result of simproc " ^ quote name ^
wenzelm@13486
   682
                      " -- does not match") t; proc_rews ps)
berghofe@10413
   683
                  | some => some)))
berghofe@10413
   684
          else proc_rews ps;
berghofe@10413
   685
  in case eta_t of
berghofe@10413
   686
       Abs _ $ _ => Some (transitive eta_thm
berghofe@12155
   687
         (beta_conversion false eta_t'), skel0)
berghofe@10413
   688
     | _ => (case rews (sort_rrules (Net.match_term rules eta_t)) of
berghofe@10413
   689
               None => proc_rews (Net.match_term procs eta_t)
berghofe@10413
   690
             | some => some)
berghofe@10413
   691
  end;
berghofe@10413
   692
berghofe@10413
   693
berghofe@10413
   694
(* conversion to apply a congruence rule to a term *)
berghofe@10413
   695
berghofe@10413
   696
fun congc (prover,signt,maxt) {thm=cong,lhs=lhs} t =
berghofe@10413
   697
  let val {sign, ...} = rep_thm cong
berghofe@10413
   698
      val _ = if Sign.subsig (sign, signt) then ()
berghofe@10413
   699
                 else error("Congruence rule from different theory")
berghofe@10413
   700
      val rthm = if maxt = ~1 then cong else Thm.incr_indexes (maxt+1) cong;
berghofe@10413
   701
      val rlhs = fst (Drule.dest_equals (Drule.strip_imp_concl (cprop_of rthm)));
berghofe@10413
   702
      val insts = Thm.cterm_match (rlhs, t)
berghofe@10413
   703
      (* Pattern.match can raise Pattern.MATCH;
berghofe@10413
   704
         is handled when congc is called *)
berghofe@10413
   705
      val thm' = Thm.instantiate insts (Thm.rename_boundvars (term_of rlhs) (term_of t) rthm);
nipkow@13569
   706
      val unit = trace_thm "Applying congruence rule:" thm';
berghofe@10413
   707
      fun err (msg, thm) = (prthm false msg thm; error "Failed congruence proof!")
berghofe@10413
   708
  in case prover thm' of
berghofe@10413
   709
       None => err ("Could not prove", thm')
berghofe@10413
   710
     | Some thm2 => (case check_conv true (beta_eta_conversion t) thm2 of
berghofe@10413
   711
          None => err ("Should not have proved", thm2)
berghofe@12155
   712
        | Some thm2' =>
berghofe@12155
   713
            if op aconv (pairself term_of (dest_equals (cprop_of thm2')))
berghofe@12155
   714
            then None else Some thm2')
berghofe@10413
   715
  end;
berghofe@10413
   716
berghofe@10413
   717
val (cA, (cB, cC)) =
berghofe@10413
   718
  apsnd dest_equals (dest_implies (hd (cprems_of Drule.imp_cong)));
berghofe@10413
   719
berghofe@13607
   720
fun transitive1 None None = None
berghofe@13607
   721
  | transitive1 (Some thm1) None = Some thm1
berghofe@13607
   722
  | transitive1 None (Some thm2) = Some thm2
berghofe@13607
   723
  | transitive1 (Some thm1) (Some thm2) = Some (transitive thm1 thm2)
berghofe@10413
   724
berghofe@13607
   725
fun transitive2 thm = transitive1 (Some thm);
berghofe@13607
   726
fun transitive3 thm = transitive1 thm o Some;
berghofe@13607
   727
berghofe@13607
   728
fun imp_cong' e = combination (combination refl_implies e);
berghofe@12155
   729
berghofe@10413
   730
fun bottomc ((simprem,useprem,mutsimp), prover, sign, maxidx) =
berghofe@10413
   731
  let
berghofe@10413
   732
    fun botc skel mss t =
berghofe@10413
   733
          if is_Var skel then None
berghofe@10413
   734
          else
berghofe@10413
   735
          (case subc skel mss t of
berghofe@10413
   736
             some as Some thm1 =>
berghofe@10413
   737
               (case rewritec (prover, sign, maxidx) mss (rhs_of thm1) of
berghofe@10413
   738
                  Some (thm2, skel2) =>
berghofe@13607
   739
                    transitive2 (transitive thm1 thm2)
berghofe@10413
   740
                      (botc skel2 mss (rhs_of thm2))
berghofe@10413
   741
                | None => some)
berghofe@10413
   742
           | None =>
berghofe@10413
   743
               (case rewritec (prover, sign, maxidx) mss t of
berghofe@13607
   744
                  Some (thm2, skel2) => transitive2 thm2
berghofe@10413
   745
                    (botc skel2 mss (rhs_of thm2))
berghofe@10413
   746
                | None => None))
berghofe@10413
   747
berghofe@10413
   748
    and try_botc mss t =
berghofe@10413
   749
          (case botc skel0 mss t of
berghofe@10413
   750
             Some trec1 => trec1 | None => (reflexive t))
berghofe@10413
   751
berghofe@10413
   752
    and subc skel
nipkow@11504
   753
          (mss as Mss{rules,congs,procs,bounds,prems,mk_rews,termless,depth}) t0 =
berghofe@10413
   754
       (case term_of t0 of
berghofe@10413
   755
           Abs (a, T, t) =>
berghofe@10413
   756
             let val b = variant bounds a
wenzelm@10767
   757
                 val (v, t') = Thm.dest_abs (Some ("." ^ b)) t0
nipkow@11504
   758
                 val mss' = mk_mss (rules, congs, procs, b :: bounds, prems, mk_rews, termless,depth)
berghofe@10413
   759
                 val skel' = case skel of Abs (_, _, sk) => sk | _ => skel0
berghofe@10413
   760
             in case botc skel' mss' t' of
berghofe@10413
   761
                  Some thm => Some (abstract_rule a v thm)
berghofe@10413
   762
                | None => None
berghofe@10413
   763
             end
berghofe@10413
   764
         | t $ _ => (case t of
berghofe@13614
   765
             Const ("==>", _) $ _  => impc t0 mss
berghofe@10413
   766
           | Abs _ =>
berghofe@10413
   767
               let val thm = beta_conversion false t0
berghofe@10413
   768
               in case subc skel0 mss (rhs_of thm) of
berghofe@10413
   769
                    None => Some thm
berghofe@10413
   770
                  | Some thm' => Some (transitive thm thm')
berghofe@10413
   771
               end
berghofe@10413
   772
           | _  =>
berghofe@10413
   773
               let fun appc () =
berghofe@10413
   774
                     let
berghofe@10413
   775
                       val (tskel, uskel) = case skel of
berghofe@10413
   776
                           tskel $ uskel => (tskel, uskel)
berghofe@10413
   777
                         | _ => (skel0, skel0);
wenzelm@10767
   778
                       val (ct, cu) = Thm.dest_comb t0
berghofe@10413
   779
                     in
berghofe@10413
   780
                     (case botc tskel mss ct of
berghofe@10413
   781
                        Some thm1 =>
berghofe@10413
   782
                          (case botc uskel mss cu of
berghofe@10413
   783
                             Some thm2 => Some (combination thm1 thm2)
berghofe@10413
   784
                           | None => Some (combination thm1 (reflexive cu)))
berghofe@10413
   785
                      | None =>
berghofe@10413
   786
                          (case botc uskel mss cu of
berghofe@10413
   787
                             Some thm1 => Some (combination (reflexive ct) thm1)
berghofe@10413
   788
                           | None => None))
berghofe@10413
   789
                     end
berghofe@10413
   790
                   val (h, ts) = strip_comb t
ballarin@13835
   791
               in case cong_name h of
ballarin@13835
   792
                    Some a =>
berghofe@10413
   793
                      (case assoc_string (fst congs, a) of
berghofe@10413
   794
                         None => appc ()
berghofe@10413
   795
                       | Some cong =>
berghofe@10413
   796
(* post processing: some partial applications h t1 ... tj, j <= length ts,
berghofe@10413
   797
   may be a redex. Example: map (%x.x) = (%xs.xs) wrt map_cong *)
berghofe@10413
   798
                          (let
berghofe@10413
   799
                             val thm = congc (prover mss, sign, maxidx) cong t0;
berghofe@12155
   800
                             val t = if_none (apsome rhs_of thm) t0;
wenzelm@10767
   801
                             val (cl, cr) = Thm.dest_comb t
berghofe@10413
   802
                             val dVar = Var(("", 0), dummyT)
berghofe@10413
   803
                             val skel =
berghofe@10413
   804
                               list_comb (h, replicate (length ts) dVar)
berghofe@10413
   805
                           in case botc skel mss cl of
berghofe@12155
   806
                                None => thm
berghofe@13607
   807
                              | Some thm' => transitive3 thm
berghofe@12155
   808
                                  (combination thm' (reflexive cr))
berghofe@10413
   809
                           end handle TERM _ => error "congc result"
berghofe@10413
   810
                                    | Pattern.MATCH => appc ()))
berghofe@10413
   811
                  | _ => appc ()
berghofe@10413
   812
               end)
berghofe@10413
   813
         | _ => None)
berghofe@10413
   814
berghofe@13607
   815
    and impc ct mss =
berghofe@13607
   816
      if mutsimp then mut_impc0 [] ct [] [] mss else nonmut_impc ct mss
berghofe@10413
   817
berghofe@13607
   818
    and rules_of_prem mss prem =
berghofe@13607
   819
      if maxidx_of_term (term_of prem) <> ~1
berghofe@13607
   820
      then (trace_cterm true
berghofe@13607
   821
        "Cannot add premise as rewrite rule because it contains (type) unknowns:" prem; ([], None))
berghofe@13607
   822
      else
berghofe@13607
   823
        let val asm = assume prem
berghofe@13607
   824
        in (extract_safe_rrules (mss, asm), Some asm) end
berghofe@10413
   825
berghofe@13607
   826
    and add_rrules (rrss, asms) mss =
berghofe@13607
   827
      add_prems (foldl (insert_rrule true) (mss, flat rrss), mapfilter I asms)
berghofe@10413
   828
berghofe@13607
   829
    and disch r (prem, eq) =
berghofe@13607
   830
      let
berghofe@13607
   831
        val (lhs, rhs) = dest_eq eq;
berghofe@13607
   832
        val eq' = implies_elim (Thm.instantiate
berghofe@13607
   833
          ([], [(cA, prem), (cB, lhs), (cC, rhs)]) Drule.imp_cong)
berghofe@13607
   834
          (implies_intr prem eq)
berghofe@13607
   835
      in if not r then eq' else
berghofe@10413
   836
        let
berghofe@13607
   837
          val (prem', concl) = dest_implies lhs;
berghofe@13607
   838
          val (prem'', _) = dest_implies rhs
berghofe@13607
   839
        in transitive (transitive
berghofe@13607
   840
          (Thm.instantiate ([], [(cA, prem'), (cB, prem), (cC, concl)])
berghofe@13607
   841
             Drule.swap_prems_eq) eq')
berghofe@13607
   842
          (Thm.instantiate ([], [(cA, prem), (cB, prem''), (cC, concl)])
berghofe@13607
   843
             Drule.swap_prems_eq)
berghofe@10413
   844
        end
berghofe@10413
   845
      end
berghofe@10413
   846
berghofe@13607
   847
    and rebuild [] _ _ _ _ eq = eq
berghofe@13607
   848
      | rebuild (prem :: prems) concl (rrs :: rrss) (asm :: asms) mss eq =
berghofe@13607
   849
          let
berghofe@13607
   850
            val mss' = add_rrules (rev rrss, rev asms) mss;
berghofe@13607
   851
            val concl' =
berghofe@13607
   852
              Drule.mk_implies (prem, if_none (apsome rhs_of eq) concl);
berghofe@13607
   853
            val dprem = apsome (curry (disch false) prem)
berghofe@13607
   854
          in case rewritec (prover, sign, maxidx) mss' concl' of
berghofe@13607
   855
              None => rebuild prems concl' rrss asms mss (dprem eq)
berghofe@13607
   856
            | Some (eq', _) => transitive2 (foldl (disch false o swap)
berghofe@13607
   857
                  (the (transitive3 (dprem eq) eq'), prems))
berghofe@13607
   858
                (mut_impc0 (rev prems) (rhs_of eq') (rev rrss) (rev asms) mss)
berghofe@13607
   859
          end
berghofe@13607
   860
          
berghofe@13607
   861
    and mut_impc0 prems concl rrss asms mss =
berghofe@13607
   862
      let
berghofe@13607
   863
        val prems' = strip_imp_prems concl;
berghofe@13607
   864
        val (rrss', asms') = split_list (map (rules_of_prem mss) prems')
berghofe@13607
   865
      in mut_impc (prems @ prems') (strip_imp_concl concl) (rrss @ rrss')
berghofe@13607
   866
        (asms @ asms') [] [] [] [] mss ~1 ~1
berghofe@13607
   867
      end
berghofe@13607
   868
 
berghofe@13607
   869
    and mut_impc [] concl [] [] prems' rrss' asms' eqns mss changed k =
berghofe@13607
   870
        transitive1 (foldl (fn (eq2, (eq1, prem)) => transitive1 eq1
berghofe@13607
   871
            (apsome (curry (disch false) prem) eq2)) (None, eqns ~~ prems'))
berghofe@13607
   872
          (if changed > 0 then
berghofe@13607
   873
             mut_impc (rev prems') concl (rev rrss') (rev asms')
berghofe@13607
   874
               [] [] [] [] mss ~1 changed
berghofe@13607
   875
           else rebuild prems' concl rrss' asms' mss
berghofe@13607
   876
             (botc skel0 (add_rrules (rev rrss', rev asms') mss) concl))
berghofe@13607
   877
berghofe@13607
   878
      | mut_impc (prem :: prems) concl (rrs :: rrss) (asm :: asms)
berghofe@13607
   879
          prems' rrss' asms' eqns mss changed k =
berghofe@13607
   880
        case (if k = 0 then None else botc skel0 (add_rrules
berghofe@13607
   881
          (rev rrss' @ rrss, rev asms' @ asms) mss) prem) of
berghofe@13607
   882
            None => mut_impc prems concl rrss asms (prem :: prems')
berghofe@13607
   883
              (rrs :: rrss') (asm :: asms') (None :: eqns) mss changed
berghofe@13607
   884
              (if k = 0 then 0 else k - 1)
berghofe@13607
   885
          | Some eqn =>
berghofe@13607
   886
            let
berghofe@13607
   887
              val prem' = rhs_of eqn;
berghofe@13607
   888
              val tprems = map term_of prems;
berghofe@13607
   889
              val i = 1 + foldl Int.max (~1, map (fn p =>
berghofe@13607
   890
                find_index_eq p tprems) (#hyps (rep_thm eqn)));
berghofe@13607
   891
              val (rrs', asm') = rules_of_prem mss prem'
berghofe@13607
   892
            in mut_impc prems concl rrss asms (prem' :: prems')
berghofe@13607
   893
              (rrs' :: rrss') (asm' :: asms') (Some (foldr (disch true)
berghofe@13607
   894
                (take (i, prems), imp_cong' eqn (reflexive (Drule.list_implies
berghofe@13607
   895
                  (drop (i, prems), concl))))) :: eqns) mss (length prems') ~1
berghofe@13607
   896
            end
berghofe@13607
   897
berghofe@10413
   898
     (* legacy code - only for backwards compatibility *)
berghofe@13607
   899
     and nonmut_impc ct mss =
berghofe@13607
   900
       let val (prem, conc) = dest_implies ct;
berghofe@13607
   901
           val thm1 = if simprem then botc skel0 mss prem else None;
berghofe@10413
   902
           val prem1 = if_none (apsome rhs_of thm1) prem;
berghofe@13607
   903
           val mss1 = if not useprem then mss else add_rrules
berghofe@13607
   904
             (apsnd single (apfst single (rules_of_prem mss prem1))) mss
berghofe@10413
   905
       in (case botc skel0 mss1 conc of
berghofe@10413
   906
           None => (case thm1 of
berghofe@10413
   907
               None => None
berghofe@13607
   908
             | Some thm1' => Some (imp_cong' thm1' (reflexive conc)))
berghofe@10413
   909
         | Some thm2 =>
berghofe@13607
   910
           let val thm2' = disch false (prem1, thm2)
berghofe@10413
   911
           in (case thm1 of
berghofe@10413
   912
               None => Some thm2'
berghofe@13607
   913
             | Some thm1' =>
berghofe@13607
   914
                 Some (transitive (imp_cong' thm1' (reflexive conc)) thm2'))
berghofe@10413
   915
           end)
berghofe@10413
   916
       end
berghofe@10413
   917
berghofe@10413
   918
 in try_botc end;
berghofe@10413
   919
berghofe@10413
   920
berghofe@10413
   921
(*** Meta-rewriting: rewrites t to u and returns the theorem t==u ***)
berghofe@10413
   922
berghofe@10413
   923
(*
berghofe@10413
   924
  Parameters:
berghofe@10413
   925
    mode = (simplify A,
berghofe@10413
   926
            use A in simplifying B,
berghofe@10413
   927
            use prems of B (if B is again a meta-impl.) to simplify A)
berghofe@10413
   928
           when simplifying A ==> B
berghofe@10413
   929
    mss: contains equality theorems of the form [|p1,...|] ==> t==u
berghofe@10413
   930
    prover: how to solve premises in conditional rewrites and congruences
berghofe@10413
   931
*)
berghofe@10413
   932
berghofe@10413
   933
fun rewrite_cterm mode prover mss ct =
berghofe@10413
   934
  let val {sign, t, maxidx, ...} = rep_cterm ct
nipkow@11505
   935
      val Mss{depth, ...} = mss
nipkow@11505
   936
  in simp_depth := depth;
nipkow@11505
   937
     bottomc (mode, prover, sign, maxidx) mss ct
nipkow@11505
   938
  end
berghofe@10413
   939
  handle THM (s, _, thms) =>
berghofe@10413
   940
    error ("Exception THM was raised in simplifier:\n" ^ s ^ "\n" ^
wenzelm@11886
   941
      Pretty.string_of (Display.pretty_thms thms));
berghofe@10413
   942
berghofe@10413
   943
(*In [A1,...,An]==>B, rewrite the selected A's only -- for rewrite_goals_tac*)
berghofe@10413
   944
fun goals_conv pred cv =
berghofe@10413
   945
  let fun gconv i ct =
berghofe@10413
   946
        let val (A,B) = Drule.dest_implies ct
berghofe@13661
   947
        in imp_cong' (if pred i then cv A else reflexive A) (gconv (i+1) B) end
berghofe@10413
   948
        handle TERM _ => reflexive ct
berghofe@10413
   949
  in gconv 1 end;
berghofe@10413
   950
berghofe@11737
   951
(* Rewrite A in !!x1,...,xn. A *)
berghofe@11736
   952
fun forall_conv cv ct =
berghofe@11736
   953
  let val p as (ct1, ct2) = Thm.dest_comb ct
berghofe@11736
   954
  in (case pairself term_of p of
berghofe@11736
   955
      (Const ("all", _), Abs (s, _, _)) =>
berghofe@11736
   956
         let val (v, ct') = Thm.dest_abs (Some "@") ct2;
berghofe@11736
   957
         in Thm.combination (Thm.reflexive ct1)
berghofe@11736
   958
           (Thm.abstract_rule s v (forall_conv cv ct'))
berghofe@11736
   959
         end
berghofe@11736
   960
    | _ => cv ct)
berghofe@11736
   961
  end handle TERM _ => cv ct;
berghofe@11736
   962
berghofe@10413
   963
(*Use a conversion to transform a theorem*)
berghofe@10413
   964
fun fconv_rule cv th = equal_elim (cv (cprop_of th)) th;
berghofe@10413
   965
wenzelm@11760
   966
(*Rewrite a cterm*)
wenzelm@11767
   967
fun rewrite_aux _ _ [] = (fn ct => Thm.reflexive ct)
wenzelm@11767
   968
  | rewrite_aux prover full thms = rewrite_cterm (full, false, false) prover (mss_of thms);
wenzelm@11672
   969
berghofe@10413
   970
(*Rewrite a theorem*)
wenzelm@11767
   971
fun simplify_aux _ _ [] = (fn th => th)
wenzelm@11767
   972
  | simplify_aux prover full thms =
wenzelm@11767
   973
      fconv_rule (rewrite_cterm (full, false, false) prover (mss_of thms));
berghofe@10413
   974
berghofe@10413
   975
fun rewrite_thm mode prover mss = fconv_rule (rewrite_cterm mode prover mss);
berghofe@10413
   976
berghofe@10413
   977
(*Rewrite the subgoals of a proof state (represented by a theorem) *)
berghofe@10413
   978
fun rewrite_goals_rule_aux _ []   th = th
berghofe@10413
   979
  | rewrite_goals_rule_aux prover thms th =
berghofe@10413
   980
      fconv_rule (goals_conv (K true) (rewrite_cterm (true, true, false) prover
berghofe@10413
   981
        (mss_of thms))) th;
berghofe@10413
   982
berghofe@10413
   983
(*Rewrite the subgoal of a proof state (represented by a theorem) *)
berghofe@10413
   984
fun rewrite_goal_rule mode prover mss i thm =
berghofe@10413
   985
  if 0 < i  andalso  i <= nprems_of thm
berghofe@10413
   986
  then fconv_rule (goals_conv (fn j => j=i) (rewrite_cterm mode prover mss)) thm
berghofe@10413
   987
  else raise THM("rewrite_goal_rule",i,[thm]);
berghofe@10413
   988
wenzelm@12783
   989
wenzelm@12783
   990
(*simple term rewriting -- without proofs*)
berghofe@13196
   991
fun rewrite_term sg rules procs =
berghofe@13196
   992
  Pattern.rewrite_term (Sign.tsig_of sg) (map decomp_simp' rules) procs;
wenzelm@12783
   993
berghofe@10413
   994
end;
berghofe@10413
   995
wenzelm@11672
   996
structure BasicMetaSimplifier: BASIC_META_SIMPLIFIER = MetaSimplifier;
wenzelm@11672
   997
open BasicMetaSimplifier;