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