src/HOL/Library/rewrite.ML
author noschinl
Wed Mar 18 13:51:33 2015 +0100 (2015-03-18)
changeset 59739 4ed50ebf5d36
child 59970 e9f73d87d904
permissions -rw-r--r--
added proof method rewrite
noschinl@59739
     1
(* Author: Christoph Traut, Lars Noschinski
noschinl@59739
     2
noschinl@59739
     3
  This is a rewrite method supports subterm-selection based on patterns.
noschinl@59739
     4
noschinl@59739
     5
  The patterns accepted by rewrite are of the following form:
noschinl@59739
     6
    <atom>    ::= <term> | "concl" | "asm" | "for" "(" <names> ")"
noschinl@59739
     7
    <pattern> ::= (in <atom> | at <atom>) [<pattern>]
noschinl@59739
     8
    <args>    ::= [<pattern>] ("to" <term>) <thms>
noschinl@59739
     9
noschinl@59739
    10
  This syntax was clearly inspired by Gonthier's and Tassi's language of
noschinl@59739
    11
  patterns but has diverged significantly during its development.
noschinl@59739
    12
noschinl@59739
    13
  We also allow introduction of identifiers for bound variables,
noschinl@59739
    14
  which can then be used to match arbitary subterms inside abstractions.
noschinl@59739
    15
*)
noschinl@59739
    16
noschinl@59739
    17
signature REWRITE1 = sig
noschinl@59739
    18
  val setup : theory -> theory
noschinl@59739
    19
end
noschinl@59739
    20
noschinl@59739
    21
structure Rewrite : REWRITE1 =
noschinl@59739
    22
struct
noschinl@59739
    23
noschinl@59739
    24
datatype ('a, 'b) pattern = At | In | Term of 'a | Concl | Asm | For of 'b list
noschinl@59739
    25
noschinl@59739
    26
fun map_term_pattern f (Term x) = f x
noschinl@59739
    27
  | map_term_pattern _ (For ss) = (For ss)
noschinl@59739
    28
  | map_term_pattern _ At = At
noschinl@59739
    29
  | map_term_pattern _ In = In
noschinl@59739
    30
  | map_term_pattern _ Concl = Concl
noschinl@59739
    31
  | map_term_pattern _ Asm = Asm
noschinl@59739
    32
noschinl@59739
    33
noschinl@59739
    34
exception NO_TO_MATCH
noschinl@59739
    35
noschinl@59739
    36
fun SEQ_CONCAT (tacq : tactic Seq.seq) : tactic = fn st => Seq.maps (fn tac => tac st) tacq
noschinl@59739
    37
noschinl@59739
    38
(* We rewrite subterms using rewrite conversions. These are conversions
noschinl@59739
    39
   that also take a context and a list of identifiers for bound variables
noschinl@59739
    40
   as parameters. *)
noschinl@59739
    41
type rewrite_conv = Proof.context -> (string * term) list -> conv
noschinl@59739
    42
noschinl@59739
    43
(* To apply such a rewrite conversion to a subterm of our goal, we use
noschinl@59739
    44
   subterm positions, which are just functions that map a rewrite conversion,
noschinl@59739
    45
   working on the top level, to a new rewrite conversion, working on
noschinl@59739
    46
   a specific subterm.
noschinl@59739
    47
noschinl@59739
    48
   During substitution, we are traversing the goal to find subterms that
noschinl@59739
    49
   we can rewrite. For each of these subterms, a subterm position is
noschinl@59739
    50
   created and later used in creating a conversion that we use to try and
noschinl@59739
    51
   rewrite this subterm. *)
noschinl@59739
    52
type subterm_position = rewrite_conv -> rewrite_conv
noschinl@59739
    53
noschinl@59739
    54
(* A focusterm represents a subterm. It is a tuple (t, p), consisting
noschinl@59739
    55
  of the subterm t itself and its subterm position p. *)
noschinl@59739
    56
type focusterm = Type.tyenv * term * subterm_position
noschinl@59739
    57
noschinl@59739
    58
val dummyN = Name.internal "__dummy"
noschinl@59739
    59
val holeN = Name.internal "_hole"
noschinl@59739
    60
noschinl@59739
    61
fun prep_meta_eq ctxt =
noschinl@59739
    62
  Simplifier.mksimps ctxt #> map Drule.zero_var_indexes
noschinl@59739
    63
noschinl@59739
    64
