src/Pure/raw_simplifier.ML
author wenzelm
Mon May 20 20:49:10 2013 +0200 (2013-05-20)
changeset 52091 9ec2d47de6a7
parent 52082 559e1398b70e
child 52232 a2d4ae3e04a2
permissions -rw-r--r--
more rigorous check of simplifier context;
tuned;
     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 
   514 (* maintain simp rules *)
   515 
   516 fun del_rrule (rrule as {thm, elhs, ...}) ctxt =
   517   ctxt |> map_simpset1 (fn (rules, prems, bounds, depth) =>
   518     (Net.delete_term eq_rrule (term_of elhs, rrule) rules, prems, bounds, depth))
   519   handle Net.DELETE => (cond_warn_thm ctxt (fn () => "Rewrite rule not in simpset:") thm; ctxt);
   520 
   521 fun insert_rrule (rrule as {thm, name, ...}) ctxt =
   522  (trace_named_thm ctxt (fn () => "Adding rewrite rule") (thm, name);
   523   ctxt |> map_simpset1 (fn (rules, prems, bounds, depth) =>
   524     let
   525       val rrule2 as {elhs, ...} = mk_rrule2 rrule;
   526       val rules' = Net.insert_term eq_rrule (term_of elhs, rrule2) rules;
   527     in (rules', prems, bounds, depth) end)
   528   handle Net.INSERT => (cond_warn_thm ctxt (fn () => "Ignoring duplicate rewrite rule:") thm; ctxt));
   529 
   530 local
   531 
   532 fun vperm (Var _, Var _) = true
   533   | vperm (Abs (_, _, s), Abs (_, _, t)) = vperm (s, t)
   534   | vperm (t1 $ t2, u1 $ u2) = vperm (t1, u1) andalso vperm (t2, u2)
   535   | vperm (t, u) = (t = u);
   536 
   537 fun var_perm (t, u) =
   538   vperm (t, u) andalso eq_set (op =) (Term.add_vars t [], Term.add_vars u []);
   539 
   540 in
   541 
   542 fun decomp_simp thm =
   543   let
   544     val prop = Thm.prop_of thm;
   545     val prems = Logic.strip_imp_prems prop;
   546     val concl = Drule.strip_imp_concl (Thm.cprop_of thm);
   547     val (lhs, rhs) = Thm.dest_equals concl handle TERM _ =>
   548       raise SIMPLIFIER ("Rewrite rule not a meta-equality", thm);
   549     val elhs = Thm.dest_arg (Thm.cprop_of (Thm.eta_conversion lhs));
   550     val erhs = Envir.eta_contract (term_of rhs);
   551     val perm =
   552       var_perm (term_of elhs, erhs) andalso
   553       not (term_of elhs aconv erhs) andalso
   554       not (is_Var (term_of elhs));
   555   in (prems, term_of lhs, elhs, term_of rhs, perm) end;
   556 
   557 end;
   558 
   559 fun decomp_simp' thm =
   560   let val (_, lhs, _, rhs, _) = decomp_simp thm in
   561     if Thm.nprems_of thm > 0 then raise SIMPLIFIER ("Bad conditional rewrite rule", thm)
   562     else (lhs, rhs)
   563   end;
   564 
   565 fun mk_eq_True ctxt (thm, name) =
   566   let val Simpset (_, {mk_rews = {mk_eq_True, ...}, ...}) = simpset_of ctxt in
   567     (case mk_eq_True ctxt thm of
   568       NONE => []
   569     | SOME eq_True =>
   570         let val (_, lhs, elhs, _, _) = decomp_simp eq_True;
   571         in [{thm = eq_True, name = name, lhs = lhs, elhs = elhs, perm = false}] end)
   572   end;
   573 
   574 (*create the rewrite rule and possibly also the eq_True variant,
   575   in case there are extra vars on the rhs*)
   576 fun rrule_eq_True ctxt thm name lhs elhs rhs thm2 =
   577   let val rrule = {thm = thm, name = name, lhs = lhs, elhs = elhs, perm = false} in
   578     if rewrite_rule_extra_vars [] lhs rhs then
   579       mk_eq_True ctxt (thm2, name) @ [rrule]
   580     else [rrule]
   581   end;
   582 
   583 fun mk_rrule ctxt (thm, name) =
   584   let val (prems, lhs, elhs, rhs, perm) = decomp_simp thm in
   585     if perm then [{thm = thm, name = name, lhs = lhs, elhs = elhs, perm = true}]
   586     else
   587       (*weak test for loops*)
   588       if rewrite_rule_extra_vars prems lhs rhs orelse is_Var (term_of elhs)
   589       then mk_eq_True ctxt (thm, name)
   590       else rrule_eq_True ctxt thm name lhs elhs rhs thm
   591   end;
   592 
   593 fun orient_rrule ctxt (thm, name) =
   594   let
   595     val (prems, lhs, elhs, rhs, perm) = decomp_simp thm;
   596     val Simpset (_, {mk_rews = {reorient, mk_sym, ...}, ...}) = simpset_of ctxt;
   597   in
   598     if perm then [{thm = thm, name = name, lhs = lhs, elhs = elhs, perm = true}]
   599     else if reorient ctxt prems lhs rhs then
   600       if reorient ctxt prems rhs lhs
   601       then mk_eq_True ctxt (thm, name)
   602       else
   603         (case mk_sym ctxt thm of
   604           NONE => []
   605         | SOME thm' =>
   606             let val (_, lhs', elhs', rhs', _) = decomp_simp thm'
   607             in rrule_eq_True ctxt thm' name lhs' elhs' rhs' thm end)
   608     else rrule_eq_True ctxt thm name lhs elhs rhs thm
   609   end;
   610 
   611 fun extract_rews (ctxt, thms) =
   612   let val Simpset (_, {mk_rews = {mk, ...}, ...}) = simpset_of ctxt
   613   in maps (fn thm => map (rpair (Thm.get_name_hint thm)) (mk ctxt thm)) thms end;
   614 
   615 fun extract_safe_rrules (ctxt, thm) =
   616   maps (orient_rrule ctxt) (extract_rews (ctxt, [thm]));
   617 
   618 
   619 (* add/del rules explicitly *)
   620 
   621 fun comb_simps comb mk_rrule (ctxt, thms) =
   622   let
   623     val rews = extract_rews (ctxt, thms);
   624   in fold (fold comb o mk_rrule) rews ctxt end;
   625 
   626 fun ctxt addsimps thms =
   627   comb_simps insert_rrule (mk_rrule ctxt) (ctxt, thms);
   628 
   629 fun ctxt delsimps thms =
   630   comb_simps del_rrule (map mk_rrule2 o mk_rrule ctxt) (ctxt, thms);
   631 
   632 fun add_simp thm ctxt = ctxt addsimps [thm];
   633 fun del_simp thm ctxt = ctxt delsimps [thm];
   634 
   635 
   636 (* congs *)
   637 
   638 local
   639 
   640 fun is_full_cong_prems [] [] = true
   641   | is_full_cong_prems [] _ = false
   642   | is_full_cong_prems (p :: prems) varpairs =
   643       (case Logic.strip_assums_concl p of
   644         Const ("==", _) $ lhs $ rhs =>
   645           let val (x, xs) = strip_comb lhs and (y, ys) = strip_comb rhs in
   646             is_Var x andalso forall is_Bound xs andalso
   647             not (has_duplicates (op =) xs) andalso xs = ys andalso
   648             member (op =) varpairs (x, y) andalso
   649             is_full_cong_prems prems (remove (op =) (x, y) varpairs)
   650           end
   651       | _ => false);
   652 
   653 fun is_full_cong thm =
   654   let
   655     val prems = Thm.prems_of thm and concl = Thm.concl_of thm;
   656     val (lhs, rhs) = Logic.dest_equals concl;
   657     val (f, xs) = strip_comb lhs and (g, ys) = strip_comb rhs;
   658   in
   659     f = g andalso not (has_duplicates (op =) (xs @ ys)) andalso length xs = length ys andalso
   660     is_full_cong_prems prems (xs ~~ ys)
   661   end;
   662 
   663 fun mk_cong ctxt =
   664   let val Simpset (_, {mk_rews = {mk_cong = f, ...}, ...}) = simpset_of ctxt
   665   in f ctxt end;
   666 
   667 in
   668 
   669 fun add_eqcong thm ctxt = ctxt |>
   670   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   671     let
   672       val (lhs, _) = Logic.dest_equals (Thm.concl_of thm)
   673         handle TERM _ => raise SIMPLIFIER ("Congruence not a meta-equality", thm);
   674     (*val lhs = Envir.eta_contract lhs;*)
   675       val a = the (cong_name (head_of lhs)) handle Option.Option =>
   676         raise SIMPLIFIER ("Congruence must start with a constant or free variable", thm);
   677       val (xs, weak) = congs;
   678       val _ =
   679         if AList.defined (op =) xs a then
   680           Context_Position.if_visible ctxt
   681             warning ("Overwriting congruence rule for " ^ quote (#2 a))
   682         else ();
   683       val xs' = AList.update (op =) (a, thm) xs;
   684       val weak' = if is_full_cong thm then weak else a :: weak;
   685     in ((xs', weak'), procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) end);
   686 
   687 fun del_eqcong thm ctxt = ctxt |>
   688   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   689     let
   690       val (lhs, _) = Logic.dest_equals (Thm.concl_of thm)
   691         handle TERM _ => raise SIMPLIFIER ("Congruence not a meta-equality", thm);
   692     (*val lhs = Envir.eta_contract lhs;*)
   693       val a = the (cong_name (head_of lhs)) handle Option.Option =>
   694         raise SIMPLIFIER ("Congruence must start with a constant", thm);
   695       val (xs, _) = congs;
   696       val xs' = filter_out (fn (x : cong_name, _) => x = a) xs;
   697       val weak' = xs' |> map_filter (fn (a, thm) =>
   698         if is_full_cong thm then NONE else SOME a);
   699     in ((xs', weak'), procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) end);
   700 
   701 fun add_cong thm ctxt = add_eqcong (mk_cong ctxt thm) ctxt;
   702 fun del_cong thm ctxt = del_eqcong (mk_cong ctxt thm) ctxt;
   703 
   704 end;
   705 
   706 
   707 (* simprocs *)
   708 
   709 datatype simproc =
   710   Simproc of
   711     {name: string,
   712      lhss: cterm list,
   713      proc: morphism -> Proof.context -> cterm -> thm option,
   714      id: stamp * thm list};
   715 
   716 fun eq_simproc (Simproc {id = id1, ...}, Simproc {id = id2, ...}) = eq_procid (id1, id2);
   717 
   718 fun transform_simproc phi (Simproc {name, lhss, proc, id = (s, ths)}) =
   719   Simproc
   720    {name = name,
   721     lhss = map (Morphism.cterm phi) lhss,
   722     proc = Morphism.transform phi proc,
   723     id = (s, Morphism.fact phi ths)};
   724 
   725 fun make_simproc {name, lhss, proc, identifier} =
   726   Simproc {name = name, lhss = lhss, proc = proc, id = (stamp (), identifier)};
   727 
   728 fun mk_simproc name lhss proc =
   729   make_simproc {name = name, lhss = lhss, proc = fn _ => fn ctxt => fn ct =>
   730     proc ctxt (Thm.term_of ct), identifier = []};
   731 
   732 (* FIXME avoid global thy and Logic.varify_global *)
   733 fun simproc_global_i thy name = mk_simproc name o map (Thm.cterm_of thy o Logic.varify_global);
   734 fun simproc_global thy name = simproc_global_i thy name o map (Syntax.read_term_global thy);
   735 
   736 
   737 local
   738 
   739 fun add_proc (proc as Proc {name, lhs, ...}) ctxt =
   740  (trace_cterm ctxt false (fn () => "Adding simplification procedure " ^ quote name ^ " for") lhs;
   741   ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   742     (congs, Net.insert_term eq_proc (term_of lhs, proc) procs,
   743       mk_rews, termless, subgoal_tac, loop_tacs, solvers))
   744   handle Net.INSERT =>
   745     (Context_Position.if_visible ctxt
   746       warning ("Ignoring duplicate simplification procedure " ^ quote name); ctxt));
   747 
   748 fun del_proc (proc as Proc {name, lhs, ...}) ctxt =
   749   ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   750     (congs, Net.delete_term eq_proc (term_of lhs, proc) procs,
   751       mk_rews, termless, subgoal_tac, loop_tacs, solvers))
   752   handle Net.DELETE =>
   753     (Context_Position.if_visible ctxt
   754       warning ("Simplification procedure " ^ quote name ^ " not in simpset"); ctxt);
   755 
   756 fun prep_procs (Simproc {name, lhss, proc, id}) =
   757   lhss |> map (fn lhs => Proc {name = name, lhs = lhs, proc = Morphism.form proc, id = id});
   758 
   759 in
   760 
   761 fun ctxt addsimprocs ps = fold (fold add_proc o prep_procs) ps ctxt;
   762 fun ctxt delsimprocs ps = fold (fold del_proc o prep_procs) ps ctxt;
   763 
   764 end;
   765 
   766 
   767 (* mk_rews *)
   768 
   769 local
   770 
   771 fun map_mk_rews f = map_simpset2 (fn (congs, procs, {mk, mk_cong, mk_sym, mk_eq_True, reorient},
   772       termless, subgoal_tac, loop_tacs, solvers) =>
   773   let
   774     val (mk', mk_cong', mk_sym', mk_eq_True', reorient') =
   775       f (mk, mk_cong, mk_sym, mk_eq_True, reorient);
   776     val mk_rews' = {mk = mk', mk_cong = mk_cong', mk_sym = mk_sym', mk_eq_True = mk_eq_True',
   777       reorient = reorient'};
   778   in (congs, procs, mk_rews', termless, subgoal_tac, loop_tacs, solvers) end);
   779 
   780 in
   781 
   782 fun mksimps ctxt =
   783   let val Simpset (_, {mk_rews = {mk, ...}, ...}) = simpset_of ctxt
   784   in mk ctxt end;
   785 
   786 fun set_mksimps mk = map_mk_rews (fn (_, mk_cong, mk_sym, mk_eq_True, reorient) =>
   787   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   788 
   789 fun set_mkcong mk_cong = map_mk_rews (fn (mk, _, mk_sym, mk_eq_True, reorient) =>
   790   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   791 
   792 fun set_mksym mk_sym = map_mk_rews (fn (mk, mk_cong, _, mk_eq_True, reorient) =>
   793   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   794 
   795 fun set_mkeqTrue mk_eq_True = map_mk_rews (fn (mk, mk_cong, mk_sym, _, reorient) =>
   796   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   797 
   798 fun set_reorient reorient = map_mk_rews (fn (mk, mk_cong, mk_sym, mk_eq_True, _) =>
   799   (mk, mk_cong, mk_sym, mk_eq_True, reorient));
   800 
   801 end;
   802 
   803 
   804 (* termless *)
   805 
   806 fun set_termless termless =
   807   map_simpset2 (fn (congs, procs, mk_rews, _, subgoal_tac, loop_tacs, solvers) =>
   808    (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers));
   809 
   810 
   811 (* tactics *)
   812 
   813 fun set_subgoaler subgoal_tac =
   814   map_simpset2 (fn (congs, procs, mk_rews, termless, _, loop_tacs, solvers) =>
   815    (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers));
   816 
   817 fun ctxt setloop tac = ctxt |>
   818   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, _, solvers) =>
   819    (congs, procs, mk_rews, termless, subgoal_tac, [("", tac)], solvers));
   820 
   821 fun ctxt addloop (name, tac) = ctxt |>
   822   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   823     (congs, procs, mk_rews, termless, subgoal_tac,
   824      AList.update (op =) (name, tac) loop_tacs, solvers));
   825 
   826 fun ctxt delloop name = ctxt |>
   827   map_simpset2 (fn (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, solvers) =>
   828     (congs, procs, mk_rews, termless, subgoal_tac,
   829      (if AList.defined (op =) loop_tacs name then ()
   830       else
   831         Context_Position.if_visible ctxt
   832           warning ("No such looper in simpset: " ^ quote name);
   833         AList.delete (op =) name loop_tacs), solvers));
   834 
   835 fun ctxt setSSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
   836   subgoal_tac, loop_tacs, (unsafe_solvers, _)) =>
   837     (congs, procs, mk_rews, termless, subgoal_tac, loop_tacs, (unsafe_solvers, [solver])));
   838 
   839 fun ctxt addSSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
   840   subgoal_tac, loop_tacs, (unsafe_solvers, solvers)) => (congs, procs, mk_rews, termless,
   841     subgoal_tac, loop_tacs, (unsafe_solvers, insert eq_solver solver solvers)));
   842 
   843 fun ctxt setSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
   844   subgoal_tac, loop_tacs, (_, solvers)) => (congs, procs, mk_rews, termless,
   845     subgoal_tac, loop_tacs, ([solver], solvers)));
   846 
   847 fun ctxt addSolver solver = ctxt |> map_simpset2 (fn (congs, procs, mk_rews, termless,
   848   subgoal_tac, loop_tacs, (unsafe_solvers, solvers)) => (congs, procs, mk_rews, termless,
   849     subgoal_tac, loop_tacs, (insert eq_solver solver unsafe_solvers, solvers)));
   850 
   851 fun set_solvers solvers = map_simpset2 (fn (congs, procs, mk_rews, termless,
   852   subgoal_tac, loop_tacs, _) => (congs, procs, mk_rews, termless,
   853   subgoal_tac, loop_tacs, (solvers, solvers)));
   854 
   855 
   856 
   857 (** rewriting **)
   858 
   859 (*
   860   Uses conversions, see:
   861     L C Paulson, A higher-order implementation of rewriting,
   862     Science of Computer Programming 3 (1983), pages 119-149.
   863 *)
   864 
   865 fun check_conv ctxt msg thm thm' =
   866   let
   867     val thm'' = Thm.transitive thm thm' handle THM _ =>
   868      Thm.transitive thm (Thm.transitive
   869        (Thm.symmetric (Drule.beta_eta_conversion (Thm.lhs_of thm'))) thm')
   870   in if msg then trace_thm ctxt (fn () => "SUCCEEDED") thm' else (); SOME thm'' end
   871   handle THM _ =>
   872     let
   873       val _ $ _ $ prop0 = Thm.prop_of thm;
   874     in
   875       trace_thm ctxt (fn () => "Proved wrong thm (Check subgoaler?)") thm';
   876       trace_term ctxt false (fn () => "Should have proved:") prop0;
   877       NONE
   878     end;
   879 
   880 
   881 (* mk_procrule *)
   882 
   883 fun mk_procrule ctxt thm =
   884   let val (prems, lhs, elhs, rhs, _) = decomp_simp thm in
   885     if rewrite_rule_extra_vars prems lhs rhs
   886     then (cond_warn_thm ctxt (fn () => "Extra vars on rhs:") thm; [])
   887     else [mk_rrule2 {thm = thm, name = "", lhs = lhs, elhs = elhs, perm = false}]
   888   end;
   889 
   890 
   891 (* rewritec: conversion to apply the meta simpset to a term *)
   892 
   893 (*Since the rewriting strategy is bottom-up, we avoid re-normalizing already
   894   normalized terms by carrying around the rhs of the rewrite rule just
   895   applied. This is called the `skeleton'. It is decomposed in parallel
   896   with the term. Once a Var is encountered, the corresponding term is
   897   already in normal form.
   898   skel0 is a dummy skeleton that is to enforce complete normalization.*)
   899 
   900 val skel0 = Bound 0;
   901 
   902 (*Use rhs as skeleton only if the lhs does not contain unnormalized bits.
   903   The latter may happen iff there are weak congruence rules for constants
   904   in the lhs.*)
   905 
   906 fun uncond_skel ((_, weak), (lhs, rhs)) =
   907   if null weak then rhs  (*optimization*)
   908   else if exists_subterm
   909     (fn Const (a, _) => member (op =) weak (true, a)
   910       | Free (a, _) => member (op =) weak (false, a)
   911       | _ => false) lhs then skel0
   912   else rhs;
   913 
   914 (*Behaves like unconditional rule if rhs does not contain vars not in the lhs.
   915   Otherwise those vars may become instantiated with unnormalized terms
   916   while the premises are solved.*)
   917 
   918 fun cond_skel (args as (_, (lhs, rhs))) =
   919   if subset (op =) (Term.add_vars rhs [], Term.add_vars lhs []) then uncond_skel args
   920   else skel0;
   921 
   922 (*
   923   Rewriting -- we try in order:
   924     (1) beta reduction
   925     (2) unconditional rewrite rules
   926     (3) conditional rewrite rules
   927     (4) simplification procedures
   928 
   929   IMPORTANT: rewrite rules must not introduce new Vars or TVars!
   930 *)
   931 
   932 fun rewritec (prover, maxt) ctxt t =
   933   let
   934     val Simpset ({rules, ...}, {congs, procs, termless, ...}) = simpset_of ctxt;
   935     val eta_thm = Thm.eta_conversion t;
   936     val eta_t' = Thm.rhs_of eta_thm;
   937     val eta_t = term_of eta_t';
   938     fun rew {thm, name, lhs, elhs, extra, fo, perm} =
   939       let
   940         val prop = Thm.prop_of thm;
   941         val (rthm, elhs') =
   942           if maxt = ~1 orelse not extra then (thm, elhs)
   943           else (Thm.incr_indexes (maxt + 1) thm, Thm.incr_indexes_cterm (maxt + 1) elhs);
   944         val insts =
   945           if fo then Thm.first_order_match (elhs', eta_t')
   946           else Thm.match (elhs', eta_t');
   947         val thm' = Thm.instantiate insts (Thm.rename_boundvars lhs eta_t rthm);
   948         val prop' = Thm.prop_of thm';
   949         val unconditional = (Logic.count_prems prop' = 0);
   950         val (lhs', rhs') = Logic.dest_equals (Logic.strip_imp_concl prop')
   951       in
   952         if perm andalso not (termless (rhs', lhs'))
   953         then (trace_named_thm ctxt (fn () => "Cannot apply permutative rewrite rule") (thm, name);
   954               trace_thm ctxt (fn () => "Term does not become smaller:") thm'; NONE)
   955         else (trace_named_thm ctxt (fn () => "Applying instance of rewrite rule") (thm, name);
   956            if unconditional
   957            then
   958              (trace_thm ctxt (fn () => "Rewriting:") thm';
   959               let
   960                 val lr = Logic.dest_equals prop;
   961                 val SOME thm'' = check_conv ctxt false eta_thm thm';
   962               in SOME (thm'', uncond_skel (congs, lr)) end)
   963            else
   964              (trace_thm ctxt (fn () => "Trying to rewrite:") thm';
   965               if simp_depth ctxt > Config.get ctxt simp_depth_limit
   966               then
   967                 let
   968                   val s = "simp_depth_limit exceeded - giving up";
   969                   val _ = trace ctxt false (fn () => s);
   970                   val _ = Context_Position.if_visible ctxt warning s;
   971                 in NONE end
   972               else
   973               case prover ctxt thm' of
   974                 NONE => (trace_thm ctxt (fn () => "FAILED") thm'; NONE)
   975               | SOME thm2 =>
   976                   (case check_conv ctxt true eta_thm thm2 of
   977                     NONE => NONE
   978                   | SOME thm2' =>
   979                       let
   980                         val concl = Logic.strip_imp_concl prop;
   981                         val lr = Logic.dest_equals concl;
   982                       in SOME (thm2', cond_skel (congs, lr)) end)))
   983       end;
   984 
   985     fun rews [] = NONE
   986       | rews (rrule :: rrules) =
   987           let val opt = rew rrule handle Pattern.MATCH => NONE
   988           in case opt of NONE => rews rrules | some => some end;
   989 
   990     fun sort_rrules rrs =
   991       let
   992         fun is_simple ({thm, ...}: rrule) =
   993           (case Thm.prop_of thm of
   994             Const ("==", _) $ _ $ _ => true
   995           | _ => false);
   996         fun sort [] (re1, re2) = re1 @ re2
   997           | sort (rr :: rrs) (re1, re2) =
   998               if is_simple rr
   999               then sort rrs (rr :: re1, re2)
  1000               else sort rrs (re1, rr :: re2);
  1001       in sort rrs ([], []) end;
  1002 
  1003     fun proc_rews [] = NONE
  1004       | proc_rews (Proc {name, proc, lhs, ...} :: ps) =
  1005           if Pattern.matches (Proof_Context.theory_of ctxt) (Thm.term_of lhs, Thm.term_of t) then
  1006             (debug_term ctxt false (fn () => "Trying procedure " ^ quote name ^ " on:") eta_t;
  1007              case proc ctxt eta_t' of
  1008                NONE => (debug ctxt false (fn () => "FAILED"); proc_rews ps)
  1009              | SOME raw_thm =>
  1010                  (trace_thm ctxt (fn () => "Procedure " ^ quote name ^ " produced rewrite rule:")
  1011                    raw_thm;
  1012                   (case rews (mk_procrule ctxt raw_thm) of
  1013                     NONE => (trace_cterm ctxt true (fn () => "IGNORED result of simproc " ^ quote name ^
  1014                       " -- does not match") t; proc_rews ps)
  1015                   | some => some)))
  1016           else proc_rews ps;
  1017   in
  1018     (case eta_t of
  1019       Abs _ $ _ => SOME (Thm.transitive eta_thm (Thm.beta_conversion false eta_t'), skel0)
  1020     | _ =>
  1021       (case rews (sort_rrules (Net.match_term rules eta_t)) of
  1022         NONE => proc_rews (Net.match_term procs eta_t)
  1023       | some => some))
  1024   end;
  1025 
  1026 
  1027 (* conversion to apply a congruence rule to a term *)
  1028 
  1029 fun congc prover ctxt maxt cong t =
  1030   let
  1031     val rthm = Thm.incr_indexes (maxt + 1) cong;
  1032     val rlhs = fst (Thm.dest_equals (Drule.strip_imp_concl (cprop_of rthm)));
  1033     val insts = Thm.match (rlhs, t)
  1034     (* Thm.match can raise Pattern.MATCH;
  1035        is handled when congc is called *)
  1036     val thm' = Thm.instantiate insts (Thm.rename_boundvars (term_of rlhs) (term_of t) rthm);
  1037     val _ = trace_thm ctxt (fn () => "Applying congruence rule:") thm';
  1038     fun err (msg, thm) = (trace_thm ctxt (fn () => msg) thm; NONE);
  1039   in
  1040     (case prover thm' of
  1041       NONE => err ("Congruence proof failed.  Could not prove", thm')
  1042     | SOME thm2 =>
  1043         (case check_conv ctxt true (Drule.beta_eta_conversion t) thm2 of
  1044           NONE => err ("Congruence proof failed.  Should not have proved", thm2)
  1045         | SOME thm2' =>
  1046             if op aconv (pairself term_of (Thm.dest_equals (cprop_of thm2')))
  1047             then NONE else SOME thm2'))
  1048   end;
  1049 
  1050 val (cA, (cB, cC)) =
  1051   apsnd Thm.dest_equals (Thm.dest_implies (hd (cprems_of Drule.imp_cong)));
  1052 
  1053 fun transitive1 NONE NONE = NONE
  1054   | transitive1 (SOME thm1) NONE = SOME thm1
  1055   | transitive1 NONE (SOME thm2) = SOME thm2
  1056   | transitive1 (SOME thm1) (SOME thm2) = SOME (Thm.transitive thm1 thm2)
  1057 
  1058 fun transitive2 thm = transitive1 (SOME thm);
  1059 fun transitive3 thm = transitive1 thm o SOME;
  1060 
  1061 fun bottomc ((simprem, useprem, mutsimp), prover, maxidx) =
  1062   let
  1063     fun botc skel ctxt t =
  1064           if is_Var skel then NONE
  1065           else
  1066           (case subc skel ctxt t of
  1067              some as SOME thm1 =>
  1068                (case rewritec (prover, maxidx) ctxt (Thm.rhs_of thm1) of
  1069                   SOME (thm2, skel2) =>
  1070                     transitive2 (Thm.transitive thm1 thm2)
  1071                       (botc skel2 ctxt (Thm.rhs_of thm2))
  1072                 | NONE => some)
  1073            | NONE =>
  1074                (case rewritec (prover, maxidx) ctxt t of
  1075                   SOME (thm2, skel2) => transitive2 thm2
  1076                     (botc skel2 ctxt (Thm.rhs_of thm2))
  1077                 | NONE => NONE))
  1078 
  1079     and try_botc ctxt t =
  1080           (case botc skel0 ctxt t of
  1081             SOME trec1 => trec1
  1082           | NONE => (Thm.reflexive t))
  1083 
  1084     and subc skel ctxt t0 =
  1085         let val Simpset ({bounds, ...}, {congs, ...}) = simpset_of ctxt in
  1086           (case term_of t0 of
  1087               Abs (a, T, _) =>
  1088                 let
  1089                     val b = Name.bound (#1 bounds);
  1090                     val (v, t') = Thm.dest_abs (SOME b) t0;
  1091                     val b' = #1 (Term.dest_Free (Thm.term_of v));
  1092                     val _ =
  1093                       if b <> b' then
  1094                         warning ("Simplifier: renamed bound variable " ^
  1095                           quote b ^ " to " ^ quote b' ^ Position.here (Position.thread_data ()))
  1096                       else ();
  1097                     val ctxt' = add_bound ((b', T), a) ctxt;
  1098                     val skel' = case skel of Abs (_, _, sk) => sk | _ => skel0;
  1099                 in
  1100                   (case botc skel' ctxt' t' of
  1101                     SOME thm => SOME (Thm.abstract_rule a v thm)
  1102                   | NONE => NONE)
  1103                 end
  1104             | t $ _ => (case t of
  1105                 Const ("==>", _) $ _  => impc t0 ctxt
  1106               | Abs _ =>
  1107                   let val thm = Thm.beta_conversion false t0
  1108                   in case subc skel0 ctxt (Thm.rhs_of thm) of
  1109                        NONE => SOME thm
  1110                      | SOME thm' => SOME (Thm.transitive thm thm')
  1111                   end
  1112               | _  =>
  1113                   let fun appc () =
  1114                         let
  1115                           val (tskel, uskel) = case skel of
  1116                               tskel $ uskel => (tskel, uskel)
  1117                             | _ => (skel0, skel0);
  1118                           val (ct, cu) = Thm.dest_comb t0
  1119                         in
  1120                         (case botc tskel ctxt ct of
  1121                            SOME thm1 =>
  1122                              (case botc uskel ctxt cu of
  1123                                 SOME thm2 => SOME (Thm.combination thm1 thm2)
  1124                               | NONE => SOME (Thm.combination thm1 (Thm.reflexive cu)))
  1125                          | NONE =>
  1126                              (case botc uskel ctxt cu of
  1127                                 SOME thm1 => SOME (Thm.combination (Thm.reflexive ct) thm1)
  1128                               | NONE => NONE))
  1129                         end
  1130                       val (h, ts) = strip_comb t
  1131                   in case cong_name h of
  1132                        SOME a =>
  1133                          (case AList.lookup (op =) (fst congs) a of
  1134                             NONE => appc ()
  1135                           | SOME cong =>
  1136      (*post processing: some partial applications h t1 ... tj, j <= length ts,
  1137        may be a redex. Example: map (%x. x) = (%xs. xs) wrt map_cong*)
  1138                              (let
  1139                                 val thm = congc (prover ctxt) ctxt maxidx cong t0;
  1140                                 val t = the_default t0 (Option.map Thm.rhs_of thm);
  1141                                 val (cl, cr) = Thm.dest_comb t
  1142                                 val dVar = Var(("", 0), dummyT)
  1143                                 val skel =
  1144                                   list_comb (h, replicate (length ts) dVar)
  1145                               in case botc skel ctxt cl of
  1146                                    NONE => thm
  1147                                  | SOME thm' => transitive3 thm
  1148                                      (Thm.combination thm' (Thm.reflexive cr))
  1149                               end handle Pattern.MATCH => appc ()))
  1150                      | _ => appc ()
  1151                   end)
  1152             | _ => NONE)
  1153         end
  1154     and impc ct ctxt =
  1155       if mutsimp then mut_impc0 [] ct [] [] ctxt else nonmut_impc ct ctxt
  1156 
  1157     and rules_of_prem ctxt prem =
  1158       if maxidx_of_term (term_of prem) <> ~1
  1159       then (trace_cterm ctxt true
  1160         (fn () => "Cannot add premise as rewrite rule because it contains (type) unknowns:")
  1161         prem; ([], NONE))
  1162       else
  1163         let val asm = Thm.assume prem
  1164         in (extract_safe_rrules (ctxt, asm), SOME asm) end
  1165 
  1166     and add_rrules (rrss, asms) ctxt =
  1167       (fold o fold) insert_rrule rrss ctxt |> add_prems (map_filter I asms)
  1168 
  1169     and disch r prem eq =
  1170       let
  1171         val (lhs, rhs) = Thm.dest_equals (Thm.cprop_of eq);
  1172         val eq' = Thm.implies_elim (Thm.instantiate
  1173           ([], [(cA, prem), (cB, lhs), (cC, rhs)]) Drule.imp_cong)
  1174           (Thm.implies_intr prem eq)
  1175       in if not r then eq' else
  1176         let
  1177           val (prem', concl) = Thm.dest_implies lhs;
  1178           val (prem'', _) = Thm.dest_implies rhs
  1179         in Thm.transitive (Thm.transitive
  1180           (Thm.instantiate ([], [(cA, prem'), (cB, prem), (cC, concl)])
  1181              Drule.swap_prems_eq) eq')
  1182           (Thm.instantiate ([], [(cA, prem), (cB, prem''), (cC, concl)])
  1183              Drule.swap_prems_eq)
  1184         end
  1185       end
  1186 
  1187     and rebuild [] _ _ _ _ eq = eq
  1188       | rebuild (prem :: prems) concl (_ :: rrss) (_ :: asms) ctxt eq =
  1189           let
  1190             val ctxt' = add_rrules (rev rrss, rev asms) ctxt;
  1191             val concl' =
  1192               Drule.mk_implies (prem, the_default concl (Option.map Thm.rhs_of eq));
  1193             val dprem = Option.map (disch false prem)
  1194           in
  1195             (case rewritec (prover, maxidx) ctxt' concl' of
  1196               NONE => rebuild prems concl' rrss asms ctxt (dprem eq)
  1197             | SOME (eq', _) => transitive2 (fold (disch false)
  1198                   prems (the (transitive3 (dprem eq) eq')))
  1199                 (mut_impc0 (rev prems) (Thm.rhs_of eq') (rev rrss) (rev asms) ctxt))
  1200           end
  1201 
  1202     and mut_impc0 prems concl rrss asms ctxt =
  1203       let
  1204         val prems' = strip_imp_prems concl;
  1205         val (rrss', asms') = split_list (map (rules_of_prem ctxt) prems')
  1206       in
  1207         mut_impc (prems @ prems') (strip_imp_concl concl) (rrss @ rrss')
  1208           (asms @ asms') [] [] [] [] ctxt ~1 ~1
  1209       end
  1210 
  1211     and mut_impc [] concl [] [] prems' rrss' asms' eqns ctxt changed k =
  1212         transitive1 (fold (fn (eq1, prem) => fn eq2 => transitive1 eq1
  1213             (Option.map (disch false prem) eq2)) (eqns ~~ prems') NONE)
  1214           (if changed > 0 then
  1215              mut_impc (rev prems') concl (rev rrss') (rev asms')
  1216                [] [] [] [] ctxt ~1 changed
  1217            else rebuild prems' concl rrss' asms' ctxt
  1218              (botc skel0 (add_rrules (rev rrss', rev asms') ctxt) concl))
  1219 
  1220       | mut_impc (prem :: prems) concl (rrs :: rrss) (asm :: asms)
  1221           prems' rrss' asms' eqns ctxt changed k =
  1222         case (if k = 0 then NONE else botc skel0 (add_rrules
  1223           (rev rrss' @ rrss, rev asms' @ asms) ctxt) prem) of
  1224             NONE => mut_impc prems concl rrss asms (prem :: prems')
  1225               (rrs :: rrss') (asm :: asms') (NONE :: eqns) ctxt changed
  1226               (if k = 0 then 0 else k - 1)
  1227           | SOME eqn =>
  1228             let
  1229               val prem' = Thm.rhs_of eqn;
  1230               val tprems = map term_of prems;
  1231               val i = 1 + fold Integer.max (map (fn p =>
  1232                 find_index (fn q => q aconv p) tprems) (Thm.hyps_of eqn)) ~1;
  1233               val (rrs', asm') = rules_of_prem ctxt prem';
  1234             in mut_impc prems concl rrss asms (prem' :: prems')
  1235               (rrs' :: rrss') (asm' :: asms') (SOME (fold_rev (disch true)
  1236                 (take i prems)
  1237                 (Drule.imp_cong_rule eqn (Thm.reflexive (Drule.list_implies
  1238                   (drop i prems, concl))))) :: eqns)
  1239                   ctxt (length prems') ~1
  1240             end
  1241 
  1242      (*legacy code - only for backwards compatibility*)
  1243     and nonmut_impc ct ctxt =
  1244       let
  1245         val (prem, conc) = Thm.dest_implies ct;
  1246         val thm1 = if simprem then botc skel0 ctxt prem else NONE;
  1247         val prem1 = the_default prem (Option.map Thm.rhs_of thm1);
  1248         val ctxt1 =
  1249           if not useprem then ctxt
  1250           else add_rrules (apsnd single (apfst single (rules_of_prem ctxt prem1))) ctxt
  1251       in
  1252         (case botc skel0 ctxt1 conc of
  1253           NONE =>
  1254             (case thm1 of
  1255               NONE => NONE
  1256             | SOME thm1' => SOME (Drule.imp_cong_rule thm1' (Thm.reflexive conc)))
  1257         | SOME thm2 =>
  1258             let val thm2' = disch false prem1 thm2 in
  1259               (case thm1 of
  1260                 NONE => SOME thm2'
  1261               | SOME thm1' =>
  1262                  SOME (Thm.transitive (Drule.imp_cong_rule thm1' (Thm.reflexive conc)) thm2'))
  1263             end)
  1264       end
  1265 
  1266  in try_botc end;
  1267 
  1268 
  1269 (* Meta-rewriting: rewrites t to u and returns the theorem t==u *)
  1270 
  1271 (*
  1272   Parameters:
  1273     mode = (simplify A,
  1274             use A in simplifying B,
  1275             use prems of B (if B is again a meta-impl.) to simplify A)
  1276            when simplifying A ==> B
  1277     prover: how to solve premises in conditional rewrites and congruences
  1278 *)
  1279 
  1280 val debug_bounds = Unsynchronized.ref false;
  1281 
  1282 fun check_bounds ctxt ct =
  1283   if ! debug_bounds then
  1284     let
  1285       val Simpset ({bounds = (_, bounds), ...}, _) = simpset_of ctxt;
  1286       val bs =
  1287         fold_aterms
  1288           (fn Free (x, _) =>
  1289             if Name.is_bound x andalso not (AList.defined eq_bound bounds x)
  1290             then insert (op =) x else I
  1291           | _ => I) (term_of ct) [];
  1292     in
  1293       if null bs then ()
  1294       else
  1295         print_term ctxt true
  1296           (fn () => "Simplifier: term contains loose bounds: " ^ commas_quote bs)
  1297           (Thm.term_of ct)
  1298     end
  1299   else ();
  1300 
  1301 fun rewrite_cterm mode prover raw_ctxt raw_ct =
  1302   let
  1303     val ctxt =
  1304       raw_ctxt
  1305       |> Context_Position.set_visible false
  1306       |> inc_simp_depth;
  1307     val thy = Proof_Context.theory_of ctxt;
  1308 
  1309     val ct = Thm.adjust_maxidx_cterm ~1 raw_ct;
  1310     val {maxidx, ...} = Thm.rep_cterm ct;
  1311     val _ =
  1312       Theory.subthy (theory_of_cterm ct, thy) orelse
  1313         raise CTERM ("rewrite_cterm: bad background theory", [ct]);
  1314 
  1315     val depth = simp_depth ctxt;
  1316     val _ =
  1317       if depth mod 20 = 0 then
  1318         Context_Position.if_visible ctxt warning ("Simplification depth " ^ string_of_int depth)
  1319       else ();
  1320     val _ = trace_cterm ctxt false (fn () => "SIMPLIFIER INVOKED ON THE FOLLOWING TERM:") ct;
  1321     val _ = check_bounds ctxt ct;
  1322   in bottomc (mode, Option.map Drule.flexflex_unique oo prover, maxidx) ctxt ct end;
  1323 
  1324 val simple_prover =
  1325   SINGLE o (fn ctxt => ALLGOALS (resolve_tac (prems_of ctxt)));
  1326 
  1327 fun rewrite _ [] ct = Thm.reflexive ct
  1328   | rewrite full thms ct =
  1329       rewrite_cterm (full, false, false) simple_prover
  1330         (global_context (Thm.theory_of_cterm ct) empty_ss addsimps thms) ct;
  1331 
  1332 fun simplify full thms = Conv.fconv_rule (rewrite full thms);
  1333 val rewrite_rule = simplify true;
  1334 
  1335 (*simple term rewriting -- no proof*)
  1336 fun rewrite_term thy rules procs =
  1337   Pattern.rewrite_term thy (map decomp_simp' rules) procs;
  1338 
  1339 fun rewrite_thm mode prover ctxt = Conv.fconv_rule (rewrite_cterm mode prover ctxt);
  1340 
  1341 (*Rewrite the subgoals of a proof state (represented by a theorem)*)
  1342 fun rewrite_goals_rule thms th =
  1343   Conv.fconv_rule (Conv.prems_conv ~1 (rewrite_cterm (true, true, true) simple_prover
  1344     (global_context (Thm.theory_of_thm th) empty_ss addsimps thms))) th;
  1345 
  1346 
  1347 (** meta-rewriting tactics **)
  1348 
  1349 (*Rewrite all subgoals*)
  1350 fun rewrite_goals_tac defs = PRIMITIVE (rewrite_goals_rule defs);
  1351 
  1352 (*Rewrite one subgoal*)
  1353 fun generic_rewrite_goal_tac mode prover_tac ctxt i thm =
  1354   if 0 < i andalso i <= Thm.nprems_of thm then
  1355     Seq.single (Conv.gconv_rule (rewrite_cterm mode (SINGLE o prover_tac) ctxt) i thm)
  1356   else Seq.empty;
  1357 
  1358 fun rewrite_goal_tac rews i st =
  1359   generic_rewrite_goal_tac (true, false, false) (K no_tac)
  1360     (global_context (Thm.theory_of_thm st) empty_ss addsimps rews) i st;
  1361 
  1362 (*Prunes all redundant parameters from the proof state by rewriting.*)
  1363 val prune_params_tac = rewrite_goals_tac [Drule.triv_forall_equality];
  1364 
  1365 
  1366 (* for folding definitions, handling critical pairs *)
  1367 
  1368 (*The depth of nesting in a term*)
  1369 fun term_depth (Abs (_, _, t)) = 1 + term_depth t
  1370   | term_depth (f $ t) = 1 + Int.max (term_depth f, term_depth t)
  1371   | term_depth _ = 0;
  1372 
  1373 val lhs_of_thm = #1 o Logic.dest_equals o prop_of;
  1374 
  1375 (*folding should handle critical pairs!  E.g. K == Inl(0),  S == Inr(Inl(0))
  1376   Returns longest lhs first to avoid folding its subexpressions.*)
  1377 fun sort_lhs_depths defs =
  1378   let val keylist = AList.make (term_depth o lhs_of_thm) defs
  1379       val keys = sort_distinct (rev_order o int_ord) (map #2 keylist)
  1380   in map (AList.find (op =) keylist) keys end;
  1381 
  1382 val rev_defs = sort_lhs_depths o map Thm.symmetric;
  1383 
  1384 fun fold_rule defs = fold rewrite_rule (rev_defs defs);
  1385 fun fold_goals_tac defs = EVERY (map rewrite_goals_tac (rev_defs defs));
  1386 
  1387 
  1388 (* HHF normal form: !! before ==>, outermost !! generalized *)
  1389 
  1390 local
  1391 
  1392 fun gen_norm_hhf ss th =
  1393   (if Drule.is_norm_hhf (Thm.prop_of th) then th
  1394    else
  1395     Conv.fconv_rule
  1396       (rewrite_cterm (true, false, false) (K (K NONE))
  1397         (global_context (Thm.theory_of_thm th) ss)) th)
  1398   |> Thm.adjust_maxidx_thm ~1
  1399   |> Drule.gen_all;
  1400 
  1401 val hhf_ss =
  1402   simpset_of (empty_simpset (Context.proof_of (Context.the_thread_data ()))
  1403     addsimps Drule.norm_hhf_eqs);
  1404 
  1405 val hhf_protect_ss =
  1406   simpset_of (empty_simpset (Context.proof_of (Context.the_thread_data ()))
  1407     addsimps Drule.norm_hhf_eqs |> add_eqcong Drule.protect_cong);
  1408 
  1409 in
  1410 
  1411 val norm_hhf = gen_norm_hhf hhf_ss;
  1412 val norm_hhf_protect = gen_norm_hhf hhf_protect_ss;
  1413 
  1414 end;
  1415 
  1416 end;
  1417 
  1418 structure Basic_Meta_Simplifier: BASIC_RAW_SIMPLIFIER = Raw_Simplifier;
  1419 open Basic_Meta_Simplifier;