Added new file meta_simplifier.ML
authorberghofe
Tue Nov 07 17:44:48 2000 +0100 (2000-11-07)
changeset 104130e015d9bea4e
parent 10412 1a1b4c1b2b7c
child 10414 f7aeff3e9e1e
Added new file meta_simplifier.ML
src/Pure/IsaMakefile
src/Pure/ROOT.ML
src/Pure/meta_simplifier.ML
     1.1 --- a/src/Pure/IsaMakefile	Tue Nov 07 17:42:19 2000 +0100
     1.2 +++ b/src/Pure/IsaMakefile	Tue Nov 07 17:44:48 2000 +0100
     1.3 @@ -45,7 +45,7 @@
     1.4    Thy/thm_database.ML Thy/thy_info.ML Thy/thy_load.ML Thy/thy_parse.ML	\
     1.5    Thy/thy_scan.ML Thy/thy_syn.ML axclass.ML basis.ML context.ML		\
     1.6    deriv.ML display.ML drule.ML envir.ML goals.ML install_pp.ML		\
     1.7 -  library.ML locale.ML logic.ML net.ML pattern.ML pure.ML pure_thy.ML	\
     1.8 +  library.ML locale.ML logic.ML meta_simplifier.ML net.ML pattern.ML pure.ML pure_thy.ML	\
     1.9    search.ML sign.ML sorts.ML tactic.ML tctical.ML term.ML theory.ML	\
    1.10    theory_data.ML thm.ML type.ML type_infer.ML unify.ML
    1.11  	@./mk
     2.1 --- a/src/Pure/ROOT.ML	Tue Nov 07 17:42:19 2000 +0100
     2.2 +++ b/src/Pure/ROOT.ML	Tue Nov 07 17:44:48 2000 +0100
     2.3 @@ -7,7 +7,7 @@
     2.4  *)
     2.5  
     2.6  val banner = "Pure Isabelle";
     2.7 -val version = "Isabelle repository version";
     2.8 +val version = "Isabelle repository";
     2.9  
    2.10  print_depth 1;
    2.11  
    2.12 @@ -43,6 +43,7 @@
    2.13  use "pure_thy.ML";
    2.14  use "deriv.ML";
    2.15  use "drule.ML";
    2.16 +use "meta_simplifier.ML";
    2.17  use "locale.ML";
    2.18  use "tctical.ML";
    2.19  use "search.ML";
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/src/Pure/meta_simplifier.ML	Tue Nov 07 17:44:48 2000 +0100
     3.3 @@ -0,0 +1,937 @@
     3.4 +(*  Title:      Pure/meta_simplifier.ML
     3.5 +    ID:         $Id$
     3.6 +    Author:     Tobias Nipkow
     3.7 +    Copyright   1994  University of Cambridge
     3.8 +
     3.9 +Meta Simplification
    3.10 +*)
    3.11 +
    3.12 +signature META_SIMPLIFIER =
    3.13 +sig
    3.14 +  exception SIMPLIFIER of string * thm
    3.15 +  type meta_simpset
    3.16 +  val dest_mss		: meta_simpset ->
    3.17 +    {simps: thm list, congs: thm list, procs: (string * cterm list) list}
    3.18 +  val empty_mss         : meta_simpset
    3.19 +  val clear_mss		: meta_simpset -> meta_simpset
    3.20 +  val merge_mss		: meta_simpset * meta_simpset -> meta_simpset
    3.21 +  val add_simps         : meta_simpset * thm list -> meta_simpset
    3.22 +  val del_simps         : meta_simpset * thm list -> meta_simpset
    3.23 +  val mss_of            : thm list -> meta_simpset
    3.24 +  val add_congs         : meta_simpset * thm list -> meta_simpset
    3.25 +  val del_congs         : meta_simpset * thm list -> meta_simpset
    3.26 +  val add_simprocs	: meta_simpset *
    3.27 +    (string * cterm list * (Sign.sg -> thm list -> term -> thm option) * stamp) list
    3.28 +      -> meta_simpset
    3.29 +  val del_simprocs	: meta_simpset *
    3.30 +    (string * cterm list * (Sign.sg -> thm list -> term -> thm option) * stamp) list
    3.31 +      -> meta_simpset
    3.32 +  val add_prems         : meta_simpset * thm list -> meta_simpset
    3.33 +  val prems_of_mss      : meta_simpset -> thm list
    3.34 +  val set_mk_rews       : meta_simpset * (thm -> thm list) -> meta_simpset
    3.35 +  val set_mk_sym        : meta_simpset * (thm -> thm option) -> meta_simpset
    3.36 +  val set_mk_eq_True    : meta_simpset * (thm -> thm option) -> meta_simpset
    3.37 +  val set_termless      : meta_simpset * (term * term -> bool) -> meta_simpset
    3.38 +  val trace_simp        : bool ref
    3.39 +  val debug_simp        : bool ref
    3.40 +  val rewrite_cterm     : bool * bool * bool
    3.41 +                          -> (meta_simpset -> thm -> thm option)
    3.42 +                          -> meta_simpset -> cterm -> thm
    3.43 +  val rewrite_rule_aux  : (meta_simpset -> thm -> thm option) -> thm list -> thm -> thm
    3.44 +  val rewrite_thm       : bool * bool * bool
    3.45 +                          -> (meta_simpset -> thm -> thm option)
    3.46 +                          -> meta_simpset -> thm -> thm
    3.47 +  val rewrite_goals_rule_aux: (meta_simpset -> thm -> thm option) -> thm list -> thm -> thm
    3.48 +  val rewrite_goal_rule : bool* bool * bool
    3.49 +                          -> (meta_simpset -> thm -> thm option)
    3.50 +                          -> meta_simpset -> int -> thm -> thm
    3.51 +end;
    3.52 +
    3.53 +structure MetaSimplifier : META_SIMPLIFIER =
    3.54 +struct
    3.55 +
    3.56 +(** diagnostics **)
    3.57 +
    3.58 +exception SIMPLIFIER of string * thm;
    3.59 +
    3.60 +fun prnt warn a = if warn then warning a else writeln a;
    3.61 +
    3.62 +fun prtm warn a sign t =
    3.63 +  (prnt warn a; prnt warn (Sign.string_of_term sign t));
    3.64 +
    3.65 +fun prctm warn a t =
    3.66 +  (prnt warn a; prnt warn (Display.string_of_cterm t));
    3.67 +
    3.68 +fun prthm warn a thm =
    3.69 +  let val {sign, prop, ...} = rep_thm thm
    3.70 +  in prtm warn a sign prop end;
    3.71 +
    3.72 +val trace_simp = ref false;
    3.73 +val debug_simp = ref false;
    3.74 +
    3.75 +fun trace warn a = if !trace_simp then prnt warn a else ();
    3.76 +fun debug warn a = if !debug_simp then prnt warn a else ();
    3.77 +
    3.78 +fun trace_term warn a sign t = if !trace_simp then prtm warn a sign t else ();
    3.79 +fun trace_cterm warn a t = if !trace_simp then prctm warn a t else ();
    3.80 +fun debug_term warn a sign t = if !debug_simp then prtm warn a sign t else ();
    3.81 +
    3.82 +fun trace_thm warn a thm =
    3.83 +  let val {sign, prop, ...} = rep_thm thm
    3.84 +  in trace_term warn a sign prop end;
    3.85 +
    3.86 +
    3.87 +
    3.88 +(** meta simp sets **)
    3.89 +
    3.90 +(* basic components *)
    3.91 +
    3.92 +type rrule = {thm: thm, lhs: term, elhs: cterm, fo: bool, perm: bool};
    3.93 +(* thm: the rewrite rule
    3.94 +   lhs: the left-hand side
    3.95 +   elhs: the etac-contracted lhs.
    3.96 +   fo:  use first-order matching
    3.97 +   perm: the rewrite rule is permutative
    3.98 +Reamrks:
    3.99 +  - elhs is used for matching,
   3.100 +    lhs only for preservation of bound variable names.
   3.101 +  - fo is set iff
   3.102 +    either elhs is first-order (no Var is applied),
   3.103 +           in which case fo-matching is complete,
   3.104 +    or elhs is not a pattern,
   3.105 +       in which case there is nothing better to do.
   3.106 +*)
   3.107 +type cong = {thm: thm, lhs: cterm};
   3.108 +type simproc =
   3.109 + {name: string, proc: Sign.sg -> thm list -> term -> thm option, lhs: cterm, id: stamp};
   3.110 +
   3.111 +fun eq_rrule ({thm = thm1, ...}: rrule, {thm = thm2, ...}: rrule) =
   3.112 +  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
   3.113 +
   3.114 +fun eq_cong ({thm = thm1, ...}: cong, {thm = thm2, ...}: cong) = 
   3.115 +  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
   3.116 +
   3.117 +fun eq_prem (thm1, thm2) =
   3.118 +  #prop (rep_thm thm1) aconv #prop (rep_thm thm2);
   3.119 +
   3.120 +fun eq_simproc ({id = s1, ...}:simproc, {id = s2, ...}:simproc) = (s1 = s2);
   3.121 +
   3.122 +fun mk_simproc (name, proc, lhs, id) =
   3.123 +  {name = name, proc = proc, lhs = lhs, id = id};
   3.124 +
   3.125 +
   3.126 +(* datatype mss *)
   3.127 +
   3.128 +(*
   3.129 +  A "mss" contains data needed during conversion:
   3.130 +    rules: discrimination net of rewrite rules;
   3.131 +    congs: association list of congruence rules and
   3.132 +           a list of `weak' congruence constants.
   3.133 +           A congruence is `weak' if it avoids normalization of some argument.
   3.134 +    procs: discrimination net of simplification procedures
   3.135 +      (functions that prove rewrite rules on the fly);
   3.136 +    bounds: names of bound variables already used
   3.137 +      (for generating new names when rewriting under lambda abstractions);
   3.138 +    prems: current premises;
   3.139 +    mk_rews: mk: turns simplification thms into rewrite rules;
   3.140 +             mk_sym: turns == around; (needs Drule!)
   3.141 +             mk_eq_True: turns P into P == True - logic specific;
   3.142 +    termless: relation for ordered rewriting;
   3.143 +*)
   3.144 +
   3.145 +datatype meta_simpset =
   3.146 +  Mss of {
   3.147 +    rules: rrule Net.net,
   3.148 +    congs: (string * cong) list * string list,
   3.149 +    procs: simproc Net.net,
   3.150 +    bounds: string list,
   3.151 +    prems: thm list,
   3.152 +    mk_rews: {mk: thm -> thm list,
   3.153 +              mk_sym: thm -> thm option,
   3.154 +              mk_eq_True: thm -> thm option},
   3.155 +    termless: term * term -> bool};
   3.156 +
   3.157 +fun mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless) =
   3.158 +  Mss {rules = rules, congs = congs, procs = procs, bounds = bounds,
   3.159 +       prems=prems, mk_rews=mk_rews, termless=termless};
   3.160 +
   3.161 +fun upd_rules(Mss{rules,congs,procs,bounds,prems,mk_rews,termless}, rules') =
   3.162 +  mk_mss(rules',congs,procs,bounds,prems,mk_rews,termless);
   3.163 +
   3.164 +val empty_mss =
   3.165 +  let val mk_rews = {mk = K [], mk_sym = K None, mk_eq_True = K None}
   3.166 +  in mk_mss (Net.empty, ([], []), Net.empty, [], [], mk_rews, Term.termless) end;
   3.167 +
   3.168 +fun clear_mss (Mss {mk_rews, termless, ...}) =
   3.169 +  mk_mss (Net.empty, ([], []), Net.empty, [], [], mk_rews, termless);
   3.170 +
   3.171 +
   3.172 +
   3.173 +(** simpset operations **)
   3.174 +
   3.175 +(* term variables *)
   3.176 +
   3.177 +val add_term_varnames = foldl_aterms (fn (xs, Var (x, _)) => ins_ix (x, xs) | (xs, _) => xs);
   3.178 +fun term_varnames t = add_term_varnames ([], t);
   3.179 +
   3.180 +
   3.181 +(* dest_mss *)
   3.182 +
   3.183 +fun dest_mss (Mss {rules, congs, procs, ...}) =
   3.184 +  {simps = map (fn (_, {thm, ...}) => thm) (Net.dest rules),
   3.185 +   congs = map (fn (_, {thm, ...}) => thm) (fst congs),
   3.186 +   procs =
   3.187 +     map (fn (_, {name, lhs, id, ...}) => ((name, lhs), id)) (Net.dest procs)
   3.188 +     |> partition_eq eq_snd
   3.189 +     |> map (fn ps => (#1 (#1 (hd ps)), map (#2 o #1) ps))
   3.190 +     |> Library.sort_wrt #1};
   3.191 +
   3.192 +
   3.193 +(* merge_mss *)		(*NOTE: ignores mk_rews and termless of 2nd mss*)
   3.194 +
   3.195 +fun merge_mss
   3.196 + (Mss {rules = rules1, congs = (congs1,weak1), procs = procs1,
   3.197 +       bounds = bounds1, prems = prems1, mk_rews, termless},
   3.198 +  Mss {rules = rules2, congs = (congs2,weak2), procs = procs2,
   3.199 +       bounds = bounds2, prems = prems2, ...}) =
   3.200 +      mk_mss
   3.201 +       (Net.merge (rules1, rules2, eq_rrule),
   3.202 +        (generic_merge (eq_cong o pairself snd) I I congs1 congs2,
   3.203 +        merge_lists weak1 weak2),
   3.204 +        Net.merge (procs1, procs2, eq_simproc),
   3.205 +        merge_lists bounds1 bounds2,
   3.206 +        generic_merge eq_prem I I prems1 prems2,
   3.207 +        mk_rews, termless);
   3.208 +
   3.209 +
   3.210 +(* add_simps *)
   3.211 +
   3.212 +fun mk_rrule2{thm,lhs,elhs,perm} =
   3.213 +  let val fo = Pattern.first_order (term_of elhs) orelse not(Pattern.pattern (term_of elhs))
   3.214 +  in {thm=thm,lhs=lhs,elhs=elhs,fo=fo,perm=perm} end
   3.215 +
   3.216 +fun insert_rrule(mss as Mss {rules,...},
   3.217 +                 rrule as {thm,lhs,elhs,perm}) =
   3.218 +  (trace_thm false "Adding rewrite rule:" thm;
   3.219 +   let val rrule2 as {elhs,...} = mk_rrule2 rrule
   3.220 +       val rules' = Net.insert_term ((term_of elhs, rrule2), rules, eq_rrule)
   3.221 +   in upd_rules(mss,rules') end
   3.222 +   handle Net.INSERT =>
   3.223 +     (prthm true "Ignoring duplicate rewrite rule:" thm; mss));
   3.224 +
   3.225 +fun vperm (Var _, Var _) = true
   3.226 +  | vperm (Abs (_, _, s), Abs (_, _, t)) = vperm (s, t)
   3.227 +  | vperm (t1 $ t2, u1 $ u2) = vperm (t1, u1) andalso vperm (t2, u2)
   3.228 +  | vperm (t, u) = (t = u);
   3.229 +
   3.230 +fun var_perm (t, u) =
   3.231 +  vperm (t, u) andalso eq_set (term_varnames t, term_varnames u);
   3.232 +
   3.233 +(* FIXME: it seems that the conditions on extra variables are too liberal if
   3.234 +prems are nonempty: does solving the prems really guarantee instantiation of
   3.235 +all its Vars? Better: a dynamic check each time a rule is applied.
   3.236 +*)
   3.237 +fun rewrite_rule_extra_vars prems elhs erhs =
   3.238 +  not (term_varnames erhs subset foldl add_term_varnames (term_varnames elhs, prems))
   3.239 +  orelse
   3.240 +  not ((term_tvars erhs) subset
   3.241 +       (term_tvars elhs  union  List.concat(map term_tvars prems)));
   3.242 +
   3.243 +(*Simple test for looping rewrite rules and stupid orientations*)
   3.244 +fun reorient sign prems lhs rhs =
   3.245 +   rewrite_rule_extra_vars prems lhs rhs
   3.246 +  orelse
   3.247 +   is_Var (head_of lhs)
   3.248 +  orelse
   3.249 +   (exists (apl (lhs, Logic.occs)) (rhs :: prems))
   3.250 +  orelse
   3.251 +   (null prems andalso
   3.252 +    Pattern.matches (#tsig (Sign.rep_sg sign)) (lhs, rhs))
   3.253 +    (*the condition "null prems" is necessary because conditional rewrites
   3.254 +      with extra variables in the conditions may terminate although
   3.255 +      the rhs is an instance of the lhs. Example: ?m < ?n ==> f(?n) == f(?m)*)
   3.256 +  orelse
   3.257 +   (is_Const lhs andalso not(is_Const rhs))
   3.258 +
   3.259 +fun decomp_simp thm =
   3.260 +  let val {sign, prop, ...} = rep_thm thm;
   3.261 +      val prems = Logic.strip_imp_prems prop;
   3.262 +      val concl = Drule.strip_imp_concl (cprop_of thm);
   3.263 +      val (lhs, rhs) = Drule.dest_equals concl handle TERM _ =>
   3.264 +        raise SIMPLIFIER ("Rewrite rule not a meta-equality", thm)
   3.265 +      val elhs = snd (Drule.dest_equals (cprop_of (Thm.eta_conversion lhs)));
   3.266 +      val elhs = if elhs=lhs then lhs else elhs (* try to share *)
   3.267 +      val erhs = Pattern.eta_contract (term_of rhs);
   3.268 +      val perm = var_perm (term_of elhs, erhs) andalso not (term_of elhs aconv erhs)
   3.269 +                 andalso not (is_Var (term_of elhs))
   3.270 +  in (sign, prems, term_of lhs, elhs, term_of rhs, perm) end;
   3.271 +
   3.272 +fun mk_eq_True (Mss{mk_rews={mk_eq_True,...},...}) thm =
   3.273 +  case mk_eq_True thm of
   3.274 +    None => []
   3.275 +  | Some eq_True => let val (_,_,lhs,elhs,_,_) = decomp_simp eq_True
   3.276 +                    in [{thm=eq_True, lhs=lhs, elhs=elhs, perm=false}] end;
   3.277 +
   3.278 +(* create the rewrite rule and possibly also the ==True variant,
   3.279 +   in case there are extra vars on the rhs *)
   3.280 +fun rrule_eq_True(thm,lhs,elhs,rhs,mss,thm2) =
   3.281 +  let val rrule = {thm=thm, lhs=lhs, elhs=elhs, perm=false}
   3.282 +  in if (term_varnames rhs)  subset (term_varnames lhs) andalso
   3.283 +        (term_tvars rhs) subset (term_tvars lhs)
   3.284 +     then [rrule]
   3.285 +     else mk_eq_True mss thm2 @ [rrule]
   3.286 +  end;
   3.287 +
   3.288 +fun mk_rrule mss thm =
   3.289 +  let val (_,prems,lhs,elhs,rhs,perm) = decomp_simp thm
   3.290 +  in if perm then [{thm=thm, lhs=lhs, elhs=elhs, perm=true}] else
   3.291 +     (* weak test for loops: *)
   3.292 +     if rewrite_rule_extra_vars prems lhs rhs orelse
   3.293 +        is_Var (term_of elhs)
   3.294 +     then mk_eq_True mss thm
   3.295 +     else rrule_eq_True(thm,lhs,elhs,rhs,mss,thm)
   3.296 +  end;
   3.297 +
   3.298 +fun orient_rrule mss thm =
   3.299 +  let val (sign,prems,lhs,elhs,rhs,perm) = decomp_simp thm
   3.300 +  in if perm then [{thm=thm,lhs=lhs,elhs=elhs,perm=true}]
   3.301 +     else if reorient sign prems lhs rhs
   3.302 +          then if reorient sign prems rhs lhs
   3.303 +               then mk_eq_True mss thm
   3.304 +               else let val Mss{mk_rews={mk_sym,...},...} = mss
   3.305 +                    in case mk_sym thm of
   3.306 +                         None => []
   3.307 +                       | Some thm' =>
   3.308 +                           let val (_,_,lhs',elhs',rhs',_) = decomp_simp thm'
   3.309 +                           in rrule_eq_True(thm',lhs',elhs',rhs',mss,thm) end
   3.310 +                    end
   3.311 +          else rrule_eq_True(thm,lhs,elhs,rhs,mss,thm)
   3.312 +  end;
   3.313 +
   3.314 +fun extract_rews(Mss{mk_rews = {mk,...},...},thms) = flat(map mk thms);
   3.315 +
   3.316 +fun orient_comb_simps comb mk_rrule (mss,thms) =
   3.317 +  let val rews = extract_rews(mss,thms)
   3.318 +      val rrules = flat (map mk_rrule rews)
   3.319 +  in foldl comb (mss,rrules) end
   3.320 +
   3.321 +(* Add rewrite rules explicitly; do not reorient! *)
   3.322 +fun add_simps(mss,thms) =
   3.323 +  orient_comb_simps insert_rrule (mk_rrule mss) (mss,thms);
   3.324 +
   3.325 +fun mss_of thms =
   3.326 +  foldl insert_rrule (empty_mss, flat(map (mk_rrule empty_mss) thms));
   3.327 +
   3.328 +fun extract_safe_rrules(mss,thm) =
   3.329 +  flat (map (orient_rrule mss) (extract_rews(mss,[thm])));
   3.330 +
   3.331 +fun add_safe_simp(mss,thm) =
   3.332 +  foldl insert_rrule (mss, extract_safe_rrules(mss,thm))
   3.333 +
   3.334 +(* del_simps *)
   3.335 +
   3.336 +fun del_rrule(mss as Mss {rules,...},
   3.337 +              rrule as {thm, elhs, ...}) =
   3.338 +  (upd_rules(mss, Net.delete_term ((term_of elhs, rrule), rules, eq_rrule))
   3.339 +   handle Net.DELETE =>
   3.340 +     (prthm true "Rewrite rule not in simpset:" thm; mss));
   3.341 +
   3.342 +fun del_simps(mss,thms) =
   3.343 +  orient_comb_simps del_rrule (map mk_rrule2 o mk_rrule mss) (mss,thms);
   3.344 +
   3.345 +
   3.346 +(* add_congs *)
   3.347 +
   3.348 +fun is_full_cong_prems [] varpairs = null varpairs
   3.349 +  | is_full_cong_prems (p::prems) varpairs =
   3.350 +    (case Logic.strip_assums_concl p of
   3.351 +       Const("==",_) $ lhs $ rhs =>
   3.352 +         let val (x,xs) = strip_comb lhs and (y,ys) = strip_comb rhs
   3.353 +         in is_Var x  andalso  forall is_Bound xs  andalso
   3.354 +            null(findrep(xs))  andalso xs=ys andalso
   3.355 +            (x,y) mem varpairs andalso
   3.356 +            is_full_cong_prems prems (varpairs\(x,y))
   3.357 +         end
   3.358 +     | _ => false);
   3.359 +
   3.360 +fun is_full_cong thm =
   3.361 +let val prems = prems_of thm
   3.362 +    and concl = concl_of thm
   3.363 +    val (lhs,rhs) = Logic.dest_equals concl
   3.364 +    val (f,xs) = strip_comb lhs
   3.365 +    and (g,ys) = strip_comb rhs
   3.366 +in
   3.367 +  f=g andalso null(findrep(xs@ys)) andalso length xs = length ys andalso
   3.368 +  is_full_cong_prems prems (xs ~~ ys)
   3.369 +end
   3.370 +
   3.371 +fun add_cong (Mss {rules,congs,procs,bounds,prems,mk_rews,termless}, thm) =
   3.372 +  let
   3.373 +    val (lhs, _) = Drule.dest_equals (Drule.strip_imp_concl (cprop_of thm)) handle TERM _ =>
   3.374 +      raise SIMPLIFIER ("Congruence not a meta-equality", thm);
   3.375 +(*   val lhs = Pattern.eta_contract lhs; *)
   3.376 +    val (a, _) = dest_Const (head_of (term_of lhs)) handle TERM _ =>
   3.377 +      raise SIMPLIFIER ("Congruence must start with a constant", thm);
   3.378 +    val (alist,weak) = congs
   3.379 +    val alist2 = overwrite_warn (alist, (a,{lhs=lhs, thm=thm}))
   3.380 +           ("Overwriting congruence rule for " ^ quote a);
   3.381 +    val weak2 = if is_full_cong thm then weak else a::weak
   3.382 +  in
   3.383 +    mk_mss (rules, (alist2,weak2), procs, bounds, prems, mk_rews, termless)
   3.384 +  end;
   3.385 +
   3.386 +val (op add_congs) = foldl add_cong;
   3.387 +
   3.388 +
   3.389 +(* del_congs *)
   3.390 +
   3.391 +fun del_cong (Mss {rules,congs,procs,bounds,prems,mk_rews,termless}, thm) =
   3.392 +  let
   3.393 +    val (lhs, _) = Logic.dest_equals (concl_of thm) handle TERM _ =>
   3.394 +      raise SIMPLIFIER ("Congruence not a meta-equality", thm);
   3.395 +(*   val lhs = Pattern.eta_contract lhs; *)
   3.396 +    val (a, _) = dest_Const (head_of lhs) handle TERM _ =>
   3.397 +      raise SIMPLIFIER ("Congruence must start with a constant", thm);
   3.398 +    val (alist,_) = congs
   3.399 +    val alist2 = filter (fn (x,_)=> x<>a) alist
   3.400 +    val weak2 = mapfilter (fn(a,{thm,...}) => if is_full_cong thm then None
   3.401 +                                              else Some a)
   3.402 +                   alist2
   3.403 +  in
   3.404 +    mk_mss (rules, (alist2,weak2), procs, bounds, prems, mk_rews, termless)
   3.405 +  end;
   3.406 +
   3.407 +val (op del_congs) = foldl del_cong;
   3.408 +
   3.409 +
   3.410 +(* add_simprocs *)
   3.411 +
   3.412 +fun add_proc (mss as Mss {rules,congs,procs,bounds,prems,mk_rews,termless},
   3.413 +    (name, lhs, proc, id)) =
   3.414 +  let val {sign, t, ...} = rep_cterm lhs
   3.415 +  in (trace_term false ("Adding simplification procedure " ^ quote name ^ " for")
   3.416 +      sign t;
   3.417 +    mk_mss (rules, congs,
   3.418 +      Net.insert_term ((t, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
   3.419 +        handle Net.INSERT => 
   3.420 +	    (warning ("Ignoring duplicate simplification procedure \"" 
   3.421 +	              ^ name ^ "\""); 
   3.422 +	     procs),
   3.423 +        bounds, prems, mk_rews, termless))
   3.424 +  end;
   3.425 +
   3.426 +fun add_simproc (mss, (name, lhss, proc, id)) =
   3.427 +  foldl add_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
   3.428 +
   3.429 +val add_simprocs = foldl add_simproc;
   3.430 +
   3.431 +
   3.432 +(* del_simprocs *)
   3.433 +
   3.434 +fun del_proc (mss as Mss {rules,congs,procs,bounds,prems,mk_rews,termless},
   3.435 +    (name, lhs, proc, id)) =
   3.436 +  mk_mss (rules, congs,
   3.437 +    Net.delete_term ((term_of lhs, mk_simproc (name, proc, lhs, id)), procs, eq_simproc)
   3.438 +      handle Net.DELETE => 
   3.439 +	  (warning ("Simplification procedure \"" ^ name ^
   3.440 +		       "\" not in simpset"); procs),
   3.441 +      bounds, prems, mk_rews, termless);
   3.442 +
   3.443 +fun del_simproc (mss, (name, lhss, proc, id)) =
   3.444 +  foldl del_proc (mss, map (fn lhs => (name, lhs, proc, id)) lhss);
   3.445 +
   3.446 +val del_simprocs = foldl del_simproc;
   3.447 +
   3.448 +
   3.449 +(* prems *)
   3.450 +
   3.451 +fun add_prems (Mss {rules,congs,procs,bounds,prems,mk_rews,termless}, thms) =
   3.452 +  mk_mss (rules, congs, procs, bounds, thms @ prems, mk_rews, termless);
   3.453 +
   3.454 +fun prems_of_mss (Mss {prems, ...}) = prems;
   3.455 +
   3.456 +
   3.457 +(* mk_rews *)
   3.458 +
   3.459 +fun set_mk_rews
   3.460 +  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, mk) =
   3.461 +    mk_mss (rules, congs, procs, bounds, prems,
   3.462 +            {mk=mk, mk_sym= #mk_sym mk_rews, mk_eq_True= #mk_eq_True mk_rews},
   3.463 +            termless);
   3.464 +
   3.465 +fun set_mk_sym
   3.466 +  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, mk_sym) =
   3.467 +    mk_mss (rules, congs, procs, bounds, prems,
   3.468 +            {mk= #mk mk_rews, mk_sym= mk_sym, mk_eq_True= #mk_eq_True mk_rews},
   3.469 +            termless);
   3.470 +
   3.471 +fun set_mk_eq_True
   3.472 +  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless}, mk_eq_True) =
   3.473 +    mk_mss (rules, congs, procs, bounds, prems,
   3.474 +            {mk= #mk mk_rews, mk_sym= #mk_sym mk_rews, mk_eq_True= mk_eq_True},
   3.475 +            termless);
   3.476 +
   3.477 +(* termless *)
   3.478 +
   3.479 +fun set_termless
   3.480 +  (Mss {rules, congs, procs, bounds, prems, mk_rews, termless = _}, termless) =
   3.481 +    mk_mss (rules, congs, procs, bounds, prems, mk_rews, termless);
   3.482 +
   3.483 +
   3.484 +
   3.485 +(** rewriting **)
   3.486 +
   3.487 +(*
   3.488 +  Uses conversions, see:
   3.489 +    L C Paulson, A higher-order implementation of rewriting,
   3.490 +    Science of Computer Programming 3 (1983), pages 119-149.
   3.491 +*)
   3.492 +
   3.493 +type prover = meta_simpset -> thm -> thm option;
   3.494 +type termrec = (Sign.sg_ref * term list) * term;
   3.495 +type conv = meta_simpset -> termrec -> termrec;
   3.496 +
   3.497 +val dest_eq = Drule.dest_equals o cprop_of;
   3.498 +val lhs_of = fst o dest_eq;
   3.499 +val rhs_of = snd o dest_eq;
   3.500 +
   3.501 +fun beta_eta_conversion t =
   3.502 +  let val thm = beta_conversion true t;
   3.503 +  in transitive thm (eta_conversion (rhs_of thm)) end;
   3.504 +
   3.505 +fun check_conv msg thm thm' =
   3.506 +  let
   3.507 +    val thm'' = transitive thm (transitive
   3.508 +      (symmetric (beta_eta_conversion (lhs_of thm'))) thm')
   3.509 +  in (if msg then trace_thm false "SUCCEEDED" thm' else (); Some thm'') end
   3.510 +  handle THM _ =>
   3.511 +    let val {sign, prop = _ $ _ $ prop0, ...} = rep_thm thm;
   3.512 +    in
   3.513 +      (trace_thm false "Proved wrong thm (Check subgoaler?)" thm';
   3.514 +       trace_term false "Should have proved:" sign prop0;
   3.515 +       None)
   3.516 +    end;
   3.517 +
   3.518 +
   3.519 +(* mk_procrule *)
   3.520 +
   3.521 +fun mk_procrule thm =
   3.522 +  let val (_,prems,lhs,elhs,rhs,_) = decomp_simp thm
   3.523 +  in if rewrite_rule_extra_vars prems lhs rhs
   3.524 +     then (prthm true "Extra vars on rhs:" thm; [])
   3.525 +     else [mk_rrule2{thm=thm, lhs=lhs, elhs=elhs, perm=false}]
   3.526 +  end;
   3.527 +
   3.528 +
   3.529 +(* conversion to apply the meta simpset to a term *)
   3.530 +
   3.531 +(* Since the rewriting strategy is bottom-up, we avoid re-normalizing already
   3.532 +   normalized terms by carrying around the rhs of the rewrite rule just
   3.533 +   applied. This is called the `skeleton'. It is decomposed in parallel
   3.534 +   with the term. Once a Var is encountered, the corresponding term is
   3.535 +   already in normal form.
   3.536 +   skel0 is a dummy skeleton that is to enforce complete normalization.
   3.537 +*)
   3.538 +val skel0 = Bound 0;
   3.539 +
   3.540 +(* Use rhs as skeleton only if the lhs does not contain unnormalized bits.
   3.541 +   The latter may happen iff there are weak congruence rules for constants
   3.542 +   in the lhs.
   3.543 +*)
   3.544 +fun uncond_skel((_,weak),(lhs,rhs)) =
   3.545 +  if null weak then rhs (* optimization *)
   3.546 +  else if exists_Const (fn (c,_) => c mem weak) lhs then skel0
   3.547 +       else rhs;
   3.548 +
   3.549 +(* Behaves like unconditional rule if rhs does not contain vars not in the lhs.
   3.550 +   Otherwise those vars may become instantiated with unnormalized terms
   3.551 +   while the premises are solved.
   3.552 +*)
   3.553 +fun cond_skel(args as (congs,(lhs,rhs))) =
   3.554 +  if term_varnames rhs subset term_varnames lhs then uncond_skel(args)
   3.555 +  else skel0;
   3.556 +
   3.557 +(*
   3.558 +  we try in order:
   3.559 +    (1) beta reduction
   3.560 +    (2) unconditional rewrite rules
   3.561 +    (3) conditional rewrite rules
   3.562 +    (4) simplification procedures
   3.563 +
   3.564 +  IMPORTANT: rewrite rules must not introduce new Vars or TVars!
   3.565 +
   3.566 +*)
   3.567 +
   3.568 +fun rewritec (prover, signt, maxt)
   3.569 +             (mss as Mss{rules, procs, termless, prems, congs, ...}) t =
   3.570 +  let
   3.571 +    val eta_thm = Thm.eta_conversion t;
   3.572 +    val eta_t' = rhs_of eta_thm;
   3.573 +    val eta_t = term_of eta_t';
   3.574 +    val tsigt = Sign.tsig_of signt;
   3.575 +    fun rew {thm, lhs, elhs, fo, perm} =
   3.576 +      let
   3.577 +        val {sign, prop, maxidx, ...} = rep_thm thm;
   3.578 +        val _ = if Sign.subsig (sign, signt) then ()
   3.579 +                else (prthm true "Ignoring rewrite rule from different theory:" thm;
   3.580 +                      raise Pattern.MATCH);
   3.581 +        val (rthm, elhs') = if maxt = ~1 then (thm, elhs)
   3.582 +          else (Thm.incr_indexes (maxt+1) thm, Thm.cterm_incr_indexes (maxt+1) elhs);
   3.583 +        val insts = if fo then Thm.cterm_first_order_match (elhs', eta_t')
   3.584 +                          else Thm.cterm_match (elhs', eta_t');
   3.585 +        val thm' = Thm.instantiate insts (Thm.rename_boundvars lhs eta_t rthm);
   3.586 +        val prop' = #prop (rep_thm thm');
   3.587 +        val unconditional = (Logic.count_prems (prop',0) = 0);
   3.588 +        val (lhs', rhs') = Logic.dest_equals (Logic.strip_imp_concl prop')
   3.589 +      in
   3.590 +        if perm andalso not (termless (rhs', lhs')) then None
   3.591 +        else
   3.592 +          (trace_thm false "Applying instance of rewrite rule:" thm;
   3.593 +           if unconditional
   3.594 +           then
   3.595 +             (trace_thm false "Rewriting:" thm';
   3.596 +              let val lr = Logic.dest_equals prop;
   3.597 +                  val Some thm'' = check_conv false eta_thm thm'
   3.598 +              in Some (thm'', uncond_skel (congs, lr)) end)
   3.599 +           else
   3.600 +             (trace_thm false "Trying to rewrite:" thm';
   3.601 +              case prover mss thm' of
   3.602 +                None       => (trace_thm false "FAILED" thm'; None)
   3.603 +              | Some thm2 =>
   3.604 +                  (case check_conv true eta_thm thm2 of
   3.605 +                     None => None |
   3.606 +                     Some thm2' =>
   3.607 +                       let val concl = Logic.strip_imp_concl prop
   3.608 +                           val lr = Logic.dest_equals concl
   3.609 +                       in Some (thm2', cond_skel (congs, lr)) end)))
   3.610 +      end
   3.611 +
   3.612 +    fun rews [] = None
   3.613 +      | rews (rrule :: rrules) =
   3.614 +          let val opt = rew rrule handle Pattern.MATCH => None
   3.615 +          in case opt of None => rews rrules | some => some end;
   3.616 +
   3.617 +    fun sort_rrules rrs = let
   3.618 +      fun is_simple({thm, ...}:rrule) = case #prop (rep_thm thm) of 
   3.619 +                                      Const("==",_) $ _ $ _ => true
   3.620 +                                      | _                   => false 
   3.621 +      fun sort []        (re1,re2) = re1 @ re2
   3.622 +        | sort (rr::rrs) (re1,re2) = if is_simple rr 
   3.623 +                                     then sort rrs (rr::re1,re2)
   3.624 +                                     else sort rrs (re1,rr::re2)
   3.625 +    in sort rrs ([],[]) end
   3.626 +
   3.627 +    fun proc_rews ([]:simproc list) = None
   3.628 +      | proc_rews ({name, proc, lhs, ...} :: ps) =
   3.629 +          if Pattern.matches tsigt (term_of lhs, term_of t) then
   3.630 +            (debug_term false ("Trying procedure " ^ quote name ^ " on:") signt eta_t;
   3.631 +             case proc signt prems eta_t of
   3.632 +               None => (debug false "FAILED"; proc_rews ps)
   3.633 +             | Some raw_thm =>
   3.634 +                 (trace_thm false ("Procedure " ^ quote name ^ " produced rewrite rule:") raw_thm;
   3.635 +                  (case rews (mk_procrule raw_thm) of
   3.636 +                    None => (trace false "IGNORED"; proc_rews ps)
   3.637 +                  | some => some)))
   3.638 +          else proc_rews ps;
   3.639 +  in case eta_t of
   3.640 +       Abs _ $ _ => Some (transitive eta_thm
   3.641 +         (beta_conversion false (rhs_of eta_thm)), skel0)
   3.642 +     | _ => (case rews (sort_rrules (Net.match_term rules eta_t)) of
   3.643 +               None => proc_rews (Net.match_term procs eta_t)
   3.644 +             | some => some)
   3.645 +  end;
   3.646 +
   3.647 +
   3.648 +(* conversion to apply a congruence rule to a term *)
   3.649 +
   3.650 +fun congc (prover,signt,maxt) {thm=cong,lhs=lhs} t =
   3.651 +  let val {sign, ...} = rep_thm cong
   3.652 +      val _ = if Sign.subsig (sign, signt) then ()
   3.653 +                 else error("Congruence rule from different theory")
   3.654 +      val rthm = if maxt = ~1 then cong else Thm.incr_indexes (maxt+1) cong;
   3.655 +      val rlhs = fst (Drule.dest_equals (Drule.strip_imp_concl (cprop_of rthm)));
   3.656 +      val insts = Thm.cterm_match (rlhs, t)
   3.657 +      (* Pattern.match can raise Pattern.MATCH;
   3.658 +         is handled when congc is called *)
   3.659 +      val thm' = Thm.instantiate insts (Thm.rename_boundvars (term_of rlhs) (term_of t) rthm);
   3.660 +      val unit = trace_thm false "Applying congruence rule:" thm';
   3.661 +      fun err (msg, thm) = (prthm false msg thm; error "Failed congruence proof!")
   3.662 +  in case prover thm' of
   3.663 +       None => err ("Could not prove", thm')
   3.664 +     | Some thm2 => (case check_conv true (beta_eta_conversion t) thm2 of
   3.665 +          None => err ("Should not have proved", thm2)
   3.666 +        | Some thm2' => thm2')
   3.667 +  end;
   3.668 +
   3.669 +val (cA, (cB, cC)) =
   3.670 +  apsnd dest_equals (dest_implies (hd (cprems_of Drule.imp_cong)));
   3.671 +
   3.672 +fun transitive' thm1 None = Some thm1
   3.673 +  | transitive' thm1 (Some thm2) = Some (transitive thm1 thm2);
   3.674 +
   3.675 +fun bottomc ((simprem,useprem,mutsimp), prover, sign, maxidx) =
   3.676 +  let
   3.677 +    fun botc skel mss t =
   3.678 +          if is_Var skel then None
   3.679 +          else
   3.680 +          (case subc skel mss t of
   3.681 +             some as Some thm1 =>
   3.682 +               (case rewritec (prover, sign, maxidx) mss (rhs_of thm1) of
   3.683 +                  Some (thm2, skel2) =>
   3.684 +                    transitive' (transitive thm1 thm2)
   3.685 +                      (botc skel2 mss (rhs_of thm2))
   3.686 +                | None => some)
   3.687 +           | None =>
   3.688 +               (case rewritec (prover, sign, maxidx) mss t of
   3.689 +                  Some (thm2, skel2) => transitive' thm2
   3.690 +                    (botc skel2 mss (rhs_of thm2))
   3.691 +                | None => None))
   3.692 +
   3.693 +    and try_botc mss t =
   3.694 +          (case botc skel0 mss t of
   3.695 +             Some trec1 => trec1 | None => (reflexive t))
   3.696 +
   3.697 +    and subc skel
   3.698 +          (mss as Mss{rules,congs,procs,bounds,prems,mk_rews,termless}) t0 =
   3.699 +       (case term_of t0 of
   3.700 +           Abs (a, T, t) =>
   3.701 +             let val b = variant bounds a
   3.702 +                 val (v, t') = dest_abs (Some ("." ^ b)) t0
   3.703 +                 val mss' = mk_mss (rules, congs, procs, b :: bounds, prems, mk_rews, termless)
   3.704 +                 val skel' = case skel of Abs (_, _, sk) => sk | _ => skel0
   3.705 +             in case botc skel' mss' t' of
   3.706 +                  Some thm => Some (abstract_rule a v thm)
   3.707 +                | None => None
   3.708 +             end
   3.709 +         | t $ _ => (case t of
   3.710 +             Const ("==>", _) $ _  =>
   3.711 +               let val (s, u) = Drule.dest_implies t0
   3.712 +               in impc (s, u, mss) end
   3.713 +           | Abs _ =>
   3.714 +               let val thm = beta_conversion false t0
   3.715 +               in case subc skel0 mss (rhs_of thm) of
   3.716 +                    None => Some thm
   3.717 +                  | Some thm' => Some (transitive thm thm')
   3.718 +               end
   3.719 +           | _  =>
   3.720 +               let fun appc () =
   3.721 +                     let
   3.722 +                       val (tskel, uskel) = case skel of
   3.723 +                           tskel $ uskel => (tskel, uskel)
   3.724 +                         | _ => (skel0, skel0);
   3.725 +                       val (ct, cu) = dest_comb t0
   3.726 +                     in
   3.727 +                     (case botc tskel mss ct of
   3.728 +                        Some thm1 =>
   3.729 +                          (case botc uskel mss cu of
   3.730 +                             Some thm2 => Some (combination thm1 thm2)
   3.731 +                           | None => Some (combination thm1 (reflexive cu)))
   3.732 +                      | None =>
   3.733 +                          (case botc uskel mss cu of
   3.734 +                             Some thm1 => Some (combination (reflexive ct) thm1)
   3.735 +                           | None => None))
   3.736 +                     end
   3.737 +                   val (h, ts) = strip_comb t
   3.738 +               in case h of
   3.739 +                    Const(a, _) =>
   3.740 +                      (case assoc_string (fst congs, a) of
   3.741 +                         None => appc ()
   3.742 +                       | Some cong =>
   3.743 +(* post processing: some partial applications h t1 ... tj, j <= length ts,
   3.744 +   may be a redex. Example: map (%x.x) = (%xs.xs) wrt map_cong *)
   3.745 +                          (let
   3.746 +                             val thm = congc (prover mss, sign, maxidx) cong t0;
   3.747 +                             val t = rhs_of thm;
   3.748 +                             val (cl, cr) = dest_comb t
   3.749 +                             val dVar = Var(("", 0), dummyT)
   3.750 +                             val skel =
   3.751 +                               list_comb (h, replicate (length ts) dVar)
   3.752 +                           in case botc skel mss cl of
   3.753 +                                None => Some thm
   3.754 +                              | Some thm' => Some (transitive thm
   3.755 +                                  (combination thm' (reflexive cr)))
   3.756 +                           end handle TERM _ => error "congc result"
   3.757 +                                    | Pattern.MATCH => appc ()))
   3.758 +                  | _ => appc ()
   3.759 +               end)
   3.760 +         | _ => None)
   3.761 +
   3.762 +    and impc args =
   3.763 +      if mutsimp
   3.764 +      then let val (prem, conc, mss) = args
   3.765 +           in apsome snd (mut_impc ([], prem, conc, mss)) end
   3.766 +      else nonmut_impc args
   3.767 +
   3.768 +    and mut_impc (prems, prem, conc, mss) = (case botc skel0 mss prem of
   3.769 +        None => mut_impc1 (prems, prem, conc, mss)
   3.770 +      | Some thm1 =>
   3.771 +          let val prem1 = rhs_of thm1
   3.772 +          in (case mut_impc1 (prems, prem1, conc, mss) of
   3.773 +              None => Some (None,
   3.774 +                combination (combination refl_implies thm1) (reflexive conc))
   3.775 +            | Some (x, thm2) => Some (x, transitive (combination (combination
   3.776 +                refl_implies thm1) (reflexive conc)) thm2))
   3.777 +          end)
   3.778 +
   3.779 +    and mut_impc1 (prems, prem1, conc, mss) =
   3.780 +      let
   3.781 +        fun uncond ({thm, lhs, elhs, perm}) =
   3.782 +          if Thm.no_prems thm then Some lhs else None
   3.783 +
   3.784 +        val (lhss1, mss1) =
   3.785 +          if maxidx_of_term (term_of prem1) <> ~1
   3.786 +          then (trace_cterm true
   3.787 +            "Cannot add premise as rewrite rule because it contains (type) unknowns:" prem1;
   3.788 +                ([],mss))
   3.789 +          else let val thm = assume prem1
   3.790 +                   val rrules1 = extract_safe_rrules (mss, thm)
   3.791 +                   val lhss1 = mapfilter uncond rrules1
   3.792 +                   val mss1 = foldl insert_rrule (add_prems (mss, [thm]), rrules1)
   3.793 +               in (lhss1, mss1) end
   3.794 +
   3.795 +        fun disch1 thm =
   3.796 +          let val (cB', cC') = dest_eq thm
   3.797 +          in
   3.798 +            implies_elim (Thm.instantiate
   3.799 +              ([], [(cA, prem1), (cB, cB'), (cC, cC')]) Drule.imp_cong)
   3.800 +              (implies_intr prem1 thm)
   3.801 +          end
   3.802 +
   3.803 +        fun rebuild None = (case rewritec (prover, sign, maxidx) mss
   3.804 +            (mk_implies (prem1, conc)) of
   3.805 +              None => None
   3.806 +            | Some (thm, _) => Some (None, thm))
   3.807 +          | rebuild (Some thm2) =
   3.808 +            let val thm = disch1 thm2
   3.809 +            in (case rewritec (prover, sign, maxidx) mss (rhs_of thm) of
   3.810 +                 None => Some (None, thm)
   3.811 +               | Some (thm', _) =>
   3.812 +                   let val (prem, conc) = Drule.dest_implies (rhs_of thm')
   3.813 +                   in (case mut_impc (prems, prem, conc, mss) of
   3.814 +                       None => Some (None, transitive thm thm')
   3.815 +                     | Some (x, thm'') =>
   3.816 +                         Some (x, transitive (transitive thm thm') thm''))
   3.817 +                   end handle TERM _ => Some (None, transitive thm thm'))
   3.818 +            end
   3.819 +
   3.820 +        fun simpconc () =
   3.821 +          let val (s, t) = Drule.dest_implies conc
   3.822 +          in case mut_impc (prems @ [prem1], s, t, mss1) of
   3.823 +               None => rebuild None
   3.824 +             | Some (Some i, thm2) =>
   3.825 +                  let
   3.826 +                    val (prem, cC') = Drule.dest_implies (rhs_of thm2);
   3.827 +                    val thm2' = transitive (disch1 thm2) (Thm.instantiate
   3.828 +                      ([], [(cA, prem1), (cB, prem), (cC, cC')])
   3.829 +                      Drule.swap_prems_eq)
   3.830 +                  in if i=0 then apsome (apsnd (transitive thm2'))
   3.831 +                       (mut_impc1 (prems, prem, mk_implies (prem1, cC'), mss))
   3.832 +                     else Some (Some (i-1), thm2')
   3.833 +                  end
   3.834 +             | Some (None, thm) => rebuild (Some thm)
   3.835 +          end handle TERM _ => rebuild (botc skel0 mss1 conc)
   3.836 +
   3.837 +      in
   3.838 +        let
   3.839 +          val tsig = Sign.tsig_of sign
   3.840 +          fun reducible t =
   3.841 +            exists (fn lhs => Pattern.matches_subterm tsig (lhs, term_of t)) lhss1;
   3.842 +        in case dropwhile (not o reducible) prems of
   3.843 +            [] => simpconc ()
   3.844 +          | red::rest => (trace_cterm false "Can now reduce premise:" red;
   3.845 +              Some (Some (length rest), reflexive (mk_implies (prem1, conc))))
   3.846 +        end
   3.847 +      end
   3.848 +
   3.849 +     (* legacy code - only for backwards compatibility *)
   3.850 +     and nonmut_impc (prem, conc, mss) =
   3.851 +       let val thm1 = if simprem then botc skel0 mss prem else None;
   3.852 +           val prem1 = if_none (apsome rhs_of thm1) prem;
   3.853 +           val maxidx1 = maxidx_of_term (term_of prem1)
   3.854 +           val mss1 =
   3.855 +             if not useprem then mss else
   3.856 +             if maxidx1 <> ~1
   3.857 +             then (trace_cterm true
   3.858 +               "Cannot add premise as rewrite rule because it contains (type) unknowns:" prem1;
   3.859 +                   mss)
   3.860 +             else let val thm = assume prem1
   3.861 +                  in add_safe_simp (add_prems (mss, [thm]), thm) end
   3.862 +       in (case botc skel0 mss1 conc of
   3.863 +           None => (case thm1 of
   3.864 +               None => None
   3.865 +             | Some thm1' => Some (combination
   3.866 +                 (combination refl_implies thm1') (reflexive conc)))
   3.867 +         | Some thm2 =>
   3.868 +           let
   3.869 +             val conc2 = rhs_of thm2;
   3.870 +             val thm2' = implies_elim (Thm.instantiate
   3.871 +               ([], [(cA, prem1), (cB, conc), (cC, conc2)]) Drule.imp_cong)
   3.872 +               (implies_intr prem1 thm2)
   3.873 +           in (case thm1 of
   3.874 +               None => Some thm2'
   3.875 +             | Some thm1' => Some (transitive (combination
   3.876 +                 (combination refl_implies thm1') (reflexive conc)) thm2'))
   3.877 +           end)
   3.878 +       end
   3.879 +
   3.880 + in try_botc end;
   3.881 +
   3.882 +
   3.883 +(*** Meta-rewriting: rewrites t to u and returns the theorem t==u ***)
   3.884 +
   3.885 +(*
   3.886 +  Parameters:
   3.887 +    mode = (simplify A,
   3.888 +            use A in simplifying B,
   3.889 +            use prems of B (if B is again a meta-impl.) to simplify A)
   3.890 +           when simplifying A ==> B
   3.891 +    mss: contains equality theorems of the form [|p1,...|] ==> t==u
   3.892 +    prover: how to solve premises in conditional rewrites and congruences
   3.893 +*)
   3.894 +
   3.895 +(* FIXME: check that #bounds(mss) does not "occur" in ct already *)
   3.896 +
   3.897 +fun rewrite_cterm mode prover mss ct =
   3.898 +  let val {sign, t, maxidx, ...} = rep_cterm ct
   3.899 +  in bottomc (mode, prover, sign, maxidx) mss ct end
   3.900 +  handle THM (s, _, thms) =>
   3.901 +    error ("Exception THM was raised in simplifier:\n" ^ s ^ "\n" ^
   3.902 +      Pretty.string_of (pretty_thms thms));
   3.903 +
   3.904 +(*In [A1,...,An]==>B, rewrite the selected A's only -- for rewrite_goals_tac*)
   3.905 +(*Do not rewrite flex-flex pairs*)
   3.906 +fun goals_conv pred cv =
   3.907 +  let fun gconv i ct =
   3.908 +        let val (A,B) = Drule.dest_implies ct
   3.909 +            val (thA,j) = case term_of A of
   3.910 +                  Const("=?=",_)$_$_ => (reflexive A, i)
   3.911 +                | _ => (if pred i then cv A else reflexive A, i+1)
   3.912 +        in  combination (combination refl_implies thA) (gconv j B) end
   3.913 +        handle TERM _ => reflexive ct
   3.914 +  in gconv 1 end;
   3.915 +
   3.916 +(*Use a conversion to transform a theorem*)
   3.917 +fun fconv_rule cv th = equal_elim (cv (cprop_of th)) th;
   3.918 +
   3.919 +(*Rewrite a theorem*)
   3.920 +fun rewrite_rule_aux _ [] = (fn th => th)
   3.921 +  | rewrite_rule_aux prover thms =
   3.922 +      fconv_rule (rewrite_cterm (true,false,false) prover (mss_of thms));
   3.923 +
   3.924 +fun rewrite_thm mode prover mss = fconv_rule (rewrite_cterm mode prover mss);
   3.925 +
   3.926 +(*Rewrite the subgoals of a proof state (represented by a theorem) *)
   3.927 +fun rewrite_goals_rule_aux _ []   th = th
   3.928 +  | rewrite_goals_rule_aux prover thms th =
   3.929 +      fconv_rule (goals_conv (K true) (rewrite_cterm (true, true, false) prover
   3.930 +        (mss_of thms))) th;
   3.931 +
   3.932 +(*Rewrite the subgoal of a proof state (represented by a theorem) *)
   3.933 +fun rewrite_goal_rule mode prover mss i thm =
   3.934 +  if 0 < i  andalso  i <= nprems_of thm
   3.935 +  then fconv_rule (goals_conv (fn j => j=i) (rewrite_cterm mode prover mss)) thm
   3.936 +  else raise THM("rewrite_goal_rule",i,[thm]);
   3.937 +
   3.938 +end;
   3.939 +
   3.940 +open MetaSimplifier;