src/HOL/Library/rewrite.ML
author wenzelm
Mon Dec 28 17:43:30 2015 +0100 (2015-12-28)
changeset 61952 546958347e05
parent 61476 1884c40f1539
child 62969 9f394a16c557
permissions -rw-r--r--
prefer symbols for "Union", "Inter";
wenzelm@59975
     1
(*  Title:      HOL/Library/rewrite.ML
wenzelm@59975
     2
    Author:     Christoph Traut, Lars Noschinski, TU Muenchen
noschinl@59739
     3
wenzelm@59975
     4
This is a rewrite method that supports subterm-selection based on patterns.
noschinl@59739
     5
wenzelm@59975
     6
The patterns accepted by rewrite are of the following form:
wenzelm@59975
     7
  <atom>    ::= <term> | "concl" | "asm" | "for" "(" <names> ")"
wenzelm@59975
     8
  <pattern> ::= (in <atom> | at <atom>) [<pattern>]
wenzelm@59975
     9
  <args>    ::= [<pattern>] ("to" <term>) <thms>
noschinl@59739
    10
wenzelm@59975
    11
This syntax was clearly inspired by Gonthier's and Tassi's language of
wenzelm@59975
    12
patterns but has diverged significantly during its development.
noschinl@59739
    13
wenzelm@59975
    14
We also allow introduction of identifiers for bound variables,
wenzelm@59975
    15
which can then be used to match arbitrary subterms inside abstractions.
noschinl@59739
    16
*)
noschinl@59739
    17
noschinl@60117
    18
infix 1 then_pconv;
noschinl@60117
    19
infix 0 else_pconv;
noschinl@60117
    20
wenzelm@59975
    21
signature REWRITE =
wenzelm@59975
    22
sig
noschinl@60117
    23
  type patconv = Proof.context -> Type.tyenv * (string * term) list -> cconv
noschinl@60117
    24
  val then_pconv: patconv * patconv -> patconv
noschinl@60117
    25
  val else_pconv: patconv * patconv -> patconv
noschinl@60117
    26
  val abs_pconv:  patconv -> string option * typ -> patconv (*XXX*)
noschinl@60117
    27
  val fun_pconv: patconv -> patconv
noschinl@60117
    28
  val arg_pconv: patconv -> patconv
noschinl@60117
    29
  val imp_pconv: patconv -> patconv
noschinl@60117
    30
  val params_pconv: patconv -> patconv
noschinl@60117
    31
  val forall_pconv: patconv -> string option * typ option -> patconv
noschinl@60117
    32
  val all_pconv: patconv
noschinl@60117
    33
  val for_pconv: patconv -> (string option * typ option) list -> patconv
noschinl@60117
    34
  val concl_pconv: patconv -> patconv
noschinl@60117
    35
  val asm_pconv: patconv -> patconv
noschinl@60117
    36
  val asms_pconv: patconv -> patconv
noschinl@60117
    37
  val judgment_pconv: patconv -> patconv
noschinl@60117
    38
  val in_pconv: patconv -> patconv
noschinl@60117
    39
  val match_pconv: patconv -> term * (string option * typ) list -> patconv
noschinl@60117
    40
  val rewrs_pconv: term option -> thm list -> patconv
noschinl@60117
    41
noschinl@60079
    42
  datatype ('a, 'b) pattern = At | In | Term of 'a | Concl | Asm | For of 'b list
noschinl@60079
    43
noschinl@60079
    44
  val mk_hole: int -> typ -> term
noschinl@60079
    45
noschinl@60117
    46
  val rewrite_conv: Proof.context
noschinl@60079
    47
    -> (term * (string * typ) list, string * typ option) pattern list * term option
noschinl@60079
    48
    -> thm list
noschinl@60117
    49
    -> conv
noschinl@59739
    50
end
noschinl@59739
    51
wenzelm@59975
    52
structure Rewrite : REWRITE =
noschinl@59739
    53
struct
noschinl@59739
    54
noschinl@59739
    55
datatype ('a, 'b) pattern = At | In | Term of 'a | Concl | Asm | For of 'b list
noschinl@59739
    56
noschinl@59739
    57
exception NO_TO_MATCH
noschinl@59739
    58
noschinl@59739
    59
