src/Tools/eqsubst.ML
author wenzelm
Tue Aug 09 15:50:13 2011 +0200 (2011-08-09)
changeset 44095 3ea5fae095dc
parent 43324 2b47822868e4
child 49339 d1fcb4de8349
permissions -rw-r--r--
misc tuning and simplification;
wenzelm@30160
     1
(*  Title:      Tools/eqsubst.ML
wenzelm@29269
     2
    Author:     Lucas Dixon, University of Edinburgh
paulson@15481
     3
wenzelm@18598
     4
A proof method to perform a substiution using an equation.
wenzelm@18598
     5
*)
dixon@15538
     6
wenzelm@18591
     7
signature EQSUBST =
paulson@15481
     8
sig
wenzelm@29269
     9
  (* a type abbreviation for match information *)
dixon@19871
    10
  type match =
dixon@19871
    11
       ((indexname * (sort * typ)) list (* type instantiations *)
dixon@19871
    12
        * (indexname * (typ * term)) list) (* term instantiations *)
dixon@19871
    13
       * (string * typ) list (* fake named type abs env *)
dixon@19871
    14
       * (string * typ) list (* type abs env *)
dixon@19871
    15
       * term (* outer term *)
dixon@19871
    16
dixon@19871
    17
  type searchinfo =
dixon@19871
    18
       theory
dixon@19871
    19
       * int (* maxidx *)
dixon@19871
    20
       * Zipper.T (* focusterm to search under *)
dixon@19871
    21
dixon@19871
    22
    exception eqsubst_occL_exp of
wenzelm@31301
    23
       string * int list * thm list * int * thm
dixon@19871
    24
    
dixon@19871
    25
    (* low level substitution functions *)
dixon@19871
    26
    val apply_subst_in_asm :
dixon@19871
    27
       int ->
wenzelm@31301
    28
       thm ->
wenzelm@31301
    29
       thm ->
