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