src/HOL/Tools/inductive.ML
author wenzelm
Mon Apr 06 23:14:05 2015 +0200 (2015-04-06)
changeset 59940 087d81f5213e
parent 59936 b8ffc3dc9e24
child 60097 d20ca79d50e4
permissions -rw-r--r--
local setup of induction tools, with restricted access to auxiliary consts;
proper antiquotations for formerly inaccessible consts;
haftmann@31723
     1
(*  Title:      HOL/Tools/inductive.ML
berghofe@5094
     2
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
wenzelm@21367
     3
    Author:     Stefan Berghofer and Markus Wenzel, TU Muenchen
berghofe@5094
     4
wenzelm@6424
     5
(Co)Inductive Definition module for HOL.
berghofe@5094
     6
berghofe@5094
     7
Features:
wenzelm@6424
     8
  * least or greatest fixedpoints
wenzelm@6424
     9
  * mutually recursive definitions
wenzelm@6424
    10
  * definitions involving arbitrary monotone operators
wenzelm@6424
    11
  * automatically proves introduction and elimination rules
berghofe@5094
    12
berghofe@5094
    13
  Introduction rules have the form
berghofe@21024
    14
  [| M Pj ti, ..., Q x, ... |] ==> Pk t
berghofe@5094
    15
  where M is some monotone operator (usually the identity)
berghofe@21024
    16
  Q x is any side condition on the free variables
berghofe@5094
    17
  ti, t are any terms
berghofe@21024
    18
  Pj, Pk are two of the predicates being defined in mutual recursion
berghofe@5094
    19
*)
berghofe@5094
    20
haftmann@31723
    21
signature BASIC_INDUCTIVE =
berghofe@5094
    22
sig
wenzelm@33458
    23
  type inductive_result =
wenzelm@33458
    24
    {preds: term list, elims: thm list, raw_induct: thm,
bulwahn@37734
    25
     induct: thm, inducts: thm list, intrs: thm list, eqs: thm list}
wenzelm@45290
    26
  val transform_result: morphism -> inductive_result -> inductive_result
wenzelm@33458
    27
  type inductive_info = {names: string list, coind: bool} * inductive_result
wenzelm@21526
    28
  val the_inductive: Proof.context -> string -> inductive_info
wenzelm@59917
    29
  val print_inductives: bool -> Proof.context -> unit
wenzelm@45651
    30
  val get_monos: Proof.context -> thm list
wenzelm@18728
    31
  val mono_add: attribute
wenzelm@18728
    32
  val mono_del: attribute
wenzelm@53994
    33
  val mk_cases_tac: Proof.context -> tactic
wenzelm@21367
    34
  val mk_cases: Proof.context -> term -> thm
wenzelm@10910
    35
  val inductive_forall_def: thm
wenzelm@51717
    36
  val rulify: Proof.context -> thm -> thm
wenzelm@28839
    37
  val inductive_cases: (Attrib.binding * string list) list -> local_theory ->
wenzelm@53995
    38
    (string * thm list) list * local_theory
wenzelm@28839
    39
  val inductive_cases_i: (Attrib.binding * term list) list -> local_theory ->
wenzelm@53995
    40
    (string * thm list) list * local_theory
wenzelm@59845
    41
  val ind_cases_rules: Proof.context ->
wenzelm@59845
    42
    string list -> (binding * string option * mixfix) list -> thm list
wenzelm@53995
    43
  val inductive_simps: (Attrib.binding * string list) list -> local_theory ->
wenzelm@53995
    44
    (string * thm list) list * local_theory
wenzelm@53995
    45
  val inductive_simps_i: (Attrib.binding * term list) list -> local_theory ->
wenzelm@53995
    46
    (string * thm list) list * local_theory
wenzelm@33458
    47
  type inductive_flags =
wenzelm@33669
    48
    {quiet_mode: bool, verbose: bool, alt_name: binding, coind: bool,
wenzelm@49170
    49
      no_elim: bool, no_ind: bool, skip_mono: bool}
wenzelm@24815
    50
  val add_inductive_i:
haftmann@29581
    51
    inductive_flags -> ((binding * typ) * mixfix) list ->
wenzelm@28084
    52
    (string * typ) list -> (Attrib.binding * term) list -> thm list -> local_theory ->
wenzelm@28084
    53
    inductive_result * local_theory
wenzelm@28083
    54
  val add_inductive: bool -> bool ->
haftmann@29581
    55
    (binding * string option * mixfix) list ->
haftmann@29581
    56
    (binding * string option * mixfix) list ->
wenzelm@28084
    57
    (Attrib.binding * string) list ->
wenzelm@58011
    58
    (Facts.ref * Token.src list) list ->
wenzelm@49324
    59
    local_theory -> inductive_result * local_theory
wenzelm@33726
    60
  val add_inductive_global: inductive_flags ->
haftmann@29581
    61
    ((binding * typ) * mixfix) list -> (string * typ) list -> (Attrib.binding * term) list ->
wenzelm@28084
    62
    thm list -> theory -> inductive_result * theory
berghofe@22789
    63
  val arities_of: thm -> (string * int) list
berghofe@22789
    64
  val params_of: thm -> term list
berghofe@22789
    65
  val partition_rules: thm -> thm list -> (string * thm list) list