val holeN = Name.internal "_hole"
noschinl@59739
    60
noschinl@60117
    61
fun prep_meta_eq ctxt = Simplifier.mksimps ctxt #> map Drule.zero_var_indexes
noschinl@59739
    62
noschinl@59739
    63
noschinl@60117
    64
(* holes *)
noschinl@59739
    65
noschinl@60079
    66
fun mk_hole i T = Var ((holeN, i), T)
noschinl@60079
    67
noschinl@59739
    68
fun is_hole (Var ((name, _), _)) = (name = holeN)
noschinl@59739
    69
  | is_hole _ = false
noschinl@59739
    70
noschinl@59739
    71
fun is_hole_const (Const (@{const_name rewrite_HOLE}, _)) = true
noschinl@59739
    72
  | is_hole_const _ = false
noschinl@59739
    73
noschinl@59739
    74
val hole_syntax =
noschinl@59739
    75
  let
noschinl@59739
    76
    (* Modified variant of Term.replace_hole *)
noschinl@59739
    77
    fun replace_hole Ts (Const (@{const_name rewrite_HOLE}, T)) i =
noschinl@60079
    78
          (list_comb (mk_hole i (Ts ---> T), map_range Bound (length Ts)), i + 1)
noschinl@59739
    79
      | replace_hole Ts (Abs (x, T, t)) i =
noschinl@59739
    80
          let val (t', i') = replace_hole (T :: Ts) t i
