src/Provers/induct_method.ML
author wenzelm
Thu Dec 22 00:28:51 2005 +0100 (2005-12-22)
changeset 18465 16dcd36499b8
parent 18330 444f16d232a2
child 18496 ef36f9be255e
permissions -rw-r--r--
simplified setup: removed dest_concls, local_impI, conjI;
improved handling of simultaneous goals: split cases;
simplified treatment of mutual rules, which are now specified as a list
instead of object-level conjunction (cf. set/type/rule);
moved join_rules to RuleCases.mutual_rule;
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@18465
    11
  val atomize_old: thm list
wenzelm@11670
    12
  val atomize: thm list
wenzelm@18465
    13
  val rulify: thm list
wenzelm@18465
    14
  val rulify_fallback: thm list
wenzelm@11670
    15
end;
wenzelm@11670
    16
wenzelm@11670
    17
signature INDUCT_METHOD =
wenzelm@11670
    18
sig
wenzelm@18250
    19
  val fix_tac: Proof.context -> int -> (string * typ) list -> int -> tactic
wenzelm@18287
    20
  val add_defs: (string option * term) option list -> Proof.context ->
wenzelm@18287
    21
    (term option list * thm list) * Proof.context
wenzelm@18250
    22
  val atomize_term: theory -> term -> term
wenzelm@18250
    23
  val atomize_tac: int -> tactic
wenzelm@18250
    24
  val rulified_term: thm -> theory * term
wenzelm@18250
    25
  val rulify_tac: int -> tactic
wenzelm@18259
    26
  val guess_instance: thm -> int -> thm -> thm Seq.seq
wenzelm@16391
    27
  val cases_tac: Proof.context -> bool -> term option list list -> thm option ->
wenzelm@18224
    28
    thm list -> int -> cases_tactic
wenzelm@18178
    29
  val induct_tac: Proof.context -> bool -> (string option * term) option list list ->
wenzelm@18465
    30
    (string * typ) list list -> term option list -> thm list option -> thm list -> int ->
wenzelm@18465
    31
    cases_tactic
wenzelm@18235
    32
  val coinduct_tac: Proof.context -> bool -> term option list -> term option list ->
wenzelm@18235
    33
    thm option -> thm list -> int -> cases_tactic
wenzelm@11670
    34
  val setup: (theory -> theory) list
wenzelm@11670
    35
end;
wenzelm@11670
    36
wenzelm@11670
    37
functor InductMethodFun(Data: INDUCT_METHOD_DATA): INDUCT_METHOD =
wenzelm@11670
    38
struct
wenzelm@11670
    39
wenzelm@18465
    40
val meta_spec = thm "Pure.meta_spec";
wenzelm@18465
    41
val all_conjunction = thm "Pure.all_conjunction";
wenzelm@18465
    42
val imp_conjunction = thm "Pure.imp_conjunction";
wenzelm@18465
    43
val conjunction_imp = thm "Pure.conjunction_imp";
wenzelm@18465
    44