berghofe@25822
    66
  val partition_rules': thm -> (thm * 'a) list -> (string * (thm * 'a) list) list
berghofe@22789
    67
  val unpartition_rules: thm list -> (string * 'a list) list -> 'a list
berghofe@22789
    68
  val infer_intro_vars: thm -> int -> thm list -> term list list
berghofe@5094
    69
end;
berghofe@5094
    70
haftmann@31723
    71
signature INDUCTIVE =
berghofe@23762
    72
sig
haftmann@31723
    73
  include BASIC_INDUCTIVE
wenzelm@59532
    74
  val select_disj_tac: Proof.context -> int -> int -> int -> tactic
wenzelm@33458
    75
  type add_ind_def =
wenzelm@33458
    76
    inductive_flags ->
wenzelm@33458
    77
    term list -> (Attrib.binding * term) list -> thm list ->
wenzelm@33458
    78
    term list -> (binding * mixfix) list ->
wenzelm@33458
    79
    local_theory -> inductive_result * local_theory
bulwahn@35757
    80
  val declare_rules: binding -> bool -> bool -> string list -> term list ->
wenzelm@58011
    81
    thm list -> binding list -> Token.src list list -> (thm * string list * int) list ->
bulwahn@37734
    82
    thm list -> thm -> local_theory -> thm list * thm list * thm list * thm * thm list * local_theory
berghofe@23762
    83
  val add_ind_def: add_ind_def
wenzelm@28083
    84
  val gen_add_inductive_i: add_ind_def -> inductive_flags ->
haftmann@29581
    85
    ((binding * typ) * mixfix) list -> (string * typ) list -> (Attrib.binding * term) list ->
wenzelm@28084
    86
    thm list -> local_theory -> inductive_result * local_theory
wenzelm@28083
    87
  val gen_add_inductive: add_ind_def -> bool -> bool ->
haftmann@29581
    88
    (binding * string option * mixfix) list ->
haftmann@29581
    89
    (binding * string option * mixfix) list ->
wenzelm@58011
    90
    (Attrib.binding * string) list -> (Facts.ref * Token.src list) list ->
wenzelm@49324
    91
    local_theory -> inductive_result * local_theory
wenzelm@49324
    92
  val gen_ind_decl: add_ind_def -> bool -> (local_theory -> local_theory) parser
berghofe@23762
    93
end;
berghofe@23762
    94
haftmann@31723
    95
structure Inductive: INDUCTIVE =
berghofe@5094
    96
struct
berghofe@5094
    97
wenzelm@10729
    98
(** theory context references **)
wenzelm@10729
    99
wenzelm@59940
   100
val inductive_forall_def = @{thm HOL.induct_forall_def};
wenzelm@59940
   101
val inductive_conj_def = @{thm HOL.induct_conj_def};
haftmann@32602
   102
val inductive_conj = @{thms induct_conj};
haftmann@32602
   103
val inductive_atomize = @{thms induct_atomize};
haftmann@32602
   104
val inductive_rulify = @{thms induct_rulify};
haftmann@32602
   105
val inductive_rulify_fallback = @{thms induct_rulify_fallback};
wenzelm@10729
   106
wenzelm@45649
   107
val simp_thms1 =
wenzelm@45649
   108
  map mk_meta_eq
wenzelm@45649
   109
    @{lemma "(~ True) = False" "(~ False) = True"
wenzelm@45649
   110
        "(True --> P) = P" "(False --> P) = True"
wenzelm@45649
   111
        "(P & True) = P" "(True & P) = P"
wenzelm@45649
   112
      by (fact simp_thms)+};
berghofe@21024
   113
wenzelm@45649
   114
val simp_thms2 =
wenzelm@45649
   115
  map mk_meta_eq [@{thm inf_fun_def}, @{thm inf_bool_def}] @ simp_thms1;
haftmann@32652
   116
wenzelm@45649
   117
val simp_thms3 =
wenzelm@45649
   118
  map mk_meta_eq [@{thm le_fun_def}, @{thm le_bool_def}, @{thm sup_fun_def}, @{thm sup_bool_def}];
wenzelm@10729
   119
wenzelm@10729
   120
wenzelm@45647
   121
wenzelm@10735
   122
(** misc utilities **)
wenzelm@6424
   123
wenzelm@26477
   124
fun message quiet_mode s = if quiet_mode then () else writeln s;
wenzelm@52059
   125
wenzelm@52059
   126
fun clean_message ctxt quiet_mode s =
wenzelm@52059
   127
  if Config.get ctxt quick_and_dirty then () else message quiet_mode s;
berghofe@5662
   128
wenzelm@6424
   129
fun coind_prefix true = "co"
wenzelm@6424
   130
  | coind_prefix false = "";
wenzelm@6424
   131
wenzelm@45651
   132
fun log (b: int) m n = if m >= n then 0 else 1 + log b (b * m) n;
wenzelm@6424
   133
berghofe@21024
   134
fun make_bool_args f g [] i = []
berghofe@21024
   135
  | make_bool_args f g (x :: xs) i =
berghofe@21024
   136
      (if i mod 2 = 0 then f x else g x) :: make_bool_args f g xs (i div 2);
berghofe@21024
   137
berghofe@21024
   138
fun make_bool_args' xs =
wenzelm@45740
   139
  make_bool_args (K @{term False}) (K @{term True}) xs;
berghofe@21024
   140
haftmann@33957
   141
fun arg_types_of k c = drop k (binder_types (fastype_of c));
haftmann@33077
   142
wenzelm@40316
   143
fun find_arg T x [] = raise Fail "find_arg"
berghofe@21024
   144
  | find_arg T x ((p as (_, (SOME _, _))) :: ps) =
berghofe@21024
   145
      apsnd (cons p) (find_arg T x ps)
berghofe@21024
   146
  | find_arg T x ((p as (U, (NONE, y))) :: ps) =
wenzelm@23577
   147
      if (T: typ) = U then (y, (U, (SOME x, y)) :: ps)
berghofe@21024
   148
      else apsnd (cons p) (find_arg T x ps);
berghofe@7020
   149
berghofe@21024
   150
fun make_args Ts xs =
haftmann@28524
   151
  map (fn (T, (NONE, ())) => Const (@{const_name undefined}, T) | (_, (SOME t, ())) => t)
berghofe@21024
   152
    (fold (fn (t, T) => snd o find_arg T t) xs (map (rpair (NONE, ())) Ts));
berghofe@7020
   153
berghofe@21024
   154
fun make_args' Ts xs Us =
berghofe@21024
   155
  fst (fold_map (fn T => find_arg T ()) Us (Ts ~~ map (pair NONE) xs));
berghofe@7020
   156
berghofe@21024
   157
fun dest_predicate cs params t =
berghofe@5094
   158
  let
berghofe@21024
   159
    val k = length params;
berghofe@21024
   160
    val (c, ts) = strip_comb t;
berghofe@21024
   161
    val (xs, ys) = chop k ts;
haftmann@31986
   162
    val i = find_index (fn c' => c' = c) cs;
berghofe@21024
   163
  in
berghofe@21024
   164
    if xs = params andalso i >= 0 then
haftmann@33077
   165
      SOME (c, i, ys, chop (length ys) (arg_types_of k c))
berghofe@21024
   166
    else NONE
berghofe@5094
   167
  end;
berghofe@5094
   168
berghofe@21024
   169
fun mk_names a 0 = []
berghofe@21024
   170
  | mk_names a 1 = [a]
berghofe@21024
   171
  | mk_names a n = map (fn i => a ^ string_of_int i) (1 upto n);
berghofe@10988
   172
wenzelm@59532
   173
fun select_disj_tac ctxt =
wenzelm@59532
   174
  let
wenzelm@59532
   175
    fun tacs 1 1 = []
wenzelm@59532
   176
      | tacs _ 1 = [resolve_tac ctxt @{thms disjI1}]
wenzelm@59532
   177
      | tacs n i = resolve_tac ctxt @{thms disjI2} :: tacs (n - 1) (i - 1);
wenzelm@59532
   178
  in fn n => fn i => EVERY' (tacs n i) end;
wenzelm@45647
   179
wenzelm@6424
   180
wenzelm@6424
   181
wenzelm@45651
   182
(** context data **)
wenzelm@45651
   183
wenzelm@45651
   184
type inductive_result =
wenzelm@45651
   185
  {preds: term list, elims: thm list, raw_induct: thm,
wenzelm@45651
   186
   induct: thm, inducts: thm list, intrs: thm list, eqs: thm list};
wenzelm@45651
   187
wenzelm@45651
   188
fun transform_result phi {preds, elims, raw_induct: thm, induct, inducts, intrs, eqs} =
wenzelm@45651
   189
  let
wenzelm@45651
   190
    val term = Morphism.term phi;
wenzelm@45651
   191
    val thm = Morphism.thm phi;
wenzelm@45651
   192
    val fact = Morphism.fact phi;
wenzelm@45651
   193
  in
wenzelm@45651
   194
   {preds = map term preds, elims = fact elims, raw_induct = thm raw_induct,
wenzelm@45651
   195
    induct = thm induct, inducts = fact inducts, intrs = fact intrs, eqs = fact eqs}
wenzelm@45651
   196
  end;
wenzelm@45651
   197
wenzelm@45651
   198
type inductive_info = {names: string list, coind: bool} * inductive_result;
wenzelm@45651
   199
wenzelm@45651
   200
val empty_equations =
wenzelm@45652
   201
  Item_Net.init Thm.eq_thm_prop
wenzelm@45652
   202
    (single o fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o Thm.prop_of);
wenzelm@45651
   203
wenzelm@45651
   204
datatype data = Data of
wenzelm@45651
   205
 {infos: inductive_info Symtab.table,
wenzelm@45651
   206
  monos: thm list,
wenzelm@45651
   207
  equations: thm Item_Net.T};
wenzelm@45651
   208
wenzelm@45651
   209
fun make_data (infos, monos, equations) =
wenzelm@45651
   210
  Data {infos = infos, monos = monos, equations = equations};
wenzelm@45651
   211
wenzelm@45651
   212
structure Data = Generic_Data
wenzelm@45651
   213
(
wenzelm@45651
   214
  type T = data;
wenzelm@45651
   215
  val empty = make_data (Symtab.empty, [], empty_equations);
wenzelm@45651
   216
  val extend = I;
wenzelm@45651
   217
  fun merge (Data {infos = infos1, monos = monos1, equations = equations1},
wenzelm@45651
   218
      Data {infos = infos2, monos = monos2, equations = equations2}) =
wenzelm@45651
   219
    make_data (Symtab.merge (K true) (infos1, infos2),
wenzelm@45651
   220
      Thm.merge_thms (monos1, monos2),
wenzelm@45651
   221
      Item_Net.merge (equations1, equations2));
wenzelm@45651
   222
);
wenzelm@45651
   223
wenzelm@45651
   224
fun map_data f =
wenzelm@45651
   225
  Data.map (fn Data {infos, monos, equations} => make_data (f (infos, monos, equations)));
wenzelm@45651
   226
wenzelm@45651
   227
fun rep_data ctxt = Data.get (Context.Proof ctxt) |> (fn Data rep => rep);
wenzelm@45651
   228
wenzelm@59917
   229
fun print_inductives verbose ctxt =
wenzelm@45651
   230
  let
wenzelm@45651
   231
    val {infos, monos, ...} = rep_data ctxt;
wenzelm@45651
   232
    val space = Consts.space_of (Proof_Context.consts_of ctxt);
wenzelm@45651
   233
  in
wenzelm@50301
   234
    [Pretty.block
wenzelm@50301
   235
      (Pretty.breaks
wenzelm@50301
   236
        (Pretty.str "(co)inductives:" ::
wenzelm@59917
   237
          map (Pretty.mark_str o #1)
wenzelm@59917
   238
            (Name_Space.markup_entries verbose ctxt space (Symtab.dest infos)))),
wenzelm@51584
   239
     Pretty.big_list "monotonicity rules:" (map (Display.pretty_thm_item ctxt) monos)]
wenzelm@56334
   240
  end |> Pretty.writeln_chunks;
wenzelm@45651
   241
wenzelm@45651
   242
wenzelm@45651
   243
(* inductive info *)
wenzelm@45651
   244
wenzelm@45651
   245
fun the_inductive ctxt name =
wenzelm@45651
   246
  (case Symtab.lookup (#infos (rep_data ctxt)) name of
wenzelm@45651
   247
    NONE => error ("Unknown (co)inductive predicate " ^ quote name)
wenzelm@45651
   248
  | SOME info => info);
wenzelm@45651
   249
wenzelm@45651
   250
fun put_inductives names info =
wenzelm@45651
   251
  map_data (fn (infos, monos, equations) =>
wenzelm@45651
   252
    (fold (fn name => Symtab.update (name, info)) names infos, monos, equations));
wenzelm@45651
   253
wenzelm@45651
   254
wenzelm@45651
   255
(* monotonicity rules *)
wenzelm@45651
   256
wenzelm@45651
   257
val get_monos = #monos o rep_data;
wenzelm@45651
   258
wenzelm@45651
   259
fun mk_mono ctxt thm =
wenzelm@45651
   260
  let
wenzelm@45651
   261
    fun eq_to_mono thm' = thm' RS (thm' RS @{thm eq_to_mono});
wenzelm@45651
   262
    fun dest_less_concl thm = dest_less_concl (thm RS @{thm le_funD})
wenzelm@45651
   263
      handle THM _ => thm RS @{thm le_boolD}
wenzelm@45651
   264
  in
wenzelm@59582
   265
    (case Thm.concl_of thm of
wenzelm@56245
   266
      Const (@{const_name Pure.eq}, _) $ _ $ _ => eq_to_mono (thm RS meta_eq_to_obj_eq)
wenzelm@45651
   267
    | _ $ (Const (@{const_name HOL.eq}, _) $ _ $ _) => eq_to_mono thm
wenzelm@45651
   268
    | _ $ (Const (@{const_name Orderings.less_eq}, _) $ _ $ _) =>
wenzelm@45651
   269
      dest_less_concl (Seq.hd (REPEAT (FIRSTGOAL
wenzelm@59498
   270
        (resolve_tac ctxt [@{thm le_funI}, @{thm le_boolI'}])) thm))
wenzelm@45651
   271
    | _ => thm)
wenzelm@45651
   272
  end handle THM _ => error ("Bad monotonicity theorem:\n" ^ Display.string_of_thm ctxt thm);
wenzelm@45651
   273
wenzelm@45651
   274
val mono_add =
wenzelm@45651
   275
  Thm.declaration_attribute (fn thm => fn context =>
wenzelm@45651
   276
    map_data (fn (infos, monos, equations) =>
wenzelm@45651
   277
      (infos, Thm.add_thm (mk_mono (Context.proof_of context) thm) monos, equations)) context);
wenzelm@45651
   278
wenzelm@45651
   279
val mono_del =
wenzelm@45651
   280
  Thm.declaration_attribute (fn thm => fn context =>
wenzelm@45651
   281
    map_data (fn (infos, monos, equations) =>
wenzelm@45651
   282
      (infos, Thm.del_thm (mk_mono (Context.proof_of context) thm) monos, equations)) context);
wenzelm@45651
   283
wenzelm@58815
   284
val _ =
wenzelm@58815
   285
  Theory.setup
wenzelm@58815
   286
    (Attrib.setup @{binding mono} (Attrib.add_del mono_add mono_del)
wenzelm@58815
   287
      "declaration of monotonicity rule");
wenzelm@58815
   288
wenzelm@45651
   289
wenzelm@45651
   290
(* equations *)
wenzelm@45651
   291
wenzelm@45651
   292
val get_equations = #equations o rep_data;
wenzelm@45651
   293
wenzelm@45652
   294
val equation_add_permissive =
wenzelm@45651
   295
  Thm.declaration_attribute (fn thm =>
wenzelm@45652
   296
    map_data (fn (infos, monos, equations) =>
wenzelm@45652
   297
      (infos, monos, perhaps (try (Item_Net.update thm)) equations)));
wenzelm@45651
   298
wenzelm@45651
   299
wenzelm@45651
   300
wenzelm@10729
   301
(** process rules **)
wenzelm@10729
   302
wenzelm@10729
   303
local
berghofe@5094
   304
berghofe@23762
   305
fun err_in_rule ctxt name t msg =
wenzelm@42381
   306
  error (cat_lines ["Ill-formed introduction rule " ^ Binding.print name,
wenzelm@24920
   307
    Syntax.string_of_term ctxt t, msg]);
wenzelm@10729
   308
berghofe@23762
   309
fun err_in_prem ctxt name t p msg =
wenzelm@24920
   310
  error (cat_lines ["Ill-formed premise", Syntax.string_of_term ctxt p,
wenzelm@42381
   311
    "in introduction rule " ^ Binding.print name, Syntax.string_of_term ctxt t, msg]);
berghofe@5094
   312
berghofe@21024
   313
val bad_concl = "Conclusion of introduction rule must be an inductive predicate";
wenzelm@10729
   314
berghofe@21024
   315
val bad_ind_occ = "Inductive predicate occurs in argument of inductive predicate";
berghofe@21024
   316
berghofe@21024
   317
val bad_app = "Inductive predicate must be applied to parameter(s) ";
paulson@11358
   318
wenzelm@41228
   319
fun atomize_term thy = Raw_Simplifier.rewrite_term thy inductive_atomize [];
wenzelm@10729
   320
wenzelm@10729
   321
in
berghofe@5094
   322
wenzelm@28083
   323
fun check_rule ctxt cs params ((binding, att), rule) =
wenzelm@10729
   324
  let
berghofe@21024
   325
    val params' = Term.variant_frees rule (Logic.strip_params rule);
berghofe@21024
   326
    val frees = rev (map Free params');
berghofe@21024
   327
    val concl = subst_bounds (frees, Logic.strip_assums_concl rule);
berghofe@21024
   328
    val prems = map (curry subst_bounds frees) (Logic.strip_assums_hyp rule);
berghofe@23762
   329
    val rule' = Logic.list_implies (prems, concl);
wenzelm@42361
   330
    val aprems = map (atomize_term (Proof_Context.theory_of ctxt)) prems;
wenzelm@46215
   331
    val arule = fold_rev (Logic.all o Free) params' (Logic.list_implies (aprems, concl));
berghofe@21024
   332
wenzelm@45647
   333
    fun check_ind err t =
wenzelm@45647
   334
      (case dest_predicate cs params t of
berghofe@21024
   335
        NONE => err (bad_app ^
wenzelm@24920
   336
          commas (map (Syntax.string_of_term ctxt) params))
berghofe@21024
   337
      | SOME (_, _, ys, _) =>
berghofe@21024
   338
          if exists (fn c => exists (fn t => Logic.occs (c, t)) ys) cs
wenzelm@45647
   339
          then err bad_ind_occ else ());
berghofe@21024
   340
berghofe@21024
   341
    fun check_prem' prem t =
haftmann@36692
   342
      if member (op =) cs (head_of t) then
wenzelm@42381
   343
        check_ind (err_in_prem ctxt binding rule prem) t
wenzelm@45647
   344
      else
wenzelm@45647
   345
        (case t of
berghofe@21024
   346
          Abs (_, _, t) => check_prem' prem t
berghofe@21024
   347
        | t $ u => (check_prem' prem t; check_prem' prem u)
berghofe@21024
   348
        | _ => ());
berghofe@5094
   349
wenzelm@10729
   350
    fun check_prem (prem, aprem) =
berghofe@21024
   351
      if can HOLogic.dest_Trueprop aprem then check_prem' prem prem
wenzelm@42381
   352
      else err_in_prem ctxt binding rule prem "Non-atomic premise";
wenzelm@45647
   353
wenzelm@45647
   354
    val _ =
wenzelm@45647
   355
      (case concl of
wenzelm@45647
   356
        Const (@{const_name Trueprop}, _) $ t =>
wenzelm@45647
   357
          if member (op =) cs (head_of t) then
wenzelm@42381
   358
           (check_ind (err_in_rule ctxt binding rule') t;
berghofe@21024
   359
            List.app check_prem (prems ~~ aprems))
wenzelm@45647
   360
          else err_in_rule ctxt binding rule' bad_concl
wenzelm@45647
   361
       | _ => err_in_rule ctxt binding rule' bad_concl);
wenzelm@45647
   362
  in
wenzelm@28083
   363
    ((binding, att), arule)
wenzelm@10729
   364
  end;
berghofe@5094
   365
wenzelm@51717
   366
fun rulify ctxt =
wenzelm@51717
   367
  hol_simplify ctxt inductive_conj
wenzelm@51717
   368
  #> hol_simplify ctxt inductive_rulify
wenzelm@51717
   369
  #> hol_simplify ctxt inductive_rulify_fallback
wenzelm@54883
   370
  #> Simplifier.norm_hhf ctxt;
wenzelm@10729
   371
wenzelm@10729
   372
end;
wenzelm@10729
   373
berghofe@5094
   374
wenzelm@6424
   375
berghofe@21024
   376
(** proofs for (co)inductive predicates **)
wenzelm@6424
   377
berghofe@26534
   378
(* prove monotonicity *)
berghofe@5094
   379
wenzelm@49170
   380
fun prove_mono quiet_mode skip_mono predT fp_fun monos ctxt =
wenzelm@52059
   381
 (message (quiet_mode orelse skip_mono andalso Config.get ctxt quick_and_dirty)
berghofe@26534
   382
    "  Proving monotonicity ...";
wenzelm@51551
   383
  (if skip_mono then Goal.prove_sorry else Goal.prove_future) ctxt
berghofe@36642
   384
    [] []
wenzelm@17985
   385
    (HOLogic.mk_Trueprop
wenzelm@24815
   386
      (Const (@{const_name Orderings.mono}, (predT --> predT) --> HOLogic.boolT) $ fp_fun))
wenzelm@59498
   387
    (fn _ => EVERY [resolve_tac ctxt @{thms monoI} 1,
wenzelm@59498
   388
      REPEAT (resolve_tac ctxt [@{thm le_funI}, @{thm le_boolI'}] 1),
berghofe@21024
   389
      REPEAT (FIRST
wenzelm@58963
   390
        [assume_tac ctxt 1,
wenzelm@59498
   391
         resolve_tac ctxt (map (mk_mono ctxt) monos @ get_monos ctxt) 1,
wenzelm@59498
   392
         eresolve_tac ctxt @{thms le_funE} 1,
wenzelm@59498
   393
         dresolve_tac ctxt @{thms le_boolD} 1])]));
berghofe@5094
   394
wenzelm@6424
   395
wenzelm@10735
   396
(* prove introduction rules *)
berghofe@5094
   397
berghofe@36642
   398
fun prove_intrs quiet_mode coind mono fp_def k intr_ts rec_preds_defs ctxt ctxt' =
berghofe@5094
   399
  let
wenzelm@52059
   400
    val _ = clean_message ctxt quiet_mode "  Proving the introduction rules ...";
berghofe@5094
   401
berghofe@21024
   402
    val unfold = funpow k (fn th => th RS fun_cong)
berghofe@21024
   403
      (mono RS (fp_def RS
haftmann@32652
   404
        (if coind then @{thm def_gfp_unfold} else @{thm def_lfp_unfold})));
berghofe@5094
   405
wenzelm@45648
   406
    val rules = [refl, TrueI, @{lemma "~ False" by (rule notI)}, exI, conjI];
berghofe@21024
   407
berghofe@36642
   408
    val intrs = map_index (fn (i, intr) =>
wenzelm@51551
   409
      Goal.prove_sorry ctxt [] [] intr (fn _ => EVERY
wenzelm@54742
   410
       [rewrite_goals_tac ctxt rec_preds_defs,
wenzelm@59498
   411
        resolve_tac ctxt [unfold RS iffD2] 1,
wenzelm@59532
   412
        select_disj_tac ctxt (length intr_ts) (i + 1) 1,
wenzelm@17985
   413
        (*Not ares_tac, since refl must be tried before any equality assumptions;
wenzelm@17985
   414
          backtracking may occur if the premises have extra variables!*)
wenzelm@59498
   415
        DEPTH_SOLVE_1 (resolve_tac ctxt rules 1 APPEND assume_tac ctxt 1)])
wenzelm@42361
   416
       |> singleton (Proof_Context.export ctxt ctxt')) intr_ts
berghofe@5094
   417
berghofe@5094
   418
  in (intrs, unfold) end;
berghofe@5094
   419
wenzelm@6424
   420
wenzelm@10735
   421
(* prove elimination rules *)
berghofe@5094
   422
berghofe@36642
   423
fun prove_elims quiet_mode cs params intr_ts intr_names unfold rec_preds_defs ctxt ctxt''' =
berghofe@5094
   424
  let
wenzelm@52059
   425
    val _ = clean_message ctxt quiet_mode "  Proving the elimination rules ...";
berghofe@5094
   426
berghofe@36642
   427
    val ([pname], ctxt') = Variable.variant_fixes ["P"] ctxt;
berghofe@21024
   428
    val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
berghofe@21024
   429
berghofe@21024
   430
    fun dest_intr r =
berghofe@21024
   431
      (the (dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))),
berghofe@21024
   432
       Logic.strip_assums_hyp r, Logic.strip_params r);
berghofe@21024
   433
berghofe@21024
   434
    val intrs = map dest_intr intr_ts ~~ intr_names;
berghofe@21024
   435
berghofe@21024
   436
    val rules1 = [disjE, exE, FalseE];
wenzelm@45648
   437
    val rules2 = [conjE, FalseE, @{lemma "~ True ==> R" by (rule notE [OF _ TrueI])}];
berghofe@21024
   438
berghofe@21024
   439
    fun prove_elim c =
berghofe@21024
   440
      let
haftmann@33077
   441
        val Ts = arg_types_of (length params) c;
berghofe@21024
   442
        val (anames, ctxt'') = Variable.variant_fixes (mk_names "a" (length Ts)) ctxt';
berghofe@21024
   443
        val frees = map Free (anames ~~ Ts);
berghofe@21024
   444
berghofe@21024
   445
        fun mk_elim_prem ((_, _, us, _), ts, params') =
wenzelm@46218
   446
          Logic.list_all (params',
berghofe@21024
   447
            Logic.list_implies (map (HOLogic.mk_Trueprop o HOLogic.mk_eq)
berghofe@21024
   448
              (frees ~~ us) @ ts, P));
wenzelm@33317
   449
        val c_intrs = filter (equal c o #1 o #1 o #1) intrs;
berghofe@21024
   450
        val prems = HOLogic.mk_Trueprop (list_comb (c, params @ frees)) ::
berghofe@21024
   451
           map mk_elim_prem (map #1 c_intrs)
berghofe@21024
   452
      in
wenzelm@51551
   453
        (Goal.prove_sorry ctxt'' [] prems P
wenzelm@54742
   454
          (fn {context = ctxt4, prems} => EVERY
wenzelm@46708
   455
            [cut_tac (hd prems) 1,
wenzelm@54742
   456
             rewrite_goals_tac ctxt4 rec_preds_defs,
wenzelm@59498
   457
             dresolve_tac ctxt4 [unfold RS iffD1] 1,
wenzelm@59498
   458
             REPEAT (FIRSTGOAL (eresolve_tac ctxt4 rules1)),
wenzelm@59498
   459
             REPEAT (FIRSTGOAL (eresolve_tac ctxt4 rules2)),
berghofe@21024
   460
             EVERY (map (fn prem =>
wenzelm@59499
   461
               DEPTH_SOLVE_1 (assume_tac ctxt4 1 ORELSE
wenzelm@59499
   462
                resolve_tac ctxt [rewrite_rule ctxt4 rec_preds_defs prem, conjI] 1))
wenzelm@54742
   463
                (tl prems))])
wenzelm@42361
   464
          |> singleton (Proof_Context.export ctxt'' ctxt'''),
berghofe@34986
   465
         map #2 c_intrs, length Ts)
berghofe@21024
   466
      end
berghofe@21024
   467
berghofe@21024
   468
   in map prove_elim cs end;
berghofe@5094
   469
wenzelm@45647
   470
bulwahn@37734
   471
(* prove simplification equations *)
wenzelm@6424
   472
wenzelm@45647
   473
fun prove_eqs quiet_mode cs params intr_ts intrs
wenzelm@45647
   474
    (elims: (thm * bstring list * int) list) ctxt ctxt'' =  (* FIXME ctxt'' ?? *)
bulwahn@37734
   475
  let
wenzelm@52059
   476
    val _ = clean_message ctxt quiet_mode "  Proving the simplification rules ...";
wenzelm@45647
   477
bulwahn@37734
   478
    fun dest_intr r =
bulwahn@37734
   479
      (the (dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))),
bulwahn@37734
   480
       Logic.strip_assums_hyp r, Logic.strip_params r);
bulwahn@37734
   481
    val intr_ts' = map dest_intr intr_ts;
wenzelm@45647
   482
wenzelm@37901
   483
    fun prove_eq c (elim: thm * 'a * 'b) =
bulwahn@37734
   484
      let
bulwahn@37734
   485
        val Ts = arg_types_of (length params) c;
bulwahn@37734
   486
        val (anames, ctxt') = Variable.variant_fixes (mk_names "a" (length Ts)) ctxt;
bulwahn@37734
   487
        val frees = map Free (anames ~~ Ts);
bulwahn@37734
   488
        val c_intrs = filter (equal c o #1 o #1 o #1) (intr_ts' ~~ intrs);
bulwahn@37734
   489
        fun mk_intr_conj (((_, _, us, _), ts, params'), _) =
bulwahn@37734
   490
          let
bulwahn@37734
   491
            fun list_ex ([], t) = t
wenzelm@45647
   492
              | list_ex ((a, T) :: vars, t) =
wenzelm@45647
   493
                  HOLogic.exists_const T $ Abs (a, T, list_ex (vars, t));
wenzelm@47876
   494
            val conjs = map2 (curry HOLogic.mk_eq) frees us @ map HOLogic.dest_Trueprop ts;
bulwahn@37734
   495
          in
bulwahn@37734
   496
            list_ex (params', if null conjs then @{term True} else foldr1 HOLogic.mk_conj conjs)
bulwahn@37734
   497
          end;
wenzelm@45647
   498
        val lhs = list_comb (c, params @ frees);
bulwahn@37734
   499
        val rhs =
wenzelm@45647
   500
          if null c_intrs then @{term False}
wenzelm@45647
   501
          else foldr1 HOLogic.mk_disj (map mk_intr_conj c_intrs);
wenzelm@45647
   502
        val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
wenzelm@59498
   503
        fun prove_intr1 (i, _) = Subgoal.FOCUS_PREMS (fn {context = ctxt'', params, prems, ...} =>
wenzelm@59532
   504
            select_disj_tac ctxt'' (length c_intrs) (i + 1) 1 THEN
wenzelm@59498
   505
            EVERY (replicate (length params) (resolve_tac ctxt'' @{thms exI} 1)) THEN
wenzelm@59498
   506
            (if null prems then resolve_tac ctxt'' @{thms TrueI} 1
wenzelm@47876
   507
             else
wenzelm@47876
   508
              let
wenzelm@47876
   509
                val (prems', last_prem) = split_last prems;
wenzelm@47876
   510
              in
wenzelm@58839
   511
                EVERY (map (fn prem =>
wenzelm@59498
   512
                  (resolve_tac ctxt'' @{thms conjI} 1 THEN resolve_tac ctxt'' [prem] 1)) prems')
wenzelm@59498
   513
                THEN resolve_tac ctxt'' [last_prem] 1
wenzelm@47876
   514
              end)) ctxt' 1;
bulwahn@37734
   515
        fun prove_intr2 (((_, _, us, _), ts, params'), intr) =
wenzelm@59498
   516
          EVERY (replicate (length params') (eresolve_tac ctxt' @{thms exE} 1)) THEN
wenzelm@59498
   517
          (if null ts andalso null us then resolve_tac ctxt' [intr] 1
wenzelm@47876
   518
           else
wenzelm@59498
   519
            EVERY (replicate (length ts + length us - 1) (eresolve_tac ctxt' @{thms conjE} 1)) THEN
haftmann@59059
   520
            Subgoal.FOCUS_PREMS (fn {context = ctxt'', prems, ...} =>
wenzelm@47876
   521
              let
wenzelm@47876
   522
                val (eqs, prems') = chop (length us) prems;
wenzelm@47876
   523
                val rew_thms = map (fn th => th RS @{thm eq_reflection}) eqs;
wenzelm@47876
   524
              in
wenzelm@54742
   525
                rewrite_goal_tac ctxt'' rew_thms 1 THEN
wenzelm@59498
   526
                resolve_tac ctxt'' [intr] 1 THEN
wenzelm@59498
   527
                EVERY (map (fn p => resolve_tac ctxt'' [p] 1) prems')
wenzelm@47876
   528
              end) ctxt' 1);
bulwahn@37734
   529
      in
wenzelm@51551
   530
        Goal.prove_sorry ctxt' [] [] eq (fn _ =>
wenzelm@59498
   531
          resolve_tac ctxt' @{thms iffI} 1 THEN
wenzelm@59498
   532
          eresolve_tac ctxt' [#1 elim] 1 THEN
wenzelm@45647
   533
          EVERY (map_index prove_intr1 c_intrs) THEN
wenzelm@59498
   534
          (if null c_intrs then eresolve_tac ctxt' @{thms FalseE} 1
wenzelm@45647
   535
           else
bulwahn@37734
   536
            let val (c_intrs', last_c_intr) = split_last c_intrs in
wenzelm@59498
   537
              EVERY (map (fn ci => eresolve_tac ctxt' @{thms disjE} 1 THEN prove_intr2 ci) c_intrs')
wenzelm@59498
   538
              THEN prove_intr2 last_c_intr
bulwahn@37734
   539
            end))
wenzelm@51717
   540
        |> rulify ctxt'
wenzelm@42361
   541
        |> singleton (Proof_Context.export ctxt' ctxt'')
wenzelm@45647
   542
      end;
bulwahn@37734
   543
  in
bulwahn@37734
   544
    map2 prove_eq cs elims
bulwahn@37734
   545
  end;
wenzelm@45647
   546
wenzelm@45647
   547
wenzelm@10735
   548
(* derivation of simplified elimination rules *)
berghofe@5094
   549
wenzelm@11682
   550
local
wenzelm@11682
   551
wenzelm@11682
   552
(*delete needless equality assumptions*)
wenzelm@29064
   553
val refl_thin = Goal.prove_global @{theory HOL} [] [] @{prop "!!P. a = a ==> P ==> P"}
wenzelm@58963
   554
  (fn {context = ctxt, ...} => assume_tac ctxt 1);
berghofe@21024
   555
val elim_rls = [asm_rl, FalseE, refl_thin, conjE, exE];
wenzelm@59498
   556
fun elim_tac ctxt = REPEAT o eresolve_tac ctxt elim_rls;
wenzelm@11682
   557
wenzelm@51717
   558
fun simp_case_tac ctxt i =
wenzelm@59498
   559
  EVERY' [elim_tac ctxt,
wenzelm@59498
   560
    asm_full_simp_tac ctxt,
wenzelm@59498
   561
    elim_tac ctxt,
wenzelm@59498
   562
    REPEAT o bound_hyp_subst_tac ctxt] i;
wenzelm@21367
   563
wenzelm@11682
   564
in
wenzelm@9598
   565
wenzelm@54742
   566
fun mk_cases_tac ctxt = ALLGOALS (simp_case_tac ctxt) THEN prune_params_tac ctxt;
wenzelm@53994
   567
wenzelm@21367
   568
fun mk_cases ctxt prop =
wenzelm@7107
   569
  let
wenzelm@21526
   570
    fun err msg =
wenzelm@21526
   571
      error (Pretty.string_of (Pretty.block
wenzelm@24920
   572
        [Pretty.str msg, Pretty.fbrk, Syntax.pretty_term ctxt prop]));
wenzelm@21526
   573
wenzelm@24861
   574
    val elims = Induct.find_casesP ctxt prop;
wenzelm@21367
   575
wenzelm@59642
   576
    val cprop = Thm.cterm_of ctxt prop;
wenzelm@21367
   577
    fun mk_elim rl =
wenzelm@53994
   578
      Thm.implies_intr cprop
wenzelm@53994
   579
        (Tactic.rule_by_tactic ctxt (mk_cases_tac ctxt) (Thm.assume cprop RS rl))
wenzelm@21367
   580
      |> singleton (Variable.export (Variable.auto_fixes prop ctxt) ctxt);
wenzelm@7107
   581
  in
wenzelm@7107
   582
    (case get_first (try mk_elim) elims of
skalberg@15531
   583
      SOME r => r
wenzelm@21526
   584
    | NONE => err "Proposition not an inductive predicate:")
wenzelm@7107
   585
  end;
wenzelm@7107
   586
wenzelm@11682
   587
end;
wenzelm@11682
   588
wenzelm@45647
   589
wenzelm@21367
   590
(* inductive_cases *)
wenzelm@7107
   591
wenzelm@21367
   592
fun gen_inductive_cases prep_att prep_prop args lthy =
wenzelm@9598
   593
  let
wenzelm@46915
   594
    val thmss =
wenzelm@46915
   595
      map snd args
wenzelm@58993
   596
      |> burrow (grouped 10 Par_List.map_independent (mk_cases lthy o prep_prop lthy));
wenzelm@46915
   597
    val facts =
wenzelm@55997
   598
      map2 (fn ((a, atts), _) => fn thms => ((a, map (prep_att lthy) atts), [(thms, [])]))
wenzelm@46915
   599
        args thmss;
wenzelm@53995
   600
  in lthy |> Local_Theory.notes facts end;
berghofe@5094
   601
wenzelm@55997
   602
val inductive_cases = gen_inductive_cases Attrib.check_src Syntax.read_prop;
wenzelm@24509
   603
val inductive_cases_i = gen_inductive_cases (K I) Syntax.check_prop;
wenzelm@7107
   604
wenzelm@59845
   605
wenzelm@59845
   606
(* ind_cases *)
wenzelm@59845
   607
wenzelm@59845
   608
fun ind_cases_rules ctxt raw_props raw_fixes =
wenzelm@59845
   609
  let
wenzelm@59845
   610
    val (props, ctxt' ) = Specification.read_props raw_props raw_fixes ctxt;
wenzelm@59845
   611
    val rules = Proof_Context.export ctxt' ctxt (map (mk_cases ctxt') props);
wenzelm@59845
   612
  in rules end;
wenzelm@59845
   613
wenzelm@58815
   614
val _ =
wenzelm@58815
   615
  Theory.setup
wenzelm@58815
   616
    (Method.setup @{binding ind_cases}
wenzelm@59845
   617
      (Scan.lift (Scan.repeat1 Parse.prop -- Parse.for_fixes) >>
wenzelm@59845
   618
        (fn (props, fixes) => fn ctxt =>
wenzelm@59845
   619
          Method.erule ctxt 0 (ind_cases_rules ctxt props fixes)))
wenzelm@59845
   620
      "case analysis for inductive definitions, based on simplified elimination rule");
wenzelm@9598
   621
wenzelm@45647
   622
bulwahn@37734
   623
(* derivation of simplified equation *)
wenzelm@9598
   624
bulwahn@37734
   625
fun mk_simp_eq ctxt prop =
bulwahn@37734
   626
  let
wenzelm@45647
   627
    val thy = Proof_Context.theory_of ctxt;
wenzelm@45647
   628
    val ctxt' = Variable.auto_fixes prop ctxt;
wenzelm@45647
   629
    val lhs_of = fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o Thm.prop_of;
wenzelm@45647
   630
    val substs =
wenzelm@45649
   631
      Item_Net.retrieve (get_equations ctxt) (HOLogic.dest_Trueprop prop)
bulwahn@38665
   632
      |> map_filter
bulwahn@38665
   633
        (fn eq => SOME (Pattern.match thy (lhs_of eq, HOLogic.dest_Trueprop prop)
bulwahn@38665
   634
            (Vartab.empty, Vartab.empty), eq)
wenzelm@45647
   635
          handle Pattern.MATCH => NONE);
wenzelm@45647
   636
    val (subst, eq) =
wenzelm@45647
   637
      (case substs of
bulwahn@38665
   638
        [s] => s
bulwahn@38665
   639
      | _ => error
wenzelm@45647
   640
        ("equations matching pattern " ^ Syntax.string_of_term ctxt prop ^ " is not unique"));
wenzelm@45647
   641
    val inst =
wenzelm@59642
   642
      map (fn v => apply2 (Thm.cterm_of ctxt') (Var v, Envir.subst_term subst (Var v)))
wenzelm@45647
   643
        (Term.add_vars (lhs_of eq) []);
wenzelm@45647
   644
  in
wenzelm@45651
   645
    Drule.cterm_instantiate inst eq
wenzelm@51717
   646
    |> Conv.fconv_rule (Conv.arg_conv (Conv.arg_conv (Simplifier.full_rewrite ctxt)))
bulwahn@37734
   647
    |> singleton (Variable.export ctxt' ctxt)
bulwahn@37734
   648
  end
bulwahn@37734
   649
wenzelm@45647
   650
bulwahn@37734
   651
(* inductive simps *)
bulwahn@37734
   652
bulwahn@37734
   653
fun gen_inductive_simps prep_att prep_prop args lthy =
bulwahn@37734
   654
  let
bulwahn@37734
   655
    val facts = args |> map (fn ((a, atts), props) =>
wenzelm@55997
   656
      ((a, map (prep_att lthy) atts),
bulwahn@37734
   657
        map (Thm.no_attributes o single o mk_simp_eq lthy o prep_prop lthy) props));
wenzelm@53995
   658
  in lthy |> Local_Theory.notes facts end;
bulwahn@37734
   659
wenzelm@55997
   660
val inductive_simps = gen_inductive_simps Attrib.check_src Syntax.read_prop;
bulwahn@37734
   661
val inductive_simps_i = gen_inductive_simps (K I) Syntax.check_prop;
bulwahn@40902
   662
wenzelm@45647
   663
wenzelm@10735
   664
(* prove induction rule *)
berghofe@5094
   665
wenzelm@26477
   666
fun prove_indrule quiet_mode cs argTs bs xs rec_const params intr_ts mono
wenzelm@45647
   667
    fp_def rec_preds_defs ctxt ctxt''' =  (* FIXME ctxt''' ?? *)
berghofe@5094
   668
  let
wenzelm@52059
   669
    val _ = clean_message ctxt quiet_mode "  Proving the induction rule ...";
berghofe@5094
   670
berghofe@21024
   671
    (* predicates for induction rule *)
berghofe@21024
   672
berghofe@36642
   673
    val (pnames, ctxt') = Variable.variant_fixes (mk_names "P" (length cs)) ctxt;
wenzelm@45647
   674
    val preds =
wenzelm@45647
   675
      map2 (curry Free) pnames
wenzelm@45647
   676
        (map (fn c => arg_types_of (length params) c ---> HOLogic.boolT) cs);
berghofe@21024
   677
berghofe@21024
   678
    (* transform an introduction rule into a premise for induction rule *)
berghofe@21024
   679
berghofe@21024
   680
    fun mk_ind_prem r =
berghofe@21024
   681
      let
wenzelm@33669
   682
        fun subst s =
wenzelm@33669
   683
          (case dest_predicate cs params s of
berghofe@21024
   684
            SOME (_, i, ys, (_, Ts)) =>
berghofe@21024
   685
              let
berghofe@21024
   686
                val k = length Ts;
berghofe@21024
   687
                val bs = map Bound (k - 1 downto 0);
wenzelm@42364
   688
                val P = list_comb (nth preds i, map (incr_boundvars k) ys @ bs);
wenzelm@46219
   689
                val Q =
wenzelm@46219
   690
                  fold_rev Term.abs (mk_names "x" k ~~ Ts)
wenzelm@59940
   691
                    (HOLogic.mk_binop @{const_name HOL.induct_conj}
wenzelm@46219
   692
                      (list_comb (incr_boundvars k s, bs), P));
berghofe@21024
   693
              in (Q, case Ts of [] => SOME (s, P) | _ => NONE) end
wenzelm@33669
   694
          | NONE =>
wenzelm@33669
   695
              (case s of
wenzelm@45647
   696
                t $ u => (fst (subst t) $ fst (subst u), NONE)
wenzelm@45647
   697
              | Abs (a, T, t) => (Abs (a, T, fst (subst t)), NONE)
wenzelm@33669
   698
              | _ => (s, NONE)));
berghofe@7293
   699
wenzelm@33338
   700
        fun mk_prem s prems =
wenzelm@33338
   701
          (case subst s of
wenzelm@33338
   702
            (_, SOME (t, u)) => t :: u :: prems
wenzelm@33338
   703
          | (t, _) => t :: prems);
berghofe@21024
   704
wenzelm@45647
   705
        val SOME (_, i, ys, _) =
wenzelm@45647
   706
          dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r));
wenzelm@42364
   707
      in
wenzelm@46215
   708
        fold_rev (Logic.all o Free) (Logic.strip_params r)
wenzelm@46215
   709
          (Logic.list_implies (map HOLogic.mk_Trueprop (fold_rev mk_prem
wenzelm@42364
   710
            (map HOLogic.dest_Trueprop (Logic.strip_assums_hyp r)) []),
wenzelm@42364
   711
              HOLogic.mk_Trueprop (list_comb (nth preds i, ys))))
berghofe@21024
   712
      end;
berghofe@21024
   713
berghofe@21024
   714
    val ind_prems = map mk_ind_prem intr_ts;
berghofe@21024
   715
wenzelm@21526
   716
berghofe@21024
   717
    (* make conclusions for induction rules *)
berghofe@21024
   718
berghofe@21024
   719
    val Tss = map (binder_types o fastype_of) preds;
wenzelm@45647
   720
    val (xnames, ctxt'') = Variable.variant_fixes (mk_names "x" (length (flat Tss))) ctxt';
wenzelm@45647
   721
    val mutual_ind_concl =
wenzelm@45647
   722
      HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
berghofe@21024
   723
        (map (fn (((xnames, Ts), c), P) =>
wenzelm@45647
   724
          let val frees = map Free (xnames ~~ Ts)
wenzelm@45647
   725
          in HOLogic.mk_imp (list_comb (c, params @ frees), list_comb (P, frees)) end)
wenzelm@45647
   726
        (unflat Tss xnames ~~ Tss ~~ cs ~~ preds)));
berghofe@5094
   727
paulson@13626
   728
berghofe@5094
   729
    (* make predicate for instantiation of abstract induction rule *)
berghofe@5094
   730
wenzelm@45647
   731
    val ind_pred =
wenzelm@45647
   732
      fold_rev lambda (bs @ xs) (foldr1 HOLogic.mk_conj
wenzelm@45647
   733
        (map_index (fn (i, P) => fold_rev (curry HOLogic.mk_imp)
wenzelm@45647
   734
           (make_bool_args HOLogic.mk_not I bs i)
wenzelm@45647
   735
           (list_comb (P, make_args' argTs xs (binder_types (fastype_of P))))) preds));
berghofe@5094
   736
wenzelm@45647
   737
    val ind_concl =
wenzelm@45647
   738
      HOLogic.mk_Trueprop
wenzelm@45647
   739
        (HOLogic.mk_binrel @{const_name Orderings.less_eq} (rec_const, ind_pred));
berghofe@5094
   740
wenzelm@45647
   741
    val raw_fp_induct = mono RS (fp_def RS @{thm def_lfp_induct});
paulson@13626
   742
wenzelm@51551
   743
    val induct = Goal.prove_sorry ctxt'' [] ind_prems ind_concl
wenzelm@54742
   744
      (fn {context = ctxt3, prems} => EVERY
wenzelm@54742
   745
        [rewrite_goals_tac ctxt3 [inductive_conj_def],
wenzelm@59498
   746
         DETERM (resolve_tac ctxt3 [raw_fp_induct] 1),
wenzelm@59498
   747
         REPEAT (resolve_tac ctxt3 [@{thm le_funI}, @{thm le_boolI}] 1),
wenzelm@54742
   748
         rewrite_goals_tac ctxt3 simp_thms2,
berghofe@21024
   749
         (*This disjE separates out the introduction rules*)
wenzelm@59498
   750
         REPEAT (FIRSTGOAL (eresolve_tac ctxt3 [disjE, exE, FalseE])),
berghofe@5094
   751
         (*Now break down the individual cases.  No disjE here in case
berghofe@5094
   752
           some premise involves disjunction.*)
wenzelm@59498
   753
         REPEAT (FIRSTGOAL (eresolve_tac ctxt3 [conjE] ORELSE' bound_hyp_subst_tac ctxt3)),
berghofe@21024
   754
         REPEAT (FIRSTGOAL
wenzelm@59498
   755
           (resolve_tac ctxt3 [conjI, impI] ORELSE'
wenzelm@59498
   756
           (eresolve_tac ctxt3 [notE] THEN' assume_tac ctxt3))),
wenzelm@59499
   757
         EVERY (map (fn prem =>
wenzelm@59499
   758
            DEPTH_SOLVE_1 (assume_tac ctxt3 1 ORELSE
wenzelm@59499
   759
              resolve_tac ctxt3
wenzelm@59499
   760
                [rewrite_rule ctxt3 (inductive_conj_def :: rec_preds_defs @ simp_thms2) prem,
wenzelm@59499
   761
                  conjI, refl] 1)) prems)]);
berghofe@5094
   762
wenzelm@51551
   763
    val lemma = Goal.prove_sorry ctxt'' [] []
wenzelm@54742
   764
      (Logic.mk_implies (ind_concl, mutual_ind_concl)) (fn {context = ctxt3, ...} => EVERY
wenzelm@54742
   765
        [rewrite_goals_tac ctxt3 rec_preds_defs,
berghofe@5094
   766
         REPEAT (EVERY
wenzelm@59498
   767
           [REPEAT (resolve_tac ctxt3 [conjI, impI] 1),
wenzelm@59498
   768
            REPEAT (eresolve_tac ctxt3 [@{thm le_funE}, @{thm le_boolE}] 1),
wenzelm@58963
   769
            assume_tac ctxt3 1,
wenzelm@54742
   770
            rewrite_goals_tac ctxt3 simp_thms1,
wenzelm@58963
   771
            assume_tac ctxt3 1])]);
berghofe@5094
   772
wenzelm@42361
   773
  in singleton (Proof_Context.export ctxt'' ctxt''') (induct RS lemma) end;
berghofe@5094
   774
wenzelm@6424
   775
wenzelm@6424
   776
berghofe@21024
   777
(** specification of (co)inductive predicates **)
wenzelm@10729
   778
wenzelm@49170
   779
fun mk_ind_def quiet_mode skip_mono alt_name coind cs intr_ts monos params cnames_syn lthy =
wenzelm@33458
   780
  let
haftmann@24915
   781
    val fp_name = if coind then @{const_name Inductive.gfp} else @{const_name Inductive.lfp};
berghofe@5094
   782
haftmann@33077
   783
    val argTs = fold (combine (op =) o arg_types_of (length params)) cs [];
berghofe@21024
   784
    val k = log 2 1 (length cs);
berghofe@21024
   785
    val predT = replicate k HOLogic.boolT ---> argTs ---> HOLogic.boolT;
wenzelm@45647
   786
    val p :: xs =
wenzelm@45647
   787
      map Free (Variable.variant_frees lthy intr_ts
wenzelm@45647
   788
        (("p", predT) :: (mk_names "x" (length argTs) ~~ argTs)));
wenzelm@45647
   789
    val bs =
wenzelm@45647
   790
      map Free (Variable.variant_frees lthy (p :: xs @ intr_ts)
wenzelm@45647
   791
        (map (rpair HOLogic.boolT) (mk_names "b" k)));
berghofe@21024
   792
wenzelm@33458
   793
    fun subst t =
wenzelm@33458
   794
      (case dest_predicate cs params t of
berghofe@21024
   795
        SOME (_, i, ts, (Ts, Us)) =>
berghofe@23762
   796
          let
berghofe@23762
   797
            val l = length Us;
wenzelm@33669
   798
            val zs = map Bound (l - 1 downto 0);
berghofe@21024
   799
          in
wenzelm@46219
   800
            fold_rev (Term.abs o pair "z") Us
wenzelm@46219
   801
              (list_comb (p,
wenzelm@46219
   802
                make_bool_args' bs i @ make_args argTs
wenzelm@46219
   803
                  ((map (incr_boundvars l) ts ~~ Ts) @ (zs ~~ Us))))
berghofe@21024
   804
          end
wenzelm@33669
   805
      | NONE =>
wenzelm@33669
   806
          (case t of
wenzelm@33669
   807
            t1 $ t2 => subst t1 $ subst t2
wenzelm@33669
   808
          | Abs (x, T, u) => Abs (x, T, subst u)
wenzelm@33669
   809
          | _ => t));
berghofe@5149
   810
berghofe@5094
   811
    (* transform an introduction rule into a conjunction  *)
berghofe@21024
   812
    (*   [| p_i t; ... |] ==> p_j u                       *)
berghofe@5094
   813
    (* is transformed into                                *)
berghofe@21024
   814
    (*   b_j & x_j = u & p b_j t & ...                    *)
berghofe@5094
   815
berghofe@5094
   816
    fun transform_rule r =
berghofe@5094
   817
      let
wenzelm@45647
   818
        val SOME (_, i, ts, (Ts, _)) =
wenzelm@45647
   819
          dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r));
wenzelm@45647
   820
        val ps =
wenzelm@45647
   821
          make_bool_args HOLogic.mk_not I bs i @
berghofe@21048
   822
          map HOLogic.mk_eq (make_args' argTs xs Ts ~~ ts) @
wenzelm@45647
   823
          map (subst o HOLogic.dest_Trueprop) (Logic.strip_assums_hyp r);
wenzelm@33338
   824
      in
wenzelm@33338
   825
        fold_rev (fn (x, T) => fn P => HOLogic.exists_const T $ Abs (x, T, P))
wenzelm@33338
   826
          (Logic.strip_params r)
wenzelm@45740
   827
          (if null ps then @{term True} else foldr1 HOLogic.mk_conj ps)
wenzelm@45647
   828
      end;
berghofe@5094
   829
berghofe@5094
   830
    (* make a disjunction of all introduction rules *)
berghofe@5094
   831
wenzelm@45647
   832
    val fp_fun =
wenzelm@45647
   833
      fold_rev lambda (p :: bs @ xs)
wenzelm@45740
   834
        (if null intr_ts then @{term False}
wenzelm@45647
   835
         else foldr1 HOLogic.mk_disj (map transform_rule intr_ts));
berghofe@5094
   836
berghofe@21024
   837
    (* add definiton of recursive predicates to theory *)
berghofe@5094
   838
wenzelm@28083
   839
    val rec_name =
haftmann@28965
   840
      if Binding.is_empty alt_name then
wenzelm@30223
   841
        Binding.name (space_implode "_" (map (Binding.name_of o fst) cnames_syn))
wenzelm@28083
   842
      else alt_name;
berghofe@5094
   843
haftmann@59060
   844
    val is_auxiliary = length cs >= 2; 
wenzelm@33458
   845
    val ((rec_const, (_, fp_def)), lthy') = lthy
wenzelm@59880
   846
      |> is_auxiliary ? Proof_Context.concealed
wenzelm@33766
   847
      |> Local_Theory.define
berghofe@21024
   848
        ((rec_name, case cnames_syn of [(_, syn)] => syn | _ => NoSyn),
wenzelm@59859
   849
         ((Binding.concealed (Thm.def_binding rec_name), @{attributes [nitpick_unfold]}),
wenzelm@45592
   850
           fold_rev lambda params
wenzelm@45592
   851
             (Const (fp_name, (predT --> predT) --> predT) $ fp_fun)))
wenzelm@59880
   852
      ||> Proof_Context.restore_naming lthy;
wenzelm@45647
   853
    val fp_def' =
wenzelm@51717
   854
      Simplifier.rewrite (put_simpset HOL_basic_ss lthy' addsimps [fp_def])
wenzelm@59621
   855
        (Thm.cterm_of lthy' (list_comb (rec_const, params)));
wenzelm@33278
   856
    val specs =
wenzelm@33278
   857
      if length cs < 2 then []
wenzelm@33278
   858
      else
wenzelm@33278
   859
        map_index (fn (i, (name_mx, c)) =>
wenzelm@33278
   860
          let
wenzelm@33278
   861
            val Ts = arg_types_of (length params) c;
wenzelm@45647
   862
            val xs =
wenzelm@45647
   863
              map Free (Variable.variant_frees lthy intr_ts (mk_names "x" (length Ts) ~~ Ts));
wenzelm@33278
   864
          in
wenzelm@59859
   865
            (name_mx, (apfst Binding.concealed Attrib.empty_binding, fold_rev lambda (params @ xs)
wenzelm@33278
   866
              (list_comb (rec_const, params @ make_bool_args' bs i @
wenzelm@33278
   867
                make_args argTs (xs ~~ Ts)))))
wenzelm@33278
   868
          end) (cnames_syn ~~ cs);
wenzelm@33458
   869
    val (consts_defs, lthy'') = lthy'
haftmann@39248
   870
      |> fold_map Local_Theory.define specs;
berghofe@21024
   871
    val preds = (case cs of [_] => [rec_const] | _ => map #1 consts_defs);
berghofe@5094
   872
berghofe@36642
   873
    val (_, lthy''') = Variable.add_fixes (map (fst o dest_Free) params) lthy'';
wenzelm@49170
   874
    val mono = prove_mono quiet_mode skip_mono predT fp_fun monos lthy''';
berghofe@36642
   875
    val (_, lthy'''') =
wenzelm@59859
   876
      Local_Theory.note (apfst Binding.concealed Attrib.empty_binding,
wenzelm@42361
   877
        Proof_Context.export lthy''' lthy'' [mono]) lthy'';
berghofe@5094
   878
berghofe@36642
   879
  in (lthy'''', lthy''', rec_name, mono, fp_def', map (#2 o #2) consts_defs,
berghofe@21024
   880
    list_comb (rec_const, params), preds, argTs, bs, xs)
berghofe@21024
   881
  end;
berghofe@5094
   882
wenzelm@33669
   883
fun declare_rules rec_binding coind no_ind cnames
bulwahn@37734
   884
    preds intrs intr_bindings intr_atts elims eqs raw_induct lthy =
berghofe@23762
   885
  let
wenzelm@30223
   886
    val rec_name = Binding.name_of rec_binding;
haftmann@32773
   887
    fun rec_qualified qualified = Binding.qualify qualified rec_name;
wenzelm@30223
   888
    val intr_names = map Binding.name_of intr_bindings;
wenzelm@33368
   889
    val ind_case_names = Rule_Cases.case_names intr_names;
berghofe@23762
   890
    val induct =
berghofe@23762
   891
      if coind then
wenzelm@50771
   892
        (raw_induct,
wenzelm@50771
   893
         [Rule_Cases.case_names [rec_name],
wenzelm@33368
   894
          Rule_Cases.case_conclusion (rec_name, intr_names),
wenzelm@50771
   895
          Rule_Cases.consumes (1 - Thm.nprems_of raw_induct),
wenzelm@50771
   896
          Induct.coinduct_pred (hd cnames)])
berghofe@23762
   897
      else if no_ind orelse length cnames > 1 then
wenzelm@50771
   898
        (raw_induct,
wenzelm@50771
   899
          [ind_case_names, Rule_Cases.consumes (~ (Thm.nprems_of raw_induct))])
wenzelm@50771
   900
      else
wenzelm@50771
   901
        (raw_induct RSN (2, rev_mp),
wenzelm@50771
   902
          [ind_case_names, Rule_Cases.consumes (~ (Thm.nprems_of raw_induct))]);
berghofe@23762
   903
wenzelm@33458
   904
    val (intrs', lthy1) =
wenzelm@33458
   905
      lthy |>
bulwahn@35757
   906
      Spec_Rules.add
bulwahn@35757
   907
        (if coind then Spec_Rules.Co_Inductive else Spec_Rules.Inductive) (preds, intrs) |>
wenzelm@33671
   908
      Local_Theory.notes
wenzelm@33278
   909
        (map (rec_qualified false) intr_bindings ~~ intr_atts ~~
wenzelm@33278
   910
          map (fn th => [([th],
blanchet@37264
   911
           [Attrib.internal (K (Context_Rules.intro_query NONE))])]) intrs) |>>
berghofe@24744
   912
      map (hd o snd);
wenzelm@33458
   913
    val (((_, elims'), (_, [induct'])), lthy2) =
wenzelm@33458
   914
      lthy1 |>
wenzelm@33671
   915
      Local_Theory.note ((rec_qualified true (Binding.name "intros"), []), intrs') ||>>
berghofe@34986
   916
      fold_map (fn (name, (elim, cases, k)) =>
wenzelm@33671
   917
        Local_Theory.note
wenzelm@33458
   918
          ((Binding.qualify true (Long_Name.base_name name) (Binding.name "cases"),
wenzelm@33458
   919
            [Attrib.internal (K (Rule_Cases.case_names cases)),
wenzelm@50771
   920
             Attrib.internal (K (Rule_Cases.consumes (1 - Thm.nprems_of elim))),
berghofe@34986
   921
             Attrib.internal (K (Rule_Cases.constraints k)),
wenzelm@33458
   922
             Attrib.internal (K (Induct.cases_pred name)),
wenzelm@33458
   923
             Attrib.internal (K (Context_Rules.elim_query NONE))]), [elim]) #>
berghofe@23762
   924
        apfst (hd o snd)) (if null elims then [] else cnames ~~ elims) ||>>
wenzelm@33671
   925
      Local_Theory.note
haftmann@32773
   926
        ((rec_qualified true (Binding.name (coind_prefix coind ^ "induct")),
wenzelm@51717
   927
          map (Attrib.internal o K) (#2 induct)), [rulify lthy1 (#1 induct)]);
berghofe@23762
   928
wenzelm@45647
   929
    val (eqs', lthy3) = lthy2 |>
bulwahn@37734
   930
      fold_map (fn (name, eq) => Local_Theory.note
bulwahn@38665
   931
          ((Binding.qualify true (Long_Name.base_name name) (Binding.name "simps"),
wenzelm@45652
   932
            [Attrib.internal (K equation_add_permissive)]), [eq])
bulwahn@37734
   933
          #> apfst (hd o snd))
bulwahn@37734
   934
        (if null eqs then [] else (cnames ~~ eqs))
bulwahn@37734
   935
    val (inducts, lthy4) =
bulwahn@37734
   936
      if no_ind orelse coind then ([], lthy3)
wenzelm@33458
   937
      else
bulwahn@37734
   938
        let val inducts = cnames ~~ Project_Rule.projects lthy3 (1 upto length cnames) induct' in
bulwahn@37734
   939
          lthy3 |>
wenzelm@33671
   940
          Local_Theory.notes [((rec_qualified true (Binding.name "inducts"), []),
wenzelm@33458
   941
            inducts |> map (fn (name, th) => ([th],
wenzelm@33458
   942
              [Attrib.internal (K ind_case_names),
wenzelm@50771
   943
               Attrib.internal (K (Rule_Cases.consumes (1 - Thm.nprems_of th))),
berghofe@35646
   944
               Attrib.internal (K (Induct.induct_pred name))])))] |>> snd o hd
wenzelm@33458
   945
        end;
bulwahn@37734
   946
  in (intrs', elims', eqs', induct', inducts, lthy4) end;
berghofe@23762
   947
berghofe@26534
   948
type inductive_flags =
wenzelm@33669
   949
  {quiet_mode: bool, verbose: bool, alt_name: binding, coind: bool,
wenzelm@49170
   950
    no_elim: bool, no_ind: bool, skip_mono: bool};
berghofe@26534
   951
berghofe@26534
   952
type add_ind_def =
berghofe@26534
   953
  inductive_flags ->
wenzelm@28084
   954
  term list -> (Attrib.binding * term) list -> thm list ->
haftmann@29581
   955
  term list -> (binding * mixfix) list ->
wenzelm@33458
   956
  local_theory -> inductive_result * local_theory;
berghofe@23762
   957
wenzelm@49170
   958
fun add_ind_def {quiet_mode, verbose, alt_name, coind, no_elim, no_ind, skip_mono}
wenzelm@33458
   959
    cs intros monos params cnames_syn lthy =
berghofe@9072
   960
  let
wenzelm@25288
   961
    val _ = null cnames_syn andalso error "No inductive predicates given";
wenzelm@30223
   962
    val names = map (Binding.name_of o fst) cnames_syn;
wenzelm@26477
   963
    val _ = message (quiet_mode andalso not verbose)
wenzelm@28083
   964
      ("Proofs for " ^ coind_prefix coind ^ "inductive predicate(s) " ^ commas_quote names);
berghofe@9072
   965
wenzelm@33671
   966
    val cnames = map (Local_Theory.full_name lthy o #1) cnames_syn;  (* FIXME *)
berghofe@23762
   967
    val ((intr_names, intr_atts), intr_ts) =
wenzelm@33458
   968
      apfst split_list (split_list (map (check_rule lthy cs params) intros));
berghofe@21024
   969
berghofe@36642
   970
    val (lthy1, lthy2, rec_name, mono, fp_def, rec_preds_defs, rec_const, preds,
wenzelm@49170
   971
      argTs, bs, xs) = mk_ind_def quiet_mode skip_mono alt_name coind cs intr_ts
wenzelm@33458
   972
        monos params cnames_syn lthy;
berghofe@9072
   973
wenzelm@26477
   974
    val (intrs, unfold) = prove_intrs quiet_mode coind mono fp_def (length bs + length xs)
berghofe@36642
   975
      intr_ts rec_preds_defs lthy2 lthy1;
wenzelm@33459
   976
    val elims =
wenzelm@33459
   977
      if no_elim then []
wenzelm@33459
   978
      else
wenzelm@33459
   979
        prove_elims quiet_mode cs params intr_ts (map Binding.name_of intr_names)
berghofe@36642
   980
          unfold rec_preds_defs lthy2 lthy1;
berghofe@22605
   981
    val raw_induct = zero_var_indexes
wenzelm@33459
   982
      (if no_ind then Drule.asm_rl
wenzelm@33459
   983
       else if coind then
wenzelm@42361
   984
         singleton (Proof_Context.export lthy2 lthy1)
wenzelm@54742
   985
           (rotate_prems ~1 (Object_Logic.rulify lthy2
wenzelm@54742
   986
             (fold_rule lthy2 rec_preds_defs
wenzelm@54742
   987
               (rewrite_rule lthy2 simp_thms3
haftmann@32652
   988
                (mono RS (fp_def RS @{thm def_coinduct}))))))
berghofe@21024
   989
       else
wenzelm@26477
   990
         prove_indrule quiet_mode cs argTs bs xs rec_const params intr_ts mono fp_def
berghofe@36642
   991
           rec_preds_defs lthy2 lthy1);
bulwahn@37734
   992
    val eqs =
wenzelm@45647
   993
      if no_elim then [] else prove_eqs quiet_mode cs params intr_ts intrs elims lthy2 lthy1;
berghofe@5094
   994
wenzelm@51717
   995
    val elims' = map (fn (th, ns, i) => (rulify lthy1 th, ns, i)) elims;
wenzelm@51717
   996
    val intrs' = map (rulify lthy1) intrs;
bulwahn@37734
   997
wenzelm@45647
   998
    val (intrs'', elims'', eqs', induct, inducts, lthy3) =
wenzelm@45647
   999
      declare_rules rec_name coind no_ind
wenzelm@45647
  1000
        cnames preds intrs' intr_names intr_atts elims' eqs raw_induct lthy1;
berghofe@21048
  1001
berghofe@21048
  1002
    val result =
berghofe@21048
  1003
      {preds = preds,
bulwahn@37734
  1004
       intrs = intrs'',
bulwahn@37734
  1005
       elims = elims'',
wenzelm@51717
  1006
       raw_induct = rulify lthy3 raw_induct,
berghofe@35646
  1007
       induct = induct,
bulwahn@37734
  1008
       inducts = inducts,
bulwahn@37734
  1009
       eqs = eqs'};
wenzelm@21367
  1010
berghofe@36642
  1011
    val lthy4 = lthy3
wenzelm@45291
  1012
      |> Local_Theory.declaration {syntax = false, pervasive = false} (fn phi =>
wenzelm@45290
  1013
        let val result' = transform_result phi result;
wenzelm@25380
  1014
        in put_inductives cnames (*global names!?*) ({names = cnames, coind = coind}, result') end);
berghofe@36642
  1015
  in (result, lthy4) end;
berghofe@5094
  1016
wenzelm@6424
  1017
wenzelm@10735
  1018
(* external interfaces *)
berghofe@5094
  1019
wenzelm@26477
  1020
fun gen_add_inductive_i mk_def
haftmann@59059
  1021
    flags cnames_syn pnames spec monos lthy =
berghofe@5094
  1022
  let
berghofe@21766
  1023
wenzelm@25029
  1024
    (* abbrevs *)
wenzelm@25029
  1025
wenzelm@30223
  1026
    val (_, ctxt1) = Variable.add_fixes (map (Binding.name_of o fst o fst) cnames_syn) lthy;
berghofe@21766
  1027
wenzelm@25029
  1028
    fun get_abbrev ((name, atts), t) =
wenzelm@25029
  1029
      if can (Logic.strip_assums_concl #> Logic.dest_equals) t then
wenzelm@25029
  1030
        let
haftmann@29006
  1031
          val _ = Binding.is_empty name andalso null atts orelse
wenzelm@25029
  1032
            error "Abbreviations may not have names or attributes";
wenzelm@35624
  1033
          val ((x, T), rhs) = Local_Defs.abs_def (snd (Local_Defs.cert_def ctxt1 t));
wenzelm@28083
  1034
          val var =
wenzelm@30223
  1035
            (case find_first (fn ((c, _), _) => Binding.name_of c = x) cnames_syn of
wenzelm@25029
  1036
              NONE => error ("Undeclared head of abbreviation " ^ quote x)
wenzelm@28083
  1037
            | SOME ((b, T'), mx) =>
wenzelm@25029
  1038
                if T <> T' then error ("Bad type specification for abbreviation " ^ quote x)
wenzelm@28083
  1039
                else (b, mx));
wenzelm@28083
  1040
        in SOME (var, rhs) end
wenzelm@25029
  1041
      else NONE;
berghofe@21766
  1042
wenzelm@25029
  1043
    val abbrevs = map_filter get_abbrev spec;
wenzelm@30223
  1044
    val bs = map (Binding.name_of o fst o fst) abbrevs;
wenzelm@25029
  1045
berghofe@21766
  1046
wenzelm@25029
  1047
    (* predicates *)
berghofe@21766
  1048
wenzelm@25029
  1049
    val pre_intros = filter_out (is_some o get_abbrev) spec;
wenzelm@30223
  1050
    val cnames_syn' = filter_out (member (op =) bs o Binding.name_of o fst o fst) cnames_syn;
wenzelm@30223
  1051
    val cs = map (Free o apfst Binding.name_of o fst) cnames_syn';
wenzelm@25029
  1052
    val ps = map Free pnames;
berghofe@5094
  1053
wenzelm@30223
  1054
    val (_, ctxt2) = lthy |> Variable.add_fixes (map (Binding.name_of o fst o fst) cnames_syn');
wenzelm@35624
  1055
    val _ = map (fn abbr => Local_Defs.fixed_abbrev abbr ctxt2) abbrevs;
wenzelm@35624
  1056
    val ctxt3 = ctxt2 |> fold (snd oo Local_Defs.fixed_abbrev) abbrevs;
wenzelm@42361
  1057
    val expand = Assumption.export_term ctxt3 lthy #> Proof_Context.cert_term lthy;
wenzelm@25029
  1058
wenzelm@46215
  1059
    fun close_rule r =
wenzelm@46215
  1060
      fold (Logic.all o Free) (fold_aterms
wenzelm@46215
  1061
        (fn t as Free (v as (s, _)) =>
wenzelm@46215
  1062
            if Variable.is_fixed ctxt1 s orelse
wenzelm@46215
  1063
              member (op =) ps t then I else insert (op =) v
wenzelm@46215
  1064
          | _ => I) r []) r;
berghofe@5094
  1065
haftmann@26736
  1066
    val intros = map (apsnd (Syntax.check_term lthy #> close_rule #> expand)) pre_intros;
wenzelm@25029
  1067
    val preds = map (fn ((c, _), mx) => (c, mx)) cnames_syn';
berghofe@21048
  1068
  in
wenzelm@25029
  1069
    lthy
wenzelm@25029
  1070
    |> mk_def flags cs intros monos ps preds
wenzelm@33671
  1071
    ||> fold (snd oo Local_Theory.abbrev Syntax.mode_default) abbrevs
berghofe@21048
  1072
  end;
berghofe@5094
  1073
wenzelm@49324
  1074
fun gen_add_inductive mk_def verbose coind cnames_syn pnames_syn intro_srcs raw_monos lthy =
berghofe@5094
  1075
  let
wenzelm@30486
  1076
    val ((vars, intrs), _) = lthy
wenzelm@42361
  1077
      |> Proof_Context.set_mode Proof_Context.mode_abbrev
wenzelm@30486
  1078
      |> Specification.read_spec (cnames_syn @ pnames_syn) intro_srcs;
wenzelm@24721
  1079
    val (cs, ps) = chop (length cnames_syn) vars;
wenzelm@24721
  1080
    val monos = Attrib.eval_thms lthy raw_monos;
wenzelm@49170
  1081
    val flags =
wenzelm@49170
  1082
     {quiet_mode = false, verbose = verbose, alt_name = Binding.empty,
wenzelm@49170
  1083
      coind = coind, no_elim = false, no_ind = false, skip_mono = false};
wenzelm@26128
  1084
  in
wenzelm@26128
  1085
    lthy
wenzelm@30223
  1086
    |> gen_add_inductive_i mk_def flags cs (map (apfst Binding.name_of o fst) ps) intrs monos
wenzelm@26128
  1087
  end;
berghofe@5094
  1088
berghofe@23762
  1089
val add_inductive_i = gen_add_inductive_i add_ind_def;
berghofe@23762
  1090
val add_inductive = gen_add_inductive add_ind_def;
berghofe@23762
  1091
wenzelm@33726
  1092
fun add_inductive_global flags cnames_syn pnames pre_intros monos thy =
wenzelm@25380
  1093
  let
haftmann@29006
  1094
    val name = Sign.full_name thy (fst (fst (hd cnames_syn)));
wenzelm@25380
  1095
    val ctxt' = thy
haftmann@38388
  1096
      |> Named_Target.theory_init
wenzelm@25380
  1097
      |> add_inductive_i flags cnames_syn pnames pre_intros monos |> snd
wenzelm@33671
  1098
      |> Local_Theory.exit;
wenzelm@25380
  1099
    val info = #2 (the_inductive ctxt' name);
wenzelm@42361
  1100
  in (info, Proof_Context.theory_of ctxt') end;
wenzelm@6424
  1101
wenzelm@6424
  1102
berghofe@22789
  1103
(* read off arities of inductive predicates from raw induction rule *)
berghofe@22789
  1104
fun arities_of induct =
berghofe@22789
  1105
  map (fn (_ $ t $ u) =>
berghofe@22789
  1106
      (fst (dest_Const (head_of t)), length (snd (strip_comb u))))
wenzelm@59582
  1107
    (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induct)));
berghofe@22789
  1108
berghofe@22789
  1109
(* read off parameters of inductive predicate from raw induction rule *)
berghofe@22789
  1110
fun params_of induct =
berghofe@22789
  1111
  let
wenzelm@59582
  1112
    val (_ $ t $ u :: _) = HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induct));
berghofe@22789
  1113
    val (_, ts) = strip_comb t;
wenzelm@45647
  1114
    val (_, us) = strip_comb u;
berghofe@22789
  1115
  in
berghofe@22789
  1116
    List.take (ts, length ts - length us)
berghofe@22789
  1117
  end;
berghofe@22789
  1118
berghofe@22789
  1119
val pname_of_intr =
wenzelm@59582
  1120
  Thm.concl_of #> HOLogic.dest_Trueprop #> head_of #> dest_Const #> fst;
berghofe@22789
  1121
berghofe@22789
  1122
(* partition introduction rules according to predicate name *)
berghofe@25822
  1123
fun gen_partition_rules f induct intros =
berghofe@25822
  1124
  fold_rev (fn r => AList.map_entry op = (pname_of_intr (f r)) (cons r)) intros
berghofe@22789
  1125
    (map (rpair [] o fst) (arities_of induct));
berghofe@22789
  1126
berghofe@25822
  1127
val partition_rules = gen_partition_rules I;
berghofe@25822
  1128
fun partition_rules' induct = gen_partition_rules fst induct;
berghofe@25822
  1129
berghofe@22789
  1130
fun unpartition_rules intros xs =
berghofe@22789
  1131
  fold_map (fn r => AList.map_entry_yield op = (pname_of_intr r)
berghofe@22789
  1132
    (fn x :: xs => (x, xs)) #>> the) intros xs |> fst;
berghofe@22789
  1133
berghofe@22789
  1134
(* infer order of variables in intro rules from order of quantifiers in elim rule *)
berghofe@22789
  1135
fun infer_intro_vars elim arity intros =
berghofe@22789
  1136
  let
wenzelm@59582
  1137
    val thy = Thm.theory_of_thm elim;
wenzelm@59582
  1138
    val _ :: cases = Thm.prems_of elim;
wenzelm@59582
  1139
    val used = map (fst o fst) (Term.add_vars (Thm.prop_of elim) []);
berghofe@22789
  1140
    fun mtch (t, u) =
berghofe@22789
  1141
      let
berghofe@22789
  1142
        val params = Logic.strip_params t;
wenzelm@45647
  1143
        val vars =
wenzelm@45647
  1144
          map (Var o apfst (rpair 0))
wenzelm@45647
  1145
            (Name.variant_list used (map fst params) ~~ map snd params);
wenzelm@45647
  1146
        val ts =
wenzelm@45647
  1147
          map (curry subst_bounds (rev vars))
wenzelm@45647
  1148
            (List.drop (Logic.strip_assums_hyp t, arity));
berghofe@22789
  1149
        val us = Logic.strip_imp_prems u;
wenzelm@45647
  1150
        val tab =
wenzelm@45647
  1151
          fold (Pattern.first_order_match thy) (ts ~~ us) (Vartab.empty, Vartab.empty);
berghofe@22789
  1152
      in
wenzelm@32035
  1153
        map (Envir.subst_term tab) vars
berghofe@22789
  1154
      end
berghofe@22789
  1155
  in
wenzelm@59582
  1156
    map (mtch o apsnd Thm.prop_of) (cases ~~ intros)
berghofe@22789
  1157
  end;
berghofe@22789
  1158
berghofe@22789
  1159
wenzelm@25978
  1160
wenzelm@58815
  1161
(** outer syntax **)
wenzelm@6424
  1162
berghofe@23762
  1163
fun gen_ind_decl mk_def coind =
wenzelm@36960
  1164
  Parse.fixes -- Parse.for_fixes --
wenzelm@36954
  1165
  Scan.optional Parse_Spec.where_alt_specs [] --
wenzelm@58028
  1166
  Scan.optional (@{keyword "monos"} |-- Parse.!!! Parse.xthms1) []
wenzelm@26988
  1167
  >> (fn (((preds, params), specs), monos) =>
wenzelm@49324
  1168
      (snd o gen_add_inductive mk_def true coind preds params specs monos));
berghofe@23762
  1169
berghofe@23762
  1170
val ind_decl = gen_ind_decl add_ind_def;
wenzelm@6424
  1171
wenzelm@33458
  1172
val _ =
wenzelm@59936
  1173
  Outer_Syntax.local_theory @{command_keyword inductive} "define inductive predicates"
wenzelm@33458
  1174
    (ind_decl false);
wenzelm@33458
  1175
wenzelm@33458
  1176
val _ =
wenzelm@59936
  1177
  Outer_Syntax.local_theory @{command_keyword coinductive} "define coinductive predicates"
wenzelm@33458
  1178
    (ind_decl true);
wenzelm@6723
  1179
wenzelm@24867
  1180
val _ =
wenzelm@59936
  1181
  Outer_Syntax.local_theory @{command_keyword inductive_cases}
wenzelm@50214
  1182
    "create simplified instances of elimination rules"
wenzelm@36960
  1183
    (Parse.and_list1 Parse_Spec.specs >> (snd oo inductive_cases));
wenzelm@7107
  1184
bulwahn@37734
  1185
val _ =
wenzelm@59936
  1186
  Outer_Syntax.local_theory @{command_keyword inductive_simps}
wenzelm@46961
  1187
    "create simplification rules for inductive predicates"
bulwahn@37734
  1188
    (Parse.and_list1 Parse_Spec.specs >> (snd oo inductive_simps));
bulwahn@37734
  1189
wenzelm@50302
  1190
val _ =
wenzelm@59936
  1191
  Outer_Syntax.command @{command_keyword print_inductives}
wenzelm@50302
  1192
    "print (co)inductive definitions and monotonicity rules"
wenzelm@59917
  1193
    (Parse.opt_bang >> (fn b => Toplevel.unknown_context o
wenzelm@59917
  1194
      Toplevel.keep (print_inductives b o Toplevel.context_of)));
wenzelm@50302
  1195
berghofe@5094
  1196
end;