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