src/Tools/induct.ML
author wenzelm
Mon Apr 06 23:14:05 2015 +0200 (2015-04-06)
changeset 59940 087d81f5213e
parent 59936 b8ffc3dc9e24
child 59970 e9f73d87d904
permissions -rw-r--r--
local setup of induction tools, with restricted access to auxiliary consts;
proper antiquotations for formerly inaccessible consts;
wenzelm@24830
     1
(*  Title:      Tools/induct.ML
wenzelm@24830
     2
    Author:     Markus Wenzel, TU Muenchen
wenzelm@24830
     3
wenzelm@26924
     4
Proof by cases, induction, and coinduction.
wenzelm@24830
     5
*)
wenzelm@24830
     6
wenzelm@37524
     7
signature INDUCT_ARGS =
wenzelm@24830
     8
sig
wenzelm@24830
     9
  val cases_default: thm
wenzelm@24830
    10
  val atomize: thm list
wenzelm@24830
    11
  val rulify: thm list
wenzelm@24830
    12
  val rulify_fallback: thm list
berghofe@34987
    13
  val equal_def: thm
berghofe@34907
    14
  val dest_def: term -> (term * term) option
wenzelm@58957
    15
  val trivial_tac: Proof.context -> int -> tactic
wenzelm@24830
    16
end;
wenzelm@24830
    17
wenzelm@24830
    18
signature INDUCT =
wenzelm@24830
    19
sig
wenzelm@24830
    20
  (*rule declarations*)
wenzelm@24830
    21
  val vars_of: term -> term list
wenzelm@24830
    22
  val dest_rules: Proof.context ->
wenzelm@24861
    23
    {type_cases: (string * thm) list, pred_cases: (string * thm) list,
wenzelm@24861
    24
      type_induct: (string * thm) list, pred_induct: (string * thm) list,
wenzelm@24861
    25
      type_coinduct: (string * thm) list, pred_coinduct: (string * thm) list}
wenzelm@24830
    26
  val print_rules: Proof.context -> unit
wenzelm@24830
    27
  val lookup_casesT: Proof.context -> string -> thm option
wenzelm@24861
    28
  val lookup_casesP: Proof.context -> string -> thm option
wenzelm@24830
    29
  val lookup_inductT: Proof.context -> string -> thm option
wenzelm@24861
    30
  val lookup_inductP: Proof.context -> string -> thm option
wenzelm@24830
    31
  val lookup_coinductT: Proof.context -> string -> thm option
wenzelm@24861
    32
  val lookup_coinductP: Proof.context -> string -> thm option
wenzelm@24830
    33
  val find_casesT: Proof.context -> typ -> thm list
wenzelm@24861
    34
  val find_casesP: Proof.context -> term -> thm list
wenzelm@24830
    35
  val find_inductT: Proof.context -> typ -> thm list
wenzelm@24861
    36
  val find_inductP: Proof.context -> term -> thm list
wenzelm@24830
    37
  val find_coinductT: Proof.context -> typ -> thm list
wenzelm@24861
    38
  val find_coinductP: Proof.context -> term -> thm list
wenzelm@24830
    39
  val cases_type: string -> attribute
wenzelm@24861
    40
  val cases_pred: string -> attribute
wenzelm@27140
    41
  val cases_del: attribute
wenzelm@24830
    42
  val induct_type: string -> attribute
wenzelm@24861
    43
  val induct_pred: string -> attribute
wenzelm@27140
    44
  val induct_del: attribute
wenzelm@24830
    45
  val coinduct_type: string -> attribute
wenzelm@24861
    46
  val coinduct_pred: string -> attribute
wenzelm@27140
    47
  val coinduct_del: attribute
wenzelm@51717
    48
  val map_simpset: (Proof.context -> Proof.context) -> Context.generic -> Context.generic
wenzelm@36602
    49
  val induct_simp_add: attribute
wenzelm@36602
    50
  val induct_simp_del: attribute
berghofe@34907
    51
  val no_simpN: string
wenzelm@24830
    52
  val casesN: string
wenzelm@24830
    53
  val inductN: string
wenzelm@24830
    54
  val coinductN: string
wenzelm@24830
    55
  val typeN: string
wenzelm@24861
    56
  val predN: string
wenzelm@24830
    57
  val setN: string
wenzelm@24830
    58
  (*proof methods*)
wenzelm@45132
    59
  val arbitrary_tac: Proof.context -> int -> (string * typ) list -> int -> tactic
berghofe@34907
    60
  val add_defs: (binding option * (term * bool)) option list -> Proof.context ->
wenzelm@24830
    61
    (term option list * thm list) * Proof.context
wenzelm@24830
    62
  val atomize_term: theory -> term -> term
wenzelm@54742
    63
  val atomize_cterm: Proof.context -> conv
wenzelm@54742
    64
  val atomize_tac: Proof.context -> int -> tactic
wenzelm@54742
    65
  val inner_atomize_tac: Proof.context -> int -> tactic
wenzelm@24830
    66
  val rulified_term: thm -> theory * term
wenzelm@54742
    67
  val rulify_tac: Proof.context -> int -> tactic
berghofe@34907
    68
  val simplified_rule: Proof.context -> thm -> thm
berghofe@34907
    69
  val simplify_tac: Proof.context -> int -> tactic
wenzelm@58957
    70
  val trivial_tac: Proof.context -> int -> tactic
berghofe@34907
    71
  val rotate_tac: int -> int -> int -> tactic
wenzelm@54742
    72
  val internalize: Proof.context -> int -> thm -> thm
wenzelm@26940
    73
  val guess_instance: Proof.context -> thm -> int -> thm -> thm Seq.seq
berghofe@34987
    74
  val cases_tac: Proof.context -> bool -> term option list list -> thm option ->
wenzelm@24830
    75
    thm list -> int -> cases_tactic
wenzelm@27323
    76
  val get_inductT: Proof.context -> term option list list -> thm list list
nipkow@45014
    77
  type case_data = (((string * string list) * string list) list * int) (* FIXME -> rule_cases.ML *)
nipkow@45014
    78
  val gen_induct_tac: (theory -> case_data * thm -> case_data * thm) ->
nipkow@45014
    79
    Proof.context -> bool -> (binding option * (term * bool)) option list list ->
nipkow@45014
    80
    (string * typ) list list -> term option list -> thm list option ->
nipkow@45014
    81
    thm list -> int -> cases_tactic
berghofe@34907
    82
  val induct_tac: Proof.context -> bool -> (binding option * (term * bool)) option list list ->
wenzelm@26924
    83
    (string * typ) list list -> term option list -> thm list option ->
wenzelm@26924
    84
    thm list -> int -> cases_tactic
wenzelm@26924
    85
  val coinduct_tac: Proof.context -> term option list -> term option list -> thm option ->
wenzelm@26924
    86
    thm list -> int -> cases_tactic
nipkow@45014
    87
  val gen_induct_setup: binding ->
nipkow@45014
    88
   (Proof.context -> bool -> (binding option * (term * bool)) option list list ->
nipkow@45014
    89
    (string * typ) list list -> term option list -> thm list option ->
nipkow@45014
    90
    thm list -> int -> cases_tactic) ->
wenzelm@59940
    91
   local_theory -> local_theory
wenzelm@24830
    92
end;
wenzelm@24830
    93
wenzelm@37524
    94
functor Induct(Induct_Args: INDUCT_ARGS): INDUCT =
wenzelm@24830
    95
struct
wenzelm@24830
    96
wenzelm@37523
    97
(** variables -- ordered left-to-right, preferring right **)
wenzelm@24830
    98
wenzelm@24830
    99
fun vars_of tm =
wenzelm@45131
   100
  rev (distinct (op =) (Term.fold_aterms (fn t as Var _ => cons t | _ => I) tm []));
wenzelm@24830
   101
wenzelm@24830
   102
local
wenzelm@24830
   103
wenzelm@37523
   104
val mk_var = Net.encode_type o #2 o Term.dest_Var;
wenzelm@24830
   105
wenzelm@47060
   106
fun concl_var which thm = mk_var (which (vars_of (Thm.concl_of thm))) handle List.Empty =>
wenzelm@24830
   107
  raise THM ("No variables in conclusion of rule", 0, [thm]);
wenzelm@24830
   108
wenzelm@24830
   109
in
wenzelm@24830
   110
wenzelm@47060
   111
