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