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