fun left_var_prem thm = mk_var (hd (vars_of (hd (Thm.prems_of thm)))) handle List.Empty =>
wenzelm@24830
   112
  raise THM ("No variables in major premise of rule", 0, [thm]);
wenzelm@24830
   113
wenzelm@24830
   114
val left_var_concl = concl_var hd;
wenzelm@24830
   115
val right_var_concl = concl_var List.last;
wenzelm@24830
   116
wenzelm@24830
   117
end;
wenzelm@24830
   118
wenzelm@24830
   119
wenzelm@24830
   120
berghofe@34907
   121
(** constraint simplification **)
berghofe@34907
   122
berghofe@34907
   123
(* rearrange parameters and premises to allow application of one-point-rules *)
berghofe@34907
   124
berghofe@34907
   125
fun swap_params_conv ctxt i j cv =
berghofe@34907
   126
  let
berghofe@34907
   127
    fun conv1 0 ctxt = Conv.forall_conv (cv o snd) ctxt
berghofe@34907
   128
      | conv1 k ctxt =
berghofe@34907
   129
          Conv.rewr_conv @{thm swap_params} then_conv
wenzelm@37525
   130
          Conv.forall_conv (conv1 (k - 1) o snd) ctxt
berghofe@34907
   131
    fun conv2 0 ctxt = conv1 j ctxt
wenzelm@37525
   132
      | conv2 k ctxt = Conv.forall_conv (conv2 (k - 1) o snd) ctxt
berghofe@34907
   133
  in conv2 i ctxt end;
berghofe@34907
   134
berghofe@34907
   135
fun swap_prems_conv 0 = Conv.all_conv
berghofe@34907
   136
  | swap_prems_conv i =
wenzelm@37525
   137
      Conv.implies_concl_conv (swap_prems_conv (i - 1)) then_conv
berghofe@34907
   138
      Conv.rewr_conv Drule.swap_prems_eq
berghofe@34907
   139
wenzelm@42361
   140
fun drop_judgment ctxt = Object_Logic.drop_judgment (Proof_Context.theory_of ctxt);
berghofe@34907
   141
berghofe@34907
   142
fun find_eq ctxt t =
berghofe@34907
   143
  let
berghofe@34907
   144
    val l = length (Logic.strip_params t);
berghofe@34907
   145
    val Hs = Logic.strip_assums_hyp t;
berghofe@34907
   146
    fun find (i, t) =
wenzelm@37525
   147
      (case Induct_Args.dest_def (drop_judgment ctxt t) of
berghofe@34907
   148
        SOME (Bound j, _) => SOME (i, j)
berghofe@34907
   149
      | SOME (_, Bound j) => SOME (i, j)
wenzelm@37525
   150
      | _ => NONE);
berghofe@34907
   151
  in
wenzelm@37525
   152
    (case get_first find (map_index I Hs) of
berghofe@34907
   153
      NONE => NONE
berghofe@34907
   154
    | SOME (0, 0) => NONE
wenzelm@37525
   155
    | SOME (i, j) => SOME (i, l - j - 1, j))
berghofe@34907
   156
  end;
berghofe@34907
   157
wenzelm@37525
   158
fun mk_swap_rrule ctxt ct =
wenzelm@59582
   159
  (case find_eq ctxt (Thm.term_of ct) of
berghofe@34907
   160
    NONE => NONE
wenzelm@37525
   161
  | SOME (i, k, j) => SOME (swap_params_conv ctxt k j (K (swap_prems_conv i)) ct));
berghofe@34907
   162
wenzelm@37525
   163
val rearrange_eqs_simproc =
wenzelm@56245
   164
  Simplifier.simproc_global Pure.thy "rearrange_eqs" ["Pure.all t"]
wenzelm@59929
   165
    (fn ctxt => fn t => mk_swap_rrule ctxt (Thm.cterm_of ctxt t));
wenzelm@37525
   166
berghofe@34907
   167
berghofe@34907
   168
(* rotate k premises to the left by j, skipping over first j premises *)
berghofe@34907
   169
berghofe@34907
   170
fun rotate_conv 0 j 0 = Conv.all_conv
wenzelm@37525
   171
  | rotate_conv 0 j k = swap_prems_conv j then_conv rotate_conv 1 j (k - 1)
wenzelm@37525
   172
  | rotate_conv i j k = Conv.implies_concl_conv (rotate_conv (i - 1) j k);
berghofe@34907
   173
berghofe@34907
   174
fun rotate_tac j 0 = K all_tac
wenzelm@37525
   175
  | rotate_tac j k = SUBGOAL (fn (goal, i) =>
wenzelm@37525
   176
      CONVERSION (rotate_conv
wenzelm@37525
   177
        j (length (Logic.strip_assums_hyp goal) - j - k) k) i);
wenzelm@37525
   178
berghofe@34907
   179
berghofe@34907
   180
(* rulify operators around definition *)
berghofe@34907
   181
berghofe@34907
   182
fun rulify_defs_conv ctxt ct =
wenzelm@59582
   183
  if exists_subterm (is_some o Induct_Args.dest_def) (Thm.term_of ct) andalso
wenzelm@59582
   184
    not (is_some (Induct_Args.dest_def (drop_judgment ctxt (Thm.term_of ct))))
berghofe@34907
   185
  then
berghofe@34907
   186
    (Conv.forall_conv (rulify_defs_conv o snd) ctxt else_conv
berghofe@34907
   187
     Conv.implies_conv (Conv.try_conv (rulify_defs_conv ctxt))
berghofe@34907
   188
       (Conv.try_conv (rulify_defs_conv ctxt)) else_conv
wenzelm@37524
   189
     Conv.first_conv (map Conv.rewr_conv Induct_Args.rulify) then_conv
berghofe@34907
   190
       Conv.try_conv (rulify_defs_conv ctxt)) ct
berghofe@34907
   191
  else Conv.no_conv ct;
berghofe@34907
   192
berghofe@34907
   193
berghofe@34907
   194
wenzelm@24830
   195
(** induct data **)
wenzelm@24830
   196
wenzelm@24830
   197
(* rules *)
wenzelm@24830
   198
wenzelm@30560
   199
type rules = (string * thm) Item_Net.T;
wenzelm@24830
   200
wenzelm@33373
   201
fun init_rules index : rules =
wenzelm@33373
   202
  Item_Net.init
wenzelm@33373
   203
    (fn ((s1, th1), (s2, th2)) => s1 = s2 andalso Thm.eq_thm_prop (th1, th2))
wenzelm@33373
   204
    (single o index);
wenzelm@24830
   205
wenzelm@27140
   206
fun filter_rules (rs: rules) th =
wenzelm@30560
   207
  filter (fn (_, th') => Thm.eq_thm_prop (th, th')) (Item_Net.content rs);
wenzelm@27140
   208
wenzelm@30560
   209
fun lookup_rule (rs: rules) = AList.lookup (op =) (Item_Net.content rs);
wenzelm@24830
   210
wenzelm@24830
   211
fun pretty_rules ctxt kind rs =
wenzelm@30560
   212
  let val thms = map snd (Item_Net.content rs)
wenzelm@51584
   213
  in Pretty.big_list kind (map (Display.pretty_thm_item ctxt) thms) end;
wenzelm@24830
   214
wenzelm@24830
   215
wenzelm@24830
   216
(* context data *)
wenzelm@24830
   217
wenzelm@37524
   218
structure Data = Generic_Data
wenzelm@24830
   219
