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