wenzelm@31301
    30
       (cterm list * int * 'a * thm) * match -> thm Seq.seq
dixon@19871
    31
    val apply_subst_in_concl :
dixon@19871
    32
       int ->
wenzelm@31301
    33
       thm ->
wenzelm@31301
    34
       cterm list * thm ->
wenzelm@31301
    35
       thm -> match -> thm Seq.seq
dixon@19871
    36
dixon@19871
    37
    (* matching/unification within zippers *)
dixon@19871
    38
    val clean_match_z :
wenzelm@31301
    39
       theory -> term -> Zipper.T -> match option
dixon@19871
    40
    val clean_unify_z :
wenzelm@31301
    41
       theory -> int -> term -> Zipper.T -> match Seq.seq
dixon@19871
    42
dixon@19871
    43
    (* skipping things in seq seq's *)
dixon@19871
    44
dixon@19871
    45
   (* skipping non-empty sub-sequences but when we reach the end
dixon@19871
    46
      of the seq, remembering how much we have left to skip. *)
dixon@19871
    47
    datatype 'a skipseq = SkipMore of int
dixon@19871
    48
      | SkipSeq of 'a Seq.seq Seq.seq;
dixon@19871
    49
dixon@19871
    50
    val skip_first_asm_occs_search :
dixon@19871
    51
       ('a -> 'b -> 'c Seq.seq Seq.seq) ->
dixon@19871
    52
       'a -> int -> 'b -> 'c skipseq
dixon@19871
    53
    val skip_first_occs_search :
dixon@19871
    54
       int -> ('a -> 'b -> 'c Seq.seq Seq.seq) -> 'a -> 'b -> 'c Seq.seq
dixon@19871
    55
    val skipto_skipseq : int -> 'a Seq.seq Seq.seq -> 'a skipseq
dixon@19871
    56
dixon@19871
    57
    (* tactics *)
dixon@19871
    58
    val eqsubst_asm_tac :
dixon@19871
    59
       Proof.context ->
wenzelm@31301
    60
       int list -> thm list -> int -> tactic
dixon@19871
    61
    val eqsubst_asm_tac' :
dixon@19871
    62
       Proof.context ->
wenzelm@31301
    63
       (searchinfo -> int -> term -> match skipseq) ->
wenzelm@31301
    64
       int -> thm -> int -> tactic
dixon@19871
    65
    val eqsubst_tac :
dixon@19871
    66
       Proof.context ->
dixon@22727
    67
       int list -> (* list of occurences to rewrite, use [0] for any *)
wenzelm@31301
    68
       thm list -> int -> tactic
dixon@19871
    69
    val eqsubst_tac' :
dixon@22727
    70
       Proof.context -> (* proof context *)
wenzelm@31301
    71
       (searchinfo -> term -> match Seq.seq) (* search function *)
wenzelm@31301
    72
       -> thm (* equation theorem to rewrite with *)
dixon@22727
    73
       -> int (* subgoal number in goal theorem *)
wenzelm@31301
    74
       -> thm (* goal theorem *)
wenzelm@31301
    75
       -> thm Seq.seq (* rewritten goal theorem *)
dixon@19871
    76
dixon@19871
    77
dixon@19871
    78
    val fakefree_badbounds :
wenzelm@31301
    79
       (string * typ) list ->
wenzelm@31301
    80
       term ->
wenzelm@31301
    81
       (string * typ) list * (string * typ) list * term
dixon@19871
    82
dixon@19871
    83
    val mk_foo_match :
wenzelm@31301
    84
       (term -> term) ->
wenzelm@31301
    85
       ('a * typ) list -> term -> term
dixon@19871
    86
dixon@19871
    87
    (* preparing substitution *)
wenzelm@31301
    88
    val prep_meta_eq : Proof.context -> thm -> thm list
dixon@19871
    89
    val prep_concl_subst :
wenzelm@31301
    90
       int -> thm -> (cterm list * thm) * searchinfo
dixon@19871
    91
    val prep_subst_in_asm :
wenzelm@31301
    92
       int -> thm -> int ->
wenzelm@31301
    93
       (cterm list * int * int * thm) * searchinfo
dixon@19871
    94
    val prep_subst_in_asms :
wenzelm@31301
    95
       int -> thm ->
wenzelm@31301
    96
       ((cterm list * int * int * thm) * searchinfo) list
dixon@19871
    97
    val prep_zipper_match :
wenzelm@31301
    98
       Zipper.T -> term * ((string * typ) list * (string * typ) list * term)
dixon@19871
    99
dixon@19871
   100
    (* search for substitutions *)
dixon@19871
   101
    val valid_match_start : Zipper.T -> bool
dixon@19871
   102
    val search_lr_all : Zipper.T -> Zipper.T Seq.seq
dixon@19871
   103
    val search_lr_valid : (Zipper.T -> bool) -> Zipper.T -> Zipper.T Seq.seq
dixon@19871
   104
    val searchf_lr_unify_all :
wenzelm@31301
   105
       searchinfo -> term -> match Seq.seq Seq.seq
dixon@19871
   106
    val searchf_lr_unify_valid :
wenzelm@31301
   107
       searchinfo -> term -> match Seq.seq Seq.seq
narboux@23064
   108
    val searchf_bt_unify_valid :
wenzelm@31301
   109
       searchinfo -> term -> match Seq.seq Seq.seq
dixon@19871
   110
dixon@19871
   111
    (* Isar level hooks *)
wenzelm@31301
   112
    val eqsubst_asm_meth : Proof.context -> int list -> thm list -> Proof.method
wenzelm@31301
   113
    val eqsubst_meth : Proof.context -> int list -> thm list -> Proof.method
dixon@19871
   114
    val setup : theory -> theory
dixon@19871
   115
paulson@15481
   116
end;
paulson@15481
   117
wenzelm@41164
   118
structure EqSubst: EQSUBST =
wenzelm@41164
   119
struct
dixon@19835
   120
dixon@19835
   121
(* changes object "=" to meta "==" which prepares a given rewrite rule *)
wenzelm@18598
   122
fun prep_meta_eq ctxt =
wenzelm@32149
   123
  Simplifier.mksimps (simpset_of ctxt) #> map Drule.zero_var_indexes;
wenzelm@18598
   124
paulson@15481
   125
dixon@15915
   126
  (* a type abriviation for match information *)
wenzelm@16978
   127
  type match =
wenzelm@16978
   128
       ((indexname * (sort * typ)) list (* type instantiations *)
wenzelm@16978
   129
        * (indexname * (typ * term)) list) (* term instantiations *)
wenzelm@16978
   130
       * (string * typ) list (* fake named type abs env *)
wenzelm@16978
   131
       * (string * typ) list (* type abs env *)
wenzelm@16978
   132
       * term (* outer term *)
dixon@15550
   133
wenzelm@16978
   134
  type searchinfo =
wenzelm@18598
   135
       theory
dixon@16004
   136
       * int (* maxidx *)
dixon@19835
   137
       * Zipper.T (* focusterm to search under *)
dixon@19835
   138
dixon@19835
   139
dixon@19835
   140
(* skipping non-empty sub-sequences but when we reach the end
dixon@19835
   141
   of the seq, remembering how much we have left to skip. *)
dixon@19835
   142
datatype 'a skipseq = SkipMore of int
dixon@19835
   143
  | SkipSeq of 'a Seq.seq Seq.seq;
dixon@19835
   144
(* given a seqseq, skip the first m non-empty seq's, note deficit *)
dixon@19835
   145
fun skipto_skipseq m s = 
dixon@19835
   146
    let 
dixon@19835
   147
      fun skip_occs n sq = 
dixon@19835
   148
          case Seq.pull sq of 
dixon@19835
   149
            NONE => SkipMore n
dixon@19835
   150
          | SOME (h,t) => 
dixon@19835
   151
            (case Seq.pull h of NONE => skip_occs n t
dixon@19835
   152
             | SOME _ => if n <= 1 then SkipSeq (Seq.cons h t)
dixon@19835
   153
                         else skip_occs (n - 1) t)
dixon@19835
   154
    in (skip_occs m s) end;
dixon@19835
   155
dixon@19835
   156
(* note: outerterm is the taget with the match replaced by a bound 
dixon@19835
   157
         variable : ie: "P lhs" beocmes "%x. P x" 
dixon@19835
   158
         insts is the types of instantiations of vars in lhs
dixon@19835
   159
         and typinsts is the type instantiations of types in the lhs
dixon@19835
   160
         Note: Final rule is the rule lifted into the ontext of the 
dixon@19835
   161
         taget thm. *)
dixon@19835
   162
fun mk_foo_match mkuptermfunc Ts t = 
dixon@19835
   163
    let 
dixon@19835
   164
      val ty = Term.type_of t
dixon@19835
   165
      val bigtype = (rev (map snd Ts)) ---> ty
dixon@19835
   166
      fun mk_foo 0 t = t
dixon@19835
   167
        | mk_foo i t = mk_foo (i - 1) (t $ (Bound (i - 1)))
dixon@19835
   168
      val num_of_bnds = (length Ts)
dixon@19835
   169
      (* foo_term = "fooabs y0 ... yn" where y's are local bounds *)
dixon@19835
   170
      val foo_term = mk_foo num_of_bnds (Bound num_of_bnds)
dixon@19835
   171
    in Abs("fooabs", bigtype, mkuptermfunc foo_term) end;
dixon@19835
   172
dixon@19835
   173
(* T is outer bound vars, n is number of locally bound vars *)
dixon@19835
   174
(* THINK: is order of Ts correct...? or reversed? *)
dixon@19835
   175
fun fakefree_badbounds Ts t = 
dixon@19835
   176
    let val (FakeTs,Ts,newnames) = 
dixon@19835
   177
            List.foldr (fn ((n,ty),(FakeTs,Ts,usednames)) => 
wenzelm@43324
   178
                           let val newname = singleton (Name.variant_list usednames) n
dixon@19835
   179
                           in ((RWTools.mk_fake_bound_name newname,ty)::FakeTs,
dixon@19835
   180
                               (newname,ty)::Ts, 
dixon@19835
   181
                               newname::usednames) end)
dixon@19835
   182
                       ([],[],[])
dixon@19835
   183
                       Ts
dixon@19835
   184
    in (FakeTs, Ts, Term.subst_bounds (map Free FakeTs, t)) end;
dixon@19835
   185
dixon@19835
   186
(* before matching we need to fake the bound vars that are missing an
dixon@19835
   187
abstraction. In this function we additionally construct the
dixon@19835
   188
abstraction environment, and an outer context term (with the focus
dixon@19835
   189
abstracted out) for use in rewriting with RWInst.rw *)
dixon@19835
   190
fun prep_zipper_match z = 
dixon@19835
   191
    let 
wenzelm@41164
   192
      val t = Zipper.trm z  
wenzelm@41164
   193
      val c = Zipper.ctxt z
wenzelm@41164
   194
      val Ts = Zipper.C.nty_ctxt c
dixon@19835
   195
      val (FakeTs', Ts', t') = fakefree_badbounds Ts t
wenzelm@41164
   196
      val absterm = mk_foo_match (Zipper.C.apply c) Ts' t'
dixon@19835
   197
    in
dixon@19835
   198
      (t', (FakeTs', Ts', absterm))
dixon@19835
   199
    end;
dixon@19835
   200
dixon@19835
   201
(* Matching and Unification with exception handled *)
dixon@19835
   202
fun clean_match thy (a as (pat, t)) =
dixon@19835
   203
  let val (tyenv, tenv) = Pattern.match thy a (Vartab.empty, Vartab.empty)
dixon@19835
   204
  in SOME (Vartab.dest tyenv, Vartab.dest tenv)
dixon@19835
   205
  end handle Pattern.MATCH => NONE;
dixon@27033
   206
dixon@19835
   207
(* given theory, max var index, pat, tgt; returns Seq of instantiations *)
dixon@27033
   208
fun clean_unify thry ix (a as (pat, tgt)) =
dixon@19835
   209
    let
dixon@19835
   210
      (* type info will be re-derived, maybe this can be cached
dixon@19835
   211
         for efficiency? *)
dixon@19835
   212
      val pat_ty = Term.type_of pat;
dixon@19835
   213
      val tgt_ty = Term.type_of tgt;
dixon@19835
   214
      (* is it OK to ignore the type instantiation info?
dixon@19835
   215
         or should I be using it? *)
dixon@19835
   216
      val typs_unify =
wenzelm@29269
   217
          SOME (Sign.typ_unify thry (pat_ty, tgt_ty) (Vartab.empty, ix))
dixon@19835
   218
            handle Type.TUNIFY => NONE;
dixon@19835
   219
    in
dixon@19835
   220
      case typs_unify of
dixon@19835
   221
        SOME (typinsttab, ix2) =>
dixon@19835
   222
        let
dixon@19835
   223
      (* is it right to throw away the flexes?
dixon@19835
   224
         or should I be using them somehow? *)
dixon@19835
   225
          fun mk_insts env =
dixon@19835
   226
            (Vartab.dest (Envir.type_env env),
wenzelm@32032
   227
             Vartab.dest (Envir.term_env env));
wenzelm@32032
   228
          val initenv =
wenzelm@32032
   229
            Envir.Envir {maxidx = ix2, tenv = Vartab.empty, tyenv = typinsttab};
dixon@27033
   230
          val useq = Unify.smash_unifiers thry [a] initenv
wenzelm@40722
   231
              handle ListPair.UnequalLengths => Seq.empty
wenzelm@32960
   232
                   | Term.TERM _ => Seq.empty;
dixon@19835
   233
          fun clean_unify' useq () =
dixon@19835
   234
              (case (Seq.pull useq) of
dixon@19835
   235
                 NONE => NONE
dixon@19835
   236
               | SOME (h,t) => SOME (mk_insts h, Seq.make (clean_unify' t)))
wenzelm@40722
   237
              handle ListPair.UnequalLengths => NONE
dixon@27033
   238
                   | Term.TERM _ => NONE
dixon@19835
   239
        in
dixon@19835
   240
          (Seq.make (clean_unify' useq))
dixon@19835
   241
        end
dixon@19835
   242
      | NONE => Seq.empty
dixon@19835
   243
    end;
dixon@19835
   244
dixon@19835
   245
(* Matching and Unification for zippers *)
dixon@19835
   246
(* Note: Ts is a modified version of the original names of the outer
dixon@19835
   247
bound variables. New names have been introduced to make sure they are
dixon@19835
   248
unique w.r.t all names in the term and each other. usednames' is
dixon@19835
   249
oldnames + new names. *)
dixon@19835
   250
fun clean_match_z thy pat z = 
dixon@19835
   251
    let val (t, (FakeTs,Ts,absterm)) = prep_zipper_match z in
dixon@19835
   252
      case clean_match thy (pat, t) of 
dixon@19835
   253
        NONE => NONE 
dixon@19835
   254
      | SOME insts => SOME (insts, FakeTs, Ts, absterm) end;
dixon@19835
   255
(* ix = max var index *)
dixon@19835
   256
fun clean_unify_z sgn ix pat z = 
dixon@19835
   257
    let val (t, (FakeTs, Ts,absterm)) = prep_zipper_match z in
dixon@19835
   258
    Seq.map (fn insts => (insts, FakeTs, Ts, absterm)) 
dixon@19835
   259
            (clean_unify sgn ix (t, pat)) end;
dixon@19835
   260
dixon@15550
   261
dixon@15538
   262
(* FOR DEBUGGING...
dixon@15538
   263
type trace_subst_errT = int (* subgoal *)
wenzelm@16978
   264
        * thm (* thm with all goals *)
wenzelm@33243
   265
        * (cterm list (* certified free var placeholders for vars *)
wenzelm@16978
   266
           * thm)  (* trivial thm of goal concl *)
dixon@15538
   267
            (* possible matches/unifiers *)
wenzelm@16978
   268
        * thm (* rule *)
wenzelm@16978
   269
        * (((indexname * typ) list (* type instantiations *)
wenzelm@16978
   270
              * (indexname * term) list ) (* term instantiations *)
wenzelm@16978
   271
             * (string * typ) list (* Type abs env *)
wenzelm@16978
   272
             * term) (* outer term *);
dixon@15538
   273
wenzelm@32740
   274
val trace_subst_err = (Unsynchronized.ref NONE : trace_subst_errT option Unsynchronized.ref);
wenzelm@32740
   275
val trace_subst_search = Unsynchronized.ref false;
dixon@15538
   276
exception trace_subst_exp of trace_subst_errT;
dixon@19835
   277
*)
dixon@19835
   278
dixon@19835
   279
dixon@19835
   280
fun bot_left_leaf_of (l $ r) = bot_left_leaf_of l
dixon@19835
   281
  | bot_left_leaf_of (Abs(s,ty,t)) = bot_left_leaf_of t
dixon@19835
   282
  | bot_left_leaf_of x = x;
dixon@15538
   283
dixon@19975
   284
(* Avoid considering replacing terms which have a var at the head as
dixon@19975
   285
   they always succeed trivially, and uninterestingly. *)
dixon@19835
   286
fun valid_match_start z =
wenzelm@41164
   287
    (case bot_left_leaf_of (Zipper.trm z) of 
dixon@19975
   288
      Var _ => false 
dixon@19975
   289
      | _ => true);
dixon@19975
   290
dixon@15814
   291
(* search from top, left to right, then down *)
dixon@19871
   292
val search_lr_all = ZipperSearch.all_bl_ur;
paulson@15481
   293
dixon@15814
   294
(* search from top, left to right, then down *)
dixon@19871
   295
fun search_lr_valid validf =
dixon@19835
   296
    let 
dixon@19835
   297
      fun sf_valid_td_lr z = 
wenzelm@41164
   298
          let val here = if validf z then [Zipper.Here z] else [] in
wenzelm@41164
   299
            case Zipper.trm z 
wenzelm@41164
   300
             of _ $ _ => [Zipper.LookIn (Zipper.move_down_left z)] 
dixon@19871
   301
                         @ here 
wenzelm@41164
   302
                         @ [Zipper.LookIn (Zipper.move_down_right z)]
wenzelm@41164
   303
              | Abs _ => here @ [Zipper.LookIn (Zipper.move_down_abs z)]
dixon@19835
   304
              | _ => here
dixon@19835
   305
          end;
wenzelm@41164
   306
    in Zipper.lzy_search sf_valid_td_lr end;
dixon@15814
   307
narboux@23064
   308
(* search from bottom to top, left to right *)
narboux@23064
   309
narboux@23064
   310
fun search_bt_valid validf =
narboux@23064
   311
    let 
narboux@23064
   312
      fun sf_valid_td_lr z = 
wenzelm@41164
   313
          let val here = if validf z then [Zipper.Here z] else [] in
wenzelm@41164
   314
            case Zipper.trm z 
wenzelm@41164
   315
             of _ $ _ => [Zipper.LookIn (Zipper.move_down_left z), 
wenzelm@41164
   316
                          Zipper.LookIn (Zipper.move_down_right z)] @ here
wenzelm@41164
   317
              | Abs _ => [Zipper.LookIn (Zipper.move_down_abs z)] @ here
narboux@23064
   318
              | _ => here
narboux@23064
   319
          end;
wenzelm@41164
   320
    in Zipper.lzy_search sf_valid_td_lr end;
narboux@23064
   321
narboux@23064
   322
fun searchf_unify_gen f (sgn, maxidx, z) lhs =
narboux@23064
   323
    Seq.map (clean_unify_z sgn maxidx lhs) 
wenzelm@41164
   324
            (Zipper.limit_apply f z);
narboux@23064
   325
dixon@15814
   326
(* search all unifications *)
narboux@23064
   327
val searchf_lr_unify_all =
narboux@23064
   328
    searchf_unify_gen search_lr_all;
paulson@15481
   329
dixon@15814
   330
(* search only for 'valid' unifiers (non abs subterms and non vars) *)
narboux@23064
   331
val searchf_lr_unify_valid = 
narboux@23064
   332
    searchf_unify_gen (search_lr_valid valid_match_start);
dixon@15929
   333
narboux@23064
   334
val searchf_bt_unify_valid =
narboux@23064
   335
    searchf_unify_gen (search_bt_valid valid_match_start);
dixon@15814
   336
dixon@15538
   337
(* apply a substitution in the conclusion of the theorem th *)
dixon@15538
   338
(* cfvs are certified free var placeholders for goal params *)
dixon@15538
   339
(* conclthm is a theorem of for just the conclusion *)
dixon@15538
   340
(* m is instantiation/match information *)
dixon@15538
   341
(* rule is the equation for substitution *)
wenzelm@16978
   342
fun apply_subst_in_concl i th (cfvs, conclthm) rule m =
dixon@15538
   343
    (RWInst.rw m rule conclthm)
dixon@15855
   344
      |> IsaND.unfix_frees cfvs
dixon@15915
   345
      |> RWInst.beta_eta_contract
dixon@15538
   346
      |> (fn r => Tactic.rtac r i th);
paulson@15481
   347
paulson@15481
   348
(* substitute within the conclusion of goal i of gth, using a meta
dixon@15538
   349
equation rule. Note that we assume rule has var indicies zero'd *)
wenzelm@16978
   350
fun prep_concl_subst i gth =
wenzelm@16978
   351
    let
paulson@15481
   352
      val th = Thm.incr_indexes 1 gth;
paulson@15481
   353
      val tgt_term = Thm.prop_of th;
paulson@15481
   354
wenzelm@22578
   355
      val sgn = Thm.theory_of_thm th;
paulson@15481
   356
      val ctermify = Thm.cterm_of sgn;
paulson@15481
   357
      val trivify = Thm.trivial o ctermify;
paulson@15481
   358
paulson@15481
   359
      val (fixedbody, fvs) = IsaND.fix_alls_term i tgt_term;
paulson@15481
   360
      val cfvs = rev (map ctermify fvs);
paulson@15481
   361
dixon@15538
   362
      val conclterm = Logic.strip_imp_concl fixedbody;
dixon@15538
   363
      val conclthm = trivify conclterm;
dixon@27033
   364
      val maxidx = Thm.maxidx_of th;
wenzelm@41164
   365
      val ft = ((Zipper.move_down_right (* ==> *)
wenzelm@41164
   366
                 o Zipper.move_down_left (* Trueprop *)
wenzelm@41164
   367
                 o Zipper.mktop
dixon@16004
   368
                 o Thm.prop_of) conclthm)
paulson@15481
   369
    in
dixon@16004
   370
      ((cfvs, conclthm), (sgn, maxidx, ft))
paulson@15481
   371
    end;
paulson@15481
   372
paulson@15481
   373
(* substitute using an object or meta level equality *)
wenzelm@18598
   374
fun eqsubst_tac' ctxt searchf instepthm i th =
wenzelm@16978
   375
    let
dixon@16004
   376
      val (cvfsconclthm, searchinfo) = prep_concl_subst i th;
wenzelm@18598
   377
      val stepthms = Seq.of_list (prep_meta_eq ctxt instepthm);
dixon@15538
   378
      fun rewrite_with_thm r =
dixon@15538
   379
          let val (lhs,_) = Logic.dest_equals (Thm.concl_of r);
wenzelm@18598
   380
          in searchf searchinfo lhs
wenzelm@18598
   381
             |> Seq.maps (apply_subst_in_concl i th cvfsconclthm r) end;
wenzelm@18598
   382
    in stepthms |> Seq.maps rewrite_with_thm end;
dixon@15538
   383
dixon@15538
   384
wenzelm@19047
   385
(* distinct subgoals *)
dixon@15959
   386
fun distinct_subgoals th =
wenzelm@19047
   387
  the_default th (SINGLE distinct_subgoals_tac th);
dixon@15538
   388
wenzelm@19047
   389
(* General substitution of multiple occurances using one of
dixon@15936
   390
   the given theorems*)
dixon@19835
   391
dixon@19835
   392
wenzelm@16978
   393
exception eqsubst_occL_exp of
wenzelm@16978
   394
          string * (int list) * (thm list) * int * thm;
wenzelm@16978
   395
fun skip_first_occs_search occ srchf sinfo lhs =
dixon@19835
   396
    case (skipto_skipseq occ (srchf sinfo lhs)) of
dixon@19835
   397
      SkipMore _ => Seq.empty
dixon@19835
   398
    | SkipSeq ss => Seq.flat ss;
dixon@16004
   399
dixon@22727
   400
(* The occL is a list of integers indicating which occurence
dixon@22727
   401
w.r.t. the search order, to rewrite. Backtracking will also find later
dixon@22727
   402
occurences, but all earlier ones are skipped. Thus you can use [0] to
dixon@22727
   403
just find all rewrites. *)
dixon@22727
   404
wenzelm@18598
   405
fun eqsubst_tac ctxt occL thms i th =
dixon@15936
   406
    let val nprems = Thm.nprems_of th in
dixon@15936
   407
      if nprems < i then Seq.empty else
wenzelm@16978
   408
      let val thmseq = (Seq.of_list thms)
wenzelm@16978
   409
        fun apply_occ occ th =
wenzelm@18598
   410
            thmseq |> Seq.maps
dixon@19835
   411
                    (fn r => eqsubst_tac' 
dixon@19835
   412
                               ctxt 
dixon@19835
   413
                               (skip_first_occs_search
dixon@19871
   414
                                  occ searchf_lr_unify_valid) r
dixon@15936
   415
                                 (i + ((Thm.nprems_of th) - nprems))
dixon@15936
   416
                                 th);
wenzelm@16978
   417
        val sortedoccL =
dixon@16004
   418
            Library.sort (Library.rev_order o Library.int_ord) occL;
dixon@15936
   419
      in
dixon@16004
   420
        Seq.map distinct_subgoals (Seq.EVERY (map apply_occ sortedoccL) th)
dixon@15936
   421
      end
dixon@15959
   422
    end
dixon@15959
   423
    handle THM _ => raise eqsubst_occL_exp ("THM",occL,thms,i,th);
dixon@15959
   424
paulson@15481
   425
paulson@15481
   426
(* inthms are the given arguments in Isar, and treated as eqstep with
paulson@15481
   427
   the first one, then the second etc *)
wenzelm@18598
   428
fun eqsubst_meth ctxt occL inthms =
wenzelm@30510
   429
    SIMPLE_METHOD' (eqsubst_tac ctxt occL inthms);
paulson@15481
   430
dixon@16004
   431
(* apply a substitution inside assumption j, keeps asm in the same place *)
wenzelm@16978
   432
fun apply_subst_in_asm i th rule ((cfvs, j, ngoalprems, pth),m) =
wenzelm@16978
   433
    let
dixon@16004
   434
      val th2 = Thm.rotate_rule (j - 1) i th; (* put premice first *)
wenzelm@16978
   435
      val preelimrule =
dixon@16004
   436
          (RWInst.rw m rule pth)
wenzelm@21708
   437
            |> (Seq.hd o prune_params_tac)
dixon@16004
   438
            |> Thm.permute_prems 0 ~1 (* put old asm first *)
dixon@16004
   439
            |> IsaND.unfix_frees cfvs (* unfix any global params *)
dixon@16004
   440
            |> RWInst.beta_eta_contract; (* normal form *)
wenzelm@16978
   441
  (*    val elimrule =
dixon@16004
   442
          preelimrule
dixon@16004
   443
            |> Tactic.make_elim (* make into elim rule *)
dixon@16004
   444
            |> Thm.lift_rule (th2, i); (* lift into context *)
dixon@16007
   445
   *)
dixon@16004
   446
    in
dixon@16004
   447
      (* ~j because new asm starts at back, thus we subtract 1 *)
dixon@16007
   448
      Seq.map (Thm.rotate_rule (~j) ((Thm.nprems_of rule) + i))
dixon@16007
   449
      (Tactic.dtac preelimrule i th2)
dixon@16007
   450
wenzelm@16978
   451
      (* (Thm.bicompose
dixon@16004
   452
                 false (* use unification *)
dixon@16004
   453
                 (true, (* elim resolution *)
dixon@16007
   454
                  elimrule, (2 + (Thm.nprems_of rule)) - ngoalprems)
dixon@16007
   455
                 i th2) *)
dixon@16004
   456
    end;
paulson@15481
   457
paulson@15481
   458
dixon@15538
   459
(* prepare to substitute within the j'th premise of subgoal i of gth,
dixon@15538
   460
using a meta-level equation. Note that we assume rule has var indicies
dixon@15538
   461
zero'd. Note that we also assume that premt is the j'th premice of
dixon@15538
   462
subgoal i of gth. Note the repetition of work done for each
dixon@15538
   463
assumption, i.e. this can be made more efficient for search over
dixon@15538
   464
multiple assumptions.  *)
wenzelm@16978
   465
fun prep_subst_in_asm i gth j =
wenzelm@16978
   466
    let
paulson@15481
   467
      val th = Thm.incr_indexes 1 gth;
paulson@15481
   468
      val tgt_term = Thm.prop_of th;
paulson@15481
   469
wenzelm@22578
   470
      val sgn = Thm.theory_of_thm th;
paulson@15481
   471
      val ctermify = Thm.cterm_of sgn;
paulson@15481
   472
      val trivify = Thm.trivial o ctermify;
paulson@15481
   473
paulson@15481
   474
      val (fixedbody, fvs) = IsaND.fix_alls_term i tgt_term;
paulson@15481
   475
      val cfvs = rev (map ctermify fvs);
paulson@15481
   476
haftmann@18011
   477
      val asmt = nth (Logic.strip_imp_prems fixedbody) (j - 1);
dixon@15538
   478
      val asm_nprems = length (Logic.strip_imp_prems asmt);
dixon@15538
   479
dixon@15538
   480
      val pth = trivify asmt;
dixon@27033
   481
      val maxidx = Thm.maxidx_of th;
dixon@15538
   482
wenzelm@41164
   483
      val ft = ((Zipper.move_down_right (* trueprop *)
wenzelm@41164
   484
                 o Zipper.mktop
dixon@16004
   485
                 o Thm.prop_of) pth)
dixon@16004
   486
    in ((cfvs, j, asm_nprems, pth), (sgn, maxidx, ft)) end;
paulson@15481
   487
dixon@15538
   488
(* prepare subst in every possible assumption *)
wenzelm@16978
   489
fun prep_subst_in_asms i gth =
dixon@16004
   490
    map (prep_subst_in_asm i gth)
dixon@19835
   491
        ((fn l => Library.upto (1, length l))
dixon@16004
   492
           (Logic.prems_of_goal (Thm.prop_of gth) i));
dixon@15538
   493
dixon@15538
   494
dixon@15538
   495
(* substitute in an assumption using an object or meta level equality *)
wenzelm@18598
   496
fun eqsubst_asm_tac' ctxt searchf skipocc instepthm i th =
wenzelm@16978
   497
    let
dixon@16004
   498
      val asmpreps = prep_subst_in_asms i th;
wenzelm@18598
   499
      val stepthms = Seq.of_list (prep_meta_eq ctxt instepthm);
dixon@16004
   500
      fun rewrite_with_thm r =
dixon@16004
   501
          let val (lhs,_) = Logic.dest_equals (Thm.concl_of r)
dixon@16004
   502
            fun occ_search occ [] = Seq.empty
dixon@16004
   503
              | occ_search occ ((asminfo, searchinfo)::moreasms) =
wenzelm@16978
   504
                (case searchf searchinfo occ lhs of
dixon@19835
   505
                   SkipMore i => occ_search i moreasms
dixon@19835
   506
                 | SkipSeq ss =>
wenzelm@19861
   507
                   Seq.append (Seq.map (Library.pair asminfo) (Seq.flat ss))
wenzelm@19861
   508
                               (occ_search 1 moreasms))
dixon@16004
   509
                              (* find later substs also *)
wenzelm@16978
   510
          in
wenzelm@18598
   511
            occ_search skipocc asmpreps |> Seq.maps (apply_subst_in_asm i th r)
dixon@16004
   512
          end;
wenzelm@18598
   513
    in stepthms |> Seq.maps rewrite_with_thm end;
dixon@15538
   514
dixon@16004
   515
wenzelm@16978
   516
fun skip_first_asm_occs_search searchf sinfo occ lhs =
dixon@19835
   517
    skipto_skipseq occ (searchf sinfo lhs);
dixon@16004
   518
wenzelm@18598
   519
fun eqsubst_asm_tac ctxt occL thms i th =
wenzelm@16978
   520
    let val nprems = Thm.nprems_of th
dixon@15538
   521
    in
dixon@16004
   522
      if nprems < i then Seq.empty else
wenzelm@16978
   523
      let val thmseq = (Seq.of_list thms)
wenzelm@16978
   524
        fun apply_occ occK th =
wenzelm@18598
   525
            thmseq |> Seq.maps
wenzelm@16978
   526
                    (fn r =>
wenzelm@18598
   527
                        eqsubst_asm_tac' ctxt (skip_first_asm_occs_search
dixon@19871
   528
                                            searchf_lr_unify_valid) occK r
dixon@16004
   529
                                         (i + ((Thm.nprems_of th) - nprems))
dixon@16004
   530
                                         th);
wenzelm@16978
   531
        val sortedoccs =
dixon@16004
   532
            Library.sort (Library.rev_order o Library.int_ord) occL
dixon@16004
   533
      in
dixon@16004
   534
        Seq.map distinct_subgoals
dixon@16004
   535
                (Seq.EVERY (map apply_occ sortedoccs) th)
dixon@16004
   536
      end
dixon@16004
   537
    end
dixon@16004
   538
    handle THM _ => raise eqsubst_occL_exp ("THM",occL,thms,i,th);
paulson@15481
   539
paulson@15481
   540
(* inthms are the given arguments in Isar, and treated as eqstep with
paulson@15481
   541
   the first one, then the second etc *)
wenzelm@18598
   542
fun eqsubst_asm_meth ctxt occL inthms =
wenzelm@30510
   543
    SIMPLE_METHOD' (eqsubst_asm_tac ctxt occL inthms);
paulson@15481
   544
wenzelm@18598
   545
(* combination method that takes a flag (true indicates that subst
wenzelm@31301
   546
   should be done to an assumption, false = apply to the conclusion of
wenzelm@31301
   547
   the goal) as well as the theorems to use *)
wenzelm@16978
   548
val setup =
wenzelm@31301
   549
  Method.setup @{binding subst}
wenzelm@44095
   550
    (Args.mode "asm" -- Scan.lift (Scan.optional (Args.parens (Scan.repeat Parse.nat)) [0]) --
wenzelm@44095
   551
        Attrib.thms >>
wenzelm@44095
   552
      (fn ((asm, occL), inthms) => fn ctxt =>
wenzelm@44095
   553
        (if asm then eqsubst_asm_meth else eqsubst_meth) ctxt occL inthms))
wenzelm@31301
   554
    "single-step substitution";
paulson@15481
   555
wenzelm@16978
   556
end;