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