noschinl@59739
    65
(* rewrite conversions *)
noschinl@59739
    66
noschinl@59739
    67
fun abs_rewr_cconv ident : subterm_position =
noschinl@59739
    68
  let
noschinl@59739
    69
    fun add_ident NONE _ l = l
noschinl@59739
    70
      | add_ident (SOME name) ct l = (name, Thm.term_of ct) :: l
noschinl@59739
    71
    fun inner rewr ctxt idents = CConv.abs_cconv (fn (ct, ctxt) => rewr ctxt (add_ident ident ct idents)) ctxt
noschinl@59739
    72
  in inner end
noschinl@59739
    73
val fun_rewr_cconv : subterm_position = fn rewr => CConv.fun_cconv oo rewr
noschinl@59739
    74
val arg_rewr_cconv : subterm_position = fn rewr => CConv.arg_cconv oo rewr
noschinl@59739
    75
noschinl@59739
    76
noschinl@59739
    77
(* focus terms *)
noschinl@59739
    78
noschinl@59739
    79
fun ft_abs ctxt (s,T) (tyenv, u, pos) =
noschinl@59739
    80
  case try (fastype_of #> dest_funT) u of
noschinl@59739
    81
    NONE => raise TERM ("ft_abs: no function type", [u])
noschinl@59739
    82
  | SOME (U, _) =>
noschinl@59739
    83
  let
noschinl@59739
    84
    val tyenv' = if T = dummyT then tyenv else Sign.typ_match (Proof_Context.theory_of ctxt) (T, U) tyenv
noschinl@59739
    85
    val x = Free (the_default (Name.internal dummyN) s, Envir.norm_type tyenv' T)
noschinl@59739
    86
    val eta_expand_cconv = CConv.rewr_cconv @{thm eta_expand}
noschinl@59739
    87
    fun eta_expand rewr ctxt bounds = eta_expand_cconv then_conv rewr ctxt bounds
noschinl@59739
    88
    val (u', pos') =
noschinl@59739
    89
      case u of
noschinl@59739
    90
        Abs (_,_,t') => (subst_bound (x, t'), pos o abs_rewr_cconv s)
noschinl@59739
    91
      | _ => (u $ x, pos o eta_expand o abs_rewr_cconv s)
noschinl@59739
    92
  in (tyenv', u', pos') end
noschinl@59739
    93
  handle Pattern.MATCH => raise TYPE ("ft_abs: types don't match", [T,U], [u])
noschinl@59739
    94
noschinl@59739
    95
fun ft_fun _ (tyenv, l $ _, pos) = (tyenv, l, pos o fun_rewr_cconv)
noschinl@59739
    96
  | ft_fun ctxt (ft as (_, Abs (_, T, _ $ Bound 0), _)) = (ft_fun ctxt o ft_abs ctxt (NONE, T)) ft
noschinl@59739
    97
  | ft_fun _ (_, t, _) = raise TERM ("ft_fun", [t])
noschinl@59739
    98
noschinl@59739
    99
fun ft_arg _ (tyenv, _ $ r, pos) = (tyenv, r, pos o arg_rewr_cconv)
noschinl@59739
   100
  | ft_arg ctxt (ft as (_, Abs (_, T, _ $ Bound 0), _)) = (ft_arg ctxt o ft_abs ctxt (NONE, T)) ft
noschinl@59739
   101
  | ft_arg _ (_, t, _) = raise TERM ("ft_arg", [t])
noschinl@59739
   102
noschinl@59739
   103
(* Move to B in !!x_1 ... x_n. B. Do not eta-expand *)
noschinl@59739
   104
fun ft_params ctxt (ft as (_, t, _) : focusterm) =
noschinl@59739
   105
  case t of
noschinl@59739
   106
    Const (@{const_name "Pure.all"}, _) $ Abs (_,T,_) =>
noschinl@59739
   107
      (ft_params ctxt o ft_abs ctxt (NONE, T) o ft_arg ctxt) ft
noschinl@59739
   108
  | Const (@{const_name "Pure.all"}, _) =>
noschinl@59739
   109
      (ft_params ctxt o ft_arg ctxt) ft
noschinl@59739
   110
  | _ => ft
noschinl@59739
   111
noschinl@59739
   112
fun ft_all ctxt ident (ft as (_, Const (@{const_name "Pure.all"}, T) $ _, _) : focusterm) =
noschinl@59739
   113
    let
noschinl@59739
   114
      val def_U = T |> dest_funT |> fst |> dest_funT |> fst
noschinl@59739
   115
      val ident' = apsnd (the_default (def_U)) ident
noschinl@59739
   116
    in (ft_abs ctxt ident' o ft_arg ctxt) ft end
noschinl@59739
   117
  | ft_all _ _ (_, t, _) = raise TERM ("ft_all", [t])
noschinl@59739
   118
noschinl@59739
   119
fun ft_for ctxt idents (ft as (_, t, _) : focusterm) =
noschinl@59739
   120
  let
noschinl@59739
   121
    fun f rev_idents (Const (@{const_name "Pure.all"}, _) $ t) =
noschinl@59739
   122
        let
noschinl@59739
   123
         val (rev_idents', desc) = f rev_idents (case t of Abs (_,_,u) => u | _ => t)
noschinl@59739
   124
        in
noschinl@59739
   125
          case rev_idents' of
noschinl@59739
   126
            [] => ([], desc o ft_all ctxt (NONE, NONE))
noschinl@59739
   127
          | (x :: xs) => (xs , desc o ft_all ctxt x)
noschinl@59739
   128
        end
noschinl@59739
   129
      | f rev_idents _ = (rev_idents, I)
noschinl@59739
   130
  in case f (rev idents) t of
noschinl@59739
   131
      ([], ft') => SOME (ft' ft)
noschinl@59739
   132
    | _ => NONE
noschinl@59739
   133
  end
noschinl@59739
   134
noschinl@59739
   135
fun ft_concl ctxt (ft as (_, t, _) : focusterm) =
noschinl@59739
   136
  case t of
noschinl@59739
   137
    (Const (@{const_name "Pure.imp"}, _) $ _) $ _ => (ft_concl ctxt o ft_arg ctxt) ft
noschinl@59739
   138
  | _ => ft
noschinl@59739
   139
noschinl@59739
   140
fun ft_assm ctxt (ft as (_, t, _) : focusterm) =
noschinl@59739
   141
  case t of
noschinl@59739
   142
    (Const (@{const_name "Pure.imp"}, _) $ _) $ _ => (ft_concl ctxt o ft_arg ctxt o ft_fun ctxt) ft
noschinl@59739
   143
  | _ => raise TERM ("ft_assm", [t])
noschinl@59739
   144
noschinl@59739
   145
fun ft_judgment ctxt (ft as (_, t, _) : focusterm) =
noschinl@59739
   146
  if Object_Logic.is_judgment (Proof_Context.theory_of ctxt) t
noschinl@59739
   147
  then ft_arg ctxt ft
noschinl@59739
   148
  else ft
noschinl@59739
   149
noschinl@59739
   150
noschinl@59739
   151
(* Return a lazy sequenze of all subterms of the focusterm for which
noschinl@59739
   152
   the condition holds. *)
noschinl@59739
   153
fun find_subterms ctxt condition (ft as (_, t, _) : focusterm) =
noschinl@59739
   154
  let
noschinl@59739
   155
    val recurse = find_subterms ctxt condition
noschinl@59739
   156
    val recursive_matches = case t of
noschinl@59739
   157
        _ $ _ => Seq.append (ft |> ft_fun ctxt |> recurse) (ft |> ft_arg ctxt |> recurse)
noschinl@59739
   158
      | Abs (_,T,_) => ft |> ft_abs ctxt (NONE, T) |> recurse
noschinl@59739
   159
      | _ => Seq.empty
noschinl@59739
   160
  in
noschinl@59739
   161
    (* If the condition is met, then the current focusterm is part of the
noschinl@59739
   162
       sequence of results. Otherwise, only the results of the recursive
noschinl@59739
   163
       application are. *)
noschinl@59739
   164
    if condition ft
noschinl@59739
   165
    then Seq.cons ft recursive_matches
noschinl@59739
   166
    else recursive_matches
noschinl@59739
   167
  end
noschinl@59739
   168
noschinl@59739
   169
(* Find all subterms that might be a valid point to apply a rule. *)
noschinl@59739
   170
fun valid_match_points ctxt =
noschinl@59739
   171
  let
noschinl@59739
   172
    fun is_valid (l $ _) = is_valid l
noschinl@59739
   173
      | is_valid (Abs (_, _, a)) = is_valid a
noschinl@59739
   174
      | is_valid (Var _) = false
noschinl@59739
   175
      | is_valid (Bound _) = false
noschinl@59739
   176
      | is_valid _ = true
noschinl@59739
   177
  in
noschinl@59739
   178
    find_subterms ctxt (#2 #> is_valid )
noschinl@59739
   179
  end
noschinl@59739
   180
noschinl@59739
   181
fun is_hole (Var ((name, _), _)) = (name = holeN)
noschinl@59739
   182
  | is_hole _ = false
noschinl@59739
   183
noschinl@59739
   184
fun is_hole_const (Const (@{const_name rewrite_HOLE}, _)) = true
noschinl@59739
   185
  | is_hole_const _ = false
noschinl@59739
   186
noschinl@59739
   187
val hole_syntax =
noschinl@59739
   188
  let
noschinl@59739
   189
    (* Modified variant of Term.replace_hole *)
noschinl@59739
   190
    fun replace_hole Ts (Const (@{const_name rewrite_HOLE}, T)) i =
noschinl@59739
   191
          (list_comb (Var ((holeN, i), Ts ---> T), map_range Bound (length Ts)), i + 1)
noschinl@59739
   192
      | replace_hole Ts (Abs (x, T, t)) i =
noschinl@59739
   193
          let val (t', i') = replace_hole (T :: Ts) t i
noschinl@59739
   194
          in (Abs (x, T, t'), i') end
noschinl@59739
   195
      | replace_hole Ts (t $ u) i =
noschinl@59739
   196
          let
noschinl@59739
   197
            val (t', i') = replace_hole Ts t i
noschinl@59739
   198
            val (u', i'') = replace_hole Ts u i'
noschinl@59739
   199
          in (t' $ u', i'') end
noschinl@59739
   200
      | replace_hole _ a i = (a, i)
noschinl@59739
   201
    fun prep_holes ts = #1 (fold_map (replace_hole []) ts 1)
noschinl@59739
   202
  in
noschinl@59739
   203
    Context.proof_map (Syntax_Phases.term_check 101 "hole_expansion" (K prep_holes))
noschinl@59739
   204
    #> Proof_Context.set_mode Proof_Context.mode_pattern
noschinl@59739
   205
  end
noschinl@59739
   206
noschinl@59739
   207
(* Find a subterm of the focusterm matching the pattern. *)
noschinl@59739
   208
fun find_matches ctxt pattern_list =
noschinl@59739
   209
  let
noschinl@59739
   210
    fun move_term ctxt (t, off) (ft : focusterm) =
noschinl@59739
   211
      let
noschinl@59739
   212
        val thy = Proof_Context.theory_of ctxt
noschinl@59739
   213
noschinl@59739
   214
        val eta_expands =
noschinl@59739
   215
          let val (_, ts) = strip_comb t
noschinl@59739
   216
          in map fastype_of (snd (take_suffix is_Var ts)) end
noschinl@59739
   217
noschinl@59739
   218
        fun do_match (tyenv, u, pos) =
noschinl@59739
   219
          case try (Pattern.match thy (t,u)) (tyenv, Vartab.empty) of
noschinl@59739
   220
            NONE => NONE
noschinl@59739
   221
          | SOME (tyenv', _) => SOME (off (tyenv', u, pos))
noschinl@59739
   222
noschinl@59739
   223
        fun match_argT T u =
noschinl@59739
   224
          let val (U, _) = dest_funT (fastype_of u)
noschinl@59739
   225
          in try (Sign.typ_match thy (T,U)) end
noschinl@59739
   226
          handle TYPE _ => K NONE
noschinl@59739
   227
noschinl@59739
   228
        fun desc [] ft = do_match ft
noschinl@59739
   229
          | desc (T :: Ts) (ft as (tyenv , u, pos)) =
noschinl@59739
   230
            case do_match ft of
noschinl@59739
   231
              NONE =>
noschinl@59739
   232
                (case match_argT T u tyenv of
noschinl@59739
   233
                  NONE => NONE
noschinl@59739
   234
                | SOME tyenv' => desc Ts (ft_abs ctxt (NONE, T) (tyenv', u, pos)))
noschinl@59739
   235
            | SOME ft => SOME ft
noschinl@59739
   236
      in desc eta_expands ft end
noschinl@59739
   237
noschinl@59739
   238
    fun seq_unfold f ft =
noschinl@59739
   239
      case f ft of
noschinl@59739
   240
        NONE => Seq.empty
noschinl@59739
   241
      | SOME ft' => Seq.cons ft' (seq_unfold f ft')
noschinl@59739
   242
noschinl@59739
   243
    fun apply_pat At = Seq.map (ft_judgment ctxt)
noschinl@59739
   244
      | apply_pat In = Seq.maps (valid_match_points ctxt)
noschinl@59739
   245
      | apply_pat Asm = Seq.maps (seq_unfold (try (ft_assm ctxt)) o ft_params ctxt)
noschinl@59739
   246
      | apply_pat Concl = Seq.map (ft_concl ctxt o ft_params ctxt)
noschinl@59739
   247
      | apply_pat (For idents) = Seq.map_filter ((ft_for ctxt (map (apfst SOME) idents)))
noschinl@59739
   248
      | apply_pat (Term x) = Seq.map_filter ( (move_term ctxt x))
noschinl@59739
   249
noschinl@59739
   250
    fun apply_pats ft = ft
noschinl@59739
   251
      |> Seq.single
noschinl@59739
   252
      |> fold apply_pat pattern_list
noschinl@59739
   253
noschinl@59739
   254
  in
noschinl@59739
   255
    apply_pats
noschinl@59739
   256
  end
noschinl@59739
   257
noschinl@59739
   258
fun instantiate_normalize_env ctxt env thm =
noschinl@59739
   259
  let
noschinl@59739
   260
    fun certs f = map (apply2 (f ctxt))
noschinl@59739
   261
    val prop = Thm.prop_of thm
noschinl@59739
   262
    val norm_type = Envir.norm_type o Envir.type_env
noschinl@59739
   263
    val insts = Term.add_vars prop []
noschinl@59739
   264
      |> map (fn x as (s,T) => (Var (s, norm_type env T), Envir.norm_term env (Var x)))
noschinl@59739
   265
      |> certs Thm.cterm_of
noschinl@59739
   266
    val tyinsts = Term.add_tvars prop []
noschinl@59739
   267
      |> map (fn x => (TVar x, norm_type env (TVar x)))
noschinl@59739
   268
      |> certs Thm.ctyp_of
noschinl@59739
   269
  in Drule.instantiate_normalize (tyinsts, insts) thm end
noschinl@59739
   270
noschinl@59739
   271
fun unify_with_rhs context to env thm =
noschinl@59739
   272
  let
noschinl@59739
   273
    val (_, rhs) = thm |> Thm.concl_of |> Logic.dest_equals
noschinl@59739
   274
    val env' = Pattern.unify context (Logic.mk_term to, Logic.mk_term rhs) env
noschinl@59739
   275
      handle Pattern.Unif => raise NO_TO_MATCH
noschinl@59739
   276
  in env' end
noschinl@59739
   277
noschinl@59739
   278
fun inst_thm_to _ (NONE, _) thm = thm
noschinl@59739
   279
  | inst_thm_to (ctxt : Proof.context) (SOME to, env) thm =
noschinl@59739
   280
      instantiate_normalize_env ctxt (unify_with_rhs (Context.Proof ctxt) to env thm) thm
noschinl@59739
   281
noschinl@59739
   282
fun inst_thm ctxt idents (to, tyenv) thm =
noschinl@59739
   283
  let
noschinl@59739
   284
    (* Replace any identifiers with their corresponding bound variables. *)
noschinl@59739
   285
    val maxidx = Term.maxidx_typs (map (snd o snd) (Vartab.dest tyenv)) 0
noschinl@59739
   286
    val env = Envir.Envir {maxidx = maxidx, tenv = Vartab.empty, tyenv = tyenv}
noschinl@59739
   287
    val replace_idents =
noschinl@59739
   288
      let
noschinl@59739
   289
        fun subst ((n1, s)::ss) (t as Free (n2, _)) = if n1 = n2 then s else subst ss t
noschinl@59739
   290
          | subst _ t = t
noschinl@59739
   291
      in Term.map_aterms (subst idents) end
noschinl@59739
   292
noschinl@59739
   293
    val maxidx = Envir.maxidx_of env |> fold Term.maxidx_term (map_filter I [to])
noschinl@59739
   294
    val thm' = Thm.incr_indexes (maxidx + 1) thm
noschinl@59739
   295
  in SOME (inst_thm_to ctxt (Option.map replace_idents to, env) thm') end
noschinl@59739
   296
  handle NO_TO_MATCH => NONE
noschinl@59739
   297
noschinl@59739
   298
(* Rewrite in subgoal i. *)
noschinl@59739
   299
fun rewrite_goal_with_thm ctxt (pattern, (to, orig_ctxt)) rules = SUBGOAL (fn (t,i) =>
noschinl@59739
   300
  let
noschinl@59739
   301
    val matches = find_matches ctxt pattern (Vartab.empty, t, I)
noschinl@59739
   302
noschinl@59739
   303
    fun rewrite_conv insty ctxt bounds =
noschinl@59739
   304
      CConv.rewrs_cconv (map_filter (inst_thm ctxt bounds insty) rules)
noschinl@59739
   305
noschinl@59739
   306
    val export = singleton (Proof_Context.export ctxt orig_ctxt)
noschinl@59739
   307
noschinl@59739
   308
    fun distinct_prems th =
noschinl@59739
   309
      case Seq.pull (distinct_subgoals_tac th) of
noschinl@59739
   310
        NONE => th
noschinl@59739
   311
      | SOME (th', _) => th'
noschinl@59739
   312
noschinl@59739
   313
    fun tac (tyenv, _, position) = CCONVERSION
noschinl@59739
   314
      (distinct_prems o export o position (rewrite_conv (to, tyenv)) ctxt []) i
noschinl@59739
   315
  in
noschinl@59739
   316
    SEQ_CONCAT (Seq.map tac matches)
noschinl@59739
   317
  end)
noschinl@59739
   318
noschinl@59739
   319
fun rewrite_tac ctxt pattern thms =
noschinl@59739
   320
  let
noschinl@59739
   321
    val thms' = maps (prep_meta_eq ctxt) thms
noschinl@59739
   322
    val tac = rewrite_goal_with_thm ctxt pattern thms'
noschinl@59739
   323
  in tac end
noschinl@59739
   324
noschinl@59739
   325
val setup =
noschinl@59739
   326
  let
noschinl@59739
   327
noschinl@59739
   328
    fun mk_fix s = (Binding.name s, NONE, NoSyn)
noschinl@59739
   329
noschinl@59739
   330
    val raw_pattern : (string, binding * string option * mixfix) pattern list parser =
noschinl@59739
   331
      let
noschinl@59739
   332
        val sep = (Args.$$$ "at" >> K At) || (Args.$$$ "in" >> K In)
noschinl@59739
   333
        val atom =  (Args.$$$ "asm" >> K Asm) ||
noschinl@59739
   334
          (Args.$$$ "concl" >> K Concl) ||
noschinl@59739
   335
          (Args.$$$ "for" |-- Args.parens (Scan.optional Parse.fixes []) >> For) ||
noschinl@59739
   336
          (Parse.term >> Term)
noschinl@59739
   337
        val sep_atom = sep -- atom >> (fn (s,a) => [s,a])
noschinl@59739
   338
noschinl@59739
   339
        fun append_default [] = [Concl, In]
noschinl@59739
   340
          | append_default (ps as Term _ :: _) = Concl :: In :: ps
noschinl@59739
   341
          | append_default ps = ps
noschinl@59739
   342
noschinl@59739
   343
      in Scan.repeat sep_atom >> (flat #> rev #> append_default) end
noschinl@59739
   344
noschinl@59739
   345
    fun ctxt_lift (scan : 'a parser) f = fn (ctxt : Context.generic, toks) =>
noschinl@59739
   346
      let
noschinl@59739
   347
        val (r, toks') = scan toks
noschinl@59739
   348
        val (r', ctxt') = Context.map_proof_result (fn ctxt => f ctxt r) ctxt
noschinl@59739
   349
      in (r', (ctxt', toks' : Token.T list))end
noschinl@59739
   350
noschinl@59739
   351
    fun read_fixes fixes ctxt =
noschinl@59739
   352
      let fun read_typ (b, rawT, mx) = (b, Option.map (Syntax.read_typ ctxt) rawT, mx)
noschinl@59739
   353
      in Proof_Context.add_fixes (map read_typ fixes) ctxt end
noschinl@59739
   354
noschinl@59739
   355
    fun prep_pats ctxt (ps : (string, binding * string option * mixfix) pattern list) =
noschinl@59739
   356
      let
noschinl@59739
   357
noschinl@59739
   358
        fun add_constrs ctxt n (Abs (x, T, t)) =
noschinl@59739
   359
            let
noschinl@59739
   360
              val (x', ctxt') = yield_singleton Proof_Context.add_fixes (mk_fix x) ctxt
noschinl@59739
   361
            in
noschinl@59739
   362
              (case add_constrs ctxt' (n+1) t of
noschinl@59739
   363
                NONE => NONE
noschinl@59739
   364
              | SOME ((ctxt'', n', xs), t') =>
noschinl@59739
   365
                  let
noschinl@59739
   366
                    val U = Type_Infer.mk_param n []
noschinl@59739
   367
                    val u = Type.constraint (U --> dummyT) (Abs (x, T, t'))
noschinl@59739
   368
                  in SOME ((ctxt'', n', (x', U) :: xs), u) end)
noschinl@59739
   369
            end
noschinl@59739
   370
          | add_constrs ctxt n (l $ r) =
noschinl@59739
   371
            (case add_constrs ctxt n l of
noschinl@59739
   372
              SOME (c, l') => SOME (c, l' $ r)
noschinl@59739
   373
            | NONE =>
noschinl@59739
   374
              (case add_constrs ctxt n r of
noschinl@59739
   375
                SOME (c, r') => SOME (c, l $ r')
noschinl@59739
   376
              | NONE => NONE))
noschinl@59739
   377
          | add_constrs ctxt n t =
noschinl@59739
   378
            if is_hole_const t then SOME ((ctxt, n, []), t) else NONE
noschinl@59739
   379
noschinl@59739
   380
        fun prep (Term s) (n, ctxt) =
noschinl@59739
   381
            let
noschinl@59739
   382
              val t = Syntax.parse_term ctxt s
noschinl@59739
   383
              val ((ctxt', n', bs), t') =
noschinl@59739
   384
                the_default ((ctxt, n, []), t) (add_constrs ctxt (n+1) t)
noschinl@59739
   385
            in (Term (t', bs), (n', ctxt')) end
noschinl@59739
   386
          | prep (For ss) (n, ctxt) =
noschinl@59739
   387
            let val (ns, ctxt') = read_fixes ss ctxt
noschinl@59739
   388
            in (For ns, (n, ctxt')) end
noschinl@59739
   389
          | prep At (n,ctxt) = (At, (n, ctxt))
noschinl@59739
   390
          | prep In (n,ctxt) = (In, (n, ctxt))
noschinl@59739
   391
          | prep Concl (n,ctxt) = (Concl, (n, ctxt))
noschinl@59739
   392
          | prep Asm (n,ctxt) = (Asm, (n, ctxt))
noschinl@59739
   393
noschinl@59739
   394
        val (xs, (_, ctxt')) = fold_map prep ps (0, ctxt)
noschinl@59739
   395
noschinl@59739
   396
      in (xs, ctxt') end
noschinl@59739
   397
noschinl@59739
   398
    fun prep_args ctxt (((raw_pats, raw_to), raw_ths)) =
noschinl@59739
   399
      let
noschinl@59739
   400
noschinl@59739
   401
        fun interpret_term_patterns ctxt =
noschinl@59739
   402
          let
noschinl@59739
   403
noschinl@59739
   404
            fun descend_hole fixes (Abs (_, _, t)) =
noschinl@59739
   405
                (case descend_hole fixes t of
noschinl@59739
   406
                  NONE => NONE
noschinl@59739
   407
                | SOME (fix :: fixes', pos) => SOME (fixes', pos o ft_abs ctxt (apfst SOME fix))
noschinl@59739
   408
                | SOME ([], _) => raise Match (* XXX -- check phases modified binding *))
noschinl@59739
   409
              | descend_hole fixes (t as l $ r) =
noschinl@59739
   410
                let val (f, _) = strip_comb t
noschinl@59739
   411
                in
noschinl@59739
   412
                  if is_hole f
noschinl@59739
   413
                  then SOME (fixes, I)
noschinl@59739
   414
                  else
noschinl@59739
   415
                    (case descend_hole fixes l of
noschinl@59739
   416
                      SOME (fixes', pos) => SOME (fixes', pos o ft_fun ctxt)
noschinl@59739
   417
                    | NONE =>
noschinl@59739
   418
                      (case descend_hole fixes r of
noschinl@59739
   419
                        SOME (fixes', pos) => SOME (fixes', pos o ft_arg ctxt)
noschinl@59739
   420
                      | NONE => NONE))
noschinl@59739
   421
                end
noschinl@59739
   422
              | descend_hole fixes t =
noschinl@59739
   423
                if is_hole t then SOME (fixes, I) else NONE
noschinl@59739
   424
noschinl@59739
   425
            fun f (t, fixes) = Term (t, (descend_hole (rev fixes) #> the_default ([], I) #> snd) t)
noschinl@59739
   426
noschinl@59739
   427
          in map (map_term_pattern f) end
noschinl@59739
   428
noschinl@59739
   429
        fun check_terms ctxt ps to =
noschinl@59739
   430
          let
noschinl@59739
   431
            fun safe_chop (0: int) xs = ([], xs)
noschinl@59739
   432
              | safe_chop n (x :: xs) = chop (n - 1) xs |>> cons x
noschinl@59739
   433
              | safe_chop _ _ = raise Match
noschinl@59739
   434
noschinl@59739
   435
            fun reinsert_pat _ (Term (_, cs)) (t :: ts) =
noschinl@59739
   436
                let val (cs', ts') = safe_chop (length cs) ts
noschinl@59739
   437
                in (Term (t, map dest_Free cs'), ts') end
noschinl@59739
   438
              | reinsert_pat _ (Term _) [] = raise Match
noschinl@59739
   439
              | reinsert_pat ctxt (For ss) ts =
noschinl@59739
   440
                let val fixes = map (fn s => (s, Variable.default_type ctxt s)) ss
noschinl@59739
   441
                in (For fixes, ts) end
noschinl@59739
   442
              | reinsert_pat _ At ts = (At, ts)
noschinl@59739
   443
              | reinsert_pat _ In ts = (In, ts)
noschinl@59739
   444
              | reinsert_pat _ Concl ts = (Concl, ts)
noschinl@59739
   445
              | reinsert_pat _ Asm ts = (Asm, ts)
noschinl@59739
   446
noschinl@59739
   447
            fun free_constr (s,T) = Type.constraint T (Free (s, dummyT))
noschinl@59739
   448
            fun mk_free_constrs (Term (t, cs)) = t :: map free_constr cs
noschinl@59739
   449
              | mk_free_constrs _ = []
noschinl@59739
   450
noschinl@59739
   451
            val ts = maps mk_free_constrs ps @ map_filter I [to]
noschinl@59739
   452
              |> Syntax.check_terms (hole_syntax ctxt)
noschinl@59739
   453
            val ctxt' = fold Variable.declare_term ts ctxt
noschinl@59739
   454
            val (ps', (to', ts')) = fold_map (reinsert_pat ctxt') ps ts
noschinl@59739
   455
              ||> (fn xs => case to of NONE => (NONE, xs) | SOME _ => (SOME (hd xs), tl xs))
noschinl@59739
   456
            val _ = case ts' of (_ :: _) => raise Match | [] => ()
noschinl@59739
   457
          in ((ps', to'), ctxt') end
noschinl@59739
   458
noschinl@59739
   459
        val (pats, ctxt') = prep_pats ctxt raw_pats
noschinl@59739
   460
noschinl@59739
   461
        val ths = Attrib.eval_thms ctxt' raw_ths
noschinl@59739
   462
        val to = Option.map (Syntax.parse_term ctxt') raw_to
noschinl@59739
   463
noschinl@59739
   464
        val ((pats', to'), ctxt'') = check_terms ctxt' pats to
noschinl@59739
   465
        val pats'' = interpret_term_patterns ctxt'' pats'
noschinl@59739
   466
noschinl@59739
   467
      in ((pats'', ths, (to', ctxt)), ctxt'') end
noschinl@59739
   468
noschinl@59739
   469
    val to_parser = Scan.option ((Args.$$$ "to") |-- Parse.term)
noschinl@59739
   470
noschinl@59739
   471
    val subst_parser =
noschinl@59739
   472
      let val scan = raw_pattern -- to_parser -- Parse.xthms1
noschinl@59739
   473
      in ctxt_lift scan prep_args end
noschinl@59739
   474
  in
noschinl@59739
   475
    Method.setup @{binding rewrite} (subst_parser >>
noschinl@59739
   476
      (fn (pattern, inthms, inst) => fn ctxt => SIMPLE_METHOD' (rewrite_tac ctxt (pattern, inst) inthms)))
noschinl@59739
   477
      "single-step rewriting, allowing subterm selection via patterns."
noschinl@59739
   478
  end
noschinl@59739
   479
end