src/Pure/raw_simplifier.ML
author wenzelm
Sun Aug 30 21:26:42 2015 +0200 (2015-08-30)
changeset 61057 5f6a1e31f3ad
parent 60822 4f58f3662e7d
child 61090 16f7f9aa4263
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 fun comb_simps ctxt comb mk_rrule thms =
   581   let
   582     val rews = extract_rews ctxt thms;
   583   in fold (fold comb o mk_rrule) rews ctxt end;
   584 
   585 fun ctxt addsimps thms =
   586   comb_simps ctxt insert_rrule (mk_rrule ctxt) thms;
   587 
   588 fun ctxt delsimps thms =
   589   comb_simps ctxt del_rrule (map mk_rrule2 o mk_rrule ctxt) thms;
   590 
   591 fun add_simp thm ctxt = ctxt addsimps [thm];
   592 fun del_simp thm ctxt = ctxt delsimps [thm];
   593 
   594 
   595 (* congs *)
   596 
   597 local
   598 
   599 fun is_full_cong_prems [] [] = true
   600   | is_full_cong_prems [] _ = false
   601   | is_full_cong_prems (p :: prems) varpairs =
   602       (case Logic.strip_assums_concl p of
   603         Const ("Pure.eq", _) $ lhs $ rhs =>
   604           let val (x, xs) = strip_comb lhs and (y, ys) = strip_comb rhs in
   605             is_Var x andalso forall is_Bound xs andalso
   606             not (has_duplicates (op =) xs) andalso xs = ys andalso
   607             member (op =) varpairs (x, y) andalso
   608             is_full_cong_prems prems (remove (op =) (x, y) varpairs)
   609           end
   610       | _ => false);
   611 
   612 fun is_full_cong thm =
   613   let
   614     val prems = Thm.prems_of thm and concl = Thm.concl_of thm;
   615     val (lhs, rhs) = Logic.dest_equals concl;
   616     val (f, xs) = strip_comb lhs and (g, ys) = strip_comb rhs;
   617   in
   618     f = g andalso not (has_duplicates (op =) (xs @ ys)) andalso length xs = length ys andalso
   619     is_full_cong_prems prems (xs ~~ ys)
   620   end;
   621 
   622 fun mk_cong ctxt =
   623   let val Simpset (_, {mk_rews = {mk_cong = f, ...}, ...}) = simpset_of ctxt
   624   in f ctxt end;
   625 
   626 in
   627 
   628 fun add_eqcong thm ctxt = ctxt |> map_simpset2
   629   (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   630     let
   631       val (lhs, _) = Logic.dest_equals (Thm.concl_of thm)
   632         handle TERM _ => raise SIMPLIFIER ("Congruence not a meta-equality", [thm]);
   633     (*val lhs = Envir.eta_contract lhs;*)
   634       val a = the (cong_name (head_of lhs)) handle Option.Option =>
   635         raise SIMPLIFIER ("Congruence must start with a constant or free variable", [thm]);
   636       val (xs, weak) = congs;
   637       val xs' = AList.update (op =) (a, thm) xs;
   638       val weak' = if is_full_cong thm then weak else a :: weak;
   639     in ((xs', weak'), procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) end);
   640 
   641 fun del_eqcong thm ctxt = ctxt |> map_simpset2
   642   (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   643     let
   644       val (lhs, _) = Logic.dest_equals (Thm.concl_of thm)
   645         handle TERM _ => raise SIMPLIFIER ("Congruence not a meta-equality", [thm]);
   646     (*val lhs = Envir.eta_contract lhs;*)
   647       val a = the (cong_name (head_of lhs)) handle Option.Option =>
   648         raise SIMPLIFIER ("Congruence must start with a constant", [thm]);
   649       val (xs, _) = congs;
   650       val xs' = filter_out (fn (x : cong_name, _) => x = a) xs;
   651       val weak' = xs' |> map_filter (fn (a, thm) =>
   652         if is_full_cong thm then NONE else SOME a);
   653     in ((xs', weak'), procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) end);
   654 
   655 fun add_cong thm ctxt = add_eqcong (mk_cong ctxt thm) ctxt;
   656 fun del_cong thm ctxt = del_eqcong (mk_cong ctxt thm) ctxt;
   657 
   658 end;
   659 
   660 
   661 (* simprocs *)
   662 
   663 datatype simproc =
   664   Simproc of
   665     {name: string,
   666      lhss: cterm list,
   667      proc: morphism -> Proof.context -> cterm -> thm option,
   668      id: stamp * thm list};
   669 
   670 fun eq_simproc (Simproc {id = id1, ...}, Simproc {id = id2, ...}) = eq_procid (id1, id2);
   671 
   672 fun transform_simproc phi (Simproc {name, lhss, proc, id = (s, ths)}) =
   673   Simproc
   674    {name = name,
   675     lhss = map (Morphism.cterm phi) lhss,
   676     proc = Morphism.transform phi proc,
   677     id = (s, Morphism.fact phi ths)};
   678 
   679 fun make_simproc {name, lhss, proc, identifier} =
   680   Simproc {name = name, lhss = lhss, proc = proc, id = (stamp (), identifier)};
   681 
   682 fun mk_simproc name lhss proc =
   683   make_simproc {name = name, lhss = lhss, proc = fn _ => fn ctxt => fn ct =>
   684     proc ctxt (Thm.term_of ct), identifier = []};
   685 
   686 (* FIXME avoid global thy and Logic.varify_global *)
   687 fun simproc_global_i thy name = mk_simproc name o map (Thm.global_cterm_of thy o Logic.varify_global);
   688 fun simproc_global thy name = simproc_global_i thy name o map (Syntax.read_term_global thy);
   689 
   690 
   691 local
   692 
   693 fun add_proc (proc as Proc {name, lhs, ...}) ctxt =
   694  (cond_tracing ctxt (fn () =>
   695     print_term ctxt ("Adding simplification procedure " ^ quote name ^ " for") (Thm.term_of lhs));
   696   ctxt |> map_simpset2
   697     (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   698       (congs, Net.insert_term eq_proc (Thm.term_of lhs, proc) procs,
   699         mk_rews, termless, subgoal_tac, loop_tacs, solvers))
   700   handle Net.INSERT =>
   701     (cond_warning ctxt (fn () => "Ignoring duplicate simplification procedure " ^ quote name);
   702       ctxt));
   703 
   704 fun del_proc (proc as Proc {name, lhs, ...}) ctxt =
   705   ctxt |> map_simpset2
   706     (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   707       (congs, Net.delete_term eq_proc (Thm.term_of lhs, proc) procs,
   708         mk_rews, termless, subgoal_tac, loop_tacs, solvers))
   709   handle Net.DELETE =>
   710     (cond_warning ctxt (fn () => "Simplification procedure " ^ quote name ^ " not in simpset");
   711       ctxt);
   712 
   713 fun prep_procs (Simproc {name, lhss, proc, id}) =
   714   lhss |> map (fn lhs => Proc {name = name, lhs = lhs, proc = Morphism.form proc, id = id});
   715 
   716 in
   717 
   718 fun ctxt addsimprocs ps = fold (fold add_proc o prep_procs) ps ctxt;
   719 fun ctxt delsimprocs ps = fold (fold del_proc o prep_procs) ps ctxt;
   720 
   721 end;
   722 
   723 
   724 (* mk_rews *)
   725 
   726 local
   727 
   728 fun map_mk_rews f =
   729   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   730     let
   731       val {mk, mk_cong, mk_sym, mk_eq_True, reorient} = mk_rews;
   732       val (mk', mk_cong', mk_sym', mk_eq_True', reorient') =
   733         f (mk, mk_cong, mk_sym, mk_eq_True, reorient);
   734       val mk_rews' = {mk = mk', mk_cong = mk_cong', mk_sym = mk_sym', mk_eq_True = mk_eq_True',
   735         reorient = reorient'};
   736     in (congs, procs, mk_rews', termless, subgoal_tac, loop_tacs, solvers) end);
   737 
   738 in
   739 
   740 fun mksimps ctxt =
   741   let val Simpset (_, {mk_rews = {mk, ...}, ...}) = simpset_of ctxt
   742   in mk ctxt end;
   743 
   744 fun set_mksimps mk = map_mk_rews (fn (_, mk_cong, mk_sym, mk_eq_True, reorient) =>
   745   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   746 
   747 fun set_mkcong mk_cong = map_mk_rews (fn (mk, _, mk_sym, mk_eq_True, reorient) =>
   748   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   749 
   750 fun set_mksym mk_sym = map_mk_rews (fn (mk, mk_cong, _, mk_eq_True, reorient) =>
   751   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   752 
   753 fun set_mkeqTrue mk_eq_True = map_mk_rews (fn (mk, mk_cong, mk_sym, _, reorient) =>
   754   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   755 
   756 fun set_reorient reorient = map_mk_rews (fn (mk, mk_cong, mk_sym, mk_eq_True, _) =>
   757   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   758 
   759 end;
   760 
   761 
   762 (* termless *)
   763 
   764 fun set_termless termless =
   765   map_simpset2 (fn (congs, procs, mk_rews, _, subgoal_tac, loop_tacs, solvers) =>
   766    (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers));
   767 
   768 
   769 (* tactics *)
   770 
   771 fun set_subgoaler subgoal_tac =
   772   map_simpset2 (fn (congs, procs, mk_rews, termless, _, loop_tacs, solvers) =>
   773    (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers));
   774 
   775 fun ctxt setloop tac = ctxt |>
   776   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, _, solvers) =>
   777    (congs, procs, mk_rews, termless, subgoal_tac, [("", tac)], solvers));
   778 
   779 fun ctxt addloop (name, tac) = ctxt |>
   780   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   781     (congs, procs, mk_rews, termless, subgoal_tac,
   782      AList.update (op =) (name, tac) loop_tacs, solvers));
   783 
   784 fun ctxt delloop name = ctxt |>
   785   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   786     (congs, procs, mk_rews, termless, subgoal_tac,
   787      (if AList.defined (op =) loop_tacs name then ()
   788       else cond_warning ctxt (fn () => "No such looper in simpset: " ^ quote name);
   789       AList.delete (op =) name loop_tacs), solvers));
   790 
   791 fun ctxt setSSolver solver = ctxt |> map_simpset2
   792   (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, (unsafe_solvers, _)) =>
   793     (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, (unsafe_solvers, [solver])));
   794 
   795 fun ctxt addSSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
   796   subgoal_tac, loop_tacs, (unsafe_solvers, solvers)) => (congs, procs, mk_rews, termless,
   797     subgoal_tac, loop_tacs, (unsafe_solvers, insert eq_solver solver solvers)));
   798 
   799 fun ctxt setSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
   800   subgoal_tac, loop_tacs, (_, solvers)) => (congs, procs, mk_rews, termless,
   801     subgoal_tac, loop_tacs, ([solver], solvers)));
   802 
   803 fun ctxt addSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
   804   subgoal_tac, loop_tacs, (unsafe_solvers, solvers)) => (congs, procs, mk_rews, termless,
   805     subgoal_tac, loop_tacs, (insert eq_solver solver unsafe_solvers, solvers)));
   806 
   807 fun set_solvers solvers = map_simpset2 (fn (congs, procs, mk_rews, termless,
   808   subgoal_tac, loop_tacs, _) => (congs, procs, mk_rews, termless,
   809   subgoal_tac, loop_tacs, (solvers, solvers)));
   810 
   811 
   812 (* trace operations *)
   813 
   814 type trace_ops =
   815  {trace_invoke: {depth: int, term: term} -> Proof.context -> Proof.context,
   816   trace_apply: {unconditional: bool, term: term, thm: thm, rrule: rrule} ->
   817     Proof.context -> (Proof.context -> (thm * term) option) -> (thm * term) option};
   818 
   819 structure Trace_Ops = Theory_Data
   820 (
   821   type T = trace_ops;
   822   val empty: T =
   823    {trace_invoke = fn _ => fn ctxt => ctxt,
   824     trace_apply = fn _ => fn ctxt => fn cont => cont ctxt};
   825   val extend = I;
   826   fun merge (trace_ops, _) = trace_ops;
   827 );
   828 
   829 val set_trace_ops = Trace_Ops.put;
   830 
   831 val trace_ops = Trace_Ops.get o Proof_Context.theory_of;
   832 fun trace_invoke args ctxt = #trace_invoke (trace_ops ctxt) args ctxt;
   833 fun trace_apply args ctxt = #trace_apply (trace_ops ctxt) args ctxt;
   834 
   835 
   836 
   837 (** rewriting **)
   838 
   839 (*
   840   Uses conversions, see:
   841     L C Paulson, A higher-order implementation of rewriting,
   842     Science of Computer Programming 3 (1983), pages 119-149.
   843 *)
   844 
   845 fun check_conv ctxt msg thm thm' =
   846   let
   847     val thm'' = Thm.transitive thm thm' handle THM _ =>
   848       let
   849         val nthm' =
   850           Thm.transitive (Thm.symmetric (Drule.beta_eta_conversion (Thm.lhs_of thm'))) thm'
   851       in Thm.transitive thm nthm' handle THM _ =>
   852            let
   853              val nthm =
   854                Thm.transitive thm (Drule.beta_eta_conversion (Thm.rhs_of thm))
   855            in Thm.transitive nthm nthm' end
   856       end
   857     val _ =
   858       if msg then cond_tracing ctxt (fn () => print_thm ctxt "SUCCEEDED" ("", thm'))
   859       else ();
   860   in SOME thm'' end
   861   handle THM _ =>
   862     let
   863       val _ $ _ $ prop0 = Thm.prop_of thm;
   864       val _ =
   865         cond_tracing ctxt (fn () =>
   866           print_thm ctxt "Proved wrong theorem (bad subgoaler?)" ("", thm') ^ "\n" ^
   867           print_term ctxt "Should have proved:" prop0);
   868     in NONE end;
   869 
   870 
   871 (* mk_procrule *)
   872 
   873 fun mk_procrule ctxt thm =
   874   let val (prems, lhs, elhs, rhs, _) = decomp_simp thm in
   875     if rewrite_rule_extra_vars prems lhs rhs
   876     then (cond_warning ctxt (fn () => print_thm ctxt "Extra vars on rhs:" ("", thm)); [])
   877     else [mk_rrule2 {thm = thm, name = "", lhs = lhs, elhs = elhs, perm = false}]
   878   end;
   879 
   880 
   881 (* rewritec: conversion to apply the meta simpset to a term *)
   882 
   883 (*Since the rewriting strategy is bottom-up, we avoid re-normalizing already
   884   normalized terms by carrying around the rhs of the rewrite rule just
   885   applied. This is called the `skeleton'. It is decomposed in parallel
   886   with the term. Once a Var is encountered, the corresponding term is
   887   already in normal form.
   888   skel0 is a dummy skeleton that is to enforce complete normalization.*)
   889 
   890 val skel0 = Bound 0;
   891 
   892 (*Use rhs as skeleton only if the lhs does not contain unnormalized bits.
   893   The latter may happen iff there are weak congruence rules for constants
   894   in the lhs.*)
   895 
   896 fun uncond_skel ((_, weak), (lhs, rhs)) =
   897   if null weak then rhs  (*optimization*)
   898   else if exists_subterm
   899     (fn Const (a, _) => member (op =) weak (true, a)
   900       | Free (a, _) => member (op =) weak (false, a)
   901       | _ => false) lhs then skel0
   902   else rhs;
   903 
   904 (*Behaves like unconditional rule if rhs does not contain vars not in the lhs.
   905   Otherwise those vars may become instantiated with unnormalized terms
   906   while the premises are solved.*)
   907 
   908 fun cond_skel (args as (_, (lhs, rhs))) =
   909   if subset (op =) (Term.add_vars rhs [], Term.add_vars lhs []) then uncond_skel args
   910   else skel0;
   911 
   912 (*
   913   Rewriting -- we try in order:
   914     (1) beta reduction
   915     (2) unconditional rewrite rules
   916     (3) conditional rewrite rules
   917     (4) simplification procedures
   918 
   919   IMPORTANT: rewrite rules must not introduce new Vars or TVars!
   920 *)
   921 
   922 fun rewritec (prover, maxt) ctxt t =
   923   let
   924     val thy = Proof_Context.theory_of ctxt;
   925     val Simpset ({rules, ...}, {congs, procs, termless, ...}) = simpset_of ctxt;
   926     val eta_thm = Thm.eta_conversion t;
   927     val eta_t' = Thm.rhs_of eta_thm;
   928     val eta_t = Thm.term_of eta_t';
   929     fun rew rrule =
   930       let
   931         val {thm = thm0, name, lhs, elhs = elhs0, extra, fo, perm} = rrule;
   932         val thm = Thm.transfer thy thm0;
   933         val elhs = Thm.transfer_cterm thy elhs0;
   934         val prop = Thm.prop_of thm;
   935         val (rthm, elhs') =
   936           if maxt = ~1 orelse not extra then (thm, elhs)
   937           else (Thm.incr_indexes (maxt + 1) thm, Thm.incr_indexes_cterm (maxt + 1) elhs);
   938 
   939         val insts =
   940           if fo then Thm.first_order_match (elhs', eta_t')
   941           else Thm.match (elhs', eta_t');
   942         val thm' = Thm.instantiate insts (Thm.rename_boundvars lhs eta_t rthm);
   943         val prop' = Thm.prop_of thm';
   944         val unconditional = (Logic.count_prems prop' = 0);
   945         val (lhs', rhs') = Logic.dest_equals (Logic.strip_imp_concl prop');
   946         val trace_args = {unconditional = unconditional, term = eta_t, thm = thm', rrule = rrule};
   947       in
   948         if perm andalso not (termless (rhs', lhs'))
   949         then
   950          (cond_tracing ctxt (fn () =>
   951             print_thm ctxt "Cannot apply permutative rewrite rule" (name, thm) ^ "\n" ^
   952             print_thm ctxt "Term does not become smaller:" ("", thm'));
   953           NONE)
   954         else
   955          (cond_tracing ctxt (fn () =>
   956             print_thm ctxt "Applying instance of rewrite rule" (name, thm));
   957           if unconditional
   958           then
   959            (cond_tracing ctxt (fn () => print_thm ctxt "Rewriting:" ("", thm'));
   960             trace_apply trace_args ctxt (fn ctxt' =>
   961               let
   962                 val lr = Logic.dest_equals prop;
   963                 val SOME thm'' = check_conv ctxt' false eta_thm thm';
   964               in SOME (thm'', uncond_skel (congs, lr)) end))
   965           else
   966            (cond_tracing ctxt (fn () => print_thm ctxt "Trying to rewrite:" ("", thm'));
   967             if simp_depth ctxt > Config.get ctxt simp_depth_limit
   968             then (cond_tracing ctxt (fn () => "simp_depth_limit exceeded - giving up"); NONE)
   969             else
   970               trace_apply trace_args ctxt (fn ctxt' =>
   971                 (case prover ctxt' thm' of
   972                   NONE => (cond_tracing ctxt' (fn () => print_thm ctxt' "FAILED" ("", thm')); NONE)
   973                 | SOME thm2 =>
   974                     (case check_conv ctxt' true eta_thm thm2 of
   975                       NONE => NONE
   976                     | SOME thm2' =>
   977                         let
   978                           val concl = Logic.strip_imp_concl prop;
   979                           val lr = Logic.dest_equals concl;
   980                         in SOME (thm2', cond_skel (congs, lr)) end)))))
   981       end;
   982 
   983     fun rews [] = NONE
   984       | rews (rrule :: rrules) =
   985           let val opt = rew rrule handle Pattern.MATCH => NONE
   986           in (case opt of NONE => rews rrules | some => some) end;
   987 
   988     fun sort_rrules rrs =
   989       let
   990         fun is_simple ({thm, ...}: rrule) =
   991           (case Thm.prop_of thm of
   992             Const ("Pure.eq", _) $ _ $ _ => true
   993           | _ => false);
   994         fun sort [] (re1, re2) = re1 @ re2
   995           | sort (rr :: rrs) (re1, re2) =
   996               if is_simple rr
   997               then sort rrs (rr :: re1, re2)
   998               else sort rrs (re1, rr :: re2);
   999       in sort rrs ([], []) end;
  1000 
  1001     fun proc_rews [] = NONE
  1002       | proc_rews (Proc {name, proc, lhs, ...} :: ps) =
  1003           if Pattern.matches (Proof_Context.theory_of ctxt) (Thm.term_of lhs, Thm.term_of t) then
  1004             (cond_tracing' ctxt simp_debug (fn () =>
  1005               print_term ctxt ("Trying procedure " ^ quote name ^ " on:") eta_t);
  1006              (case proc ctxt eta_t' of
  1007                NONE => (cond_tracing' ctxt simp_debug (fn () => "FAILED"); proc_rews ps)
  1008              | SOME raw_thm =>
  1009                  (cond_tracing ctxt (fn () =>
  1010                     print_thm ctxt ("Procedure " ^ quote name ^ " produced rewrite rule:")
  1011                       ("", raw_thm));
  1012                   (case rews (mk_procrule ctxt raw_thm) of
  1013                     NONE =>
  1014                      (cond_tracing ctxt (fn () =>
  1015                         print_term ctxt ("IGNORED result of simproc " ^ quote name ^
  1016                             " -- does not match") (Thm.term_of t));
  1017                       proc_rews ps)
  1018                   | some => some))))
  1019           else proc_rews ps;
  1020   in
  1021     (case eta_t of
  1022       Abs _ $ _ => SOME (Thm.transitive eta_thm (Thm.beta_conversion false eta_t'), skel0)
  1023     | _ =>
  1024       (case rews (sort_rrules (Net.match_term rules eta_t)) of
  1025         NONE => proc_rews (Net.match_term procs eta_t)
  1026       | some => some))
  1027   end;
  1028 
  1029 
  1030 (* conversion to apply a congruence rule to a term *)
  1031 
  1032 fun congc prover ctxt maxt cong t =
  1033   let
  1034     val rthm = Thm.incr_indexes (maxt + 1) cong;
  1035     val rlhs = fst (Thm.dest_equals (Drule.strip_imp_concl (Thm.cprop_of rthm)));
  1036     val insts = Thm.match (rlhs, t)
  1037     (* Thm.match can raise Pattern.MATCH;
  1038        is handled when congc is called *)
  1039     val thm' =
  1040       Thm.instantiate insts (Thm.rename_boundvars (Thm.term_of rlhs) (Thm.term_of t) rthm);
  1041     val _ =
  1042       cond_tracing ctxt (fn () => print_thm ctxt "Applying congruence rule:" ("", thm'));
  1043     fun err (msg, thm) = (cond_tracing ctxt (fn () => print_thm ctxt msg ("", thm)); NONE);
  1044   in
  1045     (case prover thm' of
  1046       NONE => err ("Congruence proof failed.  Could not prove", thm')
  1047     | SOME thm2 =>
  1048         (case check_conv ctxt true (Drule.beta_eta_conversion t) thm2 of
  1049           NONE => err ("Congruence proof failed.  Should not have proved", thm2)
  1050         | SOME thm2' =>
  1051             if op aconv (apply2 Thm.term_of (Thm.dest_equals (Thm.cprop_of thm2')))
  1052             then NONE else SOME thm2'))
  1053   end;
  1054 
  1055 val vA = (("A", 0), propT);
  1056 val vB = (("B", 0), propT);
  1057 val vC = (("C", 0), propT);
  1058 
  1059 fun transitive1 NONE NONE = NONE
  1060   | transitive1 (SOME thm1) NONE = SOME thm1
  1061   | transitive1 NONE (SOME thm2) = SOME thm2
  1062   | transitive1 (SOME thm1) (SOME thm2) = SOME (Thm.transitive thm1 thm2);
  1063 
  1064 fun transitive2 thm = transitive1 (SOME thm);
  1065 fun transitive3 thm = transitive1 thm o SOME;
  1066 
  1067 fun bottomc ((simprem, useprem, mutsimp), prover, maxidx) =
  1068   let
  1069     fun botc skel ctxt t =
  1070       if is_Var skel then NONE
  1071       else
  1072         (case subc skel ctxt t of
  1073            some as SOME thm1 =>
  1074              (case rewritec (prover, maxidx) ctxt (Thm.rhs_of thm1) of
  1075                 SOME (thm2, skel2) =>
  1076                   transitive2 (Thm.transitive thm1 thm2)
  1077                     (botc skel2 ctxt (Thm.rhs_of thm2))
  1078               | NONE => some)
  1079          | NONE =>
  1080              (case rewritec (prover, maxidx) ctxt t of
  1081                 SOME (thm2, skel2) => transitive2 thm2
  1082                   (botc skel2 ctxt (Thm.rhs_of thm2))
  1083               | NONE => NONE))
  1084 
  1085     and try_botc ctxt t =
  1086       (case botc skel0 ctxt t of
  1087         SOME trec1 => trec1
  1088       | NONE => Thm.reflexive t)
  1089 
  1090     and subc skel ctxt t0 =
  1091         let val Simpset (_, {congs, ...}) = simpset_of ctxt in
  1092           (case Thm.term_of t0 of
  1093               Abs (a, T, _) =>
  1094                 let
  1095                     val (v, ctxt') = Variable.next_bound (a, T) ctxt;
  1096                     val b = #1 (Term.dest_Free v);
  1097                     val (v', t') = Thm.dest_abs (SOME b) t0;
  1098                     val b' = #1 (Term.dest_Free (Thm.term_of v'));
  1099                     val _ =
  1100                       if b <> b' then
  1101                         warning ("Bad Simplifier context: renamed bound variable " ^
  1102                           quote b ^ " to " ^ quote b' ^ Position.here (Position.thread_data ()))
  1103                       else ();
  1104                     val skel' = (case skel of Abs (_, _, sk) => sk | _ => skel0);
  1105                 in
  1106                   (case botc skel' ctxt' t' of
  1107                     SOME thm => SOME (Thm.abstract_rule a v' thm)
  1108                   | NONE => NONE)
  1109                 end
  1110             | t $ _ =>
  1111               (case t of
  1112                 Const ("Pure.imp", _) $ _  => impc t0 ctxt
  1113               | Abs _ =>
  1114                   let val thm = Thm.beta_conversion false t0
  1115                   in
  1116                     (case subc skel0 ctxt (Thm.rhs_of thm) of
  1117                       NONE => SOME thm
  1118                     | SOME thm' => SOME (Thm.transitive thm thm'))
  1119                   end
  1120               | _  =>
  1121                   let
  1122                     fun appc () =
  1123                       let
  1124                         val (tskel, uskel) =
  1125                           (case skel of
  1126                             tskel $ uskel => (tskel, uskel)
  1127                           | _ => (skel0, skel0));
  1128                         val (ct, cu) = Thm.dest_comb t0;
  1129                       in
  1130                         (case botc tskel ctxt ct of
  1131                           SOME thm1 =>
  1132                             (case botc uskel ctxt cu of
  1133                               SOME thm2 => SOME (Thm.combination thm1 thm2)
  1134                             | NONE => SOME (Thm.combination thm1 (Thm.reflexive cu)))
  1135                         | NONE =>
  1136                             (case botc uskel ctxt cu of
  1137                               SOME thm1 => SOME (Thm.combination (Thm.reflexive ct) thm1)
  1138                             | NONE => NONE))
  1139                       end;
  1140                     val (h, ts) = strip_comb t;
  1141                   in
  1142                     (case cong_name h of
  1143                       SOME a =>
  1144                         (case AList.lookup (op =) (fst congs) a of
  1145                            NONE => appc ()
  1146                         | SOME cong =>
  1147      (*post processing: some partial applications h t1 ... tj, j <= length ts,
  1148        may be a redex. Example: map (%x. x) = (%xs. xs) wrt map_cong*)
  1149                            (let
  1150                               val thm = congc (prover ctxt) ctxt maxidx cong t0;
  1151                               val t = the_default t0 (Option.map Thm.rhs_of thm);
  1152                               val (cl, cr) = Thm.dest_comb t
  1153                               val dVar = Var(("", 0), dummyT)
  1154                               val skel =
  1155                                 list_comb (h, replicate (length ts) dVar)
  1156                             in
  1157                               (case botc skel ctxt cl of
  1158                                 NONE => thm
  1159                               | SOME thm' =>
  1160                                   transitive3 thm (Thm.combination thm' (Thm.reflexive cr)))
  1161                             end handle Pattern.MATCH => appc ()))
  1162                      | _ => appc ())
  1163                   end)
  1164             | _ => NONE)
  1165         end
  1166     and impc ct ctxt =
  1167       if mutsimp then mut_impc0 [] ct [] [] ctxt
  1168       else nonmut_impc ct ctxt
  1169 
  1170     and rules_of_prem prem ctxt =
  1171       if maxidx_of_term (Thm.term_of prem) <> ~1
  1172       then
  1173        (cond_tracing ctxt (fn () =>
  1174           print_term ctxt "Cannot add premise as rewrite rule because it contains (type) unknowns:"
  1175             (Thm.term_of prem));
  1176         (([], NONE), ctxt))
  1177       else
  1178         let val (asm, ctxt') = Thm.assume_hyps prem ctxt
  1179         in ((extract_safe_rrules ctxt' asm, SOME asm), ctxt') end
  1180 
  1181     and add_rrules (rrss, asms) ctxt =
  1182       (fold o fold) insert_rrule rrss ctxt |> add_prems (map_filter I asms)
  1183 
  1184     and disch r prem eq =
  1185       let
  1186         val (lhs, rhs) = Thm.dest_equals (Thm.cprop_of eq);
  1187         val eq' =
  1188           Thm.implies_elim
  1189             (Thm.instantiate ([], [(vA, prem), (vB, lhs), (vC, rhs)]) Drule.imp_cong)
  1190             (Thm.implies_intr prem eq);
  1191       in
  1192         if not r then eq'
  1193         else
  1194           let
  1195             val (prem', concl) = Thm.dest_implies lhs;
  1196             val (prem'', _) = Thm.dest_implies rhs;
  1197           in
  1198             Thm.transitive
  1199               (Thm.transitive
  1200                 (Thm.instantiate ([], [(vA, prem'), (vB, prem), (vC, concl)]) Drule.swap_prems_eq)
  1201                 eq')
  1202               (Thm.instantiate ([], [(vA, prem), (vB, prem''), (vC, concl)]) Drule.swap_prems_eq)
  1203           end
  1204       end
  1205 
  1206     and rebuild [] _ _ _ _ eq = eq
  1207       | rebuild (prem :: prems) concl (_ :: rrss) (_ :: asms) ctxt eq =
  1208           let
  1209             val ctxt' = add_rrules (rev rrss, rev asms) ctxt;
  1210             val concl' =
  1211               Drule.mk_implies (prem, the_default concl (Option.map Thm.rhs_of eq));
  1212             val dprem = Option.map (disch false prem);
  1213           in
  1214             (case rewritec (prover, maxidx) ctxt' concl' of
  1215               NONE => rebuild prems concl' rrss asms ctxt (dprem eq)
  1216             | SOME (eq', _) =>
  1217                 transitive2 (fold (disch false) prems (the (transitive3 (dprem eq) eq')))
  1218                   (mut_impc0 (rev prems) (Thm.rhs_of eq') (rev rrss) (rev asms) ctxt))
  1219           end
  1220 
  1221     and mut_impc0 prems concl rrss asms ctxt =
  1222       let
  1223         val prems' = strip_imp_prems concl;
  1224         val ((rrss', asms'), ctxt') = fold_map rules_of_prem prems' ctxt |>> split_list;
  1225       in
  1226         mut_impc (prems @ prems') (strip_imp_concl concl) (rrss @ rrss')
  1227           (asms @ asms') [] [] [] [] ctxt' ~1 ~1
  1228       end
  1229 
  1230     and mut_impc [] concl [] [] prems' rrss' asms' eqns ctxt changed k =
  1231         transitive1 (fold (fn (eq1, prem) => fn eq2 => transitive1 eq1
  1232             (Option.map (disch false prem) eq2)) (eqns ~~ prems') NONE)
  1233           (if changed > 0 then
  1234              mut_impc (rev prems') concl (rev rrss') (rev asms')
  1235                [] [] [] [] ctxt ~1 changed
  1236            else rebuild prems' concl rrss' asms' ctxt
  1237              (botc skel0 (add_rrules (rev rrss', rev asms') ctxt) concl))
  1238 
  1239       | mut_impc (prem :: prems) concl (rrs :: rrss) (asm :: asms)
  1240           prems' rrss' asms' eqns ctxt changed k =
  1241         (case (if k = 0 then NONE else botc skel0 (add_rrules
  1242           (rev rrss' @ rrss, rev asms' @ asms) ctxt) prem) of
  1243             NONE => mut_impc prems concl rrss asms (prem :: prems')
  1244               (rrs :: rrss') (asm :: asms') (NONE :: eqns) ctxt changed
  1245               (if k = 0 then 0 else k - 1)
  1246         | SOME eqn =>
  1247             let
  1248               val prem' = Thm.rhs_of eqn;
  1249               val tprems = map Thm.term_of prems;
  1250               val i = 1 + fold Integer.max (map (fn p =>
  1251                 find_index (fn q => q aconv p) tprems) (Thm.hyps_of eqn)) ~1;
  1252               val ((rrs', asm'), ctxt') = rules_of_prem prem' ctxt;
  1253             in
  1254               mut_impc prems concl rrss asms (prem' :: prems')
  1255                 (rrs' :: rrss') (asm' :: asms')
  1256                 (SOME (fold_rev (disch true)
  1257                   (take i prems)
  1258                   (Drule.imp_cong_rule eqn (Thm.reflexive (Drule.list_implies
  1259                     (drop i prems, concl))))) :: eqns)
  1260                 ctxt' (length prems') ~1
  1261             end)
  1262 
  1263     (*legacy code -- only for backwards compatibility*)
  1264     and nonmut_impc ct ctxt =
  1265       let
  1266         val (prem, conc) = Thm.dest_implies ct;
  1267         val thm1 = if simprem then botc skel0 ctxt prem else NONE;
  1268         val prem1 = the_default prem (Option.map Thm.rhs_of thm1);
  1269         val ctxt1 =
  1270           if not useprem then ctxt
  1271           else
  1272             let val ((rrs, asm), ctxt') = rules_of_prem prem1 ctxt
  1273             in add_rrules ([rrs], [asm]) ctxt' end;
  1274       in
  1275         (case botc skel0 ctxt1 conc of
  1276           NONE =>
  1277             (case thm1 of
  1278               NONE => NONE
  1279             | SOME thm1' => SOME (Drule.imp_cong_rule thm1' (Thm.reflexive conc)))
  1280         | SOME thm2 =>
  1281             let val thm2' = disch false prem1 thm2 in
  1282               (case thm1 of
  1283                 NONE => SOME thm2'
  1284               | SOME thm1' =>
  1285                  SOME (Thm.transitive (Drule.imp_cong_rule thm1' (Thm.reflexive conc)) thm2'))
  1286             end)
  1287       end;
  1288 
  1289   in try_botc end;
  1290 
  1291 
  1292 (* Meta-rewriting: rewrites t to u and returns the theorem t==u *)
  1293 
  1294 (*
  1295   Parameters:
  1296     mode = (simplify A,
  1297             use A in simplifying B,
  1298             use prems of B (if B is again a meta-impl.) to simplify A)
  1299            when simplifying A ==> B
  1300     prover: how to solve premises in conditional rewrites and congruences
  1301 *)
  1302 
  1303 fun rewrite_cterm mode prover raw_ctxt raw_ct =
  1304   let
  1305     val thy = Proof_Context.theory_of raw_ctxt;
  1306 
  1307     val ct = raw_ct
  1308       |> Thm.transfer_cterm thy
  1309       |> Thm.adjust_maxidx_cterm ~1;
  1310     val maxidx = Thm.maxidx_of_cterm ct;
  1311 
  1312     val ctxt =
  1313       raw_ctxt
  1314       |> Context_Position.set_visible false
  1315       |> inc_simp_depth
  1316       |> (fn ctxt => trace_invoke {depth = simp_depth ctxt, term = Thm.term_of ct} ctxt);
  1317 
  1318     val _ =
  1319       cond_tracing ctxt (fn () =>
  1320         print_term ctxt "SIMPLIFIER INVOKED ON THE FOLLOWING TERM:" (Thm.term_of ct));
  1321   in bottomc (mode, Option.map (Drule.flexflex_unique (SOME ctxt)) oo prover, maxidx) ctxt ct end;
  1322 
  1323 val simple_prover =
  1324   SINGLE o (fn ctxt => ALLGOALS (resolve_tac ctxt (prems_of ctxt)));
  1325 
  1326 fun rewrite _ _ [] = Thm.reflexive
  1327   | rewrite ctxt full thms =
  1328       rewrite_cterm (full, false, false) simple_prover
  1329         (empty_simpset ctxt addsimps thms);
  1330 
  1331 fun rewrite_rule ctxt = Conv.fconv_rule o rewrite ctxt true;
  1332 
  1333 (*simple term rewriting -- no proof*)
  1334 fun rewrite_term thy rules procs =
  1335   Pattern.rewrite_term thy (map decomp_simp' rules) procs;
  1336 
  1337 fun rewrite_thm mode prover ctxt = Conv.fconv_rule (rewrite_cterm mode prover ctxt);
  1338 
  1339 (*Rewrite the subgoals of a proof state (represented by a theorem)*)
  1340 fun rewrite_goals_rule ctxt thms th =
  1341   Conv.fconv_rule (Conv.prems_conv ~1 (rewrite_cterm (true, true, true) simple_prover
  1342     (empty_simpset ctxt addsimps thms))) th;
  1343 
  1344 
  1345 (** meta-rewriting tactics **)
  1346 
  1347 (*Rewrite all subgoals*)
  1348 fun rewrite_goals_tac ctxt defs = PRIMITIVE (rewrite_goals_rule ctxt defs);
  1349 
  1350 (*Rewrite one subgoal*)
  1351 fun generic_rewrite_goal_tac mode prover_tac ctxt i thm =
  1352   if 0 < i andalso i <= Thm.nprems_of thm then
  1353     Seq.single (Conv.gconv_rule (rewrite_cterm mode (SINGLE o prover_tac) ctxt) i thm)
  1354   else Seq.empty;
  1355 
  1356 fun rewrite_goal_tac ctxt rews =
  1357   generic_rewrite_goal_tac (true, false, false) (K no_tac)
  1358     (empty_simpset ctxt addsimps rews);
  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 th =
  1391   (if Drule.is_norm_hhf (Thm.prop_of th) then th
  1392    else
  1393     Conv.fconv_rule
  1394       (rewrite_cterm (true, false, false) (K (K NONE)) (put_simpset ss ctxt)) th)
  1395   |> Thm.adjust_maxidx_thm ~1
  1396   |> Variable.gen_all ctxt;
  1397 
  1398 val hhf_ss =
  1399   simpset_of (empty_simpset (Context.proof_of (Context.the_thread_data ()))
  1400     addsimps Drule.norm_hhf_eqs);
  1401 
  1402 val hhf_protect_ss =
  1403   simpset_of (empty_simpset (Context.proof_of (Context.the_thread_data ()))
  1404     addsimps Drule.norm_hhf_eqs |> add_eqcong Drule.protect_cong);
  1405 
  1406 in
  1407 
  1408 val norm_hhf = gen_norm_hhf hhf_ss;
  1409 val norm_hhf_protect = gen_norm_hhf hhf_protect_ss;
  1410 
  1411 end;
  1412 
  1413 end;
  1414 
  1415 structure Basic_Meta_Simplifier: BASIC_RAW_SIMPLIFIER = Raw_Simplifier;
  1416 open Basic_Meta_Simplifier;