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