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