val conjunction_assoc = thm "Pure.conjunction_assoc";
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@11735
    55
  in if m < n then raise ERROR_MESSAGE 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@11735
    59
  in if m < n then raise ERROR_MESSAGE 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@11735
    74
            else raise ERROR_MESSAGE (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
skalberg@15570
    83
    |> List.mapPartial 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@18224
    96
  RuleCases.make is_open NONE (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@18205
   132
        |> (List.concat o map (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@18465
   159
fun common_atomize_term is_old thy =
wenzelm@18465
   160
  MetaSimplifier.rewrite_term thy (if is_old then Data.atomize_old else Data.atomize) []
wenzelm@18465
   161
  #> ObjectLogic.drop_judgment thy;
wenzelm@18465
   162
wenzelm@18465
   163
val atomize_term = common_atomize_term false;
wenzelm@18465
   164
wenzelm@18465
   165
fun common_atomize_cterm is_old =
wenzelm@18465
   166
  Tactic.rewrite true (if is_old then Data.atomize_old else Data.atomize);
wenzelm@18465
   167
wenzelm@18465
   168
fun common_atomize_tac is_old inner =
wenzelm@18465
   169
  if is_old then
wenzelm@18465
   170
    Tactic.rewrite_goal_tac [conjunction_assoc]
wenzelm@18465
   171
    THEN' Tactic.rewrite_goal_tac Data.atomize_old
wenzelm@18465
   172
  else
wenzelm@18465
   173
    (if inner then Tactic.rewrite_goal_tac (map Thm.symmetric conjunction_congs) else K all_tac)
wenzelm@18465
   174
    THEN' Tactic.rewrite_goal_tac Data.atomize;
wenzelm@18465
   175
wenzelm@18465
   176
val atomize_tac = common_atomize_tac false false;
wenzelm@18465
   177
val inner_atomize_tac = common_atomize_tac false true;
wenzelm@18465
   178
wenzelm@18465
   179
wenzelm@18465
   180
(* rulify *)
wenzelm@18465
   181
wenzelm@18465
   182
fun rulify_term thy =
wenzelm@18465
   183
  MetaSimplifier.rewrite_term thy (Data.rulify @ conjunction_congs) [] #>
wenzelm@18465
   184
  MetaSimplifier.rewrite_term thy Data.rulify_fallback [];
wenzelm@18465
   185
wenzelm@18465
   186
fun rulified_term thm =
wenzelm@18465
   187
  let
wenzelm@18465
   188
    val thy = Thm.theory_of_thm thm;
wenzelm@18465
   189
    val rulify = rulify_term thy;
wenzelm@18465
   190
    val (As, B) = Logic.strip_horn (Thm.prop_of thm);
wenzelm@18465
   191
  in (thy, Logic.list_implies (map rulify As, rulify B)) end;
wenzelm@18465
   192
wenzelm@18465
   193
val curry_prems_tac =
wenzelm@18465
   194
  let
wenzelm@18465
   195
    val rule = conjunction_imp;
wenzelm@18465
   196
    val thy = Thm.theory_of_thm rule;
wenzelm@18465
   197
    val proc = Simplifier.simproc_i thy "curry_prems"
wenzelm@18465
   198
      [#1 (Logic.dest_equals (Thm.prop_of rule))]
wenzelm@18465
   199
      (fn _ => fn ss => fn _ =>  (*WORKAROUND: prevent descending into meta conjunctions*)
wenzelm@18465
   200
        if exists (equal propT o #2 o #1) (#2 (#bounds (#1 (Simplifier.rep_ss ss))))
wenzelm@18465
   201
        then NONE else SOME rule);
wenzelm@18465
   202
    val ss = MetaSimplifier.theory_context thy Simplifier.empty_ss addsimprocs [proc];
wenzelm@18465
   203
  in Simplifier.full_simp_tac ss end;
wenzelm@18465
   204
wenzelm@18465
   205
val rulify_tac =
wenzelm@18465
   206
  Tactic.rewrite_goal_tac (Data.rulify @ conjunction_congs) THEN'
wenzelm@18465
   207
  Tactic.rewrite_goal_tac Data.rulify_fallback THEN'
wenzelm@18465
   208
  Tactic.conjunction_tac THEN_ALL_NEW
wenzelm@18465
   209
  (curry_prems_tac THEN' Tactic.norm_hhf_tac);
wenzelm@18465
   210
wenzelm@18465
   211
wenzelm@18465
   212
(* prepare rule *)
wenzelm@18465
   213
wenzelm@18465
   214
fun rule_instance thy inst rule =
wenzelm@18465
   215
  Drule.cterm_instantiate (prep_inst thy align_left I (Thm.prop_of rule, inst)) rule;
wenzelm@18465
   216
wenzelm@18465
   217
fun mutual_rule ths =
wenzelm@18465
   218
  (case RuleCases.mutual_rule ths of
wenzelm@18465
   219
    NONE => error "Failed to join given rules into one mutual rule"
wenzelm@18465
   220
  | SOME res => res);
wenzelm@18465
   221
wenzelm@18465
   222
fun internalize is_old k th =
wenzelm@18465
   223
  th |> Thm.permute_prems 0 k
wenzelm@18465
   224
  |> Drule.fconv_rule (Drule.concl_conv (Thm.nprems_of th - k) (common_atomize_cterm is_old));
wenzelm@18465
   225
wenzelm@18465
   226
wenzelm@18465
   227
(* guess rule instantiation -- cannot handle pending goal parameters *)
wenzelm@18465
   228
wenzelm@18465
   229
local
wenzelm@18465
   230
wenzelm@18465
   231
fun dest_env thy (env as Envir.Envir {iTs, ...}) =
wenzelm@18465
   232
  let
wenzelm@18465
   233
    val cert = Thm.cterm_of thy;
wenzelm@18465
   234
    val certT = Thm.ctyp_of thy;
wenzelm@18465
   235
    val pairs = Envir.alist_of env;
wenzelm@18465
   236
    val ts = map (cert o Envir.norm_term env o #2 o #2) pairs;
wenzelm@18465
   237
    val xs = map2 (curry (cert o Var)) (map #1 pairs) (map (#T o Thm.rep_cterm) ts);
wenzelm@18465
   238
  in (map (fn (xi, (S, T)) => (certT (TVar (xi, S)), certT T)) (Vartab.dest iTs), xs ~~ ts) end;
wenzelm@18465
   239
wenzelm@18465
   240
in
wenzelm@18465
   241
wenzelm@18465
   242
fun guess_instance rule i st =
wenzelm@18465
   243
  let
wenzelm@18465
   244
    val {thy, maxidx, ...} = Thm.rep_thm st;
wenzelm@18465
   245
    val goal = Thm.term_of (Thm.cprem_of st i);  (*exception Subscript*)
wenzelm@18465
   246
    val params = rev (rename_wrt_term goal (Logic.strip_params goal));
wenzelm@18465
   247
  in
wenzelm@18465
   248
    if not (null params) then
wenzelm@18465
   249
      (warning ("Cannot determine rule instantiation due to pending parameter(s): " ^
wenzelm@18465
   250
        commas_quote (map (Sign.string_of_term thy o Syntax.mark_boundT) params));
wenzelm@18465
   251
      Seq.single rule)
wenzelm@18465
   252
    else
wenzelm@18465
   253
      let
wenzelm@18465
   254
        val rule' = Thm.incr_indexes (maxidx + 1) rule;
wenzelm@18465
   255
        val concl = Logic.strip_assums_concl goal;
wenzelm@18465
   256
      in
wenzelm@18465
   257
        Unify.smash_unifiers (thy, Envir.empty (#maxidx (Thm.rep_thm rule')),
wenzelm@18465
   258
          [(Thm.concl_of rule', concl)])
wenzelm@18465
   259
        |> Seq.map (fn env => Drule.instantiate (dest_env thy env) rule')
wenzelm@18465
   260
      end
wenzelm@18465
   261
  end handle Subscript => Seq.empty;
wenzelm@18465
   262
wenzelm@18465
   263
end;
wenzelm@18465
   264
wenzelm@18465
   265
wenzelm@18465
   266
(* special renaming of rule parameters *)
wenzelm@18465
   267
wenzelm@18465
   268
fun special_rename_params ctxt [[SOME (Free (z, Type (T, _)))]] [thm] =
wenzelm@18465
   269
      let
wenzelm@18465
   270
        val x = ProofContext.revert_skolem ctxt z;
wenzelm@18465
   271
        fun index i [] = []
wenzelm@18465
   272
          | index i (y :: ys) =
wenzelm@18465
   273
              if x = y then x ^ string_of_int i :: index (i + 1) ys
wenzelm@18465
   274
              else y :: index i ys;
wenzelm@18465
   275
        fun rename_params [] = []
wenzelm@18465
   276
          | rename_params ((y, Type (U, _)) :: ys) =
wenzelm@18465
   277
              (if U = T then x else y) :: rename_params ys
wenzelm@18465
   278
          | rename_params ((y, _) :: ys) = y :: rename_params ys;
wenzelm@18465
   279
        fun rename_asm A =
wenzelm@18465
   280
          let
wenzelm@18465
   281
            val xs = rename_params (Logic.strip_params A);
wenzelm@18465
   282
            val xs' =
wenzelm@18465
   283
              (case List.filter (equal x) xs of
wenzelm@18465
   284
                [] => xs | [_] => xs | _ => index 1 xs);
wenzelm@18465
   285
          in Logic.list_rename_params (xs', A) end;
wenzelm@18465
   286
        fun rename_prop p =
wenzelm@18465
   287
          let val (As, C) = Logic.strip_horn p
wenzelm@18465
   288
          in Logic.list_implies (map rename_asm As, C) end;
wenzelm@18465
   289
        val cp' = cterm_fun rename_prop (Thm.cprop_of thm);
wenzelm@18465
   290
        val thm' = Thm.equal_elim (Thm.reflexive cp') thm;
wenzelm@18465
   291
      in [RuleCases.save thm thm'] end
wenzelm@18465
   292
  | special_rename_params _ _ ths = ths;
wenzelm@18465
   293
wenzelm@18465
   294
wenzelm@18235
   295
(* fix_tac *)
wenzelm@11670
   296
wenzelm@18250
   297
local
wenzelm@18240
   298
wenzelm@18250
   299
fun goal_prefix k ((c as Const ("all", _)) $ Abs (a, T, B)) = c $ Abs (a, T, goal_prefix k B)
wenzelm@18250
   300
  | goal_prefix 0 _ = Term.dummy_pattern propT
wenzelm@18250
   301
  | goal_prefix k ((c as Const ("==>", _)) $ A $ B) = c $ A $ goal_prefix (k - 1) B
wenzelm@18250
   302
  | goal_prefix _ _ = Term.dummy_pattern propT;
wenzelm@18250
   303
wenzelm@18250
   304
fun goal_params k (Const ("all", _) $ Abs (_, _, B)) = goal_params k B + 1
wenzelm@18250
   305
  | goal_params 0 _ = 0
wenzelm@18250
   306
  | goal_params k (Const ("==>", _) $ _ $ B) = goal_params (k - 1) B
wenzelm@18250
   307
  | goal_params _ _ = 0;
wenzelm@11670
   308
wenzelm@18250
   309
fun meta_spec_tac ctxt n (x, T) = SUBGOAL (fn (goal, i) =>
wenzelm@18178
   310
  let
wenzelm@18250
   311
    val thy = ProofContext.theory_of ctxt;
wenzelm@18178
   312
    val cert = Thm.cterm_of thy;
wenzelm@18178
   313
    val certT = Thm.ctyp_of thy;
wenzelm@18178
   314
wenzelm@18178
   315
    val v = Free (x, T);
wenzelm@18250
   316
    fun spec_rule prfx (xs, body) =
wenzelm@18250
   317
      meta_spec
wenzelm@18250
   318
      |> Thm.rename_params_rule ([ProofContext.revert_skolem ctxt x], 1)
wenzelm@18250
   319
      |> Thm.lift_rule (cert prfx)
wenzelm@18250
   320
      |> `(Thm.prop_of #> Logic.strip_assums_concl)
wenzelm@18250
   321
      |-> (fn pred $ arg =>
wenzelm@18250
   322
        Drule.cterm_instantiate
wenzelm@18250
   323
          [(cert (Term.head_of pred), cert (Unify.rlist_abs (xs, body))),
wenzelm@18250
   324
           (cert (Term.head_of arg), cert (Unify.rlist_abs (xs, v)))]);
wenzelm@18250
   325
wenzelm@18250
   326
    fun goal_concl k xs (Const ("all", _) $ Abs (a, T, B)) = goal_concl k ((a, T) :: xs) B
wenzelm@18250
   327
      | goal_concl 0 xs B =
wenzelm@18250
   328
          if not (Term.exists_subterm (fn t => t aconv v) B) then NONE
wenzelm@18250
   329
          else SOME (xs, Term.absfree (x, T, Term.incr_boundvars 1 B))
wenzelm@18250
   330
      | goal_concl k xs (Const ("==>", _) $ _ $ B) = goal_concl (k - 1) xs B
wenzelm@18250
   331
      | goal_concl _ _ _ = NONE;
wenzelm@18205
   332
  in
wenzelm@18250
   333
    (case goal_concl n [] goal of
wenzelm@18250
   334
      SOME concl =>
wenzelm@18250
   335
        (compose_tac (false, spec_rule (goal_prefix n goal) concl, 1) THEN' rtac asm_rl) i
wenzelm@18465
   336
    | NONE => (warning ("Induction: no variable " ^ quote (ProofContext.string_of_term ctxt v) ^
wenzelm@18250
   337
        " to be fixed -- ignored"); all_tac))
wenzelm@18250
   338
  end);
wenzelm@18250
   339
wenzelm@18465
   340
fun miniscope_tac p i = PRIMITIVE (Drule.fconv_rule
wenzelm@18250
   341
  (Drule.goals_conv (Library.equal i)
wenzelm@18465
   342
    (Drule.forall_conv p (Tactic.rewrite true [Thm.symmetric Drule.norm_hhf_eq]))));
wenzelm@18178
   343
wenzelm@18178
   344
in
wenzelm@18178
   345
wenzelm@18250
   346
fun fix_tac _ _ [] = K all_tac
wenzelm@18250
   347
  | fix_tac ctxt n xs = SUBGOAL (fn (goal, i) =>
wenzelm@18250
   348
     (EVERY' (map (meta_spec_tac ctxt n) xs) THEN'
wenzelm@18250
   349
      (miniscope_tac (goal_params n goal))) i);
wenzelm@18178
   350
wenzelm@18178
   351
end;
wenzelm@18178
   352
wenzelm@18178
   353
wenzelm@18235
   354
(* add_defs *)
wenzelm@18178
   355
wenzelm@18178
   356
fun add_defs def_insts =
wenzelm@18178
   357
  let
wenzelm@18178
   358
    fun add (SOME (SOME x, t)) ctxt =
wenzelm@18178
   359
          let val ((lhs, def), ctxt') = ProofContext.add_def (x, t) ctxt
wenzelm@18178
   360
          in ((SOME (Free lhs), [def]), ctxt') end
wenzelm@18178
   361
      | add (SOME (NONE, t)) ctxt = ((SOME t, []), ctxt)
wenzelm@18178
   362
      | add NONE ctxt = ((NONE, []), ctxt);
wenzelm@18178
   363
  in fold_map add def_insts #> apfst (split_list #> apsnd List.concat) end;
wenzelm@18178
   364
wenzelm@11790
   365
wenzelm@18178
   366
(* induct_tac *)
wenzelm@18178
   367
wenzelm@18178
   368
(*
wenzelm@18178
   369
  rule selection scheme:
wenzelm@18178
   370
    `x:A` induct ...     - set induction
wenzelm@18178
   371
          induct x       - type induction
wenzelm@18178
   372
    ...   induct ... r   - explicit rule
wenzelm@18178
   373
*)
wenzelm@18178
   374
wenzelm@18178
   375
local
nipkow@15235
   376
wenzelm@11735
   377
fun find_inductT ctxt insts =
wenzelm@18147
   378
  fold_rev multiply (insts |> List.mapPartial (fn [] => NONE | ts => List.last ts)
wenzelm@18205
   379
    |> map (InductAttrib.find_inductT ctxt o Term.fastype_of)) [[]]
wenzelm@18465
   380
  |> filter_out (forall Drule.is_internal);
wenzelm@11670
   381
wenzelm@18465
   382
fun find_inductS ctxt (fact :: _) = map single (InductAttrib.find_inductS ctxt (Thm.concl_of fact))
wenzelm@11735
   383
  | find_inductS _ _ = [];
wenzelm@11735
   384
wenzelm@16391
   385
in
wenzelm@11790
   386
wenzelm@18465
   387
fun common_induct_tac is_old ctxt is_open def_insts fixing taking opt_rule facts =
wenzelm@11670
   388
  let
wenzelm@18224
   389
    val _ = warn_open is_open;
wenzelm@18147
   390
    val thy = ProofContext.theory_of ctxt;
wenzelm@18147
   391
    val cert = Thm.cterm_of thy;
wenzelm@11670
   392
wenzelm@18178
   393
    val ((insts, defs), defs_ctxt) = fold_map add_defs def_insts ctxt |>> split_list;
wenzelm@18259
   394
    val atomized_defs = map (map ObjectLogic.atomize_thm) defs;
wenzelm@18178
   395
wenzelm@18465
   396
    fun inst_rule (concls, r) =
wenzelm@18465
   397
      (if null insts then `RuleCases.get r
wenzelm@18465
   398
       else (align_right "Rule has fewer conclusions than arguments given"
wenzelm@18465
   399
          (map Logic.strip_imp_concl (Logic.dest_conjunctions (Thm.concl_of r))) insts
wenzelm@18465
   400
        |> (List.concat o map (prep_inst thy align_right (common_atomize_term is_old thy)))
wenzelm@18465
   401
        |> Drule.cterm_instantiate) r |> pair (RuleCases.get r))
wenzelm@18465
   402
      |> (fn ((cases, consumes), th) => (((cases, concls), consumes), th));
wenzelm@11670
   403
wenzelm@11735
   404
    val ruleq =
wenzelm@11735
   405
      (case opt_rule of
wenzelm@18465
   406
        SOME rs => Seq.single (inst_rule (mutual_rule rs))
wenzelm@18205
   407
      | NONE =>
wenzelm@18205
   408
          (find_inductS ctxt facts @
wenzelm@18205
   409
            map (special_rename_params defs_ctxt insts) (find_inductT ctxt insts))
wenzelm@18465
   410
          |> List.mapPartial RuleCases.mutual_rule
wenzelm@18465
   411
          |> tap (trace_rules ctxt InductAttrib.inductN o map #2)
wenzelm@18465
   412
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@11670
   413
wenzelm@18224
   414
    fun rule_cases rule = RuleCases.make is_open (SOME (Thm.prop_of rule)) (rulified_term rule);
wenzelm@18178
   415
  in
wenzelm@18205
   416
    (fn i => fn st =>
wenzelm@18224
   417
      ruleq
wenzelm@18235
   418
      |> Seq.maps (RuleCases.consume (List.concat defs) facts)
wenzelm@18465
   419
      |> Seq.maps (fn (((cases, concls), (more_consumes, more_facts)), rule) =>
wenzelm@18465
   420
        (CONJUNCTS (length concls) (ALLGOALS (fn j =>
wenzelm@18465
   421
          (CONJUNCTS ~1 (ALLGOALS
wenzelm@18465
   422
            (Method.insert_tac (more_facts @ nth_list atomized_defs (j - 1))
wenzelm@18465
   423
              THEN' fix_tac defs_ctxt
wenzelm@18465
   424
                (nth concls (j - 1) + more_consumes)
wenzelm@18465
   425
                (nth_list fixing (j - 1))))
wenzelm@18465
   426
          THEN' common_atomize_tac is_old true) j))
wenzelm@18465
   427
        THEN' common_atomize_tac is_old false) i st |> Seq.maps (fn st' =>
wenzelm@18465
   428
            guess_instance (internalize is_old more_consumes rule) i st'
wenzelm@18235
   429
            |> Seq.map (rule_instance thy taking)
wenzelm@18235
   430
            |> Seq.maps (fn rule' =>
wenzelm@18224
   431
              CASES (rule_cases rule' cases)
wenzelm@18224
   432
                (Tactic.rtac rule' i THEN
wenzelm@18224
   433
                  PRIMSEQ (ProofContext.exports defs_ctxt ctxt)) st'))))
wenzelm@18178
   434
    THEN_ALL_NEW_CASES rulify_tac
wenzelm@18178
   435
  end;
wenzelm@11670
   436
wenzelm@18465
   437
val induct_tac = common_induct_tac false;
wenzelm@18465
   438
wenzelm@18205
   439
end;
wenzelm@18205
   440
wenzelm@18205
   441
wenzelm@18205
   442
wenzelm@18205
   443
(** coinduct method **)
wenzelm@18205
   444
wenzelm@18205
   445
(*
wenzelm@18205
   446
  rule selection scheme:
wenzelm@18224
   447
    goal "x:A" coinduct ...   - set coinduction
wenzelm@18224
   448
               coinduct x     - type coinduction
wenzelm@18224
   449
               coinduct ... r - explicit rule
wenzelm@18205
   450
*)
wenzelm@18205
   451
wenzelm@18205
   452
local
wenzelm@18205
   453
wenzelm@18205
   454
fun find_coinductT ctxt (SOME t :: _) = InductAttrib.find_coinductT ctxt (Term.fastype_of t)
wenzelm@18205
   455
  | find_coinductT _ _ = [];
wenzelm@18205
   456
wenzelm@18224
   457
fun find_coinductS ctxt goal = InductAttrib.find_coinductS ctxt (Logic.strip_assums_concl goal);
wenzelm@18205
   458
wenzelm@18205
   459
in
wenzelm@18205
   460
wenzelm@18235
   461
fun coinduct_tac ctxt is_open inst taking opt_rule facts =
wenzelm@18205
   462
  let
wenzelm@18224
   463
    val _ = warn_open is_open;
wenzelm@18205
   464
    val thy = ProofContext.theory_of ctxt;
wenzelm@18205
   465
    val cert = Thm.cterm_of thy;
wenzelm@18205
   466
wenzelm@18465
   467
    fun inst_rule r =
wenzelm@18465
   468
      if null inst then `RuleCases.get r
wenzelm@18465
   469
      else Drule.cterm_instantiate (prep_inst thy align_left I (Thm.concl_of r, inst)) r
wenzelm@18465
   470
        |> pair (RuleCases.get r);
wenzelm@18205
   471
wenzelm@18224
   472
    fun ruleq goal =
wenzelm@18205
   473
      (case opt_rule of
wenzelm@18465
   474
        SOME r => Seq.single (inst_rule r)
wenzelm@18205
   475
      | NONE =>
wenzelm@18224
   476
          (find_coinductS ctxt goal @ find_coinductT ctxt inst)
wenzelm@18205
   477
          |> tap (trace_rules ctxt InductAttrib.coinductN)
wenzelm@18465
   478
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@18205
   479
  in
wenzelm@18224
   480
    SUBGOAL_CASES (fn (goal, i) => fn st =>
wenzelm@18224
   481
      ruleq goal
wenzelm@18235
   482
      |> Seq.maps (RuleCases.consume [] facts)
wenzelm@18224
   483
      |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
wenzelm@18259
   484
        guess_instance rule i st
wenzelm@18235
   485
        |> Seq.map (rule_instance thy taking)
wenzelm@18235
   486
        |> Seq.maps (fn rule' =>
wenzelm@18224
   487
          CASES (make_cases is_open rule' cases)
wenzelm@18224
   488
            (Method.insert_tac more_facts i THEN Tactic.rtac rule' i) st)))
wenzelm@18205
   489
  end;
wenzelm@18205
   490
wenzelm@11670
   491
end;
wenzelm@11670
   492
wenzelm@11670
   493
wenzelm@11670
   494
wenzelm@11670
   495
(** concrete syntax **)
wenzelm@11670
   496
wenzelm@11670
   497
val openN = "open";
wenzelm@18205
   498
val fixingN = "fixing";
wenzelm@18235
   499
val takingN = "taking";
wenzelm@11670
   500
val ruleN = "rule";
wenzelm@11670
   501
wenzelm@11670
   502
local
wenzelm@11670
   503
wenzelm@18465
   504
fun single_rule [rule] = rule
wenzelm@18465
   505
  | single_rule _ = error "Single rule expected";
wenzelm@18465
   506
wenzelm@15703
   507
fun named_rule k arg get =
wenzelm@18465
   508
  Scan.lift (Args.$$$ k -- Args.colon) |-- Scan.repeat arg :--
wenzelm@18465
   509
    (fn names => Scan.peek (fn ctxt => Scan.succeed (names |> map (fn name =>
wenzelm@18465
   510
      (case get ctxt name of SOME x => x
wenzelm@18465
   511
      | NONE => error ("No rule for " ^ k ^ " " ^ quote name)))))) >> #2;
wenzelm@11670
   512
wenzelm@11670
   513
fun rule get_type get_set =
wenzelm@15703
   514
  named_rule InductAttrib.typeN Args.local_tyname get_type ||
wenzelm@15703
   515
  named_rule InductAttrib.setN Args.local_const get_set ||
wenzelm@18465
   516
  Scan.lift (Args.$$$ ruleN -- Args.colon) |-- Attrib.local_thmss;
wenzelm@11670
   517
wenzelm@18465
   518
val cases_rule = rule InductAttrib.lookup_casesT InductAttrib.lookup_casesS >> single_rule;
wenzelm@11670
   519
val induct_rule = rule InductAttrib.lookup_inductT InductAttrib.lookup_inductS;
wenzelm@18465
   520
val coinduct_rule =
wenzelm@18465
   521
  rule InductAttrib.lookup_coinductT InductAttrib.lookup_coinductS >> single_rule;
wenzelm@11670
   522
wenzelm@18178
   523
val inst = Scan.lift (Args.$$$ "_") >> K NONE || Args.local_term >> SOME;
wenzelm@18147
   524
wenzelm@18178
   525
val def_inst =
wenzelm@18178
   526
  ((Scan.lift (Args.name --| (Args.$$$ "\\<equiv>" || Args.$$$ "==")) >> SOME)
wenzelm@18178
   527
      -- Args.local_term) >> SOME ||
wenzelm@18178
   528
    inst >> Option.map (pair NONE);
wenzelm@11670
   529
wenzelm@18147
   530
val free = Scan.state -- Args.local_term >> (fn (_, Free v) => v | (ctxt, t) =>
wenzelm@18147
   531
  error ("Bad free variable: " ^ ProofContext.string_of_term ctxt t));
wenzelm@18147
   532
wenzelm@18178
   533
fun unless_more_args scan = Scan.unless (Scan.lift
wenzelm@18235
   534
  ((Args.$$$ fixingN || Args.$$$ takingN || Args.$$$ InductAttrib.typeN ||
wenzelm@18235
   535
    Args.$$$ InductAttrib.setN || Args.$$$ ruleN) -- Args.colon)) scan;
wenzelm@18205
   536
wenzelm@18205
   537
val fixing = Scan.optional (Scan.lift (Args.$$$ fixingN -- Args.colon) |--
wenzelm@18205
   538
  Args.and_list1 (Scan.repeat (unless_more_args free))) [];
wenzelm@18178
   539
wenzelm@18235
   540
val taking = Scan.optional (Scan.lift (Args.$$$ takingN -- Args.colon) |--
wenzelm@18235
   541
  Scan.repeat1 (unless_more_args inst)) [];
wenzelm@18235
   542
wenzelm@11670
   543
in
wenzelm@11670
   544
wenzelm@18235
   545
fun cases_meth src =
wenzelm@18235
   546
  Method.syntax (Args.mode openN --
wenzelm@18235
   547
    (Args.and_list (Scan.repeat (unless_more_args inst)) -- Scan.option cases_rule)) src
wenzelm@18235
   548
  #> (fn (ctxt, (is_open, (insts, opt_rule))) =>
wenzelm@18235
   549
    Method.METHOD_CASES (fn facts =>
wenzelm@18235
   550
      Seq.DETERM (HEADGOAL (cases_tac ctxt is_open insts opt_rule facts))));
wenzelm@18178
   551
wenzelm@18465
   552
fun induct_meth is_old src =
wenzelm@18235
   553
  Method.syntax (Args.mode openN --
wenzelm@18235
   554
    (Args.and_list (Scan.repeat (unless_more_args def_inst)) --
wenzelm@18235
   555
    (fixing -- taking -- Scan.option induct_rule))) src
wenzelm@18235
   556
  #> (fn (ctxt, (is_open, (insts, ((fixing, taking), opt_rule)))) =>
wenzelm@18235
   557
    Method.RAW_METHOD_CASES (fn facts =>
wenzelm@18465
   558
      Seq.DETERM (HEADGOAL
wenzelm@18465
   559
        (common_induct_tac is_old ctxt is_open insts fixing taking opt_rule facts))));
wenzelm@18205
   560
wenzelm@18235
   561
fun coinduct_meth src =
wenzelm@18235
   562
  Method.syntax (Args.mode openN --
wenzelm@18235
   563
    (Scan.repeat (unless_more_args inst) -- taking -- Scan.option coinduct_rule)) src
wenzelm@18235
   564
  #> (fn (ctxt, (is_open, ((insts, taking), opt_rule))) =>
wenzelm@18235
   565
    Method.RAW_METHOD_CASES (fn facts =>
wenzelm@18235
   566
      Seq.DETERM (HEADGOAL (coinduct_tac ctxt is_open insts taking opt_rule facts))));
wenzelm@11670
   567
wenzelm@11670
   568
end;
wenzelm@11670
   569
wenzelm@11670
   570
wenzelm@11670
   571
wenzelm@11670
   572
(** theory setup **)
wenzelm@11670
   573
wenzelm@11670
   574
val setup =
wenzelm@11670
   575
  [Method.add_methods
wenzelm@18235
   576
    [(InductAttrib.casesN, cases_meth, "case analysis on types or sets"),
wenzelm@18465
   577
     (InductAttrib.inductN, induct_meth false, "induction on types or sets"),
wenzelm@18465
   578
     ("old_" ^ InductAttrib.inductN, induct_meth true, "induction on types or sets (legacy)"),
wenzelm@18235
   579
     (InductAttrib.coinductN, coinduct_meth, "coinduction on types or sets")]];
wenzelm@11670
   580
wenzelm@11670
   581
end;