noschinl@59739
    81
          in (Abs (x, T, t'), i') end
noschinl@59739
    82
      | replace_hole Ts (t $ u) i =
noschinl@59739
    83
          let
noschinl@59739
    84
            val (t', i') = replace_hole Ts t i
noschinl@59739
    85
            val (u', i'') = replace_hole Ts u i'
noschinl@59739
    86
          in (t' $ u', i'') end
noschinl@59739
    87
      | replace_hole _ a i = (a, i)
noschinl@59739
    88
    fun prep_holes ts = #1 (fold_map (replace_hole []) ts 1)
noschinl@59739
    89
  in
noschinl@59739
    90
    Context.proof_map (Syntax_Phases.term_check 101 "hole_expansion" (K prep_holes))
noschinl@59739
    91
    #> Proof_Context.set_mode Proof_Context.mode_pattern
noschinl@59739
    92
  end
noschinl@59739
    93
noschinl@60117
    94
noschinl@60117
    95
(* pattern conversions *)
noschinl@60117
    96
noschinl@60117
    97
type patconv = Proof.context -> Type.tyenv * (string * term) list -> cterm -> thm
noschinl@60117
    98
noschinl@60117
    99
fun (cv1 then_pconv cv2) ctxt tytenv ct = (cv1 ctxt tytenv then_conv cv2 ctxt tytenv) ct
noschinl@60117
   100
noschinl@60117
   101
fun (cv1 else_pconv cv2) ctxt tytenv ct = (cv1 ctxt tytenv else_conv cv2 ctxt tytenv) ct
noschinl@59739
   102
noschinl@60117
   103
fun raw_abs_pconv cv ctxt tytenv ct =
noschinl@60117
   104
  case Thm.term_of ct of
noschinl@60117
   105
    Abs _ => CConv.abs_cconv (fn (x, ctxt') => cv x ctxt' tytenv) ctxt ct
noschinl@60117
   106
  | t => raise TERM ("raw_abs_pconv", [t])
noschinl@59739
   107
noschinl@60117
   108
fun raw_fun_pconv cv ctxt tytenv ct =
noschinl@60117
   109
  case Thm.term_of ct of
noschinl@60117
   110
    _ $ _ => CConv.fun_cconv (cv ctxt tytenv) ct
noschinl@60117
   111
  | t => raise TERM ("raw_fun_pconv", [t])
noschinl@59739
   112
noschinl@60117
   113
fun raw_arg_pconv cv ctxt tytenv ct =
noschinl@60117
   114
  case Thm.term_of ct of
noschinl@60117
   115
    _ $ _ => CConv.arg_cconv (cv ctxt tytenv) ct
noschinl@60117
   116
  | t => raise TERM ("raw_arg_pconv", [t])
noschinl@59739
   117
noschinl@60117
   118
fun abs_pconv cv (s,T) ctxt (tyenv, ts) ct =
noschinl@60117
   119
  let val u = Thm.term_of ct
noschinl@59739
   120
  in
noschinl@60117
   121
    case try (fastype_of #> dest_funT) u of
noschinl@60117
   122
      NONE => raise TERM ("abs_pconv: no function type", [u])
noschinl@60117
   123
    | SOME (U, _) =>
noschinl@60117
   124
        let
noschinl@60117
   125
          val tyenv' =
noschinl@60117
   126
            if T = dummyT then tyenv
noschinl@60117
   127
            else Sign.typ_match (Proof_Context.theory_of ctxt) (T, U) tyenv
noschinl@60117
   128
          val eta_expand_cconv =
noschinl@60117
   129
            case u of
noschinl@60117
   130
              Abs _=> Thm.reflexive
noschinl@60117
   131
            | _ => CConv.rewr_cconv @{thm eta_expand}
noschinl@60117
   132
          fun add_ident NONE _ l = l
noschinl@60117
   133
            | add_ident (SOME name) ct l = (name, Thm.term_of ct) :: l
noschinl@60117
   134
          val abs_cv = CConv.abs_cconv (fn (ct, ctxt) => cv ctxt (tyenv', add_ident s ct ts)) ctxt
noschinl@60117
   135
        in (eta_expand_cconv then_conv abs_cv) ct end
noschinl@60117
   136
        handle Pattern.MATCH => raise TYPE ("abs_pconv: types don't match", [T,U], [u])
noschinl@59739
   137
  end
noschinl@59739
   138
noschinl@60117
   139
fun fun_pconv cv ctxt tytenv ct =
noschinl@60117
   140
  case Thm.term_of ct of
noschinl@60117
   141
    _ $ _ => CConv.fun_cconv (cv ctxt tytenv) ct
noschinl@60117
   142
  | Abs (_, T, _ $ Bound 0) => abs_pconv (fun_pconv cv) (NONE, T) ctxt tytenv ct
noschinl@60117
   143
  | t => raise TERM ("fun_pconv", [t])
noschinl@59739
   144
noschinl@60079
   145
local
noschinl@60079
   146
noschinl@60117
   147
fun arg_pconv_gen cv0 cv ctxt tytenv ct =
noschinl@60117
   148
  case Thm.term_of ct of
noschinl@60117
   149
    _ $ _ => cv0 (cv ctxt tytenv) ct
noschinl@60117
   150
  | Abs (_, T, _ $ Bound 0) => abs_pconv (arg_pconv_gen cv0 cv) (NONE, T) ctxt tytenv ct
noschinl@60117
   151
  | t => raise TERM ("arg_pconv_gen", [t])
noschinl@60117
   152
noschinl@60117
   153
in
noschinl@60117
   154
wenzelm@60122
   155
fun arg_pconv ctxt = arg_pconv_gen CConv.arg_cconv ctxt
wenzelm@60122
   156
fun imp_pconv ctxt = arg_pconv_gen (CConv.concl_cconv 1) ctxt
noschinl@60117
   157
noschinl@60117
   158
end
noschinl@60117
   159
noschinl@60117
   160
(* Move to B in !!x_1 ... x_n. B. Do not eta-expand *)
noschinl@60117
   161
fun params_pconv cv ctxt tytenv ct =
noschinl@60117
   162
  let val pconv =
noschinl@60117
   163
    case Thm.term_of ct of
noschinl@60117
   164
      Const (@{const_name "Pure.all"}, _) $ Abs _ => (raw_arg_pconv o raw_abs_pconv) (fn _ => params_pconv cv)
noschinl@60117
   165
    | Const (@{const_name "Pure.all"}, _) => raw_arg_pconv (params_pconv cv)
noschinl@60117
   166
    | _ => cv
noschinl@60117
   167
  in pconv ctxt tytenv ct end
noschinl@60117
   168
noschinl@60117
   169
fun forall_pconv cv ident ctxt tytenv ct =
noschinl@60117
   170
  case Thm.term_of ct of
noschinl@60117
   171
    Const (@{const_name "Pure.all"}, T) $ _ =>
noschinl@60117
   172
      let
noschinl@60117
   173
        val def_U = T |> dest_funT |> fst |> dest_funT |> fst
noschinl@60117
   174
        val ident' = apsnd (the_default (def_U)) ident
noschinl@60117
   175
      in arg_pconv (abs_pconv cv ident') ctxt tytenv ct end
noschinl@60117
   176
  | t => raise TERM ("forall_pconv", [t])
noschinl@60117
   177
noschinl@60117
   178
fun all_pconv _ _ = Thm.reflexive
noschinl@60117
   179
noschinl@60117
   180
fun for_pconv cv idents ctxt tytenv ct =
noschinl@59739
   181
  let
noschinl@60117
   182
    fun f rev_idents (Const (@{const_name "Pure.all"}, _) $ t) =
noschinl@60117
   183
        let val (rev_idents', cv') = f rev_idents (case t of Abs (_,_,u) => u | _ => t)
noschinl@60117
   184
        in
noschinl@60117
   185
          case rev_idents' of
noschinl@60117
   186
            [] => ([], forall_pconv cv' (NONE, NONE))
noschinl@60117
   187
          | (x :: xs) => (xs, forall_pconv cv' x)
noschinl@60117
   188
        end
noschinl@60117
   189
      | f rev_idents _ = (rev_idents, cv)
noschinl@60117
   190
  in
noschinl@60117
   191
    case f (rev idents) (Thm.term_of ct) of
noschinl@60117
   192
      ([], cv') => cv' ctxt tytenv ct
noschinl@60117
   193
    | _ => raise CTERM ("for_pconv", [ct])
noschinl@60117
   194
  end
noschinl@60117
   195
noschinl@60117
   196
fun concl_pconv cv ctxt tytenv ct =
noschinl@60117
   197
  case Thm.term_of ct of
noschinl@60117
   198
    (Const (@{const_name "Pure.imp"}, _) $ _) $ _ => imp_pconv (concl_pconv cv) ctxt tytenv ct
noschinl@60117
   199
  | _ => cv ctxt tytenv ct
noschinl@60117
   200
noschinl@60117
   201
fun asm_pconv cv ctxt tytenv ct =
noschinl@60117
   202
  case Thm.term_of ct of
noschinl@60117
   203
    (Const (@{const_name "Pure.imp"}, _) $ _) $ _ => CConv.with_prems_cconv ~1 (cv ctxt tytenv) ct
noschinl@60117
   204
  | t => raise TERM ("asm_pconv", [t])
noschinl@60117
   205
noschinl@60117
   206
fun asms_pconv cv ctxt tytenv ct =
noschinl@60117
   207
  case Thm.term_of ct of
noschinl@60117
   208
    (Const (@{const_name "Pure.imp"}, _) $ _) $ _ =>
noschinl@60117
   209
      ((CConv.with_prems_cconv ~1 oo cv) else_pconv imp_pconv (asms_pconv cv)) ctxt tytenv ct
noschinl@60117
   210
  | t => raise TERM ("asms_pconv", [t])
noschinl@60117
   211
noschinl@60117
   212
fun judgment_pconv cv ctxt tytenv ct =
noschinl@60117
   213
  if Object_Logic.is_judgment ctxt (Thm.term_of ct)
noschinl@60117
   214
  then arg_pconv cv ctxt tytenv ct
noschinl@60117
   215
  else cv ctxt tytenv ct
noschinl@60117
   216
noschinl@60117
   217
fun in_pconv cv ctxt tytenv ct =
noschinl@60117
   218
  (cv else_pconv 
noschinl@60117
   219
   raw_fun_pconv (in_pconv cv) else_pconv
noschinl@60117
   220
   raw_arg_pconv (in_pconv cv) else_pconv
noschinl@60117
   221
   raw_abs_pconv (fn _  => in_pconv cv))
noschinl@60117
   222
  ctxt tytenv ct
noschinl@60117
   223
noschinl@60117
   224
fun replace_idents idents t =
noschinl@60117
   225
  let
noschinl@60117
   226
    fun subst ((n1, s)::ss) (t as Free (n2, _)) = if n1 = n2 then s else subst ss t
noschinl@60117
   227
      | subst _ t = t
noschinl@60117
   228
  in Term.map_aterms (subst idents) t end
noschinl@60117
   229
noschinl@60117
   230
fun match_pconv cv (t,fixes) ctxt (tyenv, env_ts) ct =
noschinl@60117
   231
  let
noschinl@60117
   232
    val t' = replace_idents env_ts t
noschinl@60117
   233
    val thy = Proof_Context.theory_of ctxt
noschinl@60117
   234
    val u = Thm.term_of ct
noschinl@60117
   235
noschinl@60117
   236
    fun descend_hole fixes (Abs (_, _, t)) =
noschinl@60117
   237
        (case descend_hole fixes t of
noschinl@60117
   238
          NONE => NONE
noschinl@60117
   239
        | SOME (fix :: fixes', pos) => SOME (fixes', abs_pconv pos fix)
noschinl@60117
   240
        | SOME ([], _) => raise Match (* less fixes than abstractions on path to hole *))
noschinl@60117
   241
      | descend_hole fixes (t as l $ r) =
noschinl@60117
   242
        let val (f, _) = strip_comb t
noschinl@60117
   243
        in
noschinl@60117
   244
          if is_hole f
noschinl@60117
   245
          then SOME (fixes, cv)
noschinl@60117
   246
          else
noschinl@60117
   247
            (case descend_hole fixes l of
noschinl@60117
   248
              SOME (fixes', pos) => SOME (fixes', fun_pconv pos)
noschinl@60117
   249
            | NONE =>
noschinl@60117
   250
              (case descend_hole fixes r of
noschinl@60117
   251
                SOME (fixes', pos) => SOME (fixes', arg_pconv pos)
noschinl@60117
   252
              | NONE => NONE))
noschinl@60117
   253
        end
noschinl@60117
   254
      | descend_hole fixes t =
noschinl@60117
   255
        if is_hole t then SOME (fixes, cv) else NONE
noschinl@60117
   256
noschinl@60117
   257
    val to_hole = descend_hole (rev fixes) #> the_default ([], cv) #> snd
noschinl@60117
   258
  in
noschinl@60117
   259
    case try (Pattern.match thy (apply2 Logic.mk_term (t',u))) (tyenv, Vartab.empty) of
noschinl@60117
   260
      NONE => raise TERM ("match_pconv: Does not match pattern", [t, t',u])
noschinl@60117
   261
    | SOME (tyenv', _) => to_hole t ctxt (tyenv', env_ts) ct
noschinl@60117
   262
  end
noschinl@60117
   263
noschinl@60117
   264
fun rewrs_pconv to thms ctxt (tyenv, env_ts) =
noschinl@60117
   265
  let
noschinl@60117
   266
    fun instantiate_normalize_env ctxt env thm =
noschinl@60079
   267
      let
noschinl@60117
   268
        val prop = Thm.prop_of thm
noschinl@60117
   269
        val norm_type = Envir.norm_type o Envir.type_env
noschinl@60117
   270
        val insts = Term.add_vars prop []
wenzelm@60642
   271
          |> map (fn x as (s, T) =>
wenzelm@60642
   272
              ((s, norm_type env T), Thm.cterm_of ctxt (Envir.norm_term env (Var x))))
noschinl@60117
   273
        val tyinsts = Term.add_tvars prop []
wenzelm@60642
   274
          |> map (fn x => (x, Thm.ctyp_of ctxt (norm_type env (TVar x))))
noschinl@60117
   275
      in Drule.instantiate_normalize (tyinsts, insts) thm end
noschinl@60079
   276
    
noschinl@60117
   277
    fun unify_with_rhs context to env thm =
noschinl@60117
   278
      let
noschinl@60117
   279
        val (_, rhs) = thm |> Thm.concl_of |> Logic.dest_equals
noschinl@60117
   280
        val env' = Pattern.unify context (Logic.mk_term to, Logic.mk_term rhs) env
noschinl@60117
   281
          handle Pattern.Unif => raise NO_TO_MATCH
noschinl@60117
   282
      in env' end
noschinl@60117
   283
    
noschinl@60117
   284
    fun inst_thm_to _ (NONE, _) thm = thm
noschinl@60117
   285
      | inst_thm_to (ctxt : Proof.context) (SOME to, env) thm =
noschinl@60117
   286
          instantiate_normalize_env ctxt (unify_with_rhs (Context.Proof ctxt) to env thm) thm
noschinl@60079
   287
    
noschinl@60117
   288
    fun inst_thm ctxt idents (to, tyenv) thm =
noschinl@60117
   289
      let
noschinl@60117
   290
        (* Replace any identifiers with their corresponding bound variables. *)
noschinl@60117
   291
        val maxidx = Term.maxidx_typs (map (snd o snd) (Vartab.dest tyenv)) 0
noschinl@60117
   292
        val env = Envir.Envir {maxidx = maxidx, tenv = Vartab.empty, tyenv = tyenv}
noschinl@60117
   293
        val maxidx = Envir.maxidx_of env |> fold Term.maxidx_term (the_list to)
noschinl@60117
   294
        val thm' = Thm.incr_indexes (maxidx + 1) thm
noschinl@60117
   295
      in SOME (inst_thm_to ctxt (Option.map (replace_idents idents) to, env) thm') end
noschinl@60117
   296
      handle NO_TO_MATCH => NONE
noschinl@60079
   297
    
noschinl@60117
   298
  in CConv.rewrs_cconv (map_filter (inst_thm ctxt env_ts (to, tyenv)) thms) end
noschinl@60079
   299
noschinl@60117
   300
fun rewrite_conv ctxt (pattern, to) thms ct =
noschinl@60117
   301
  let
noschinl@60117
   302
    fun apply_pat At = judgment_pconv
noschinl@60117
   303
      | apply_pat In = in_pconv
noschinl@60117
   304
      | apply_pat Asm = params_pconv o asms_pconv
noschinl@60117
   305
      | apply_pat Concl = params_pconv o concl_pconv
noschinl@60117
   306
      | apply_pat (For idents) = (fn cv => for_pconv cv (map (apfst SOME) idents))
noschinl@60117
   307
      | apply_pat (Term x) = (fn cv => match_pconv cv (apsnd (map (apfst SOME)) x))
noschinl@60079
   308
noschinl@60117
   309
    val cv = fold_rev apply_pat pattern
noschinl@59739
   310
noschinl@59739
   311
    fun distinct_prems th =
noschinl@59739
   312
      case Seq.pull (distinct_subgoals_tac th) of
noschinl@59739
   313
        NONE => th
noschinl@59739
   314
      | SOME (th', _) => th'
noschinl@59739
   315
noschinl@60117
   316
    val rewrite = rewrs_pconv to (maps (prep_meta_eq ctxt) thms)
noschinl@60117
   317
  in cv rewrite ctxt (Vartab.empty, []) ct |> distinct_prems end
noschinl@59739
   318
noschinl@60079
   319
fun rewrite_export_tac ctxt (pat, pat_ctxt) thms =
noschinl@59739
   320
  let
noschinl@60079
   321
    val export = case pat_ctxt of
noschinl@60079
   322
        NONE => I
noschinl@60079
   323
      | SOME inner => singleton (Proof_Context.export inner ctxt)
noschinl@60117
   324
  in CCONVERSION (export o rewrite_conv ctxt pat thms) end
noschinl@60079
   325
wenzelm@59975
   326
val _ =
wenzelm@59975
   327
  Theory.setup
noschinl@59739
   328
  let
noschinl@59739
   329
    fun mk_fix s = (Binding.name s, NONE, NoSyn)
noschinl@59739
   330
noschinl@59739
   331
    val raw_pattern : (string, binding * string option * mixfix) pattern list parser =
noschinl@59739
   332
      let
noschinl@59739
   333
        val sep = (Args.$$$ "at" >> K At) || (Args.$$$ "in" >> K In)
noschinl@59739
   334
        val atom =  (Args.$$$ "asm" >> K Asm) ||
noschinl@59739
   335
          (Args.$$$ "concl" >> K Concl) ||
noschinl@59739
   336
          (Args.$$$ "for" |-- Args.parens (Scan.optional Parse.fixes []) >> For) ||
noschinl@59739
   337
          (Parse.term >> Term)
noschinl@59739
   338
        val sep_atom = sep -- atom >> (fn (s,a) => [s,a])
noschinl@59739
   339
noschinl@59739
   340
        fun append_default [] = [Concl, In]
noschinl@59739
   341
          | append_default (ps as Term _ :: _) = Concl :: In :: ps
noschinl@60108
   342
          | append_default [For x, In] = [For x, Concl, In]
noschinl@60108
   343
          | append_default (For x :: (ps as In :: Term _:: _)) = For x :: Concl :: ps
noschinl@59739
   344
          | append_default ps = ps
noschinl@59739
   345
wenzelm@61476
   346
      in Scan.repeats sep_atom >> (rev #> append_default) end
noschinl@59739
   347
wenzelm@59975
   348
    fun context_lift (scan : 'a parser) f = fn (context : Context.generic, toks) =>
noschinl@59739
   349
      let
noschinl@59739
   350
        val (r, toks') = scan toks
wenzelm@59975
   351
        val (r', context') = Context.map_proof_result (fn ctxt => f ctxt r) context
wenzelm@59975
   352
      in (r', (context', toks' : Token.T list)) end
noschinl@59739
   353
noschinl@59739
   354
    fun read_fixes fixes ctxt =
noschinl@59739
   355
      let fun read_typ (b, rawT, mx) = (b, Option.map (Syntax.read_typ ctxt) rawT, mx)
noschinl@59739
   356
      in Proof_Context.add_fixes (map read_typ fixes) ctxt end
noschinl@59739
   357
noschinl@59739
   358
    fun prep_pats ctxt (ps : (string, binding * string option * mixfix) pattern list) =
noschinl@59739
   359
      let
noschinl@59739
   360
        fun add_constrs ctxt n (Abs (x, T, t)) =
noschinl@59739
   361
            let
noschinl@59739
   362
              val (x', ctxt') = yield_singleton Proof_Context.add_fixes (mk_fix x) ctxt
noschinl@59739
   363
            in
noschinl@59739
   364
              (case add_constrs ctxt' (n+1) t of
noschinl@59739
   365
                NONE => NONE
noschinl@59739
   366
              | SOME ((ctxt'', n', xs), t') =>
noschinl@59739
   367
                  let
noschinl@59739
   368
                    val U = Type_Infer.mk_param n []
noschinl@59739
   369
                    val u = Type.constraint (U --> dummyT) (Abs (x, T, t'))
noschinl@59739
   370
                  in SOME ((ctxt'', n', (x', U) :: xs), u) end)
noschinl@59739
   371
            end
noschinl@59739
   372
          | add_constrs ctxt n (l $ r) =
noschinl@59739
   373
            (case add_constrs ctxt n l of
noschinl@59739
   374
              SOME (c, l') => SOME (c, l' $ r)
noschinl@59739
   375
            | NONE =>
noschinl@59739
   376
              (case add_constrs ctxt n r of
noschinl@59739
   377
                SOME (c, r') => SOME (c, l $ r')
noschinl@59739
   378
              | NONE => NONE))
noschinl@59739
   379
          | add_constrs ctxt n t =
noschinl@59739
   380
            if is_hole_const t then SOME ((ctxt, n, []), t) else NONE
noschinl@59739
   381
noschinl@59739
   382
        fun prep (Term s) (n, ctxt) =
noschinl@59739
   383
            let
noschinl@59739
   384
              val t = Syntax.parse_term ctxt s
noschinl@59739
   385
              val ((ctxt', n', bs), t') =
noschinl@59739
   386
                the_default ((ctxt, n, []), t) (add_constrs ctxt (n+1) t)
noschinl@59739
   387
            in (Term (t', bs), (n', ctxt')) end
noschinl@59739
   388
          | prep (For ss) (n, ctxt) =
noschinl@59739
   389
            let val (ns, ctxt') = read_fixes ss ctxt
noschinl@59739
   390
            in (For ns, (n, ctxt')) end
noschinl@59739
   391
          | prep At (n,ctxt) = (At, (n, ctxt))
noschinl@59739
   392
          | prep In (n,ctxt) = (In, (n, ctxt))
noschinl@59739
   393
          | prep Concl (n,ctxt) = (Concl, (n, ctxt))
noschinl@59739
   394
          | prep Asm (n,ctxt) = (Asm, (n, ctxt))
noschinl@59739
   395
noschinl@59739
   396
        val (xs, (_, ctxt')) = fold_map prep ps (0, ctxt)
noschinl@59739
   397
noschinl@59739
   398
      in (xs, ctxt') end
noschinl@59739
   399
noschinl@59739
   400
    fun prep_args ctxt (((raw_pats, raw_to), raw_ths)) =
noschinl@59739
   401
      let
noschinl@59739
   402
noschinl@59739
   403
        fun check_terms ctxt ps to =
noschinl@59739
   404
          let
noschinl@59739
   405
            fun safe_chop (0: int) xs = ([], xs)
noschinl@59739
   406
              | safe_chop n (x :: xs) = chop (n - 1) xs |>> cons x
noschinl@59739
   407
              | safe_chop _ _ = raise Match
noschinl@59739
   408
noschinl@59739
   409
            fun reinsert_pat _ (Term (_, cs)) (t :: ts) =
noschinl@59739
   410
                let val (cs', ts') = safe_chop (length cs) ts
noschinl@59739
   411
                in (Term (t, map dest_Free cs'), ts') end
noschinl@59739
   412
              | reinsert_pat _ (Term _) [] = raise Match
noschinl@59739
   413
              | reinsert_pat ctxt (For ss) ts =
noschinl@59739
   414
                let val fixes = map (fn s => (s, Variable.default_type ctxt s)) ss
noschinl@59739
   415
                in (For fixes, ts) end
noschinl@59739
   416
              | reinsert_pat _ At ts = (At, ts)
noschinl@59739
   417
              | reinsert_pat _ In ts = (In, ts)
noschinl@59739
   418
              | reinsert_pat _ Concl ts = (Concl, ts)
noschinl@59739
   419
              | reinsert_pat _ Asm ts = (Asm, ts)
noschinl@59739
   420
noschinl@59739
   421
            fun free_constr (s,T) = Type.constraint T (Free (s, dummyT))
noschinl@59739
   422
            fun mk_free_constrs (Term (t, cs)) = t :: map free_constr cs
noschinl@59739
   423
              | mk_free_constrs _ = []
noschinl@59739
   424
noschinl@60051
   425
            val ts = maps mk_free_constrs ps @ the_list to
noschinl@59739
   426
              |> Syntax.check_terms (hole_syntax ctxt)
noschinl@59739
   427
            val ctxt' = fold Variable.declare_term ts ctxt
noschinl@59739
   428
            val (ps', (to', ts')) = fold_map (reinsert_pat ctxt') ps ts
noschinl@59739
   429
              ||> (fn xs => case to of NONE => (NONE, xs) | SOME _ => (SOME (hd xs), tl xs))
noschinl@59739
   430
            val _ = case ts' of (_ :: _) => raise Match | [] => ()
noschinl@59739
   431
          in ((ps', to'), ctxt') end
noschinl@59739
   432
noschinl@59739
   433
        val (pats, ctxt') = prep_pats ctxt raw_pats
noschinl@59739
   434
noschinl@59739
   435
        val ths = Attrib.eval_thms ctxt' raw_ths
noschinl@59739
   436
        val to = Option.map (Syntax.parse_term ctxt') raw_to
noschinl@59739
   437
noschinl@59739
   438
        val ((pats', to'), ctxt'') = check_terms ctxt' pats to
noschinl@59739
   439
noschinl@60079
   440
      in ((pats', ths, (to', ctxt)), ctxt'') end
noschinl@59739
   441
noschinl@59739
   442
    val to_parser = Scan.option ((Args.$$$ "to") |-- Parse.term)
noschinl@59739
   443
noschinl@59739
   444
    val subst_parser =
noschinl@59739
   445
      let val scan = raw_pattern -- to_parser -- Parse.xthms1
wenzelm@59975
   446
      in context_lift scan prep_args end
noschinl@59739
   447
  in
noschinl@59739
   448
    Method.setup @{binding rewrite} (subst_parser >>
noschinl@60079
   449
      (fn (pattern, inthms, (to, pat_ctxt)) => fn orig_ctxt =>
noschinl@60079
   450
        SIMPLE_METHOD' (rewrite_export_tac orig_ctxt ((pattern, to), SOME pat_ctxt) inthms)))
noschinl@59739
   451
      "single-step rewriting, allowing subterm selection via patterns."
noschinl@59739
   452
  end
noschinl@59739
   453
end