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