src/Provers/induct_method.ML
author wenzelm
Wed Apr 04 23:29:33 2007 +0200 (2007-04-04)
changeset 22596 d0d2af4db18f
parent 21879 a3efbae45735
child 22826 0f4c501a691e
permissions -rw-r--r--
rep_thm/cterm/ctyp: removed obsolete sign field;
wenzelm@11670
     1
(*  Title:      Provers/induct_method.ML
wenzelm@11670
     2
    ID:         $Id$
wenzelm@11670
     3
    Author:     Markus Wenzel, TU Muenchen
wenzelm@11670
     4
wenzelm@11735
     5
Proof by cases and induction on sets and types.
wenzelm@11670
     6
*)
wenzelm@11670
     7
wenzelm@11670
     8
signature INDUCT_METHOD_DATA =
wenzelm@11670
     9
sig
wenzelm@11670
    10
  val cases_default: thm
wenzelm@11670
    11
  val atomize: thm list
wenzelm@18465
    12
  val rulify: thm list
wenzelm@18465
    13
  val rulify_fallback: thm list
wenzelm@11670
    14
end;
wenzelm@11670
    15
wenzelm@11670
    16
signature INDUCT_METHOD =
wenzelm@11670
    17
sig
wenzelm@18250
    18
  val fix_tac: Proof.context -> int -> (string * typ) list -> int -> tactic
wenzelm@18287
    19
  val add_defs: (string option * term) option list -> Proof.context ->
wenzelm@18287
    20
    (term option list * thm list) * Proof.context
wenzelm@18250
    21
  val atomize_term: theory -> term -> term
wenzelm@18250
    22
  val atomize_tac: int -> tactic
wenzelm@18512
    23
  val inner_atomize_tac: int -> tactic
wenzelm@18250
    24
  val rulified_term: thm -> theory * term
wenzelm@18250
    25
  val rulify_tac: int -> tactic
wenzelm@18580
    26
  val internalize: int -> thm -> thm
wenzelm@18259
    27
  val guess_instance: thm -> int -> thm -> thm Seq.seq
wenzelm@16391
    28
  val cases_tac: Proof.context -> bool -> term option list list -> thm option ->
wenzelm@18224
    29
    thm list -> int -> cases_tactic
wenzelm@18178
    30
  val induct_tac: Proof.context -> bool -> (string option * term) option list list ->
wenzelm@18465
    31
    (string * typ) list list -> term option list -> thm list option -> thm list -> int ->
wenzelm@18465
    32
    cases_tactic
wenzelm@18235
    33
  val coinduct_tac: Proof.context -> bool -> term option list -> term option list ->
wenzelm@18235
    34
    thm option -> thm list -> int -> cases_tactic
wenzelm@18708
    35
  val setup: theory -> theory
wenzelm@11670
    36
end;
wenzelm@11670
    37
wenzelm@11670
    38
functor InductMethodFun(Data: INDUCT_METHOD_DATA): INDUCT_METHOD =
wenzelm@11670
    39
struct
wenzelm@11670
    40
wenzelm@18465
    41
val meta_spec = thm "Pure.meta_spec";
wenzelm@18465
    42
val all_conjunction = thm "Pure.all_conjunction";
wenzelm@18465
    43
val imp_conjunction = thm "Pure.imp_conjunction";
wenzelm@18465
    44
val conjunction_imp = thm "Pure.conjunction_imp";
wenzelm@18465
    45
val conjunction_congs = [all_conjunction, imp_conjunction];
wenzelm@18465
    46
wenzelm@18465
    47
wenzelm@11670
    48
wenzelm@11670
    49
(** misc utils **)
wenzelm@11670
    50
wenzelm@18287
    51
(* alignment *)
wenzelm@11670
    52
wenzelm@11670
    53
fun align_left msg xs ys =
wenzelm@11670
    54
  let val m = length xs and n = length ys
wenzelm@18678
    55
  in if m < n then error msg else (Library.take (n, xs) ~~ ys) end;
wenzelm@11670
    56
wenzelm@11670
    57
fun align_right msg xs ys =
wenzelm@11670
    58
  let val m = length xs and n = length ys
wenzelm@18678
    59
  in if m < n then error msg else (Library.drop (m - n, xs) ~~ ys) end;
wenzelm@11670
    60
wenzelm@11670
    61
wenzelm@11735
    62
(* prep_inst *)
wenzelm@11670
    63
wenzelm@18205
    64
fun prep_inst thy align tune (tm, ts) =
wenzelm@11670
    65
  let
wenzelm@18205
    66
    val cert = Thm.cterm_of thy;
skalberg@15531
    67
    fun prep_var (x, SOME t) =
wenzelm@11670
    68
          let
wenzelm@11670
    69
            val cx = cert x;
wenzelm@18147
    70
            val {T = xT, thy, ...} = Thm.rep_cterm cx;
