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