src/Pure/raw_simplifier.ML
author wenzelm
Thu Dec 12 14:35:31 2013 +0100 (2013-12-12)
changeset 54724 b92694e756b8
parent 52232 a2d4ae3e04a2
child 54725 fc384e0a7f51
permissions -rw-r--r--
removed dead code -- ctxt is never visible (see also 658fcba35ed7);
     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 (trace_named_thm ctxt (fn () => "Cannot apply permutative rewrite rule") (thm, name);
   953               trace_thm ctxt (fn () => "Term does not become smaller:") thm'; NONE)
   954         else (trace_named_thm ctxt (fn () => "Applying instance of rewrite rule") (thm, name);
   955            if unconditional
   956            then
   957              (trace_thm ctxt (fn () => "Rewriting:") thm';
   958               let
   959                 val lr = Logic.dest_equals prop;
   960                 val SOME thm'' = check_conv ctxt false eta_thm thm';
   961               in SOME (thm'', uncond_skel (congs, lr)) end)
   962            else
   963              (trace_thm ctxt (fn () => "Trying to rewrite:") thm';
   964               if simp_depth ctxt > Config.get ctxt simp_depth_limit
   965               then
   966                 let
   967                   val s = "simp_depth_limit exceeded - giving up";
   968                   val _ = trace ctxt false (fn () => s);
   969                   val _ = Context_Position.if_visible ctxt warning s;
   970                 in NONE end
   971               else
   972               case prover ctxt thm' of
   973                 NONE => (trace_thm ctxt (fn () => "FAILED") thm'; NONE)
   974               | SOME thm2 =>
   975                   (case check_conv ctxt true eta_thm thm2 of
   976                     NONE => NONE
   977                   | SOME thm2' =>
   978                       let
   979                         val concl = Logic.strip_imp_concl prop;
   980                         val lr = Logic.dest_equals concl;
   981                       in SOME (thm2', cond_skel (congs, lr)) end)))
   982       end;
   983 
   984     fun rews [] = NONE
   985       | rews (rrule :: rrules) =
   986           let val opt = rew rrule handle Pattern.MATCH => NONE
   987           in case opt of NONE => rews rrules | some => some end;
   988 
   989     fun sort_rrules rrs =
   990       let
   991         fun is_simple ({thm, ...}: rrule) =
   992           (case Thm.prop_of thm of
   993             Const ("==", _) $ _ $ _ => true
   994           | _ => false);
   995         fun sort [] (re1, re2) = re1 @ re2
   996           | sort (rr :: rrs) (re1, re2) =
   997               if is_simple rr
   998               then sort rrs (rr :: re1, re2)
   999               else sort rrs (re1, rr :: re2);
  1000       in sort rrs ([], []) end;
  1001 
  1002     fun proc_rews [] = NONE
  1003       | proc_rews (Proc {name, proc, lhs, ...} :: ps) =
  1004           if Pattern.matches (Proof_Context.theory_of ctxt) (Thm.term_of lhs, Thm.term_of t) then
  1005             (debug_term ctxt false (fn () => "Trying procedure " ^ quote name ^ " on:") eta_t;
  1006              case proc ctxt eta_t' of
  1007                NONE => (debug ctxt false (fn () => "FAILED"); proc_rews ps)
  1008              | SOME raw_thm =>
  1009                  (trace_thm ctxt (fn () => "Procedure " ^ quote name ^ " produced rewrite rule:")
  1010                    raw_thm;
  1011                   (case rews (mk_procrule ctxt raw_thm) of
  1012                     NONE => (trace_cterm ctxt true (fn () => "IGNORED result of simproc " ^ quote name ^
  1013                       " -- does not match") t; proc_rews ps)
  1014                   | some => some)))
  1015           else proc_rews ps;
  1016   in
  1017     (case eta_t of
  1018       Abs _ $ _ => SOME (Thm.transitive eta_thm (Thm.beta_conversion false eta_t'), skel0)
  1019     | _ =>
  1020       (case rews (sort_rrules (Net.match_term rules eta_t)) of
  1021         NONE => proc_rews (Net.match_term procs eta_t)
  1022       | some => some))
  1023   end;
  1024 
  1025 
  1026 (* conversion to apply a congruence rule to a term *)
  1027 
  1028 fun congc prover ctxt maxt cong t =
  1029   let
  1030     val rthm = Thm.incr_indexes (maxt + 1) cong;
  1031     val rlhs = fst (Thm.dest_equals (Drule.strip_imp_concl (cprop_of rthm)));
  1032     val insts = Thm.match (rlhs, t)
  1033     (* Thm.match can raise Pattern.MATCH;
  1034        is handled when congc is called *)
  1035     val thm' = Thm.instantiate insts (Thm.rename_boundvars (term_of rlhs) (term_of t) rthm);
  1036     val _ = trace_thm ctxt (fn () => "Applying congruence rule:") thm';
  1037     fun err (msg, thm) = (trace_thm ctxt (fn () => msg) thm; NONE);
  1038   in
  1039     (case prover thm' of
  1040       NONE => err ("Congruence proof failed.  Could not prove", thm')
  1041     | SOME thm2 =>
  1042         (case check_conv ctxt true (Drule.beta_eta_conversion t) thm2 of
  1043           NONE => err ("Congruence proof failed.  Should not have proved", thm2)
  1044         | SOME thm2' =>
  1045             if op aconv (pairself term_of (Thm.dest_equals (cprop_of thm2')))
  1046             then NONE else SOME thm2'))
  1047   end;
  1048 
  1049 val (cA, (cB, cC)) =
  1050   apsnd Thm.dest_equals (Thm.dest_implies (hd (cprems_of Drule.imp_cong)));
  1051 
  1052 fun transitive1 NONE NONE = NONE
  1053   | transitive1 (SOME thm1) NONE = SOME thm1
  1054   | transitive1 NONE (SOME thm2) = SOME thm2
  1055   | transitive1 (SOME thm1) (SOME thm2) = SOME (Thm.transitive thm1 thm2)
  1056 
  1057 fun transitive2 thm = transitive1 (SOME thm);
  1058 fun transitive3 thm = transitive1 thm o SOME;
  1059 
  1060 fun bottomc ((simprem, useprem, mutsimp), prover, maxidx) =
  1061   let
  1062     fun botc skel ctxt t =
  1063           if is_Var skel then NONE
  1064           else
  1065           (case subc skel ctxt t of
  1066              some as SOME thm1 =>
  1067                (case rewritec (prover, maxidx) ctxt (Thm.rhs_of thm1) of
  1068                   SOME (thm2, skel2) =>
  1069                     transitive2 (Thm.transitive thm1 thm2)
  1070                       (botc skel2 ctxt (Thm.rhs_of thm2))
  1071                 | NONE => some)
  1072            | NONE =>
  1073                (case rewritec (prover, maxidx) ctxt t of
  1074                   SOME (thm2, skel2) => transitive2 thm2
  1075                     (botc skel2 ctxt (Thm.rhs_of thm2))
  1076                 | NONE => NONE))
  1077 
  1078     and try_botc ctxt t =
  1079           (case botc skel0 ctxt t of
  1080             SOME trec1 => trec1
  1081           | NONE => (Thm.reflexive t))
  1082 
  1083     and subc skel ctxt t0 =
  1084         let val Simpset ({bounds, ...}, {congs, ...}) = simpset_of ctxt in
  1085           (case term_of t0 of
  1086               Abs (a, T, _) =>
  1087                 let
  1088                     val b = Name.bound (#1 bounds);
  1089                     val (v, t') = Thm.dest_abs (SOME b) t0;
  1090                     val b' = #1 (Term.dest_Free (Thm.term_of v));
  1091                     val _ =
  1092                       if b <> b' then
  1093                         warning ("Simplifier: renamed bound variable " ^
  1094                           quote b ^ " to " ^ quote b' ^ Position.here (Position.thread_data ()))
  1095                       else ();
  1096                     val ctxt' = add_bound ((b', T), a) ctxt;
  1097                     val skel' = case skel of Abs (_, _, sk) => sk | _ => skel0;
  1098                 in
  1099                   (case botc skel' ctxt' t' of
  1100                     SOME thm => SOME (Thm.abstract_rule a v thm)
  1101                   | NONE => NONE)
  1102                 end
  1103             | t $ _ => (case t of
  1104                 Const ("==>", _) $ _  => impc t0 ctxt
  1105               | Abs _ =>
  1106                   let val thm = Thm.beta_conversion false t0
  1107                   in case subc skel0 ctxt (Thm.rhs_of thm) of
  1108                        NONE => SOME thm
  1109                      | SOME thm' => SOME (Thm.transitive thm thm')
  1110                   end
  1111               | _  =>
  1112                   let fun appc () =
  1113                         let
  1114                           val (tskel, uskel) = case skel of
  1115                               tskel $ uskel => (tskel, uskel)
  1116                             | _ => (skel0, skel0);
  1117                           val (ct, cu) = Thm.dest_comb t0
  1118                         in
  1119                         (case botc tskel ctxt ct of
  1120                            SOME thm1 =>
  1121                              (case botc uskel ctxt cu of
  1122                                 SOME thm2 => SOME (Thm.combination thm1 thm2)
  1123                               | NONE => SOME (Thm.combination thm1 (Thm.reflexive cu)))
  1124                          | NONE =>
  1125                              (case botc uskel ctxt cu of
  1126                                 SOME thm1 => SOME (Thm.combination (Thm.reflexive ct) thm1)
  1127                               | NONE => NONE))
  1128                         end
  1129                       val (h, ts) = strip_comb t
  1130                   in case cong_name h of
  1131                        SOME a =>
  1132                          (case AList.lookup (op =) (fst congs) a of
  1133                             NONE => appc ()
  1134                           | SOME cong =>
  1135      (*post processing: some partial applications h t1 ... tj, j <= length ts,
  1136        may be a redex. Example: map (%x. x) = (%xs. xs) wrt map_cong*)
  1137                              (let
  1138                                 val thm = congc (prover ctxt) ctxt maxidx cong t0;
  1139                                 val t = the_default t0 (Option.map Thm.rhs_of thm);
  1140                                 val (cl, cr) = Thm.dest_comb t
  1141                                 val dVar = Var(("", 0), dummyT)
  1142                                 val skel =
  1143                                   list_comb (h, replicate (length ts) dVar)
  1144                               in case botc skel ctxt cl of
  1145                                    NONE => thm
  1146                                  | SOME thm' => transitive3 thm
  1147                                      (Thm.combination thm' (Thm.reflexive cr))
  1148                               end handle Pattern.MATCH => appc ()))
  1149                      | _ => appc ()
  1150                   end)
  1151             | _ => NONE)
  1152         end
  1153     and impc ct ctxt =
  1154       if mutsimp then mut_impc0 [] ct [] [] ctxt else nonmut_impc ct ctxt
  1155 
  1156     and rules_of_prem ctxt prem =
  1157       if maxidx_of_term (term_of prem) <> ~1
  1158       then (trace_cterm ctxt true
  1159         (fn () => "Cannot add premise as rewrite rule because it contains (type) unknowns:")
  1160         prem; ([], NONE))
  1161       else
  1162         let val asm = Thm.assume prem
  1163         in (extract_safe_rrules (ctxt, asm), SOME asm) end
  1164 
  1165     and add_rrules (rrss, asms) ctxt =
  1166       (fold o fold) insert_rrule rrss ctxt |> add_prems (map_filter I asms)
  1167 
  1168     and disch r prem eq =
  1169       let
  1170         val (lhs, rhs) = Thm.dest_equals (Thm.cprop_of eq);
  1171         val eq' = Thm.implies_elim (Thm.instantiate
  1172           ([], [(cA, prem), (cB, lhs), (cC, rhs)]) Drule.imp_cong)
  1173           (Thm.implies_intr prem eq)
  1174       in if not r then eq' else
  1175         let
  1176           val (prem', concl) = Thm.dest_implies lhs;
  1177           val (prem'', _) = Thm.dest_implies rhs
  1178         in Thm.transitive (Thm.transitive
  1179           (Thm.instantiate ([], [(cA, prem'), (cB, prem), (cC, concl)])
  1180              Drule.swap_prems_eq) eq')
  1181           (Thm.instantiate ([], [(cA, prem), (cB, prem''), (cC, concl)])
  1182              Drule.swap_prems_eq)
  1183         end
  1184       end
  1185 
  1186     and rebuild [] _ _ _ _ eq = eq
  1187       | rebuild (prem :: prems) concl (_ :: rrss) (_ :: asms) ctxt eq =
  1188           let
  1189             val ctxt' = add_rrules (rev rrss, rev asms) ctxt;
  1190             val concl' =
  1191               Drule.mk_implies (prem, the_default concl (Option.map Thm.rhs_of eq));
  1192             val dprem = Option.map (disch false prem)
  1193           in
  1194             (case rewritec (prover, maxidx) ctxt' concl' of
  1195               NONE => rebuild prems concl' rrss asms ctxt (dprem eq)
  1196             | SOME (eq', _) => transitive2 (fold (disch false)
  1197                   prems (the (transitive3 (dprem eq) eq')))
  1198                 (mut_impc0 (rev prems) (Thm.rhs_of eq') (rev rrss) (rev asms) ctxt))
  1199           end
  1200 
  1201     and mut_impc0 prems concl rrss asms ctxt =
  1202       let
  1203         val prems' = strip_imp_prems concl;
  1204         val (rrss', asms') = split_list (map (rules_of_prem ctxt) prems')
  1205       in
  1206         mut_impc (prems @ prems') (strip_imp_concl concl) (rrss @ rrss')
  1207           (asms @ asms') [] [] [] [] ctxt ~1 ~1
  1208       end
  1209 
  1210     and mut_impc [] concl [] [] prems' rrss' asms' eqns ctxt changed k =
  1211         transitive1 (fold (fn (eq1, prem) => fn eq2 => transitive1 eq1
  1212             (Option.map (disch false prem) eq2)) (eqns ~~ prems') NONE)
  1213           (if changed > 0 then
  1214              mut_impc (rev prems') concl (rev rrss') (rev asms')
  1215                [] [] [] [] ctxt ~1 changed
  1216            else rebuild prems' concl rrss' asms' ctxt
  1217              (botc skel0 (add_rrules (rev rrss', rev asms') ctxt) concl))
  1218 
  1219       | mut_impc (prem :: prems) concl (rrs :: rrss) (asm :: asms)
  1220           prems' rrss' asms' eqns ctxt changed k =
  1221         case (if k = 0 then NONE else botc skel0 (add_rrules
  1222           (rev rrss' @ rrss, rev asms' @ asms) ctxt) prem) of
  1223             NONE => mut_impc prems concl rrss asms (prem :: prems')
  1224               (rrs :: rrss') (asm :: asms') (NONE :: eqns) ctxt changed
  1225               (if k = 0 then 0 else k - 1)
  1226           | SOME eqn =>
  1227             let
  1228               val prem' = Thm.rhs_of eqn;
  1229               val tprems = map term_of prems;
  1230               val i = 1 + fold Integer.max (map (fn p =>
  1231                 find_index (fn q => q aconv p) tprems) (Thm.hyps_of eqn)) ~1;
  1232               val (rrs', asm') = rules_of_prem ctxt prem';
  1233             in mut_impc prems concl rrss asms (prem' :: prems')
  1234               (rrs' :: rrss') (asm' :: asms') (SOME (fold_rev (disch true)
  1235                 (take i prems)
  1236                 (Drule.imp_cong_rule eqn (Thm.reflexive (Drule.list_implies
  1237                   (drop i prems, concl))))) :: eqns)
  1238                   ctxt (length prems') ~1
  1239             end
  1240 
  1241      (*legacy code - only for backwards compatibility*)
  1242     and nonmut_impc ct ctxt =
  1243       let
  1244         val (prem, conc) = Thm.dest_implies ct;
  1245         val thm1 = if simprem then botc skel0 ctxt prem else NONE;
  1246         val prem1 = the_default prem (Option.map Thm.rhs_of thm1);
  1247         val ctxt1 =
  1248           if not useprem then ctxt
  1249           else add_rrules (apsnd single (apfst single (rules_of_prem ctxt prem1))) ctxt
  1250       in
  1251         (case botc skel0 ctxt1 conc of
  1252           NONE =>
  1253             (case thm1 of
  1254               NONE => NONE
  1255             | SOME thm1' => SOME (Drule.imp_cong_rule thm1' (Thm.reflexive conc)))
  1256         | SOME thm2 =>
  1257             let val thm2' = disch false prem1 thm2 in
  1258               (case thm1 of
  1259                 NONE => SOME thm2'
  1260               | SOME thm1' =>
  1261                  SOME (Thm.transitive (Drule.imp_cong_rule thm1' (Thm.reflexive conc)) thm2'))
  1262             end)
  1263       end
  1264 
  1265  in try_botc end;
  1266 
  1267 
  1268 (* Meta-rewriting: rewrites t to u and returns the theorem t==u *)
  1269 
  1270 (*
  1271   Parameters:
  1272     mode = (simplify A,
  1273             use A in simplifying B,
  1274             use prems of B (if B is again a meta-impl.) to simplify A)
  1275            when simplifying A ==> B
  1276     prover: how to solve premises in conditional rewrites and congruences
  1277 *)
  1278 
  1279 val debug_bounds = Unsynchronized.ref false;
  1280 
  1281 fun check_bounds ctxt ct =
  1282   if ! debug_bounds then
  1283     let
  1284       val Simpset ({bounds = (_, bounds), ...}, _) = simpset_of ctxt;
  1285       val bs =
  1286         fold_aterms
  1287           (fn Free (x, _) =>
  1288             if Name.is_bound x andalso not (AList.defined eq_bound bounds x)
  1289             then insert (op =) x else I
  1290           | _ => I) (term_of ct) [];
  1291     in
  1292       if null bs then ()
  1293       else
  1294         print_term ctxt true
  1295           (fn () => "Simplifier: term contains loose bounds: " ^ commas_quote bs)
  1296           (Thm.term_of ct)
  1297     end
  1298   else ();
  1299 
  1300 fun rewrite_cterm mode prover raw_ctxt raw_ct =
  1301   let
  1302     val ctxt =
  1303       raw_ctxt
  1304       |> Context_Position.set_visible false
  1305       |> inc_simp_depth;
  1306     val thy = Proof_Context.theory_of ctxt;
  1307 
  1308     val ct = Thm.adjust_maxidx_cterm ~1 raw_ct;
  1309     val {maxidx, ...} = Thm.rep_cterm ct;
  1310     val _ =
  1311       Theory.subthy (theory_of_cterm ct, thy) orelse
  1312         raise CTERM ("rewrite_cterm: bad background theory", [ct]);
  1313 
  1314     val _ = trace_cterm ctxt false (fn () => "SIMPLIFIER INVOKED ON THE FOLLOWING TERM:") ct;
  1315     val _ = check_bounds ctxt ct;
  1316   in bottomc (mode, Option.map Drule.flexflex_unique oo prover, maxidx) ctxt ct end;
  1317 
  1318 val simple_prover =
  1319   SINGLE o (fn ctxt => ALLGOALS (resolve_tac (prems_of ctxt)));
  1320 
  1321 fun rewrite _ [] ct = Thm.reflexive ct
  1322   | rewrite full thms ct =
  1323       rewrite_cterm (full, false, false) simple_prover
  1324         (global_context (Thm.theory_of_cterm ct) empty_ss addsimps thms) ct;
  1325 
  1326 val rewrite_rule = Conv.fconv_rule o rewrite true;
  1327 
  1328 (*simple term rewriting -- no proof*)
  1329 fun rewrite_term thy rules procs =
  1330   Pattern.rewrite_term thy (map decomp_simp' rules) procs;
  1331 
  1332 fun rewrite_thm mode prover ctxt = Conv.fconv_rule (rewrite_cterm mode prover ctxt);
  1333 
  1334 (*Rewrite the subgoals of a proof state (represented by a theorem)*)
  1335 fun rewrite_goals_rule thms th =
  1336   Conv.fconv_rule (Conv.prems_conv ~1 (rewrite_cterm (true, true, true) simple_prover
  1337     (global_context (Thm.theory_of_thm th) empty_ss addsimps thms))) th;
  1338 
  1339 
  1340 (** meta-rewriting tactics **)
  1341 
  1342 (*Rewrite all subgoals*)
  1343 fun rewrite_goals_tac defs = PRIMITIVE (rewrite_goals_rule defs);
  1344 
  1345 (*Rewrite one subgoal*)
  1346 fun generic_rewrite_goal_tac mode prover_tac ctxt i thm =
  1347   if 0 < i andalso i <= Thm.nprems_of thm then
  1348     Seq.single (Conv.gconv_rule (rewrite_cterm mode (SINGLE o prover_tac) ctxt) i thm)
  1349   else Seq.empty;
  1350 
  1351 fun rewrite_goal_tac rews i st =
  1352   generic_rewrite_goal_tac (true, false, false) (K no_tac)
  1353     (global_context (Thm.theory_of_thm st) empty_ss addsimps rews) i st;
  1354 
  1355 (*Prunes all redundant parameters from the proof state by rewriting.*)
  1356 val prune_params_tac = rewrite_goals_tac [Drule.triv_forall_equality];
  1357 
  1358 
  1359 (* for folding definitions, handling critical pairs *)
  1360 
  1361 (*The depth of nesting in a term*)
  1362 fun term_depth (Abs (_, _, t)) = 1 + term_depth t
  1363   | term_depth (f $ t) = 1 + Int.max (term_depth f, term_depth t)
  1364   | term_depth _ = 0;
  1365 
  1366 val lhs_of_thm = #1 o Logic.dest_equals o prop_of;
  1367 
  1368 (*folding should handle critical pairs!  E.g. K == Inl(0),  S == Inr(Inl(0))
  1369   Returns longest lhs first to avoid folding its subexpressions.*)
  1370 fun sort_lhs_depths defs =
  1371   let val keylist = AList.make (term_depth o lhs_of_thm) defs
  1372       val keys = sort_distinct (rev_order o int_ord) (map #2 keylist)
  1373   in map (AList.find (op =) keylist) keys end;
  1374 
  1375 val rev_defs = sort_lhs_depths o map Thm.symmetric;
  1376 
  1377 fun fold_rule defs = fold rewrite_rule (rev_defs defs);
  1378 fun fold_goals_tac defs = EVERY (map rewrite_goals_tac (rev_defs defs));
  1379 
  1380 
  1381 (* HHF normal form: !! before ==>, outermost !! generalized *)
  1382 
  1383 local
  1384 
  1385 fun gen_norm_hhf ss th =
  1386   (if Drule.is_norm_hhf (Thm.prop_of th) then th
  1387    else
  1388     Conv.fconv_rule
  1389       (rewrite_cterm (true, false, false) (K (K NONE))
  1390         (global_context (Thm.theory_of_thm th) ss)) th)
  1391   |> Thm.adjust_maxidx_thm ~1
  1392   |> Drule.gen_all;
  1393 
  1394 val hhf_ss =
  1395   simpset_of (empty_simpset (Context.proof_of (Context.the_thread_data ()))
  1396     addsimps Drule.norm_hhf_eqs);
  1397 
  1398 val hhf_protect_ss =
  1399   simpset_of (empty_simpset (Context.proof_of (Context.the_thread_data ()))
  1400     addsimps Drule.norm_hhf_eqs |> add_eqcong Drule.protect_cong);
  1401 
  1402 in
  1403 
  1404 val norm_hhf = gen_norm_hhf hhf_ss;
  1405 val norm_hhf_protect = gen_norm_hhf hhf_protect_ss;
  1406 
  1407 end;
  1408 
  1409 end;
  1410 
  1411 structure Basic_Meta_Simplifier: BASIC_RAW_SIMPLIFIER = Raw_Simplifier;
  1412 open Basic_Meta_Simplifier;