wenzelm@12799
    71
            val ct = cert (tune t);
wenzelm@11670
    72
          in
wenzelm@18147
    73
            if Sign.typ_instance thy (#T (Thm.rep_cterm ct), xT) then SOME (cx, ct)
wenzelm@18678
    74
            else error (Pretty.string_of (Pretty.block
wenzelm@11735
    75
             [Pretty.str "Ill-typed instantiation:", Pretty.fbrk,
wenzelm@11735
    76
              Display.pretty_cterm ct, Pretty.str " ::", Pretty.brk 1,
wenzelm@11735
    77
              Display.pretty_ctyp (#T (Thm.crep_cterm ct))]))
wenzelm@11670
    78
          end
skalberg@15531
    79
      | prep_var (_, NONE) = NONE;
wenzelm@11735
    80
    val xs = InductAttrib.vars_of tm;
wenzelm@11670
    81
  in
wenzelm@11735
    82
    align "Rule has fewer variables than instantiations given" xs ts
wenzelm@19482
    83
    |> map_filter prep_var
wenzelm@11670
    84
  end;
wenzelm@11670
    85
wenzelm@11670
    86
wenzelm@18205
    87
(* trace_rules *)
wenzelm@18205
    88
wenzelm@18205
    89
fun trace_rules _ kind [] = error ("Unable to figure out " ^ kind ^ " rule")
wenzelm@18205
    90
  | trace_rules ctxt _ rules = Method.trace ctxt rules;
wenzelm@18205
    91
wenzelm@18205
    92
wenzelm@18205
    93
(* make_cases *)
wenzelm@18178
    94
wenzelm@18224
    95
fun make_cases is_open rule =
wenzelm@18602
    96
  RuleCases.make_common is_open (Thm.theory_of_thm rule, Thm.prop_of rule);
wenzelm@18224
    97
wenzelm@18178
    98
fun warn_open true = warning "Encountered open rule cases -- deprecated"
wenzelm@18178
    99
  | warn_open false = ();
wenzelm@18178
   100
wenzelm@18178
   101
wenzelm@11670
   102
wenzelm@11670
   103
(** cases method **)
wenzelm@11670
   104
wenzelm@11670
   105
(*
wenzelm@11735
   106
  rule selection scheme:
wenzelm@18178
   107
          cases         - default case split
wenzelm@18178
   108
    `x:A` cases ...     - set cases
wenzelm@11735
   109
          cases t       - type cases
wenzelm@18178
   110
    ...   cases ... r   - explicit rule
wenzelm@11670
   111
*)
wenzelm@11670
   112
wenzelm@11670
   113
local
wenzelm@11670
   114
wenzelm@18178
   115
fun find_casesT ctxt ((SOME t :: _) :: _) = InductAttrib.find_casesT ctxt (Term.fastype_of t)
wenzelm@11735
   116
  | find_casesT _ _ = [];
wenzelm@11735
   117
wenzelm@18224
   118
fun find_casesS ctxt (fact :: _) = InductAttrib.find_casesS ctxt (Thm.concl_of fact)
wenzelm@11735
   119
  | find_casesS _ _ = [];
wenzelm@11735
   120
wenzelm@16391
   121
in
wenzelm@16391
   122
wenzelm@16391
   123
fun cases_tac ctxt is_open insts opt_rule facts =
wenzelm@11670
   124
  let
wenzelm@18224
   125
    val _ = warn_open is_open;
wenzelm@18147
   126
    val thy = ProofContext.theory_of ctxt;
wenzelm@18147
   127
    val cert = Thm.cterm_of thy;
wenzelm@11670
   128
wenzelm@11735
   129
    fun inst_rule r =
wenzelm@18224
   130
      if null insts then `RuleCases.get r
wenzelm@11735
   131
      else (align_left "Rule has fewer premises than arguments given" (Thm.prems_of r) insts
wenzelm@19482
   132
        |> maps (prep_inst thy align_left I)
wenzelm@18224
   133
        |> Drule.cterm_instantiate) r |> pair (RuleCases.get r);
wenzelm@11670
   134
wenzelm@11735
   135
    val ruleq =
wenzelm@12852
   136
      (case opt_rule of
wenzelm@18205
   137
        SOME r => Seq.single (inst_rule r)
wenzelm@18205
   138
      | NONE =>
wenzelm@18205
   139
          (find_casesS ctxt facts @ find_casesT ctxt insts @ [Data.cases_default])
wenzelm@18205
   140
          |> tap (trace_rules ctxt InductAttrib.casesN)
wenzelm@18224
   141
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@18178
   142
  in
wenzelm@18178
   143
    fn i => fn st =>
wenzelm@18224
   144
      ruleq
wenzelm@18235
   145
      |> Seq.maps (RuleCases.consume [] facts)
wenzelm@18224
   146
      |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
wenzelm@18224
   147
        CASES (make_cases is_open rule cases)
wenzelm@18224
   148
          (Method.insert_tac more_facts i THEN Tactic.rtac rule i) st)
wenzelm@18178
   149
  end;
wenzelm@11670
   150
wenzelm@11670
   151
end;
wenzelm@11670
   152
wenzelm@11670
   153
wenzelm@11670
   154
wenzelm@11670
   155
(** induct method **)
wenzelm@11670
   156
wenzelm@18465
   157
(* atomize *)
wenzelm@18465
   158
wenzelm@18512
   159
fun atomize_term thy =
wenzelm@18512
   160
  MetaSimplifier.rewrite_term thy Data.atomize []
wenzelm@18465
   161
  #> ObjectLogic.drop_judgment thy;
wenzelm@18465
   162
wenzelm@21708
   163
val atomize_cterm = MetaSimplifier.rewrite true Data.atomize;
wenzelm@18465
   164
wenzelm@21687
   165
val atomize_tac = Goal.rewrite_goal_tac Data.atomize;
wenzelm@18465
   166
wenzelm@18512
   167
val inner_atomize_tac =
wenzelm@21687
   168
  Goal.rewrite_goal_tac (map Thm.symmetric conjunction_congs) THEN' atomize_tac;
wenzelm@18465
   169
wenzelm@18465
   170
wenzelm@18465
   171
(* rulify *)
wenzelm@18465
   172
wenzelm@18465
   173
fun rulify_term thy =
wenzelm@18465
   174
  MetaSimplifier.rewrite_term thy (Data.rulify @ conjunction_congs) [] #>
wenzelm@18465
   175
  MetaSimplifier.rewrite_term thy Data.rulify_fallback [];
wenzelm@18465
   176
wenzelm@18465
   177
fun rulified_term thm =
wenzelm@18465
   178
  let
wenzelm@18465
   179
    val thy = Thm.theory_of_thm thm;
wenzelm@18465
   180
    val rulify = rulify_term thy;
wenzelm@18465
   181
    val (As, B) = Logic.strip_horn (Thm.prop_of thm);
wenzelm@18465
   182
  in (thy, Logic.list_implies (map rulify As, rulify B)) end;
wenzelm@18465
   183
wenzelm@18465
   184
val rulify_tac =
wenzelm@21687
   185
  Goal.rewrite_goal_tac (Data.rulify @ conjunction_congs) THEN'
wenzelm@21687
   186
  Goal.rewrite_goal_tac Data.rulify_fallback THEN'
wenzelm@21687
   187
  Goal.conjunction_tac THEN_ALL_NEW
wenzelm@21687
   188
  (Goal.rewrite_goal_tac [conjunction_imp] THEN' Goal.norm_hhf_tac);
wenzelm@18465
   189
wenzelm@18465
   190
wenzelm@18465
   191
(* prepare rule *)
wenzelm@18465
   192
wenzelm@18465
   193
fun rule_instance thy inst rule =
wenzelm@18465
   194
  Drule.cterm_instantiate (prep_inst thy align_left I (Thm.prop_of rule, inst)) rule;
wenzelm@18465
   195
wenzelm@18512
   196
fun internalize k th =
wenzelm@18465
   197
  th |> Thm.permute_prems 0 k
wenzelm@18512
   198
  |> Drule.fconv_rule (Drule.concl_conv (Thm.nprems_of th - k) atomize_cterm);
wenzelm@18465
   199
wenzelm@18465
   200
wenzelm@18465
   201
(* guess rule instantiation -- cannot handle pending goal parameters *)
wenzelm@18465
   202
wenzelm@18465
   203
local
wenzelm@18465
   204
wenzelm@18465
   205
fun dest_env thy (env as Envir.Envir {iTs, ...}) =
wenzelm@18465
   206
  let
wenzelm@18465
   207
    val cert = Thm.cterm_of thy;
wenzelm@18465
   208
    val certT = Thm.ctyp_of thy;
wenzelm@18465
   209
    val pairs = Envir.alist_of env;
wenzelm@18465
   210
    val ts = map (cert o Envir.norm_term env o #2 o #2) pairs;
wenzelm@18465
   211
    val xs = map2 (curry (cert o Var)) (map #1 pairs) (map (#T o Thm.rep_cterm) ts);
wenzelm@18465
   212
  in (map (fn (xi, (S, T)) => (certT (TVar (xi, S)), certT T)) (Vartab.dest iTs), xs ~~ ts) end;
wenzelm@18465
   213
wenzelm@18465
   214
in
wenzelm@18465
   215
wenzelm@18465
   216
fun guess_instance rule i st =
wenzelm@18465
   217
  let
wenzelm@18465
   218
    val {thy, maxidx, ...} = Thm.rep_thm st;
wenzelm@18465
   219
    val goal = Thm.term_of (Thm.cprem_of st i);  (*exception Subscript*)
wenzelm@18465
   220
    val params = rev (rename_wrt_term goal (Logic.strip_params goal));
wenzelm@18465
   221
  in
wenzelm@18465
   222
    if not (null params) then
wenzelm@18465
   223
      (warning ("Cannot determine rule instantiation due to pending parameter(s): " ^
wenzelm@18465
   224
        commas_quote (map (Sign.string_of_term thy o Syntax.mark_boundT) params));
wenzelm@18465
   225
      Seq.single rule)
wenzelm@18465
   226
    else
wenzelm@18465
   227
      let
wenzelm@18465
   228
        val rule' = Thm.incr_indexes (maxidx + 1) rule;
wenzelm@18465
   229
        val concl = Logic.strip_assums_concl goal;
wenzelm@18465
   230
      in
wenzelm@19861
   231
        Unify.smash_unifiers thy [(Thm.concl_of rule', concl)]
wenzelm@19861
   232
          (Envir.empty (#maxidx (Thm.rep_thm rule')))
wenzelm@18465
   233
        |> Seq.map (fn env => Drule.instantiate (dest_env thy env) rule')
wenzelm@18465
   234
      end
wenzelm@18465
   235
  end handle Subscript => Seq.empty;
wenzelm@18465
   236
wenzelm@18465
   237
end;
wenzelm@18465
   238
wenzelm@18465
   239
wenzelm@18465
   240
(* special renaming of rule parameters *)
wenzelm@18465
   241
wenzelm@18465
   242
fun special_rename_params ctxt [[SOME (Free (z, Type (T, _)))]] [thm] =
wenzelm@18465
   243
      let
wenzelm@18465
   244
        val x = ProofContext.revert_skolem ctxt z;
wenzelm@18465
   245
        fun index i [] = []
wenzelm@18465
   246
          | index i (y :: ys) =
wenzelm@18465
   247
              if x = y then x ^ string_of_int i :: index (i + 1) ys
wenzelm@18465
   248
              else y :: index i ys;
wenzelm@18465
   249
        fun rename_params [] = []
wenzelm@18465
   250
          | rename_params ((y, Type (U, _)) :: ys) =
wenzelm@18465
   251
              (if U = T then x else y) :: rename_params ys
wenzelm@18465
   252
          | rename_params ((y, _) :: ys) = y :: rename_params ys;
wenzelm@18465
   253
        fun rename_asm A =
wenzelm@18465
   254
          let
wenzelm@18465
   255
            val xs = rename_params (Logic.strip_params A);
wenzelm@18465
   256
            val xs' =
wenzelm@18465
   257
              (case List.filter (equal x) xs of
wenzelm@18465
   258
                [] => xs | [_] => xs | _ => index 1 xs);
wenzelm@18465
   259
          in Logic.list_rename_params (xs', A) end;
wenzelm@18465
   260
        fun rename_prop p =
wenzelm@18465
   261
          let val (As, C) = Logic.strip_horn p
wenzelm@18465
   262
          in Logic.list_implies (map rename_asm As, C) end;
wenzelm@18465
   263
        val cp' = cterm_fun rename_prop (Thm.cprop_of thm);
wenzelm@18465
   264
        val thm' = Thm.equal_elim (Thm.reflexive cp') thm;
wenzelm@18465
   265
      in [RuleCases.save thm thm'] end
wenzelm@18465
   266
  | special_rename_params _ _ ths = ths;
wenzelm@18465
   267
wenzelm@18465
   268
wenzelm@18235
   269
(* fix_tac *)
wenzelm@11670
   270
wenzelm@18250
   271
local
wenzelm@18240
   272
wenzelm@18250
   273
fun goal_prefix k ((c as Const ("all", _)) $ Abs (a, T, B)) = c $ Abs (a, T, goal_prefix k B)
wenzelm@18250
   274
  | goal_prefix 0 _ = Term.dummy_pattern propT
wenzelm@18250
   275
  | goal_prefix k ((c as Const ("==>", _)) $ A $ B) = c $ A $ goal_prefix (k - 1) B
wenzelm@18250
   276
  | goal_prefix _ _ = Term.dummy_pattern propT;
wenzelm@18250
   277
wenzelm@18250
   278
fun goal_params k (Const ("all", _) $ Abs (_, _, B)) = goal_params k B + 1
wenzelm@18250
   279
  | goal_params 0 _ = 0
wenzelm@18250
   280
  | goal_params k (Const ("==>", _) $ _ $ B) = goal_params (k - 1) B
wenzelm@18250
   281
  | goal_params _ _ = 0;
wenzelm@11670
   282
wenzelm@18250
   283
fun meta_spec_tac ctxt n (x, T) = SUBGOAL (fn (goal, i) =>
wenzelm@18178
   284
  let
wenzelm@18250
   285
    val thy = ProofContext.theory_of ctxt;
wenzelm@18178
   286
    val cert = Thm.cterm_of thy;
wenzelm@18178
   287
    val certT = Thm.ctyp_of thy;
wenzelm@18178
   288
wenzelm@18178
   289
    val v = Free (x, T);
wenzelm@18250
   290
    fun spec_rule prfx (xs, body) =
wenzelm@18250
   291
      meta_spec
wenzelm@18250
   292
      |> Thm.rename_params_rule ([ProofContext.revert_skolem ctxt x], 1)
wenzelm@18250
   293
      |> Thm.lift_rule (cert prfx)
wenzelm@18250
   294
      |> `(Thm.prop_of #> Logic.strip_assums_concl)
wenzelm@18250
   295
      |-> (fn pred $ arg =>
wenzelm@18250
   296
        Drule.cterm_instantiate
wenzelm@18933
   297
          [(cert (Term.head_of pred), cert (Logic.rlist_abs (xs, body))),
wenzelm@18933
   298
           (cert (Term.head_of arg), cert (Logic.rlist_abs (xs, v)))]);
wenzelm@18250
   299
wenzelm@18250
   300
    fun goal_concl k xs (Const ("all", _) $ Abs (a, T, B)) = goal_concl k ((a, T) :: xs) B
wenzelm@18250
   301
      | goal_concl 0 xs B =
wenzelm@18250
   302
          if not (Term.exists_subterm (fn t => t aconv v) B) then NONE
wenzelm@18250
   303
          else SOME (xs, Term.absfree (x, T, Term.incr_boundvars 1 B))
wenzelm@18250
   304
      | goal_concl k xs (Const ("==>", _) $ _ $ B) = goal_concl (k - 1) xs B
wenzelm@18250
   305
      | goal_concl _ _ _ = NONE;
wenzelm@18205
   306
  in
wenzelm@18250
   307
    (case goal_concl n [] goal of
wenzelm@18250
   308
      SOME concl =>
wenzelm@18250
   309
        (compose_tac (false, spec_rule (goal_prefix n goal) concl, 1) THEN' rtac asm_rl) i
wenzelm@18631
   310
    | NONE => all_tac)
wenzelm@18250
   311
  end);
wenzelm@18250
   312
wenzelm@18465
   313
fun miniscope_tac p i = PRIMITIVE (Drule.fconv_rule
wenzelm@18250
   314
  (Drule.goals_conv (Library.equal i)
wenzelm@21708
   315
    (Drule.forall_conv p (MetaSimplifier.rewrite true [Thm.symmetric Drule.norm_hhf_eq]))));
wenzelm@18178
   316
wenzelm@18178
   317
in
wenzelm@18178
   318
wenzelm@18250
   319
fun fix_tac _ _ [] = K all_tac
wenzelm@18250
   320
  | fix_tac ctxt n xs = SUBGOAL (fn (goal, i) =>
wenzelm@18250
   321
     (EVERY' (map (meta_spec_tac ctxt n) xs) THEN'
wenzelm@18250
   322
      (miniscope_tac (goal_params n goal))) i);
wenzelm@18178
   323
wenzelm@18178
   324
end;
wenzelm@18178
   325
wenzelm@18178
   326
wenzelm@18235
   327
(* add_defs *)
wenzelm@18178
   328
wenzelm@18178
   329
fun add_defs def_insts =
wenzelm@18178
   330
  let
wenzelm@18178
   331
    fun add (SOME (SOME x, t)) ctxt =
wenzelm@20879
   332
          let val ([(lhs, (_, th))], ctxt') = LocalDefs.add_defs [((x, NoSyn), (("", []), t))] ctxt
wenzelm@20879
   333
          in ((SOME lhs, [th]), ctxt') end
wenzelm@18178
   334
      | add (SOME (NONE, t)) ctxt = ((SOME t, []), ctxt)
wenzelm@18178
   335
      | add NONE ctxt = ((NONE, []), ctxt);
wenzelm@19482
   336
  in fold_map add def_insts #> apfst (split_list #> apsnd flat) end;
wenzelm@18178
   337
wenzelm@11790
   338
wenzelm@18178
   339
(* induct_tac *)
wenzelm@18178
   340
wenzelm@18178
   341
(*
wenzelm@18178
   342
  rule selection scheme:
wenzelm@18178
   343
    `x:A` induct ...     - set induction
wenzelm@18178
   344
          induct x       - type induction
wenzelm@18178
   345
    ...   induct ... r   - explicit rule
wenzelm@18178
   346
*)
wenzelm@18178
   347
wenzelm@18178
   348
local
nipkow@15235
   349
wenzelm@11735
   350
fun find_inductT ctxt insts =
wenzelm@19482
   351
  fold_rev multiply (insts |> map_filter (fn [] => NONE | ts => List.last ts)
wenzelm@18205
   352
    |> map (InductAttrib.find_inductT ctxt o Term.fastype_of)) [[]]
wenzelm@18799
   353
  |> filter_out (forall PureThy.is_internal);
wenzelm@11670
   354
wenzelm@18465
   355
fun find_inductS ctxt (fact :: _) = map single (InductAttrib.find_inductS ctxt (Thm.concl_of fact))
wenzelm@11735
   356
  | find_inductS _ _ = [];
wenzelm@11735
   357
wenzelm@16391
   358
in
wenzelm@11790
   359
wenzelm@20503
   360
fun induct_tac ctxt is_open def_insts arbitrary taking opt_rule facts =
wenzelm@11670
   361
  let
wenzelm@18224
   362
    val _ = warn_open is_open;
wenzelm@18147
   363
    val thy = ProofContext.theory_of ctxt;
wenzelm@18147
   364
    val cert = Thm.cterm_of thy;
wenzelm@11670
   365
wenzelm@18178
   366
    val ((insts, defs), defs_ctxt) = fold_map add_defs def_insts ctxt |>> split_list;
wenzelm@18259
   367
    val atomized_defs = map (map ObjectLogic.atomize_thm) defs;
wenzelm@18178
   368
wenzelm@18465
   369
    fun inst_rule (concls, r) =
wenzelm@18465
   370
      (if null insts then `RuleCases.get r
wenzelm@18512
   371
       else (align_left "Rule has fewer conclusions than arguments given"
wenzelm@18465
   372
          (map Logic.strip_imp_concl (Logic.dest_conjunctions (Thm.concl_of r))) insts
wenzelm@19482
   373
        |> maps (prep_inst thy align_right (atomize_term thy))
wenzelm@18465
   374
        |> Drule.cterm_instantiate) r |> pair (RuleCases.get r))
wenzelm@18465
   375
      |> (fn ((cases, consumes), th) => (((cases, concls), consumes), th));
wenzelm@11670
   376
wenzelm@11735
   377
    val ruleq =
wenzelm@11735
   378
      (case opt_rule of
wenzelm@19904
   379
        SOME rs => Seq.single (inst_rule (RuleCases.strict_mutual_rule ctxt rs))
wenzelm@18205
   380
      | NONE =>
wenzelm@18205
   381
          (find_inductS ctxt facts @
wenzelm@18205
   382
            map (special_rename_params defs_ctxt insts) (find_inductT ctxt insts))
wenzelm@19904
   383
          |> map_filter (RuleCases.mutual_rule ctxt)
wenzelm@18465
   384
          |> tap (trace_rules ctxt InductAttrib.inductN o map #2)
wenzelm@18465
   385
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@11670
   386
wenzelm@18602
   387
    fun rule_cases rule =
wenzelm@18602
   388
      RuleCases.make_nested is_open (Thm.prop_of rule) (rulified_term rule);
wenzelm@18178
   389
  in
wenzelm@18205
   390
    (fn i => fn st =>
wenzelm@18224
   391
      ruleq
wenzelm@19482
   392
      |> Seq.maps (RuleCases.consume (flat defs) facts)
wenzelm@18465
   393
      |> Seq.maps (fn (((cases, concls), (more_consumes, more_facts)), rule) =>
wenzelm@18496
   394
        (PRECISE_CONJUNCTS (length concls) (ALLGOALS (fn j =>
wenzelm@18496
   395
          (CONJUNCTS (ALLGOALS
wenzelm@18465
   396
            (Method.insert_tac (more_facts @ nth_list atomized_defs (j - 1))
wenzelm@18465
   397
              THEN' fix_tac defs_ctxt
wenzelm@18465
   398
                (nth concls (j - 1) + more_consumes)
wenzelm@20503
   399
                (nth_list arbitrary (j - 1))))
wenzelm@18512
   400
          THEN' inner_atomize_tac) j))
wenzelm@18512
   401
        THEN' atomize_tac) i st |> Seq.maps (fn st' =>
wenzelm@18512
   402
            guess_instance (internalize more_consumes rule) i st'
wenzelm@18235
   403
            |> Seq.map (rule_instance thy taking)
wenzelm@18235
   404
            |> Seq.maps (fn rule' =>
wenzelm@18224
   405
              CASES (rule_cases rule' cases)
wenzelm@18224
   406
                (Tactic.rtac rule' i THEN
wenzelm@20288
   407
                  PRIMITIVE (singleton (ProofContext.export defs_ctxt ctxt))) st'))))
wenzelm@18178
   408
    THEN_ALL_NEW_CASES rulify_tac
wenzelm@18178
   409
  end;
wenzelm@11670
   410
wenzelm@18205
   411
end;
wenzelm@18205
   412
wenzelm@18205
   413
wenzelm@18205
   414
wenzelm@18205
   415
(** coinduct method **)
wenzelm@18205
   416
wenzelm@18205
   417
(*
wenzelm@18205
   418
  rule selection scheme:
wenzelm@18224
   419
    goal "x:A" coinduct ...   - set coinduction
wenzelm@18224
   420
               coinduct x     - type coinduction
wenzelm@18224
   421
               coinduct ... r - explicit rule
wenzelm@18205
   422
*)
wenzelm@18205
   423
wenzelm@18205
   424
local
wenzelm@18205
   425
wenzelm@18205
   426
fun find_coinductT ctxt (SOME t :: _) = InductAttrib.find_coinductT ctxt (Term.fastype_of t)
wenzelm@18205
   427
  | find_coinductT _ _ = [];
wenzelm@18205
   428
wenzelm@18224
   429
fun find_coinductS ctxt goal = InductAttrib.find_coinductS ctxt (Logic.strip_assums_concl goal);
wenzelm@18205
   430
wenzelm@18205
   431
in
wenzelm@18205
   432
wenzelm@18235
   433
fun coinduct_tac ctxt is_open inst taking opt_rule facts =
wenzelm@18205
   434
  let
wenzelm@18224
   435
    val _ = warn_open is_open;
wenzelm@18205
   436
    val thy = ProofContext.theory_of ctxt;
wenzelm@18205
   437
    val cert = Thm.cterm_of thy;
wenzelm@18205
   438
wenzelm@18465
   439
    fun inst_rule r =
wenzelm@18465
   440
      if null inst then `RuleCases.get r
wenzelm@18465
   441
      else Drule.cterm_instantiate (prep_inst thy align_left I (Thm.concl_of r, inst)) r
wenzelm@18465
   442
        |> pair (RuleCases.get r);
wenzelm@18205
   443
wenzelm@18224
   444
    fun ruleq goal =
wenzelm@18205
   445
      (case opt_rule of
wenzelm@18465
   446
        SOME r => Seq.single (inst_rule r)
wenzelm@18205
   447
      | NONE =>
wenzelm@18224
   448
          (find_coinductS ctxt goal @ find_coinductT ctxt inst)
wenzelm@18205
   449
          |> tap (trace_rules ctxt InductAttrib.coinductN)
wenzelm@18465
   450
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@18205
   451
  in
wenzelm@18224
   452
    SUBGOAL_CASES (fn (goal, i) => fn st =>
wenzelm@18224
   453
      ruleq goal
wenzelm@18235
   454
      |> Seq.maps (RuleCases.consume [] facts)
wenzelm@18224
   455
      |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
wenzelm@18259
   456
        guess_instance rule i st
wenzelm@18235
   457
        |> Seq.map (rule_instance thy taking)
wenzelm@18235
   458
        |> Seq.maps (fn rule' =>
wenzelm@18224
   459
          CASES (make_cases is_open rule' cases)
wenzelm@18224
   460
            (Method.insert_tac more_facts i THEN Tactic.rtac rule' i) st)))
wenzelm@18205
   461
  end;
wenzelm@18205
   462
wenzelm@11670
   463
end;
wenzelm@11670
   464
wenzelm@11670
   465
wenzelm@11670
   466
wenzelm@11670
   467
(** concrete syntax **)
wenzelm@11670
   468
wenzelm@11670
   469
val openN = "open";
wenzelm@20503
   470
val arbitraryN = "arbitrary";
wenzelm@18235
   471
val takingN = "taking";
wenzelm@11670
   472
val ruleN = "rule";
wenzelm@11670
   473
wenzelm@11670
   474
local
wenzelm@11670
   475
wenzelm@18465
   476
fun single_rule [rule] = rule
wenzelm@18465
   477
  | single_rule _ = error "Single rule expected";
wenzelm@18465
   478
wenzelm@15703
   479
fun named_rule k arg get =
wenzelm@18465
   480
  Scan.lift (Args.$$$ k -- Args.colon) |-- Scan.repeat arg :--
wenzelm@18988
   481
    (fn names => Scan.peek (fn context => Scan.succeed (names |> map (fn name =>
wenzelm@18988
   482
      (case get (Context.proof_of context) name of SOME x => x
wenzelm@18465
   483
      | NONE => error ("No rule for " ^ k ^ " " ^ quote name)))))) >> #2;
wenzelm@11670
   484
wenzelm@11670
   485
fun rule get_type get_set =
wenzelm@18988
   486
  named_rule InductAttrib.typeN Args.tyname get_type ||
wenzelm@18988
   487
  named_rule InductAttrib.setN Args.const get_set ||
wenzelm@18988
   488
  Scan.lift (Args.$$$ ruleN -- Args.colon) |-- Attrib.thms;
wenzelm@11670
   489
wenzelm@18465
   490
val cases_rule = rule InductAttrib.lookup_casesT InductAttrib.lookup_casesS >> single_rule;
wenzelm@11670
   491
val induct_rule = rule InductAttrib.lookup_inductT InductAttrib.lookup_inductS;
wenzelm@18465
   492
val coinduct_rule =
wenzelm@18465
   493
  rule InductAttrib.lookup_coinductT InductAttrib.lookup_coinductS >> single_rule;
wenzelm@11670
   494
wenzelm@18988
   495
val inst = Scan.lift (Args.$$$ "_") >> K NONE || Args.term >> SOME;
wenzelm@18147
   496
wenzelm@18178
   497
val def_inst =
wenzelm@18178
   498
  ((Scan.lift (Args.name --| (Args.$$$ "\\<equiv>" || Args.$$$ "==")) >> SOME)
wenzelm@18988
   499
      -- Args.term) >> SOME ||
wenzelm@18178
   500
    inst >> Option.map (pair NONE);
wenzelm@11670
   501
wenzelm@18988
   502
val free = Scan.state -- Args.term >> (fn (_, Free v) => v | (context, t) =>
wenzelm@18988
   503
  error ("Bad free variable: " ^ ProofContext.string_of_term (Context.proof_of context) t));
wenzelm@18147
   504
wenzelm@18178
   505
fun unless_more_args scan = Scan.unless (Scan.lift
wenzelm@20503
   506
  ((Args.$$$ arbitraryN || Args.$$$ takingN || Args.$$$ InductAttrib.typeN ||
wenzelm@18235
   507
    Args.$$$ InductAttrib.setN || Args.$$$ ruleN) -- Args.colon)) scan;
wenzelm@18205
   508
wenzelm@20503
   509
val arbitrary = Scan.optional (Scan.lift (Args.$$$ arbitraryN -- Args.colon) |--
wenzelm@18205
   510
  Args.and_list1 (Scan.repeat (unless_more_args free))) [];
wenzelm@18178
   511
wenzelm@18235
   512
val taking = Scan.optional (Scan.lift (Args.$$$ takingN -- Args.colon) |--
wenzelm@18235
   513
  Scan.repeat1 (unless_more_args inst)) [];
wenzelm@18235
   514
wenzelm@11670
   515
in
wenzelm@11670
   516
wenzelm@18235
   517
fun cases_meth src =
wenzelm@18235
   518
  Method.syntax (Args.mode openN --
wenzelm@18235
   519
    (Args.and_list (Scan.repeat (unless_more_args inst)) -- Scan.option cases_rule)) src
haftmann@21879
   520
  #> (fn ((is_open, (insts, opt_rule)), ctxt) =>
wenzelm@18235
   521
    Method.METHOD_CASES (fn facts =>
wenzelm@18235
   522
      Seq.DETERM (HEADGOAL (cases_tac ctxt is_open insts opt_rule facts))));
wenzelm@18178
   523
wenzelm@18512
   524
fun induct_meth src =
wenzelm@18235
   525
  Method.syntax (Args.mode openN --
wenzelm@18235
   526
    (Args.and_list (Scan.repeat (unless_more_args def_inst)) --
wenzelm@20503
   527
    (arbitrary -- taking -- Scan.option induct_rule))) src
haftmann@21879
   528
  #> (fn ((is_open, (insts, ((arbitrary, taking), opt_rule))), ctxt) =>
wenzelm@18235
   529
    Method.RAW_METHOD_CASES (fn facts =>
wenzelm@20503
   530
      Seq.DETERM (HEADGOAL (induct_tac ctxt is_open insts arbitrary taking opt_rule facts))));
wenzelm@18205
   531
wenzelm@18235
   532
fun coinduct_meth src =
wenzelm@18235
   533
  Method.syntax (Args.mode openN --
wenzelm@18235
   534
    (Scan.repeat (unless_more_args inst) -- taking -- Scan.option coinduct_rule)) src
haftmann@21879
   535
  #> (fn ((is_open, ((insts, taking), opt_rule)), ctxt) =>
wenzelm@18235
   536
    Method.RAW_METHOD_CASES (fn facts =>
wenzelm@18235
   537
      Seq.DETERM (HEADGOAL (coinduct_tac ctxt is_open insts taking opt_rule facts))));
wenzelm@11670
   538
wenzelm@11670
   539
end;
wenzelm@11670
   540
wenzelm@11670
   541
wenzelm@11670
   542
wenzelm@11670
   543
(** theory setup **)
wenzelm@11670
   544
wenzelm@11670
   545
val setup =
wenzelm@18708
   546
  Method.add_methods
wenzelm@18235
   547
    [(InductAttrib.casesN, cases_meth, "case analysis on types or sets"),
wenzelm@18512
   548
     (InductAttrib.inductN, induct_meth, "induction on types or sets"),
wenzelm@18708
   549
     (InductAttrib.coinductN, coinduct_meth, "coinduction on types or sets")];
wenzelm@11670
   550
wenzelm@11670
   551
end;