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