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