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