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