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