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