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