(
berghofe@34907
   220
  type T = (rules * rules) * (rules * rules) * (rules * rules) * simpset;
wenzelm@24830
   221
  val empty =
wenzelm@24830
   222
    ((init_rules (left_var_prem o #2), init_rules (Thm.major_prem_of o #2)),
wenzelm@24830
   223
     (init_rules (right_var_concl o #2), init_rules (Thm.major_prem_of o #2)),
berghofe@34907
   224
     (init_rules (left_var_concl o #2), init_rules (Thm.concl_of o #2)),
wenzelm@51717
   225
     simpset_of (empty_simpset @{context}
wenzelm@51717
   226
      addsimprocs [rearrange_eqs_simproc] addsimps [Drule.norm_hhf_eq]));
wenzelm@24830
   227
  val extend = I;
berghofe@34907
   228
  fun merge (((casesT1, casesP1), (inductT1, inductP1), (coinductT1, coinductP1), simpset1),
berghofe@34907
   229
      ((casesT2, casesP2), (inductT2, inductP2), (coinductT2, coinductP2), simpset2)) =
wenzelm@30560
   230
    ((Item_Net.merge (casesT1, casesT2), Item_Net.merge (casesP1, casesP2)),
berghofe@34907
   231
     (Item_Net.merge (inductT1, inductT2), Item_Net.merge (inductP1, inductP2)),
berghofe@34907
   232
     (Item_Net.merge (coinductT1, coinductT2), Item_Net.merge (coinductP1, coinductP2)),
berghofe@34907
   233
     merge_ss (simpset1, simpset2));
wenzelm@24830
   234
);
wenzelm@24830
   235
wenzelm@37524
   236
val get_local = Data.get o Context.Proof;
wenzelm@24830
   237
wenzelm@24830
   238
fun dest_rules ctxt =
berghofe@34907
   239
  let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP), _) = get_local ctxt in
wenzelm@30560
   240
    {type_cases = Item_Net.content casesT,
wenzelm@30560
   241
     pred_cases = Item_Net.content casesP,
wenzelm@30560
   242
     type_induct = Item_Net.content inductT,
wenzelm@30560
   243
     pred_induct = Item_Net.content inductP,
wenzelm@30560
   244
     type_coinduct = Item_Net.content coinductT,
wenzelm@30560
   245
     pred_coinduct = Item_Net.content coinductP}
wenzelm@24830
   246
  end;
wenzelm@24830
   247
wenzelm@24830
   248
fun print_rules ctxt =
berghofe@34907
   249
  let val ((casesT, casesP), (inductT, inductP), (coinductT, coinductP), _) = get_local ctxt in
wenzelm@24830
   250
   [pretty_rules ctxt "coinduct type:" coinductT,
wenzelm@24861
   251
    pretty_rules ctxt "coinduct pred:" coinductP,
wenzelm@24830
   252
    pretty_rules ctxt "induct type:" inductT,
wenzelm@24861
   253
    pretty_rules ctxt "induct pred:" inductP,
wenzelm@24830
   254
    pretty_rules ctxt "cases type:" casesT,
wenzelm@24861
   255
    pretty_rules ctxt "cases pred:" casesP]
wenzelm@56334
   256
    |> Pretty.writeln_chunks
wenzelm@24830
   257
  end;
wenzelm@24830
   258
wenzelm@24867
   259
val _ =
wenzelm@59936
   260
  Outer_Syntax.command @{command_keyword print_induct_rules}
wenzelm@46961
   261
    "print induction and cases rules"
wenzelm@51658
   262
    (Scan.succeed (Toplevel.unknown_context o
wenzelm@24867
   263
      Toplevel.keep (print_rules o Toplevel.context_of)));
wenzelm@24830
   264
wenzelm@24830
   265
wenzelm@24830
   266
(* access rules *)
wenzelm@24830
   267
wenzelm@24830
   268
val lookup_casesT = lookup_rule o #1 o #1 o get_local;
wenzelm@24861
   269
val lookup_casesP = lookup_rule o #2 o #1 o get_local;
wenzelm@24830
   270
val lookup_inductT = lookup_rule o #1 o #2 o get_local;
wenzelm@24861
   271
val lookup_inductP = lookup_rule o #2 o #2 o get_local;
wenzelm@24830
   272
val lookup_coinductT = lookup_rule o #1 o #3 o get_local;
wenzelm@24861
   273
val lookup_coinductP = lookup_rule o #2 o #3 o get_local;
wenzelm@24830
   274
wenzelm@24830
   275
wenzelm@24830
   276
fun find_rules which how ctxt x =
wenzelm@30560
   277
  map snd (Item_Net.retrieve (which (get_local ctxt)) (how x));
wenzelm@24830
   278
wenzelm@37523
   279
val find_casesT = find_rules (#1 o #1) Net.encode_type;
wenzelm@24861
   280
val find_casesP = find_rules (#2 o #1) I;
wenzelm@37523
   281
val find_inductT = find_rules (#1 o #2) Net.encode_type;
wenzelm@24861
   282
val find_inductP = find_rules (#2 o #2) I;
wenzelm@37523
   283
val find_coinductT = find_rules (#1 o #3) Net.encode_type;
wenzelm@24861
   284
val find_coinductP = find_rules (#2 o #3) I;
wenzelm@24830
   285
wenzelm@24830
   286
wenzelm@24830
   287
wenzelm@24830
   288
(** attributes **)
wenzelm@24830
   289
wenzelm@24830
   290
local
wenzelm@24830
   291
wenzelm@45375
   292
fun mk_att f g name =
wenzelm@45375
   293
  Thm.mixed_attribute (fn (context, thm) =>
wenzelm@45375
   294
    let
wenzelm@45375
   295
      val thm' = g thm;
wenzelm@45375
   296
      val context' = Data.map (f (name, thm')) context;
wenzelm@45375
   297
    in (context', thm') end);
wenzelm@27140
   298
wenzelm@37525
   299
fun del_att which =
wenzelm@59058
   300
  Thm.declaration_attribute (fn th => Data.map (which (apply2 (fn rs =>
wenzelm@37525
   301
    fold Item_Net.remove (filter_rules rs th) rs))));
wenzelm@24830
   302
wenzelm@59057
   303
fun add_casesT rule x = @{apply 4(1)} (apfst (Item_Net.update rule)) x;
wenzelm@59057
   304
fun add_casesP rule x = @{apply 4(1)} (apsnd (Item_Net.update rule)) x;
wenzelm@59057
   305
fun add_inductT rule x = @{apply 4(2)} (apfst (Item_Net.update rule)) x;
wenzelm@59057
   306
fun add_inductP rule x = @{apply 4(2)} (apsnd (Item_Net.update rule)) x;
wenzelm@59057
   307
fun add_coinductT rule x = @{apply 4(3)} (apfst (Item_Net.update rule)) x;
wenzelm@59057
   308
fun add_coinductP rule x = @{apply 4(3)} (apsnd (Item_Net.update rule)) x;
wenzelm@24830
   309
wenzelm@45375
   310
val consumes0 = Rule_Cases.default_consumes 0;
wenzelm@45375
   311
val consumes1 = Rule_Cases.default_consumes 1;
wenzelm@24830
   312
wenzelm@24830
   313
in
wenzelm@24830
   314
wenzelm@24830
   315
val cases_type = mk_att add_casesT consumes0;
wenzelm@24861
   316
val cases_pred = mk_att add_casesP consumes1;
wenzelm@59057
   317
val cases_del = del_att @{apply 4(1)};
wenzelm@27140
   318
wenzelm@24830
   319
val induct_type = mk_att add_inductT consumes0;
wenzelm@24861
   320
val induct_pred = mk_att add_inductP consumes1;
wenzelm@59057
   321
val induct_del = del_att @{apply 4(2)};
wenzelm@27140
   322
wenzelm@24830
   323
val coinduct_type = mk_att add_coinductT consumes0;
wenzelm@24861
   324
val coinduct_pred = mk_att add_coinductP consumes1;
wenzelm@59057
   325
val coinduct_del = del_att @{apply 4(3)};
wenzelm@24830
   326
wenzelm@51717
   327
fun map_simpset f context =
wenzelm@59057
   328
  context |> (Data.map o @{apply 4(4)} o Simplifier.simpset_map (Context.proof_of context)) f;
wenzelm@36602
   329
wenzelm@36602
   330
fun induct_simp f =
wenzelm@51717
   331
  Thm.declaration_attribute (fn thm => map_simpset (fn ctxt => f (ctxt, [thm])));
wenzelm@36602
   332
wenzelm@36602
   333
val induct_simp_add = induct_simp (op addsimps);
wenzelm@36602
   334
val induct_simp_del = induct_simp (op delsimps);
berghofe@34907
   335
wenzelm@24830
   336
end;
wenzelm@24830
   337
wenzelm@24830
   338
wenzelm@24830
   339
wenzelm@24830
   340
(** attribute syntax **)
wenzelm@24830
   341
berghofe@34907
   342
val no_simpN = "no_simp";
wenzelm@24830
   343
val casesN = "cases";
wenzelm@24830
   344
val inductN = "induct";
wenzelm@24830
   345
val coinductN = "coinduct";
wenzelm@24830
   346
wenzelm@24830
   347
val typeN = "type";
wenzelm@24861
   348
val predN = "pred";
wenzelm@24830
   349
val setN = "set";
wenzelm@24830
   350
wenzelm@24830
   351
local
wenzelm@24830
   352
wenzelm@24830
   353
fun spec k arg =
wenzelm@24830
   354
  Scan.lift (Args.$$$ k -- Args.colon) |-- arg ||
wenzelm@24830
   355
  Scan.lift (Args.$$$ k) >> K "";
wenzelm@24830
   356
wenzelm@30528
   357
fun attrib add_type add_pred del =
wenzelm@55951
   358
  spec typeN (Args.type_name {proper = false, strict = false}) >> add_type ||
wenzelm@55954
   359
  spec predN (Args.const {proper = false, strict = false}) >> add_pred ||
wenzelm@55954
   360
  spec setN (Args.const {proper = false, strict = false}) >> add_pred ||
wenzelm@30528
   361
  Scan.lift Args.del >> K del;
wenzelm@24830
   362
wenzelm@24830
   363
in
wenzelm@24830
   364
wenzelm@58826
   365
val _ =
wenzelm@59940
   366
  Theory.local_setup
wenzelm@59940
   367
   (Attrib.local_setup @{binding cases} (attrib cases_type cases_pred cases_del)
wenzelm@58826
   368
      "declaration of cases rule" #>
wenzelm@59940
   369
    Attrib.local_setup @{binding induct} (attrib induct_type induct_pred induct_del)
wenzelm@58826
   370
      "declaration of induction rule" #>
wenzelm@59940
   371
    Attrib.local_setup @{binding coinduct} (attrib coinduct_type coinduct_pred coinduct_del)
wenzelm@58826
   372
      "declaration of coinduction rule" #>
wenzelm@59940
   373
    Attrib.local_setup @{binding induct_simp} (Attrib.add_del induct_simp_add induct_simp_del)
wenzelm@58826
   374
      "declaration of rules for simplifying induction or cases rules");
wenzelm@24830
   375
wenzelm@24830
   376
end;
wenzelm@24830
   377
wenzelm@24830
   378
wenzelm@24830
   379
wenzelm@24830
   380
(** method utils **)
wenzelm@24830
   381
wenzelm@24830
   382
(* alignment *)
wenzelm@24830
   383
wenzelm@24830
   384
fun align_left msg xs ys =
wenzelm@24830
   385
  let val m = length xs and n = length ys
haftmann@33957
   386
  in if m < n then error msg else (take n xs ~~ ys) end;
wenzelm@24830
   387
wenzelm@24830
   388
fun align_right msg xs ys =
wenzelm@24830
   389
  let val m = length xs and n = length ys
haftmann@33957
   390
  in if m < n then error msg else (drop (m - n) xs ~~ ys) end;
wenzelm@24830
   391
wenzelm@24830
   392
wenzelm@24830
   393
(* prep_inst *)
wenzelm@24830
   394
wenzelm@32432
   395
fun prep_inst ctxt align tune (tm, ts) =
wenzelm@24830
   396
  let
wenzelm@24830
   397
    fun prep_var (x, SOME t) =
wenzelm@24830
   398
          let
wenzelm@59843
   399
            val cx = Thm.cterm_of ctxt x;
wenzelm@59586
   400
            val xT = Thm.typ_of_cterm cx;
wenzelm@59843
   401
            val ct = Thm.cterm_of ctxt (tune t);
wenzelm@59586
   402
            val tT = Thm.typ_of_cterm ct;
wenzelm@24830
   403
          in
wenzelm@32432
   404
            if Type.could_unify (tT, xT) then SOME (cx, ct)
wenzelm@24830
   405
            else error (Pretty.string_of (Pretty.block
wenzelm@24830
   406
             [Pretty.str "Ill-typed instantiation:", Pretty.fbrk,
wenzelm@32432
   407
              Syntax.pretty_term ctxt (Thm.term_of ct), Pretty.str " ::", Pretty.brk 1,
wenzelm@32432
   408
              Syntax.pretty_typ ctxt tT]))
wenzelm@24830
   409
          end
wenzelm@24830
   410
      | prep_var (_, NONE) = NONE;
wenzelm@24830
   411
    val xs = vars_of tm;
wenzelm@24830
   412
  in
wenzelm@24830
   413
    align "Rule has fewer variables than instantiations given" xs ts
wenzelm@24830
   414
    |> map_filter prep_var
wenzelm@24830
   415
  end;
wenzelm@24830
   416
wenzelm@24830
   417
wenzelm@24830
   418
(* trace_rules *)
wenzelm@24830
   419
wenzelm@24830
   420
fun trace_rules _ kind [] = error ("Unable to figure out " ^ kind ^ " rule")
wenzelm@24830
   421
  | trace_rules ctxt _ rules = Method.trace ctxt rules;
wenzelm@24830
   422
wenzelm@24830
   423
berghofe@34987
   424
(* mark equality constraints in cases rule *)
berghofe@34987
   425
wenzelm@37524
   426
val equal_def' = Thm.symmetric Induct_Args.equal_def;
berghofe@34987
   427
berghofe@34987
   428
fun mark_constraints n ctxt = Conv.fconv_rule
wenzelm@45130
   429
  (Conv.prems_conv ~1 (Conv.params_conv ~1 (K (Conv.prems_conv n
wenzelm@54742
   430
     (Raw_Simplifier.rewrite ctxt false [equal_def']))) ctxt));
berghofe@34987
   431
wenzelm@54742
   432
fun unmark_constraints ctxt =
wenzelm@54742
   433
  Conv.fconv_rule (Raw_Simplifier.rewrite ctxt true [Induct_Args.equal_def]);
berghofe@34987
   434
wenzelm@37525
   435
berghofe@34987
   436
(* simplify *)
berghofe@34987
   437
berghofe@34987
   438
fun simplify_conv' ctxt =
wenzelm@51717
   439
  Simplifier.full_rewrite (put_simpset (#4 (get_local ctxt)) ctxt);
berghofe@34987
   440
berghofe@34987
   441
fun simplify_conv ctxt ct =
wenzelm@59582
   442
  if exists_subterm (is_some o Induct_Args.dest_def) (Thm.term_of ct) then
berghofe@34987
   443
    (Conv.try_conv (rulify_defs_conv ctxt) then_conv simplify_conv' ctxt) ct
berghofe@34987
   444
  else Conv.all_conv ct;
berghofe@34987
   445
berghofe@34987
   446
fun gen_simplified_rule cv ctxt =
berghofe@34987
   447
  Conv.fconv_rule (Conv.prems_conv ~1 (cv ctxt));
berghofe@34987
   448
berghofe@34987
   449
val simplified_rule' = gen_simplified_rule simplify_conv';
berghofe@34987
   450
val simplified_rule = gen_simplified_rule simplify_conv;
berghofe@34987
   451
berghofe@34987
   452
fun simplify_tac ctxt = CONVERSION (simplify_conv ctxt);
berghofe@34987
   453
wenzelm@37524
   454
val trivial_tac = Induct_Args.trivial_tac;
berghofe@34987
   455
berghofe@34987
   456
wenzelm@24830
   457
wenzelm@24830
   458
(** cases method **)
wenzelm@24830
   459
wenzelm@24830
   460
(*
wenzelm@24830
   461
  rule selection scheme:
wenzelm@24830
   462
          cases         - default case split
wenzelm@24861
   463
    `A t` cases ...     - predicate/set cases
wenzelm@24830
   464
          cases t       - type cases
wenzelm@24830
   465
    ...   cases ... r   - explicit rule
wenzelm@24830
   466
*)
wenzelm@24830
   467
wenzelm@24830
   468
local
wenzelm@24830
   469
wenzelm@24830
   470
fun get_casesT ctxt ((SOME t :: _) :: _) = find_casesT ctxt (Term.fastype_of t)
wenzelm@24830
   471
  | get_casesT _ _ = [];
wenzelm@24830
   472
wenzelm@24861
   473
fun get_casesP ctxt (fact :: _) = find_casesP ctxt (Thm.concl_of fact)
wenzelm@24861
   474
  | get_casesP _ _ = [];
wenzelm@24830
   475
wenzelm@24830
   476
in
wenzelm@24830
   477
berghofe@34987
   478
fun cases_tac ctxt simp insts opt_rule facts =
wenzelm@24830
   479
  let
wenzelm@24830
   480
    fun inst_rule r =
berghofe@34987
   481
      (if null insts then r
wenzelm@45131
   482
       else
wenzelm@45131
   483
         (align_left "Rule has fewer premises than arguments given" (Thm.prems_of r) insts
wenzelm@45131
   484
           |> maps (prep_inst ctxt align_left I)
wenzelm@45131
   485
           |> Drule.cterm_instantiate) r)
wenzelm@45131
   486
      |> simp ? mark_constraints (Rule_Cases.get_constraints r) ctxt
wenzelm@45131
   487
      |> pair (Rule_Cases.get r);
wenzelm@24830
   488
wenzelm@24830
   489
    val ruleq =
wenzelm@24830
   490
      (case opt_rule of
wenzelm@24830
   491
        SOME r => Seq.single (inst_rule r)
wenzelm@24830
   492
      | NONE =>
wenzelm@37524
   493
          (get_casesP ctxt facts @ get_casesT ctxt insts @ [Induct_Args.cases_default])
wenzelm@24830
   494
          |> tap (trace_rules ctxt casesN)
wenzelm@24830
   495
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@24830
   496
  in
wenzelm@24830
   497
    fn i => fn st =>
wenzelm@24830
   498
      ruleq
wenzelm@54742
   499
      |> Seq.maps (Rule_Cases.consume ctxt [] facts)
wenzelm@24830
   500
      |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
wenzelm@45131
   501
        let
wenzelm@45131
   502
          val rule' = rule
wenzelm@54742
   503
            |> simp ? (simplified_rule' ctxt #> unmark_constraints ctxt);
berghofe@34987
   504
        in
wenzelm@59843
   505
          CASES (Rule_Cases.make_common (Proof_Context.theory_of ctxt,
berghofe@34987
   506
              Thm.prop_of (Rule_Cases.internalize_params rule')) cases)
wenzelm@59498
   507
            ((Method.insert_tac more_facts THEN' resolve_tac ctxt [rule'] THEN_ALL_NEW
wenzelm@58957
   508
                (if simp then TRY o trivial_tac ctxt else K all_tac)) i) st
berghofe@34987
   509
        end)
wenzelm@24830
   510
  end;
wenzelm@24830
   511
wenzelm@24830
   512
end;
wenzelm@24830
   513
wenzelm@24830
   514
wenzelm@24830
   515
wenzelm@24830
   516
(** induct method **)
wenzelm@24830
   517
wenzelm@59929
   518
val conjunction_congs = @{thms Pure.all_conjunction imp_conjunction};
wenzelm@24830
   519
wenzelm@24830
   520
wenzelm@24830
   521
(* atomize *)
wenzelm@24830
   522
wenzelm@24830
   523
fun atomize_term thy =
wenzelm@41228
   524
  Raw_Simplifier.rewrite_term thy Induct_Args.atomize []
wenzelm@35625
   525
  #> Object_Logic.drop_judgment thy;
wenzelm@24830
   526
wenzelm@54742
   527
fun atomize_cterm ctxt = Raw_Simplifier.rewrite ctxt true Induct_Args.atomize;
wenzelm@24830
   528
wenzelm@54742
   529
fun atomize_tac ctxt = rewrite_goal_tac ctxt Induct_Args.atomize;
wenzelm@24830
   530
wenzelm@54742
   531
fun inner_atomize_tac ctxt =
wenzelm@54742
   532
  rewrite_goal_tac ctxt (map Thm.symmetric conjunction_congs) THEN' atomize_tac ctxt;
wenzelm@24830
   533
wenzelm@24830
   534
wenzelm@24830
   535
(* rulify *)
wenzelm@24830
   536
wenzelm@24830
   537
fun rulify_term thy =
wenzelm@41228
   538
  Raw_Simplifier.rewrite_term thy (Induct_Args.rulify @ conjunction_congs) [] #>
wenzelm@41228
   539
  Raw_Simplifier.rewrite_term thy Induct_Args.rulify_fallback [];
wenzelm@24830
   540
wenzelm@24830
   541
fun rulified_term thm =
wenzelm@24830
   542
  let
wenzelm@24830
   543
    val thy = Thm.theory_of_thm thm;
wenzelm@24830
   544
    val rulify = rulify_term thy;
wenzelm@24830
   545
    val (As, B) = Logic.strip_horn (Thm.prop_of thm);
wenzelm@24830
   546
  in (thy, Logic.list_implies (map rulify As, rulify B)) end;
wenzelm@24830
   547
wenzelm@54742
   548
fun rulify_tac ctxt =
wenzelm@54742
   549
  rewrite_goal_tac ctxt (Induct_Args.rulify @ conjunction_congs) THEN'
wenzelm@54742
   550
  rewrite_goal_tac ctxt Induct_Args.rulify_fallback THEN'
wenzelm@24830
   551
  Goal.conjunction_tac THEN_ALL_NEW
wenzelm@59929
   552
  (rewrite_goal_tac ctxt @{thms Pure.conjunction_imp} THEN' Goal.norm_hhf_tac ctxt);
wenzelm@24830
   553
wenzelm@24830
   554
wenzelm@24830
   555
(* prepare rule *)
wenzelm@24830
   556
wenzelm@32432
   557
fun rule_instance ctxt inst rule =
wenzelm@32432
   558
  Drule.cterm_instantiate (prep_inst ctxt align_left I (Thm.prop_of rule, inst)) rule;
wenzelm@24830
   559
wenzelm@54742
   560
fun internalize ctxt k th =
wenzelm@24830
   561
  th |> Thm.permute_prems 0 k
wenzelm@54742
   562
  |> Conv.fconv_rule (Conv.concl_conv (Thm.nprems_of th - k) (atomize_cterm ctxt));
wenzelm@24830
   563
wenzelm@24830
   564
wenzelm@24830
   565
(* guess rule instantiation -- cannot handle pending goal parameters *)
wenzelm@24830
   566
wenzelm@24830
   567
local
wenzelm@24830
   568
wenzelm@59843
   569
fun dest_env ctxt env =
wenzelm@24830
   570
  let
wenzelm@32032
   571
    val pairs = Vartab.dest (Envir.term_env env);
wenzelm@32032
   572
    val types = Vartab.dest (Envir.type_env env);
wenzelm@59843
   573
    val ts = map (Thm.cterm_of ctxt o Envir.norm_term env o #2 o #2) pairs;
wenzelm@59843
   574
    val xs = map2 (curry (Thm.cterm_of ctxt o Var)) (map #1 pairs) (map Thm.typ_of_cterm ts);
wenzelm@59843
   575
  in (map (fn (xi, (S, T)) => apply2 (Thm.ctyp_of ctxt) (TVar (xi, S), T)) types, xs ~~ ts) end;
wenzelm@24830
   576
wenzelm@24830
   577
in
wenzelm@24830
   578
wenzelm@26940
   579
fun guess_instance ctxt rule i st =
wenzelm@24830
   580
  let
wenzelm@26626
   581
    val maxidx = Thm.maxidx_of st;
wenzelm@24830
   582
    val goal = Thm.term_of (Thm.cprem_of st i);  (*exception Subscript*)
wenzelm@29276
   583
    val params = rev (Term.rename_wrt_term goal (Logic.strip_params goal));
wenzelm@24830
   584
  in
wenzelm@24830
   585
    if not (null params) then
wenzelm@24830
   586
      (warning ("Cannot determine rule instantiation due to pending parameter(s): " ^
wenzelm@49660
   587
        commas_quote (map (Syntax.string_of_term ctxt o Syntax_Trans.mark_bound_abs) params));
wenzelm@24830
   588
      Seq.single rule)
wenzelm@24830
   589
    else
wenzelm@24830
   590
      let
wenzelm@24830
   591
        val rule' = Thm.incr_indexes (maxidx + 1) rule;
wenzelm@24830
   592
        val concl = Logic.strip_assums_concl goal;
wenzelm@24830
   593
      in
wenzelm@58950
   594
        Unify.smash_unifiers (Context.Proof ctxt)
wenzelm@58950
   595
          [(Thm.concl_of rule', concl)] (Envir.empty (Thm.maxidx_of rule'))
wenzelm@59843
   596
        |> Seq.map (fn env => Drule.instantiate_normalize (dest_env ctxt env) rule')
wenzelm@24830
   597
      end
wenzelm@43333
   598
  end
wenzelm@43333
   599
  handle General.Subscript => Seq.empty;
wenzelm@24830
   600
wenzelm@24830
   601
end;
wenzelm@24830
   602
wenzelm@24830
   603
wenzelm@24830
   604
(* special renaming of rule parameters *)
wenzelm@24830
   605
wenzelm@24830
   606
fun special_rename_params ctxt [[SOME (Free (z, Type (T, _)))]] [thm] =
wenzelm@24830
   607
      let
wenzelm@42488
   608
        val x = Name.clean (Variable.revert_fixed ctxt z);
wenzelm@24830
   609
        fun index i [] = []
wenzelm@24830
   610
          | index i (y :: ys) =
wenzelm@24830
   611
              if x = y then x ^ string_of_int i :: index (i + 1) ys
wenzelm@24830
   612
              else y :: index i ys;
wenzelm@24830
   613
        fun rename_params [] = []
wenzelm@24830
   614
          | rename_params ((y, Type (U, _)) :: ys) =
wenzelm@24830
   615
              (if U = T then x else y) :: rename_params ys
wenzelm@24830
   616
          | rename_params ((y, _) :: ys) = y :: rename_params ys;
wenzelm@24830
   617
        fun rename_asm A =
wenzelm@24830
   618
          let
wenzelm@24830
   619
            val xs = rename_params (Logic.strip_params A);
wenzelm@24830
   620
            val xs' =
wenzelm@28375
   621
              (case filter (fn x' => x' = x) xs of
wenzelm@24830
   622
                [] => xs | [_] => xs | _ => index 1 xs);
wenzelm@45328
   623
          in Logic.list_rename_params xs' A end;
wenzelm@24830
   624
        fun rename_prop p =
wenzelm@24830
   625
          let val (As, C) = Logic.strip_horn p
wenzelm@24830
   626
          in Logic.list_implies (map rename_asm As, C) end;
wenzelm@24830
   627
        val cp' = cterm_fun rename_prop (Thm.cprop_of thm);
wenzelm@24830
   628
        val thm' = Thm.equal_elim (Thm.reflexive cp') thm;
wenzelm@33368
   629
      in [Rule_Cases.save thm thm'] end
wenzelm@24830
   630
  | special_rename_params _ _ ths = ths;
wenzelm@24830
   631
wenzelm@24830
   632
wenzelm@45132
   633
(* arbitrary_tac *)
wenzelm@24830
   634
wenzelm@24830
   635
local
wenzelm@24830
   636
wenzelm@56245
   637
fun goal_prefix k ((c as Const (@{const_name Pure.all}, _)) $ Abs (a, T, B)) =
wenzelm@56245
   638
      c $ Abs (a, T, goal_prefix k B)
wenzelm@45156
   639
  | goal_prefix 0 _ = Term.dummy_prop
wenzelm@56245
   640
  | goal_prefix k ((c as Const (@{const_name Pure.imp}, _)) $ A $ B) =
wenzelm@56245
   641
      c $ A $ goal_prefix (k - 1) B
wenzelm@45156
   642
  | goal_prefix _ _ = Term.dummy_prop;
wenzelm@24830
   643
wenzelm@56245
   644
fun goal_params k (Const (@{const_name Pure.all}, _) $ Abs (_, _, B)) = goal_params k B + 1
wenzelm@24830
   645
  | goal_params 0 _ = 0
wenzelm@56245
   646
  | goal_params k (Const (@{const_name Pure.imp}, _) $ _ $ B) = goal_params (k - 1) B
wenzelm@24830
   647
  | goal_params _ _ = 0;
wenzelm@24830
   648
wenzelm@24830
   649
fun meta_spec_tac ctxt n (x, T) = SUBGOAL (fn (goal, i) =>
wenzelm@24830
   650
  let
wenzelm@24830
   651
    val v = Free (x, T);
wenzelm@24830
   652
    fun spec_rule prfx (xs, body) =
wenzelm@24830
   653
      @{thm Pure.meta_spec}
wenzelm@42488
   654
      |> Thm.rename_params_rule ([Name.clean (Variable.revert_fixed ctxt x)], 1)
wenzelm@59843
   655
      |> Thm.lift_rule (Thm.cterm_of ctxt prfx)
wenzelm@24830
   656
      |> `(Thm.prop_of #> Logic.strip_assums_concl)
wenzelm@24830
   657
      |-> (fn pred $ arg =>
wenzelm@24830
   658
        Drule.cterm_instantiate
wenzelm@59843
   659
          (map (apply2 (Thm.cterm_of ctxt))
wenzelm@59843
   660
            [(Term.head_of pred, Logic.rlist_abs (xs, body)),
wenzelm@59843
   661
             (Term.head_of arg, Logic.rlist_abs (xs, v))]));
wenzelm@24830
   662
wenzelm@56245
   663
    fun goal_concl k xs (Const (@{const_name Pure.all}, _) $ Abs (a, T, B)) =
wenzelm@56245
   664
          goal_concl k ((a, T) :: xs) B
wenzelm@24830
   665
      | goal_concl 0 xs B =
wenzelm@24830
   666
          if not (Term.exists_subterm (fn t => t aconv v) B) then NONE
wenzelm@44241
   667
          else SOME (xs, absfree (x, T) (Term.incr_boundvars 1 B))
wenzelm@56245
   668
      | goal_concl k xs (Const (@{const_name Pure.imp}, _) $ _ $ B) =
wenzelm@56245
   669
          goal_concl (k - 1) xs B
wenzelm@24830
   670
      | goal_concl _ _ _ = NONE;
wenzelm@24830
   671
  in
wenzelm@24830
   672
    (case goal_concl n [] goal of
wenzelm@24830
   673
      SOME concl =>
wenzelm@58956
   674
        (compose_tac ctxt (false, spec_rule (goal_prefix n goal) concl, 1) THEN'
wenzelm@59498
   675
          resolve_tac ctxt [asm_rl]) i
wenzelm@24830
   676
    | NONE => all_tac)
wenzelm@24830
   677
  end);
wenzelm@24830
   678
wenzelm@54742
   679
fun miniscope_tac p =
wenzelm@54742
   680
  CONVERSION o
wenzelm@54742
   681
    Conv.params_conv p (fn ctxt =>
wenzelm@54742
   682
      Raw_Simplifier.rewrite ctxt true [Thm.symmetric Drule.norm_hhf_eq]);
wenzelm@24830
   683
wenzelm@24830
   684
in
wenzelm@24830
   685
wenzelm@45132
   686
fun arbitrary_tac _ _ [] = K all_tac
wenzelm@45132
   687
  | arbitrary_tac ctxt n xs = SUBGOAL (fn (goal, i) =>
wenzelm@24830
   688
     (EVERY' (map (meta_spec_tac ctxt n) xs) THEN'
wenzelm@24832
   689
      (miniscope_tac (goal_params n goal) ctxt)) i);
wenzelm@24830
   690
wenzelm@24830
   691
end;
wenzelm@24830
   692
wenzelm@24830
   693
wenzelm@24830
   694
(* add_defs *)
wenzelm@24830
   695
wenzelm@24830
   696
fun add_defs def_insts =
wenzelm@24830
   697
  let
berghofe@34907
   698
    fun add (SOME (_, (t, true))) ctxt = ((SOME t, []), ctxt)
berghofe@34907
   699
      | add (SOME (SOME x, (t, _))) ctxt =
wenzelm@28083
   700
          let val ([(lhs, (_, th))], ctxt') =
wenzelm@49748
   701
            Local_Defs.add_defs [((x, NoSyn), ((Thm.def_binding x, []), t))] ctxt
wenzelm@24830
   702
          in ((SOME lhs, [th]), ctxt') end
berghofe@34907
   703
      | add (SOME (NONE, (t as Free _, _))) ctxt = ((SOME t, []), ctxt)
berghofe@34907
   704
      | add (SOME (NONE, (t, _))) ctxt =
berghofe@34907
   705
          let
wenzelm@43326
   706
            val (s, _) = Name.variant "x" (Variable.names_of ctxt);
wenzelm@49748
   707
            val x = Binding.name s;
wenzelm@49748
   708
            val ([(lhs, (_, th))], ctxt') = ctxt
wenzelm@49748
   709
              |> Local_Defs.add_defs [((x, NoSyn), ((Thm.def_binding x, []), t))];
berghofe@34907
   710
          in ((SOME lhs, [th]), ctxt') end
wenzelm@24830
   711
      | add NONE ctxt = ((NONE, []), ctxt);
wenzelm@24830
   712
  in fold_map add def_insts #> apfst (split_list #> apsnd flat) end;
wenzelm@24830
   713
wenzelm@24830
   714
wenzelm@24830
   715
(* induct_tac *)
wenzelm@24830
   716
wenzelm@24830
   717
(*
wenzelm@24830
   718
  rule selection scheme:
wenzelm@24861
   719
    `A x` induct ...     - predicate/set induction
wenzelm@24830
   720
          induct x       - type induction
wenzelm@24830
   721
    ...   induct ... r   - explicit rule
wenzelm@24830
   722
*)
wenzelm@24830
   723
wenzelm@24830
   724
fun get_inductT ctxt insts =
wenzelm@32188
   725
  fold_rev (map_product cons) (insts |> map
wenzelm@27323
   726
      ((fn [] => NONE | ts => List.last ts) #>
wenzelm@27323
   727
        (fn NONE => TVar (("'a", 0), []) | SOME t => Term.fastype_of t) #>
wenzelm@27323
   728
        find_inductT ctxt)) [[]]
wenzelm@33368
   729
  |> filter_out (forall Rule_Cases.is_inner_rule);
wenzelm@24830
   730
wenzelm@24861
   731
fun get_inductP ctxt (fact :: _) = map single (find_inductP ctxt (Thm.concl_of fact))
wenzelm@24861
   732
  | get_inductP _ _ = [];
wenzelm@24830
   733
wenzelm@45130
   734
type case_data = (((string * string list) * string list) list * int);
nipkow@45014
   735
nipkow@45014
   736
fun gen_induct_tac mod_cases ctxt simp def_insts arbitrary taking opt_rule facts =
wenzelm@56231
   737
  SUBGOAL_CASES (fn (_, i, st) =>
wenzelm@56231
   738
    let
wenzelm@56231
   739
      val thy = Proof_Context.theory_of ctxt;
wenzelm@59940
   740
wenzelm@56231
   741
      val ((insts, defs), defs_ctxt) = fold_map add_defs def_insts ctxt |>> split_list;
wenzelm@56231
   742
      val atomized_defs = map (map (Conv.fconv_rule (atomize_cterm defs_ctxt))) defs;
wenzelm@59940
   743
wenzelm@56231
   744
      fun inst_rule (concls, r) =
wenzelm@56231
   745
        (if null insts then `Rule_Cases.get r
wenzelm@56231
   746
         else (align_left "Rule has fewer conclusions than arguments given"
wenzelm@56231
   747
            (map Logic.strip_imp_concl (Logic.dest_conjunctions (Thm.concl_of r))) insts
wenzelm@56231
   748
          |> maps (prep_inst ctxt align_right (atomize_term thy))
wenzelm@56231
   749
          |> Drule.cterm_instantiate) r |> pair (Rule_Cases.get r))
wenzelm@56231
   750
        |> mod_cases thy
wenzelm@56231
   751
        |> (fn ((cases, consumes), th) => (((cases, concls), consumes), th));
wenzelm@59940
   752
wenzelm@56231
   753
      val ruleq =
wenzelm@56231
   754
        (case opt_rule of
wenzelm@56231
   755
          SOME rs => Seq.single (inst_rule (Rule_Cases.strict_mutual_rule ctxt rs))
wenzelm@56231
   756
        | NONE =>
wenzelm@56231
   757
            (get_inductP ctxt facts @
wenzelm@56231
   758
              map (special_rename_params defs_ctxt insts) (get_inductT ctxt insts))
wenzelm@56231
   759
            |> map_filter (Rule_Cases.mutual_rule ctxt)
wenzelm@56231
   760
            |> tap (trace_rules ctxt inductN o map #2)
wenzelm@56231
   761
            |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@59940
   762
wenzelm@56231
   763
      fun rule_cases ctxt rule cases =
wenzelm@56231
   764
        let
wenzelm@56231
   765
          val rule' = Rule_Cases.internalize_params rule;
wenzelm@56231
   766
          val rule'' = rule' |> simp ? simplified_rule ctxt;
wenzelm@56231
   767
          val nonames = map (fn ((cn, _), cls) => ((cn, []), cls));
wenzelm@56231
   768
          val cases' = if Thm.eq_thm_prop (rule', rule'') then cases else nonames cases;
wenzelm@56231
   769
        in Rule_Cases.make_nested (Thm.prop_of rule'') (rulified_term rule'') cases' end;
wenzelm@56231
   770
    in
wenzelm@56231
   771
      fn st =>
wenzelm@56231
   772
        ruleq
wenzelm@56231
   773
        |> Seq.maps (Rule_Cases.consume defs_ctxt (flat defs) facts)
wenzelm@56231
   774
        |> Seq.maps (fn (((cases, concls), (more_consumes, more_facts)), rule) =>
wenzelm@56231
   775
          (PRECISE_CONJUNCTS (length concls) (ALLGOALS (fn j =>
wenzelm@56231
   776
            (CONJUNCTS (ALLGOALS
wenzelm@56231
   777
              let
wenzelm@56231
   778
                val adefs = nth_list atomized_defs (j - 1);
wenzelm@56231
   779
                val frees = fold (Term.add_frees o Thm.prop_of) adefs [];
wenzelm@56231
   780
                val xs = nth_list arbitrary (j - 1);
wenzelm@56231
   781
                val k = nth concls (j - 1) + more_consumes
wenzelm@56231
   782
              in
wenzelm@56231
   783
                Method.insert_tac (more_facts @ adefs) THEN'
wenzelm@56231
   784
                  (if simp then
wenzelm@56231
   785
                     rotate_tac k (length adefs) THEN'
wenzelm@56231
   786
                     arbitrary_tac defs_ctxt k (List.partition (member op = frees) xs |> op @)
wenzelm@56231
   787
                   else
wenzelm@56231
   788
                     arbitrary_tac defs_ctxt k xs)
wenzelm@56231
   789
               end)
wenzelm@56231
   790
            THEN' inner_atomize_tac defs_ctxt) j))
wenzelm@56231
   791
          THEN' atomize_tac defs_ctxt) i st |> Seq.maps (fn st' =>
wenzelm@56231
   792
              guess_instance ctxt (internalize ctxt more_consumes rule) i st'
wenzelm@56231
   793
              |> Seq.map (rule_instance ctxt (burrow_options (Variable.polymorphic ctxt) taking))
wenzelm@56231
   794
              |> Seq.maps (fn rule' =>
wenzelm@56231
   795
                CASES (rule_cases ctxt rule' cases)
wenzelm@59498
   796
                  (resolve_tac ctxt [rule'] i THEN
wenzelm@56231
   797
                    PRIMITIVE (singleton (Proof_Context.export defs_ctxt ctxt))) st')))
wenzelm@56231
   798
      end)
wenzelm@56231
   799
      THEN_ALL_NEW_CASES
wenzelm@58957
   800
        ((if simp then simplify_tac ctxt THEN' (TRY o trivial_tac ctxt) else K all_tac)
wenzelm@56231
   801
         THEN_ALL_NEW rulify_tac ctxt);
wenzelm@24830
   802
nipkow@45014
   803
val induct_tac = gen_induct_tac (K I);
wenzelm@24830
   804
wenzelm@45130
   805
wenzelm@45130
   806
wenzelm@24830
   807
(** coinduct method **)
wenzelm@24830
   808
wenzelm@24830
   809
(*
wenzelm@24830
   810
  rule selection scheme:
wenzelm@24861
   811
    goal "A x" coinduct ...   - predicate/set coinduction
wenzelm@24830
   812
               coinduct x     - type coinduction
wenzelm@24830
   813
               coinduct ... r - explicit rule
wenzelm@24830
   814
*)
wenzelm@24830
   815
wenzelm@24830
   816
local
wenzelm@24830
   817
wenzelm@24830
   818
fun get_coinductT ctxt (SOME t :: _) = find_coinductT ctxt (Term.fastype_of t)
wenzelm@24830
   819
  | get_coinductT _ _ = [];
wenzelm@24830
   820
wenzelm@24861
   821
fun get_coinductP ctxt goal = find_coinductP ctxt (Logic.strip_assums_concl goal);
wenzelm@24861
   822
wenzelm@24861
   823
fun main_prop_of th =
wenzelm@33368
   824
  if Rule_Cases.get_consumes th > 0 then Thm.major_prem_of th else Thm.concl_of th;
wenzelm@24830
   825
wenzelm@24830
   826
in
wenzelm@24830
   827
wenzelm@56231
   828
fun coinduct_tac ctxt inst taking opt_rule facts = SUBGOAL_CASES (fn (goal, i, st) =>
wenzelm@24830
   829
  let
wenzelm@24830
   830
    fun inst_rule r =
wenzelm@33368
   831
      if null inst then `Rule_Cases.get r
wenzelm@32432
   832
      else Drule.cterm_instantiate (prep_inst ctxt align_right I (main_prop_of r, inst)) r
wenzelm@33368
   833
        |> pair (Rule_Cases.get r);
wenzelm@24830
   834
wenzelm@24830
   835
    fun ruleq goal =
wenzelm@24830
   836
      (case opt_rule of
wenzelm@24830
   837
        SOME r => Seq.single (inst_rule r)
wenzelm@24830
   838
      | NONE =>
wenzelm@24861
   839
          (get_coinductP ctxt goal @ get_coinductT ctxt inst)
wenzelm@24830
   840
          |> tap (trace_rules ctxt coinductN)
wenzelm@24830
   841
          |> Seq.of_list |> Seq.maps (Seq.try inst_rule));
wenzelm@24830
   842
  in
wenzelm@56231
   843
    fn st =>
wenzelm@24830
   844
      ruleq goal
wenzelm@54742
   845
      |> Seq.maps (Rule_Cases.consume ctxt [] facts)
wenzelm@24830
   846
      |> Seq.maps (fn ((cases, (_, more_facts)), rule) =>
wenzelm@26940
   847
        guess_instance ctxt rule i st
wenzelm@32432
   848
        |> Seq.map (rule_instance ctxt (burrow_options (Variable.polymorphic ctxt) taking))
wenzelm@24830
   849
        |> Seq.maps (fn rule' =>
wenzelm@59843
   850
          CASES (Rule_Cases.make_common (Proof_Context.theory_of ctxt,
berghofe@34907
   851
              Thm.prop_of (Rule_Cases.internalize_params rule')) cases)
wenzelm@59498
   852
            (Method.insert_tac more_facts i THEN resolve_tac ctxt [rule'] i) st))
wenzelm@56231
   853
  end);
wenzelm@24830
   854
wenzelm@24830
   855
end;
wenzelm@24830
   856
wenzelm@24830
   857
wenzelm@24830
   858
wenzelm@24830
   859
(** concrete syntax **)
wenzelm@24830
   860
wenzelm@24830
   861
val arbitraryN = "arbitrary";
wenzelm@24830
   862
val takingN = "taking";
wenzelm@24830
   863
val ruleN = "rule";
wenzelm@24830
   864
wenzelm@24830
   865
local
wenzelm@24830
   866
wenzelm@24830
   867
fun single_rule [rule] = rule
wenzelm@24830
   868
  | single_rule _ = error "Single rule expected";
wenzelm@24830
   869
wenzelm@24830
   870
fun named_rule k arg get =
wenzelm@24830
   871
  Scan.lift (Args.$$$ k -- Args.colon) |-- Scan.repeat arg :|--
wenzelm@24830
   872
    (fn names => Scan.peek (fn context => Scan.succeed (names |> map (fn name =>
wenzelm@24830
   873
      (case get (Context.proof_of context) name of SOME x => x
wenzelm@24830
   874
      | NONE => error ("No rule for " ^ k ^ " " ^ quote name))))));
wenzelm@24830
   875
wenzelm@24861
   876
fun rule get_type get_pred =
wenzelm@55951
   877
  named_rule typeN (Args.type_name {proper = false, strict = false}) get_type ||
wenzelm@55954
   878
  named_rule predN (Args.const {proper = false, strict = false}) get_pred ||
wenzelm@55954
   879
  named_rule setN (Args.const {proper = false, strict = false}) get_pred ||
wenzelm@24830
   880
  Scan.lift (Args.$$$ ruleN -- Args.colon) |-- Attrib.thms;
wenzelm@24830
   881
wenzelm@24861
   882
val cases_rule = rule lookup_casesT lookup_casesP >> single_rule;
wenzelm@24861
   883
val induct_rule = rule lookup_inductT lookup_inductP;
wenzelm@24861
   884
val coinduct_rule = rule lookup_coinductT lookup_coinductP >> single_rule;
wenzelm@24830
   885
wenzelm@24830
   886
val inst = Scan.lift (Args.$$$ "_") >> K NONE || Args.term >> SOME;
wenzelm@24830
   887
berghofe@34907
   888
val inst' = Scan.lift (Args.$$$ "_") >> K NONE ||
berghofe@34907
   889
  Args.term >> (SOME o rpair false) ||
berghofe@34907
   890
  Scan.lift (Args.$$$ "(") |-- (Args.term >> (SOME o rpair true)) --|
berghofe@34907
   891
    Scan.lift (Args.$$$ ")");
berghofe@34907
   892
wenzelm@24830
   893
val def_inst =
wenzelm@28083
   894
  ((Scan.lift (Args.binding --| (Args.$$$ "\<equiv>" || Args.$$$ "==")) >> SOME)
berghofe@34907
   895
      -- (Args.term >> rpair false)) >> SOME ||
berghofe@34907
   896
    inst' >> Option.map (pair NONE);
wenzelm@24830
   897
wenzelm@27370
   898
val free = Args.context -- Args.term >> (fn (_, Free v) => v | (ctxt, t) =>
wenzelm@27370
   899
  error ("Bad free variable: " ^ Syntax.string_of_term ctxt t));
wenzelm@24830
   900
wenzelm@24830
   901
fun unless_more_args scan = Scan.unless (Scan.lift
wenzelm@24830
   902
  ((Args.$$$ arbitraryN || Args.$$$ takingN || Args.$$$ typeN ||
wenzelm@24861
   903
    Args.$$$ predN || Args.$$$ setN || Args.$$$ ruleN) -- Args.colon)) scan;
wenzelm@24830
   904
wenzelm@24830
   905
val arbitrary = Scan.optional (Scan.lift (Args.$$$ arbitraryN -- Args.colon) |--
wenzelm@36960
   906
  Parse.and_list1' (Scan.repeat (unless_more_args free))) [];
wenzelm@24830
   907
wenzelm@24830
   908
val taking = Scan.optional (Scan.lift (Args.$$$ takingN -- Args.colon) |--
wenzelm@24830
   909
  Scan.repeat1 (unless_more_args inst)) [];
wenzelm@24830
   910
wenzelm@24830
   911
in
wenzelm@24830
   912
wenzelm@58002
   913
fun gen_induct_setup binding tac =
wenzelm@59940
   914
  Method.local_setup binding
wenzelm@53168
   915
    (Scan.lift (Args.mode no_simpN) --
wenzelm@53168
   916
      (Parse.and_list' (Scan.repeat (unless_more_args def_inst)) --
wenzelm@53168
   917
        (arbitrary -- taking -- Scan.option induct_rule)) >>
wenzelm@58002
   918
      (fn (no_simp, (insts, ((arbitrary, taking), opt_rule))) => fn ctxt => fn facts =>
wenzelm@58002
   919
        Seq.DETERM (HEADGOAL (tac ctxt (not no_simp) insts arbitrary taking opt_rule facts))))
wenzelm@30722
   920
    "induction on types or predicates/sets";
wenzelm@24830
   921
wenzelm@58826
   922
val _ =
wenzelm@59940
   923
  Theory.local_setup
wenzelm@59940
   924
    (Method.local_setup @{binding cases}
wenzelm@59940
   925
      (Scan.lift (Args.mode no_simpN) --
wenzelm@59940
   926
        (Parse.and_list' (Scan.repeat (unless_more_args inst)) -- Scan.option cases_rule) >>
wenzelm@59940
   927
        (fn (no_simp, (insts, opt_rule)) => fn ctxt =>
wenzelm@59940
   928
          METHOD_CASES (fn facts => Seq.DETERM (HEADGOAL
wenzelm@59940
   929
            (cases_tac ctxt (not no_simp) insts opt_rule facts)))))
wenzelm@59940
   930
      "case analysis on types or predicates/sets" #>
wenzelm@59940
   931
    gen_induct_setup @{binding induct} induct_tac #>
wenzelm@59940
   932
     Method.local_setup @{binding coinduct}
wenzelm@58826
   933
      (Scan.repeat (unless_more_args inst) -- taking -- Scan.option coinduct_rule >>
wenzelm@58826
   934
        (fn ((insts, taking), opt_rule) => fn ctxt => fn facts =>
wenzelm@58826
   935
          Seq.DETERM (HEADGOAL (coinduct_tac ctxt insts taking opt_rule facts))))
wenzelm@58826
   936
      "coinduction on types or predicates/sets");
wenzelm@24830
   937
wenzelm@24830
   938
end;
wenzelm@24830
   939
wenzelm@24830
   940
end;