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