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