src/HOL/Tools/inductive_package.ML
author wenzelm
Tue Oct 02 22:23:26 2007 +0200 (2007-10-02)
changeset 24815 f7093e90f36c
parent 24744 dcb8cf5fc99c
child 24830 a7b3ab44d993
permissions -rw-r--r--
tuned internal interfaces: flags record, added kind for results;
tuned;
berghofe@5094
     1
(*  Title:      HOL/Tools/inductive_package.ML
berghofe@5094
     2
    ID:         $Id$
berghofe@5094
     3
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
wenzelm@21367
     4
    Author:     Stefan Berghofer and Markus Wenzel, TU Muenchen
berghofe@5094
     5
wenzelm@6424
     6
(Co)Inductive Definition module for HOL.
berghofe@5094
     7
berghofe@5094
     8
Features:
wenzelm@6424
     9
  * least or greatest fixedpoints
wenzelm@6424
    10
  * mutually recursive definitions
wenzelm@6424
    11
  * definitions involving arbitrary monotone operators
wenzelm@6424
    12
  * automatically proves introduction and elimination rules
berghofe@5094
    13
berghofe@5094
    14
  Introduction rules have the form
berghofe@21024
    15
  [| M Pj ti, ..., Q x, ... |] ==> Pk t
berghofe@5094
    16
  where M is some monotone operator (usually the identity)
berghofe@21024
    17
  Q x is any side condition on the free variables
berghofe@5094
    18
  ti, t are any terms
berghofe@21024
    19
  Pj, Pk are two of the predicates being defined in mutual recursion
berghofe@5094
    20
*)
berghofe@5094
    21
berghofe@23762
    22
signature BASIC_INDUCTIVE_PACKAGE =
berghofe@5094
    23
sig
wenzelm@6424
    24
  val quiet_mode: bool ref
berghofe@21024
    25
  type inductive_result
wenzelm@21526
    26
  val morph_result: morphism -> inductive_result -> inductive_result
berghofe@21024
    27
  type inductive_info
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_name: string
wenzelm@10910
    35
  val inductive_forall_def: thm
wenzelm@10910
    36
  val rulify: thm -> thm
wenzelm@21367
    37
  val inductive_cases: ((bstring * Attrib.src list) * string list) list ->
wenzelm@21367
    38
    Proof.context -> thm list list * local_theory
wenzelm@21367
    39
  val inductive_cases_i: ((bstring * Attrib.src list) * term list) list ->
wenzelm@21367
    40
    Proof.context -> thm list list * local_theory
wenzelm@24815
    41
  val add_inductive_i:
wenzelm@24815
    42
    {verbose: bool, kind: string, alt_name: bstring, coind: bool, no_elim: bool, no_ind: bool} ->
berghofe@24744
    43
    ((string * typ) * mixfix) list ->
berghofe@24744
    44
    (string * typ) list -> ((bstring * Attrib.src list) * term) list -> thm list ->
wenzelm@21367
    45
      local_theory -> inductive_result * local_theory
berghofe@21024
    46
  val add_inductive: bool -> bool -> (string * string option * mixfix) list ->
berghofe@21024
    47
    (string * string option * mixfix) list ->
berghofe@21024
    48
    ((bstring * Attrib.src list) * string) list -> (thmref * Attrib.src list) list ->
wenzelm@21367
    49
    local_theory -> inductive_result * local_theory
wenzelm@24815
    50
  val add_inductive_global:
wenzelm@24815
    51
    {verbose: bool, kind: string, alt_name: bstring, coind: bool, no_elim: bool, no_ind: bool} ->
berghofe@24744
    52
    ((string * typ) * mixfix) list -> (string * typ) list ->
wenzelm@21526
    53
    ((bstring * Attrib.src list) * term) list -> thm list -> theory -> inductive_result * theory
berghofe@22789
    54
  val arities_of: thm -> (string * int) list
berghofe@22789
    55
  val params_of: thm -> term list
berghofe@22789
    56
  val partition_rules: thm -> thm list -> (string * thm list) list
berghofe@22789
    57
  val unpartition_rules: thm list -> (string * 'a list) list -> 'a list
berghofe@22789
    58
  val infer_intro_vars: thm -> int -> thm list -> term list list
wenzelm@18708
    59
  val setup: theory -> theory
berghofe@5094
    60
end;
berghofe@5094
    61
berghofe@23762
    62
signature INDUCTIVE_PACKAGE =
berghofe@23762
    63
sig
berghofe@23762
    64
  include BASIC_INDUCTIVE_PACKAGE
berghofe@23762
    65
  type add_ind_def
wenzelm@24815
    66
  val declare_rules: string -> bstring -> bool -> bool -> string list ->
berghofe@23762
    67
    thm list -> bstring list -> Attrib.src list list -> (thm * string list) list ->
berghofe@23762
    68
    thm -> local_theory -> thm list * thm list * thm * local_theory
berghofe@23762
    69
  val add_ind_def: add_ind_def
berghofe@23762
    70
  val gen_add_inductive_i: add_ind_def ->
wenzelm@24815
    71
    {verbose: bool, kind: string, alt_name: bstring, coind: bool, no_elim: bool, no_ind: bool} ->
berghofe@24744
    72
    ((string * typ) * mixfix) list ->
berghofe@24744
    73
    (string * typ) list -> ((bstring * Attrib.src list) * term) list -> thm list ->
berghofe@23762
    74
      local_theory -> inductive_result * local_theory
berghofe@23762
    75
  val gen_add_inductive: add_ind_def ->
berghofe@23762
    76
    bool -> bool -> (string * string option * mixfix) list ->
berghofe@23762
    77
    (string * string option * mixfix) list ->
berghofe@23762
    78
    ((bstring * Attrib.src list) * string) list -> (thmref * Attrib.src list) list ->
berghofe@23762
    79
    local_theory -> inductive_result * local_theory
berghofe@23762
    80
  val gen_ind_decl: add_ind_def ->
berghofe@23762
    81
    bool -> OuterParse.token list ->
berghofe@23762
    82
    (Toplevel.transition -> Toplevel.transition) * OuterParse.token list
berghofe@23762
    83
end;
berghofe@23762
    84
wenzelm@6424
    85
structure InductivePackage: INDUCTIVE_PACKAGE =
berghofe@5094
    86
struct
berghofe@5094
    87
wenzelm@9598
    88
wenzelm@10729
    89
(** theory context references **)
wenzelm@10729
    90
wenzelm@11991
    91
val inductive_forall_name = "HOL.induct_forall";
wenzelm@11991
    92
val inductive_forall_def = thm "induct_forall_def";
wenzelm@11991
    93
val inductive_conj_name = "HOL.induct_conj";
wenzelm@11991
    94
val inductive_conj_def = thm "induct_conj_def";
wenzelm@11991
    95
val inductive_conj = thms "induct_conj";
wenzelm@11991
    96
val inductive_atomize = thms "induct_atomize";
wenzelm@18463
    97
val inductive_rulify = thms "induct_rulify";
wenzelm@18463
    98
val inductive_rulify_fallback = thms "induct_rulify_fallback";
wenzelm@10729
    99
berghofe@21024
   100
val notTrueE = TrueI RSN (2, notE);
berghofe@21024
   101
val notFalseI = Seq.hd (atac 1 notI);
berghofe@21024
   102
val simp_thms' = map (fn s => mk_meta_eq (the (find_first
wenzelm@22675
   103
  (equal (Sign.read_prop HOL.thy s) o prop_of) simp_thms)))
berghofe@21024
   104
  ["(~True) = False", "(~False) = True",
berghofe@21024
   105
   "(True --> ?P) = ?P", "(False --> ?P) = True",
berghofe@21024
   106
   "(?P & True) = ?P", "(True & ?P) = ?P"];
berghofe@21024
   107
wenzelm@10729
   108
wenzelm@10729
   109
wenzelm@22846
   110
(** context data **)
berghofe@7710
   111
berghofe@21024
   112
type inductive_result =
berghofe@23762
   113
  {preds: term list, elims: thm list, raw_induct: thm,
berghofe@23762
   114
   induct: thm, intrs: thm list};
berghofe@7710
   115
berghofe@23762
   116
fun morph_result phi {preds, elims, raw_induct: thm, induct, intrs} =
wenzelm@21526
   117
  let
wenzelm@21526
   118
    val term = Morphism.term phi;
wenzelm@21526
   119
    val thm = Morphism.thm phi;
wenzelm@21526
   120
    val fact = Morphism.fact phi;
wenzelm@21526
   121
  in
berghofe@23762
   122
   {preds = map term preds, elims = fact elims, raw_induct = thm raw_induct,
berghofe@23762
   123
    induct = thm induct, intrs = fact intrs}
wenzelm@21526
   124
  end;
wenzelm@21526
   125
berghofe@21024
   126
type inductive_info =
berghofe@21024
   127
  {names: string list, coind: bool} * inductive_result;
berghofe@21024
   128
berghofe@21024
   129
structure InductiveData = GenericDataFun
wenzelm@22846
   130
(
berghofe@7710
   131
  type T = inductive_info Symtab.table * thm list;
berghofe@7710
   132
  val empty = (Symtab.empty, []);
wenzelm@16432
   133
  val extend = I;
wenzelm@16432
   134
  fun merge _ ((tab1, monos1), (tab2, monos2)) =
wenzelm@24039
   135
    (Symtab.merge (K true) (tab1, tab2), Thm.merge_thms (monos1, monos2));
wenzelm@22846
   136
);
berghofe@7710
   137
wenzelm@21526
   138
val get_inductives = InductiveData.get o Context.Proof;
wenzelm@22846
   139
wenzelm@22846
   140
fun print_inductives ctxt =
wenzelm@22846
   141
  let
wenzelm@22846
   142
    val (tab, monos) = get_inductives ctxt;
wenzelm@22846
   143
    val space = Consts.space_of (ProofContext.consts_of ctxt);
wenzelm@22846
   144
  in
wenzelm@22846
   145
    [Pretty.strs ("(co)inductives:" :: map #1 (NameSpace.extern_table (space, tab))),
wenzelm@22846
   146
     Pretty.big_list "monotonicity rules:" (map (ProofContext.pretty_thm ctxt) monos)]
wenzelm@22846
   147
    |> Pretty.chunks |> Pretty.writeln
wenzelm@22846
   148
  end;
berghofe@7710
   149
berghofe@7710
   150
berghofe@7710
   151
(* get and put data *)
berghofe@7710
   152
wenzelm@21367
   153
fun the_inductive ctxt name =
wenzelm@21526
   154
  (case Symtab.lookup (#1 (get_inductives ctxt)) name of
berghofe@21024
   155
    NONE => error ("Unknown (co)inductive predicate " ^ quote name)
skalberg@15531
   156
  | SOME info => info);
wenzelm@9598
   157
wenzelm@18222
   158
fun put_inductives names info = InductiveData.map (apfst (fn tab =>
wenzelm@18222
   159
  fold (fn name => Symtab.update_new (name, info)) names tab
wenzelm@21526
   160
    handle Symtab.DUP d => error ("Duplicate definition of (co)inductive predicate " ^ quote d)));
berghofe@7710
   161
wenzelm@8277
   162
berghofe@7710
   163
berghofe@7710
   164
(** monotonicity rules **)
berghofe@7710
   165
wenzelm@21526
   166
val get_monos = #2 o get_inductives;
wenzelm@21367
   167
val map_monos = InductiveData.map o apsnd;
wenzelm@8277
   168
berghofe@7710
   169
fun mk_mono thm =
berghofe@7710
   170
  let
berghofe@22275
   171
    val concl = concl_of thm;
berghofe@22275
   172
    fun eq2mono thm' = [thm' RS (thm' RS eq_to_mono)] @
berghofe@22275
   173
      (case concl of
berghofe@7710
   174
          (_ $ (_ $ (Const ("Not", _) $ _) $ _)) => []
berghofe@22275
   175
        | _ => [thm' RS (thm' RS eq_to_mono2)]);
berghofe@22275
   176
    fun dest_less_concl thm = dest_less_concl (thm RS le_funD)
wenzelm@22846
   177
      handle THM _ => thm RS le_boolD
berghofe@7710
   178
  in
berghofe@22275
   179
    case concl of
berghofe@22275
   180
      Const ("==", _) $ _ $ _ => eq2mono (thm RS meta_eq_to_obj_eq)
berghofe@22275
   181
    | _ $ (Const ("op =", _) $ _ $ _) => eq2mono thm
haftmann@23881
   182
    | _ $ (Const ("HOL.ord_class.less_eq", _) $ _ $ _) =>
berghofe@22275
   183
      [dest_less_concl (Seq.hd (REPEAT (FIRSTGOAL
berghofe@22275
   184
         (resolve_tac [le_funI, le_boolI'])) thm))]
berghofe@22275
   185
    | _ => [thm]
berghofe@23762
   186
  end handle THM _ => error ("Bad monotonicity theorem:\n" ^ string_of_thm thm);
berghofe@7710
   187
wenzelm@24039
   188
val mono_add = Thm.declaration_attribute (map_monos o fold Thm.add_thm o mk_mono);
wenzelm@24039
   189
val mono_del = Thm.declaration_attribute (map_monos o fold Thm.del_thm o mk_mono);
berghofe@7710
   190
berghofe@7710
   191
wenzelm@7107
   192
wenzelm@10735
   193
(** misc utilities **)
wenzelm@6424
   194
berghofe@5662
   195
val quiet_mode = ref false;
wenzelm@10735
   196
fun message s = if ! quiet_mode then () else writeln s;
wenzelm@10735
   197
fun clean_message s = if ! quick_and_dirty then () else message s;
berghofe@5662
   198
wenzelm@6424
   199
fun coind_prefix true = "co"
wenzelm@6424
   200
  | coind_prefix false = "";
wenzelm@6424
   201
wenzelm@24133
   202
fun log (b:int) m n = if m >= n then 0 else 1 + log b (b * m) n;
wenzelm@6424
   203
berghofe@21024
   204
fun make_bool_args f g [] i = []
berghofe@21024
   205
  | make_bool_args f g (x :: xs) i =
berghofe@21024
   206
      (if i mod 2 = 0 then f x else g x) :: make_bool_args f g xs (i div 2);
berghofe@21024
   207
berghofe@21024
   208
fun make_bool_args' xs =
berghofe@21024
   209
  make_bool_args (K HOLogic.false_const) (K HOLogic.true_const) xs;
berghofe@21024
   210
berghofe@21024
   211
fun find_arg T x [] = sys_error "find_arg"
berghofe@21024
   212
  | find_arg T x ((p as (_, (SOME _, _))) :: ps) =
berghofe@21024
   213
      apsnd (cons p) (find_arg T x ps)
berghofe@21024
   214
  | find_arg T x ((p as (U, (NONE, y))) :: ps) =
wenzelm@23577
   215
      if (T: typ) = U then (y, (U, (SOME x, y)) :: ps)
berghofe@21024
   216
      else apsnd (cons p) (find_arg T x ps);
berghofe@7020
   217
berghofe@21024
   218
fun make_args Ts xs =
berghofe@21024
   219
  map (fn (T, (NONE, ())) => Const ("arbitrary", T) | (_, (SOME t, ())) => t)
berghofe@21024
   220
    (fold (fn (t, T) => snd o find_arg T t) xs (map (rpair (NONE, ())) Ts));
berghofe@7020
   221
berghofe@21024
   222
fun make_args' Ts xs Us =
berghofe@21024
   223
  fst (fold_map (fn T => find_arg T ()) Us (Ts ~~ map (pair NONE) xs));
berghofe@7020
   224
berghofe@21024
   225
fun dest_predicate cs params t =
berghofe@5094
   226
  let
berghofe@21024
   227
    val k = length params;
berghofe@21024
   228
    val (c, ts) = strip_comb t;
berghofe@21024
   229
    val (xs, ys) = chop k ts;
berghofe@21024
   230
    val i = find_index_eq c cs;
berghofe@21024
   231
  in
berghofe@21024
   232
    if xs = params andalso i >= 0 then
berghofe@21024
   233
      SOME (c, i, ys, chop (length ys)
berghofe@21024
   234
        (List.drop (binder_types (fastype_of c), k)))
berghofe@21024
   235
    else NONE
berghofe@5094
   236
  end;
berghofe@5094
   237
berghofe@21024
   238
fun mk_names a 0 = []
berghofe@21024
   239
  | mk_names a 1 = [a]
berghofe@21024
   240
  | mk_names a n = map (fn i => a ^ string_of_int i) (1 upto n);
berghofe@10988
   241
wenzelm@6424
   242
wenzelm@6424
   243
wenzelm@10729
   244
(** process rules **)
wenzelm@10729
   245
wenzelm@10729
   246
local
berghofe@5094
   247
berghofe@23762
   248
fun err_in_rule ctxt name t msg =
wenzelm@16432
   249
  error (cat_lines ["Ill-formed introduction rule " ^ quote name,
berghofe@23762
   250
    ProofContext.string_of_term ctxt t, msg]);
wenzelm@10729
   251
berghofe@23762
   252
fun err_in_prem ctxt name t p msg =
berghofe@23762
   253
  error (cat_lines ["Ill-formed premise", ProofContext.string_of_term ctxt p,
berghofe@23762
   254
    "in introduction rule " ^ quote name, ProofContext.string_of_term ctxt t, msg]);
berghofe@5094
   255
berghofe@21024
   256
val bad_concl = "Conclusion of introduction rule must be an inductive predicate";
wenzelm@10729
   257
berghofe@21024
   258
val bad_ind_occ = "Inductive predicate occurs in argument of inductive predicate";
berghofe@21024
   259
berghofe@21024
   260
val bad_app = "Inductive predicate must be applied to parameter(s) ";
paulson@11358
   261
wenzelm@16432
   262
fun atomize_term thy = MetaSimplifier.rewrite_term thy inductive_atomize [];
wenzelm@10729
   263
wenzelm@10729
   264
in
berghofe@5094
   265
berghofe@23762
   266
fun check_rule ctxt cs params ((name, att), rule) =
wenzelm@10729
   267
  let
berghofe@21024
   268
    val params' = Term.variant_frees rule (Logic.strip_params rule);
berghofe@21024
   269
    val frees = rev (map Free params');
berghofe@21024
   270
    val concl = subst_bounds (frees, Logic.strip_assums_concl rule);
berghofe@21024
   271
    val prems = map (curry subst_bounds frees) (Logic.strip_assums_hyp rule);
berghofe@23762
   272
    val rule' = Logic.list_implies (prems, concl);
berghofe@23762
   273
    val aprems = map (atomize_term (ProofContext.theory_of ctxt)) prems;
berghofe@21024
   274
    val arule = list_all_free (params', Logic.list_implies (aprems, concl));
berghofe@21024
   275
berghofe@21024
   276
    fun check_ind err t = case dest_predicate cs params t of
berghofe@21024
   277
        NONE => err (bad_app ^
berghofe@23762
   278
          commas (map (ProofContext.string_of_term ctxt) params))
berghofe@21024
   279
      | SOME (_, _, ys, _) =>
berghofe@21024
   280
          if exists (fn c => exists (fn t => Logic.occs (c, t)) ys) cs
berghofe@21024
   281
          then err bad_ind_occ else ();
berghofe@21024
   282
berghofe@21024
   283
    fun check_prem' prem t =
berghofe@21024
   284
      if head_of t mem cs then
berghofe@23762
   285
        check_ind (err_in_prem ctxt name rule prem) t
berghofe@21024
   286
      else (case t of
berghofe@21024
   287
          Abs (_, _, t) => check_prem' prem t
berghofe@21024
   288
        | t $ u => (check_prem' prem t; check_prem' prem u)
berghofe@21024
   289
        | _ => ());
berghofe@5094
   290
wenzelm@10729
   291
    fun check_prem (prem, aprem) =
berghofe@21024
   292
      if can HOLogic.dest_Trueprop aprem then check_prem' prem prem
berghofe@23762
   293
      else err_in_prem ctxt name rule prem "Non-atomic premise";
wenzelm@10729
   294
  in
paulson@11358
   295
    (case concl of
wenzelm@21367
   296
       Const ("Trueprop", _) $ t =>
berghofe@21024
   297
         if head_of t mem cs then
berghofe@23762
   298
           (check_ind (err_in_rule ctxt name rule') t;
berghofe@21024
   299
            List.app check_prem (prems ~~ aprems))
berghofe@23762
   300
         else err_in_rule ctxt name rule' bad_concl
berghofe@23762
   301
     | _ => err_in_rule ctxt name rule' bad_concl);
berghofe@21024
   302
    ((name, att), arule)
wenzelm@10729
   303
  end;
berghofe@5094
   304
berghofe@24744
   305
val rulify =
wenzelm@18222
   306
  hol_simplify inductive_conj
wenzelm@18463
   307
  #> hol_simplify inductive_rulify
wenzelm@18463
   308
  #> hol_simplify inductive_rulify_fallback
berghofe@24744
   309
  #> MetaSimplifier.norm_hhf;
wenzelm@10729
   310
wenzelm@10729
   311
end;
wenzelm@10729
   312
berghofe@5094
   313
wenzelm@6424
   314
berghofe@21024
   315
(** proofs for (co)inductive predicates **)
wenzelm@6424
   316
wenzelm@10735
   317
(* prove monotonicity -- NOT subject to quick_and_dirty! *)
berghofe@5094
   318
berghofe@21024
   319
fun prove_mono predT fp_fun monos ctxt =
wenzelm@10735
   320
 (message "  Proving monotonicity ...";
berghofe@21024
   321
  Goal.prove ctxt [] []   (*NO quick_and_dirty here!*)
wenzelm@17985
   322
    (HOLogic.mk_Trueprop
wenzelm@24815
   323
      (Const (@{const_name Orderings.mono}, (predT --> predT) --> HOLogic.boolT) $ fp_fun))
wenzelm@17985
   324
    (fn _ => EVERY [rtac monoI 1,
berghofe@21024
   325
      REPEAT (resolve_tac [le_funI, le_boolI'] 1),
berghofe@21024
   326
      REPEAT (FIRST
berghofe@21024
   327
        [atac 1,
wenzelm@21367
   328
         resolve_tac (List.concat (map mk_mono monos) @ get_monos ctxt) 1,
berghofe@21024
   329
         etac le_funE 1, dtac le_boolD 1])]));
berghofe@5094
   330
wenzelm@6424
   331
wenzelm@10735
   332
(* prove introduction rules *)
berghofe@5094
   333
berghofe@22605
   334
fun prove_intrs coind mono fp_def k params intr_ts rec_preds_defs ctxt =
berghofe@5094
   335
  let
wenzelm@10735
   336
    val _ = clean_message "  Proving the introduction rules ...";
berghofe@5094
   337
berghofe@21024
   338
    val unfold = funpow k (fn th => th RS fun_cong)
berghofe@21024
   339
      (mono RS (fp_def RS
berghofe@21024
   340
        (if coind then def_gfp_unfold else def_lfp_unfold)));
berghofe@5094
   341
berghofe@5094
   342
    fun select_disj 1 1 = []
berghofe@5094
   343
      | select_disj _ 1 = [rtac disjI1]
berghofe@5094
   344
      | select_disj n i = (rtac disjI2)::(select_disj (n - 1) (i - 1));
berghofe@5094
   345
berghofe@21024
   346
    val rules = [refl, TrueI, notFalseI, exI, conjI];
berghofe@21024
   347
berghofe@22605
   348
    val intrs = map_index (fn (i, intr) => rulify
berghofe@22605
   349
      (SkipProof.prove ctxt (map (fst o dest_Free) params) [] intr (fn _ => EVERY
berghofe@21024
   350
       [rewrite_goals_tac rec_preds_defs,
berghofe@21024
   351
        rtac (unfold RS iffD2) 1,
berghofe@21024
   352
        EVERY1 (select_disj (length intr_ts) (i + 1)),
wenzelm@17985
   353
        (*Not ares_tac, since refl must be tried before any equality assumptions;
wenzelm@17985
   354
          backtracking may occur if the premises have extra variables!*)
berghofe@21024
   355
        DEPTH_SOLVE_1 (resolve_tac rules 1 APPEND assume_tac 1)]))) intr_ts
berghofe@5094
   356
berghofe@5094
   357
  in (intrs, unfold) end;
berghofe@5094
   358
wenzelm@6424
   359
wenzelm@10735
   360
(* prove elimination rules *)
berghofe@5094
   361
berghofe@21024
   362
fun prove_elims cs params intr_ts intr_names unfold rec_preds_defs ctxt =
berghofe@5094
   363
  let
wenzelm@10735
   364
    val _ = clean_message "  Proving the elimination rules ...";
berghofe@5094
   365
berghofe@22605
   366
    val ([pname], ctxt') = ctxt |>
berghofe@22605
   367
      Variable.add_fixes (map (fst o dest_Free) params) |> snd |>
berghofe@22605
   368
      Variable.variant_fixes ["P"];
berghofe@21024
   369
    val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
berghofe@21024
   370
berghofe@21024
   371
    fun dest_intr r =
berghofe@21024
   372
      (the (dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))),
berghofe@21024
   373
       Logic.strip_assums_hyp r, Logic.strip_params r);
berghofe@21024
   374
berghofe@21024
   375
    val intrs = map dest_intr intr_ts ~~ intr_names;
berghofe@21024
   376
berghofe@21024
   377
    val rules1 = [disjE, exE, FalseE];
berghofe@21024
   378
    val rules2 = [conjE, FalseE, notTrueE];
berghofe@21024
   379
berghofe@21024
   380
    fun prove_elim c =
berghofe@21024
   381
      let
berghofe@21024
   382
        val Ts = List.drop (binder_types (fastype_of c), length params);
berghofe@21024
   383
        val (anames, ctxt'') = Variable.variant_fixes (mk_names "a" (length Ts)) ctxt';
berghofe@21024
   384
        val frees = map Free (anames ~~ Ts);
berghofe@21024
   385
berghofe@21024
   386
        fun mk_elim_prem ((_, _, us, _), ts, params') =
berghofe@21024
   387
          list_all (params',
berghofe@21024
   388
            Logic.list_implies (map (HOLogic.mk_Trueprop o HOLogic.mk_eq)
berghofe@21024
   389
              (frees ~~ us) @ ts, P));
berghofe@21024
   390
        val c_intrs = (List.filter (equal c o #1 o #1 o #1) intrs);
berghofe@21024
   391
        val prems = HOLogic.mk_Trueprop (list_comb (c, params @ frees)) ::
berghofe@21024
   392
           map mk_elim_prem (map #1 c_intrs)
berghofe@21024
   393
      in
berghofe@21048
   394
        (SkipProof.prove ctxt'' [] prems P
berghofe@21024
   395
          (fn {prems, ...} => EVERY
berghofe@21024
   396
            [cut_facts_tac [hd prems] 1,
berghofe@21024
   397
             rewrite_goals_tac rec_preds_defs,
berghofe@21024
   398
             dtac (unfold RS iffD1) 1,
berghofe@21024
   399
             REPEAT (FIRSTGOAL (eresolve_tac rules1)),
berghofe@21024
   400
             REPEAT (FIRSTGOAL (eresolve_tac rules2)),
berghofe@21024
   401
             EVERY (map (fn prem =>
berghofe@21024
   402
               DEPTH_SOLVE_1 (ares_tac [rewrite_rule rec_preds_defs prem, conjI] 1)) (tl prems))])
berghofe@21024
   403
          |> rulify
berghofe@21048
   404
          |> singleton (ProofContext.export ctxt'' ctxt),
berghofe@21048
   405
         map #2 c_intrs)
berghofe@21024
   406
      end
berghofe@21024
   407
berghofe@21024
   408
   in map prove_elim cs end;
berghofe@5094
   409
wenzelm@6424
   410
wenzelm@10735
   411
(* derivation of simplified elimination rules *)
berghofe@5094
   412
wenzelm@11682
   413
local
wenzelm@11682
   414
wenzelm@11682
   415
(*delete needless equality assumptions*)
haftmann@22838
   416
val refl_thin = Goal.prove_global HOL.thy [] []
haftmann@22838
   417
  (Sign.read_prop HOL.thy "!!P. a = a ==> P ==> P")
haftmann@22838
   418
  (fn _ => assume_tac 1);
berghofe@21024
   419
val elim_rls = [asm_rl, FalseE, refl_thin, conjE, exE];
wenzelm@11682
   420
val elim_tac = REPEAT o Tactic.eresolve_tac elim_rls;
wenzelm@11682
   421
berghofe@23762
   422
fun simp_case_tac ss i =
berghofe@23762
   423
  EVERY' [elim_tac, asm_full_simp_tac ss, elim_tac, REPEAT o bound_hyp_subst_tac] i;
wenzelm@21367
   424
wenzelm@11682
   425
in
wenzelm@9598
   426
wenzelm@21367
   427
fun mk_cases ctxt prop =
wenzelm@7107
   428
  let
wenzelm@21367
   429
    val thy = ProofContext.theory_of ctxt;
wenzelm@21367
   430
    val ss = Simplifier.local_simpset_of ctxt;
wenzelm@21367
   431
wenzelm@21526
   432
    fun err msg =
wenzelm@21526
   433
      error (Pretty.string_of (Pretty.block
wenzelm@21526
   434
        [Pretty.str msg, Pretty.fbrk, ProofContext.pretty_term ctxt prop]));
wenzelm@21526
   435
berghofe@23762
   436
    val elims = InductAttrib.find_casesS ctxt prop;
wenzelm@21367
   437
wenzelm@21367
   438
    val cprop = Thm.cterm_of thy prop;
berghofe@23762
   439
    val tac = ALLGOALS (simp_case_tac ss) THEN prune_params_tac;
wenzelm@21367
   440
    fun mk_elim rl =
wenzelm@21367
   441
      Thm.implies_intr cprop (Tactic.rule_by_tactic tac (Thm.assume cprop RS rl))
wenzelm@21367
   442
      |> singleton (Variable.export (Variable.auto_fixes prop ctxt) ctxt);
wenzelm@7107
   443
  in
wenzelm@7107
   444
    (case get_first (try mk_elim) elims of
skalberg@15531
   445
      SOME r => r
wenzelm@21526
   446
    | NONE => err "Proposition not an inductive predicate:")
wenzelm@7107
   447
  end;
wenzelm@7107
   448
wenzelm@11682
   449
end;
wenzelm@11682
   450
wenzelm@7107
   451
wenzelm@21367
   452
(* inductive_cases *)
wenzelm@7107
   453
wenzelm@21367
   454
fun gen_inductive_cases prep_att prep_prop args lthy =
wenzelm@9598
   455
  let
wenzelm@21367
   456
    val thy = ProofContext.theory_of lthy;
wenzelm@12876
   457
    val facts = args |> map (fn ((a, atts), props) =>
wenzelm@21367
   458
      ((a, map (prep_att thy) atts),
wenzelm@21367
   459
        map (Thm.no_attributes o single o mk_cases lthy o prep_prop lthy) props));
wenzelm@24815
   460
  in lthy |> LocalTheory.notes Thm.theoremK facts |>> map snd end;
berghofe@5094
   461
wenzelm@24509
   462
val inductive_cases = gen_inductive_cases Attrib.intern_src Syntax.read_prop;
wenzelm@24509
   463
val inductive_cases_i = gen_inductive_cases (K I) Syntax.check_prop;
wenzelm@7107
   464
wenzelm@6424
   465
berghofe@22275
   466
fun ind_cases src = Method.syntax (Scan.lift (Scan.repeat1 Args.name --
berghofe@22275
   467
    Scan.optional (Args.$$$ "for" |-- Scan.repeat1 Args.name) [])) src
berghofe@22275
   468
  #> (fn ((raw_props, fixes), ctxt) =>
berghofe@22275
   469
    let
berghofe@22275
   470
      val (_, ctxt') = Variable.add_fixes fixes ctxt;
wenzelm@24509
   471
      val props = Syntax.read_props ctxt' raw_props;
berghofe@22275
   472
      val ctxt'' = fold Variable.declare_term props ctxt';
berghofe@22275
   473
      val rules = ProofContext.export ctxt'' ctxt (map (mk_cases ctxt'') props)
berghofe@22275
   474
    in Method.erule 0 rules end);
wenzelm@9598
   475
wenzelm@9598
   476
wenzelm@9598
   477
wenzelm@10735
   478
(* prove induction rule *)
berghofe@5094
   479
berghofe@21024
   480
fun prove_indrule cs argTs bs xs rec_const params intr_ts mono
berghofe@21024
   481
    fp_def rec_preds_defs ctxt =
berghofe@5094
   482
  let
wenzelm@10735
   483
    val _ = clean_message "  Proving the induction rule ...";
wenzelm@20047
   484
    val thy = ProofContext.theory_of ctxt;
berghofe@5094
   485
berghofe@21024
   486
    (* predicates for induction rule *)
berghofe@21024
   487
berghofe@22605
   488
    val (pnames, ctxt') = ctxt |>
berghofe@22605
   489
      Variable.add_fixes (map (fst o dest_Free) params) |> snd |>
berghofe@22605
   490
      Variable.variant_fixes (mk_names "P" (length cs));
berghofe@21024
   491
    val preds = map Free (pnames ~~
berghofe@21024
   492
      map (fn c => List.drop (binder_types (fastype_of c), length params) --->
berghofe@21024
   493
        HOLogic.boolT) cs);
berghofe@21024
   494
berghofe@21024
   495
    (* transform an introduction rule into a premise for induction rule *)
berghofe@21024
   496
berghofe@21024
   497
    fun mk_ind_prem r =
berghofe@21024
   498
      let
berghofe@21024
   499
        fun subst s = (case dest_predicate cs params s of
berghofe@21024
   500
            SOME (_, i, ys, (_, Ts)) =>
berghofe@21024
   501
              let
berghofe@21024
   502
                val k = length Ts;
berghofe@21024
   503
                val bs = map Bound (k - 1 downto 0);
berghofe@23762
   504
                val P = list_comb (List.nth (preds, i),
berghofe@23762
   505
                  map (incr_boundvars k) ys @ bs);
berghofe@21024
   506
                val Q = list_abs (mk_names "x" k ~~ Ts,
berghofe@23762
   507
                  HOLogic.mk_binop inductive_conj_name
berghofe@23762
   508
                    (list_comb (incr_boundvars k s, bs), P))
berghofe@21024
   509
              in (Q, case Ts of [] => SOME (s, P) | _ => NONE) end
berghofe@21024
   510
          | NONE => (case s of
berghofe@21024
   511
              (t $ u) => (fst (subst t) $ fst (subst u), NONE)
berghofe@21024
   512
            | (Abs (a, T, t)) => (Abs (a, T, fst (subst t)), NONE)
berghofe@21024
   513
            | _ => (s, NONE)));
berghofe@7293
   514
berghofe@21024
   515
        fun mk_prem (s, prems) = (case subst s of
berghofe@21024
   516
              (_, SOME (t, u)) => t :: u :: prems
berghofe@21024
   517
            | (t, _) => t :: prems);
berghofe@21024
   518
berghofe@21024
   519
        val SOME (_, i, ys, _) = dest_predicate cs params
berghofe@21024
   520
          (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))
berghofe@21024
   521
berghofe@21024
   522
      in list_all_free (Logic.strip_params r,
berghofe@21024
   523
        Logic.list_implies (map HOLogic.mk_Trueprop (foldr mk_prem
berghofe@21024
   524
          [] (map HOLogic.dest_Trueprop (Logic.strip_assums_hyp r))),
berghofe@21024
   525
            HOLogic.mk_Trueprop (list_comb (List.nth (preds, i), ys))))
berghofe@21024
   526
      end;
berghofe@21024
   527
berghofe@21024
   528
    val ind_prems = map mk_ind_prem intr_ts;
berghofe@21024
   529
wenzelm@21526
   530
berghofe@21024
   531
    (* make conclusions for induction rules *)
berghofe@21024
   532
berghofe@21024
   533
    val Tss = map (binder_types o fastype_of) preds;
berghofe@21024
   534
    val (xnames, ctxt'') =
berghofe@21024
   535
      Variable.variant_fixes (mk_names "x" (length (flat Tss))) ctxt';
berghofe@21024
   536
    val mutual_ind_concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
berghofe@21024
   537
        (map (fn (((xnames, Ts), c), P) =>
berghofe@21024
   538
           let val frees = map Free (xnames ~~ Ts)
berghofe@21024
   539
           in HOLogic.mk_imp
berghofe@21024
   540
             (list_comb (c, params @ frees), list_comb (P, frees))
berghofe@21024
   541
           end) (unflat Tss xnames ~~ Tss ~~ cs ~~ preds)));
berghofe@5094
   542
paulson@13626
   543
berghofe@5094
   544
    (* make predicate for instantiation of abstract induction rule *)
berghofe@5094
   545
berghofe@21024
   546
    val ind_pred = fold_rev lambda (bs @ xs) (foldr1 HOLogic.mk_conj
berghofe@21024
   547
      (map_index (fn (i, P) => foldr HOLogic.mk_imp
berghofe@21024
   548
         (list_comb (P, make_args' argTs xs (binder_types (fastype_of P))))
berghofe@21024
   549
         (make_bool_args HOLogic.mk_not I bs i)) preds));
berghofe@5094
   550
berghofe@5094
   551
    val ind_concl = HOLogic.mk_Trueprop
haftmann@23881
   552
      (HOLogic.mk_binrel "HOL.ord_class.less_eq" (rec_const, ind_pred));
berghofe@5094
   553
paulson@13626
   554
    val raw_fp_induct = (mono RS (fp_def RS def_lfp_induct));
paulson@13626
   555
berghofe@21024
   556
    val induct = SkipProof.prove ctxt'' [] ind_prems ind_concl
wenzelm@20248
   557
      (fn {prems, ...} => EVERY
wenzelm@17985
   558
        [rewrite_goals_tac [inductive_conj_def],
berghofe@21024
   559
         DETERM (rtac raw_fp_induct 1),
berghofe@21024
   560
         REPEAT (resolve_tac [le_funI, le_boolI] 1),
haftmann@22460
   561
         rewrite_goals_tac (inf_fun_eq :: inf_bool_eq :: simp_thms'),
berghofe@21024
   562
         (*This disjE separates out the introduction rules*)
berghofe@21024
   563
         REPEAT (FIRSTGOAL (eresolve_tac [disjE, exE, FalseE])),
berghofe@5094
   564
         (*Now break down the individual cases.  No disjE here in case
berghofe@5094
   565
           some premise involves disjunction.*)
paulson@13747
   566
         REPEAT (FIRSTGOAL (etac conjE ORELSE' bound_hyp_subst_tac)),
berghofe@21024
   567
         REPEAT (FIRSTGOAL
berghofe@21024
   568
           (resolve_tac [conjI, impI] ORELSE' (etac notE THEN' atac))),
berghofe@21024
   569
         EVERY (map (fn prem => DEPTH_SOLVE_1 (ares_tac [rewrite_rule
berghofe@22980
   570
             (inductive_conj_def :: rec_preds_defs @ simp_thms') prem,
berghofe@22980
   571
           conjI, refl] 1)) prems)]);
berghofe@5094
   572
berghofe@21024
   573
    val lemma = SkipProof.prove ctxt'' [] []
wenzelm@17985
   574
      (Logic.mk_implies (ind_concl, mutual_ind_concl)) (fn _ => EVERY
berghofe@21024
   575
        [rewrite_goals_tac rec_preds_defs,
berghofe@5094
   576
         REPEAT (EVERY
berghofe@5094
   577
           [REPEAT (resolve_tac [conjI, impI] 1),
berghofe@21024
   578
            REPEAT (eresolve_tac [le_funE, le_boolE] 1),
berghofe@21024
   579
            atac 1,
berghofe@21024
   580
            rewrite_goals_tac simp_thms',
berghofe@21024
   581
            atac 1])])
berghofe@5094
   582
berghofe@21024
   583
  in singleton (ProofContext.export ctxt'' ctxt) (induct RS lemma) end;
berghofe@5094
   584
wenzelm@6424
   585
wenzelm@6424
   586
berghofe@21024
   587
(** specification of (co)inductive predicates **)
wenzelm@10729
   588
berghofe@21024
   589
fun mk_ind_def alt_name coind cs intr_ts monos
berghofe@21024
   590
      params cnames_syn ctxt =
berghofe@5094
   591
  let
wenzelm@24815
   592
    val fp_name = if coind then @{const_name FixedPoint.gfp} else @{const_name FixedPoint.lfp};
berghofe@5094
   593
berghofe@21024
   594
    val argTs = fold (fn c => fn Ts => Ts @
berghofe@21024
   595
      (List.drop (binder_types (fastype_of c), length params) \\ Ts)) cs [];
berghofe@21024
   596
    val k = log 2 1 (length cs);
berghofe@21024
   597
    val predT = replicate k HOLogic.boolT ---> argTs ---> HOLogic.boolT;
berghofe@21024
   598
    val p :: xs = map Free (Variable.variant_frees ctxt intr_ts
berghofe@21024
   599
      (("p", predT) :: (mk_names "x" (length argTs) ~~ argTs)));
berghofe@21024
   600
    val bs = map Free (Variable.variant_frees ctxt (p :: xs @ intr_ts)
berghofe@21024
   601
      (map (rpair HOLogic.boolT) (mk_names "b" k)));
berghofe@21024
   602
berghofe@21024
   603
    fun subst t = (case dest_predicate cs params t of
berghofe@21024
   604
        SOME (_, i, ts, (Ts, Us)) =>
berghofe@23762
   605
          let
berghofe@23762
   606
            val l = length Us;
berghofe@23762
   607
            val zs = map Bound (l - 1 downto 0)
berghofe@21024
   608
          in
berghofe@21024
   609
            list_abs (map (pair "z") Us, list_comb (p,
berghofe@23762
   610
              make_bool_args' bs i @ make_args argTs
berghofe@23762
   611
                ((map (incr_boundvars l) ts ~~ Ts) @ (zs ~~ Us))))
berghofe@21024
   612
          end
berghofe@21024
   613
      | NONE => (case t of
berghofe@21024
   614
          t1 $ t2 => subst t1 $ subst t2
berghofe@21024
   615
        | Abs (x, T, u) => Abs (x, T, subst u)
berghofe@21024
   616
        | _ => t));
berghofe@5149
   617
berghofe@5094
   618
    (* transform an introduction rule into a conjunction  *)
berghofe@21024
   619
    (*   [| p_i t; ... |] ==> p_j u                       *)
berghofe@5094
   620
    (* is transformed into                                *)
berghofe@21024
   621
    (*   b_j & x_j = u & p b_j t & ...                    *)
berghofe@5094
   622
berghofe@5094
   623
    fun transform_rule r =
berghofe@5094
   624
      let
berghofe@21024
   625
        val SOME (_, i, ts, (Ts, _)) = dest_predicate cs params
berghofe@21048
   626
          (HOLogic.dest_Trueprop (Logic.strip_assums_concl r));
berghofe@21048
   627
        val ps = make_bool_args HOLogic.mk_not I bs i @
berghofe@21048
   628
          map HOLogic.mk_eq (make_args' argTs xs Ts ~~ ts) @
berghofe@21048
   629
          map (subst o HOLogic.dest_Trueprop)
berghofe@21048
   630
            (Logic.strip_assums_hyp r)
berghofe@21024
   631
      in foldr (fn ((x, T), P) => HOLogic.exists_const T $ (Abs (x, T, P)))
berghofe@21048
   632
        (if null ps then HOLogic.true_const else foldr1 HOLogic.mk_conj ps)
berghofe@21048
   633
        (Logic.strip_params r)
berghofe@5094
   634
      end
berghofe@5094
   635
berghofe@5094
   636
    (* make a disjunction of all introduction rules *)
berghofe@5094
   637
berghofe@21024
   638
    val fp_fun = fold_rev lambda (p :: bs @ xs)
berghofe@21024
   639
      (if null intr_ts then HOLogic.false_const
berghofe@21024
   640
       else foldr1 HOLogic.mk_disj (map transform_rule intr_ts));
berghofe@5094
   641
berghofe@21024
   642
    (* add definiton of recursive predicates to theory *)
berghofe@5094
   643
berghofe@14235
   644
    val rec_name = if alt_name = "" then
berghofe@21024
   645
      space_implode "_" (map fst cnames_syn) else alt_name;
berghofe@5094
   646
berghofe@21024
   647
    val ((rec_const, (_, fp_def)), ctxt') = ctxt |>
wenzelm@21433
   648
      LocalTheory.def Thm.internalK
berghofe@21024
   649
        ((rec_name, case cnames_syn of [(_, syn)] => syn | _ => NoSyn),
berghofe@21024
   650
         (("", []), fold_rev lambda params
berghofe@21024
   651
           (Const (fp_name, (predT --> predT) --> predT) $ fp_fun)));
berghofe@21024
   652
    val fp_def' = Simplifier.rewrite (HOL_basic_ss addsimps [fp_def])
berghofe@21024
   653
      (cterm_of (ProofContext.theory_of ctxt') (list_comb (rec_const, params)));
berghofe@21024
   654
    val specs = if length cs < 2 then [] else
berghofe@21024
   655
      map_index (fn (i, (name_mx, c)) =>
berghofe@21024
   656
        let
berghofe@21024
   657
          val Ts = List.drop (binder_types (fastype_of c), length params);
berghofe@21024
   658
          val xs = map Free (Variable.variant_frees ctxt intr_ts
berghofe@21024
   659
            (mk_names "x" (length Ts) ~~ Ts))
berghofe@21024
   660
        in
berghofe@21024
   661
          (name_mx, (("", []), fold_rev lambda (params @ xs)
berghofe@21024
   662
            (list_comb (rec_const, params @ make_bool_args' bs i @
berghofe@21024
   663
              make_args argTs (xs ~~ Ts)))))
berghofe@21024
   664
        end) (cnames_syn ~~ cs);
berghofe@23762
   665
    val (consts_defs, ctxt'') = LocalTheory.defs Thm.internalK specs ctxt';
berghofe@21024
   666
    val preds = (case cs of [_] => [rec_const] | _ => map #1 consts_defs);
berghofe@5094
   667
berghofe@21024
   668
    val mono = prove_mono predT fp_fun monos ctxt''
berghofe@5094
   669
berghofe@21024
   670
  in (ctxt'', rec_name, mono, fp_def', map (#2 o #2) consts_defs,
berghofe@21024
   671
    list_comb (rec_const, params), preds, argTs, bs, xs)
berghofe@21024
   672
  end;
berghofe@5094
   673
wenzelm@24815
   674
fun declare_rules kind rec_name coind no_ind cnames intrs intr_names intr_atts
berghofe@23762
   675
      elims raw_induct ctxt =
berghofe@23762
   676
  let
berghofe@23762
   677
    val ind_case_names = RuleCases.case_names intr_names;
berghofe@23762
   678
    val induct =
berghofe@23762
   679
      if coind then
berghofe@23762
   680
        (raw_induct, [RuleCases.case_names [rec_name],
berghofe@23762
   681
          RuleCases.case_conclusion (rec_name, intr_names),
berghofe@23762
   682
          RuleCases.consumes 1, InductAttrib.coinduct_set (hd cnames)])
berghofe@23762
   683
      else if no_ind orelse length cnames > 1 then
berghofe@23762
   684
        (raw_induct, [ind_case_names, RuleCases.consumes 0])
berghofe@23762
   685
      else (raw_induct RSN (2, rev_mp), [ind_case_names, RuleCases.consumes 1]);
berghofe@23762
   686
berghofe@23762
   687
    val (intrs', ctxt1) =
berghofe@23762
   688
      ctxt |>
wenzelm@24815
   689
      LocalTheory.notes kind
berghofe@23762
   690
        (map (NameSpace.qualified rec_name) intr_names ~~
berghofe@23762
   691
         intr_atts ~~ map (fn th => [([th],
berghofe@23762
   692
           [Attrib.internal (K (ContextRules.intro_query NONE))])]) intrs) |>>
berghofe@24744
   693
      map (hd o snd);
berghofe@23762
   694
    val (((_, elims'), (_, [induct'])), ctxt2) =
berghofe@23762
   695
      ctxt1 |>
wenzelm@24815
   696
      LocalTheory.note kind ((NameSpace.qualified rec_name "intros", []), intrs') ||>>
berghofe@23762
   697
      fold_map (fn (name, (elim, cases)) =>
wenzelm@24815
   698
        LocalTheory.note kind ((NameSpace.qualified (Sign.base_name name) "cases",
berghofe@23762
   699
          [Attrib.internal (K (RuleCases.case_names cases)),
berghofe@23762
   700
           Attrib.internal (K (RuleCases.consumes 1)),
berghofe@23762
   701
           Attrib.internal (K (InductAttrib.cases_set name)),
berghofe@23762
   702
           Attrib.internal (K (ContextRules.elim_query NONE))]), [elim]) #>
berghofe@23762
   703
        apfst (hd o snd)) (if null elims then [] else cnames ~~ elims) ||>>
wenzelm@24815
   704
      LocalTheory.note kind ((NameSpace.qualified rec_name (coind_prefix coind ^ "induct"),
berghofe@23762
   705
        map (Attrib.internal o K) (#2 induct)), [rulify (#1 induct)]);
berghofe@23762
   706
berghofe@23762
   707
    val ctxt3 = if no_ind orelse coind then ctxt2 else
berghofe@23762
   708
      let val inducts = cnames ~~ ProjectRule.projects ctxt2 (1 upto length cnames) induct'
berghofe@23762
   709
      in
berghofe@23762
   710
        ctxt2 |>
wenzelm@24815
   711
        LocalTheory.notes kind [((NameSpace.qualified rec_name "inducts", []),
berghofe@23762
   712
          inducts |> map (fn (name, th) => ([th],
berghofe@23762
   713
            [Attrib.internal (K ind_case_names),
berghofe@23762
   714
             Attrib.internal (K (RuleCases.consumes 1)),
berghofe@23762
   715
             Attrib.internal (K (InductAttrib.induct_set name))])))] |> snd
berghofe@23762
   716
      end
berghofe@23762
   717
  in (intrs', elims', induct', ctxt3) end;
berghofe@23762
   718
wenzelm@24815
   719
type add_ind_def =
wenzelm@24815
   720
  {verbose: bool, kind: string, alt_name: bstring, coind: bool, no_elim: bool, no_ind: bool} ->
berghofe@23762
   721
  term list -> ((string * Attrib.src list) * term) list -> thm list ->
berghofe@23762
   722
  term list -> (string * mixfix) list ->
berghofe@23762
   723
  local_theory -> inductive_result * local_theory
berghofe@23762
   724
wenzelm@24815
   725
fun add_ind_def {verbose, kind, alt_name, coind, no_elim, no_ind}
wenzelm@24815
   726
    cs intros monos params cnames_syn ctxt =
berghofe@9072
   727
  let
wenzelm@10735
   728
    val _ =
berghofe@21024
   729
      if verbose then message ("Proofs for " ^ coind_prefix coind ^ "inductive predicate(s) " ^
berghofe@21024
   730
        commas_quote (map fst cnames_syn)) else ();
berghofe@9072
   731
wenzelm@21526
   732
    val cnames = map (Sign.full_name (ProofContext.theory_of ctxt) o #1) cnames_syn;  (* FIXME *)
berghofe@23762
   733
    val ((intr_names, intr_atts), intr_ts) =
berghofe@23762
   734
      apfst split_list (split_list (map (check_rule ctxt cs params) intros));
berghofe@21024
   735
berghofe@21024
   736
    val (ctxt1, rec_name, mono, fp_def, rec_preds_defs, rec_const, preds,
berghofe@21024
   737
      argTs, bs, xs) = mk_ind_def alt_name coind cs intr_ts
berghofe@21024
   738
        monos params cnames_syn ctxt;
berghofe@9072
   739
berghofe@21024
   740
    val (intrs, unfold) = prove_intrs coind mono fp_def (length bs + length xs)
berghofe@22605
   741
      params intr_ts rec_preds_defs ctxt1;
berghofe@21048
   742
    val elims = if no_elim then [] else
berghofe@23762
   743
      prove_elims cs params intr_ts intr_names unfold rec_preds_defs ctxt1;
berghofe@22605
   744
    val raw_induct = zero_var_indexes
berghofe@21024
   745
      (if no_ind then Drule.asm_rl else
berghofe@23762
   746
       if coind then
berghofe@23762
   747
         singleton (ProofContext.export
berghofe@23762
   748
           (snd (Variable.add_fixes (map (fst o dest_Free) params) ctxt1)) ctxt1)
berghofe@23762
   749
           (rotate_prems ~1 (ObjectLogic.rulify (rule_by_tactic
wenzelm@24516
   750
             (rewrite_tac [le_fun_def, le_bool_def, @{thm sup_fun_eq}, @{thm sup_bool_eq}] THEN
berghofe@23762
   751
               fold_tac rec_preds_defs) (mono RS (fp_def RS def_coinduct)))))
berghofe@21024
   752
       else
berghofe@21024
   753
         prove_indrule cs argTs bs xs rec_const params intr_ts mono fp_def
berghofe@22605
   754
           rec_preds_defs ctxt1);
berghofe@5094
   755
wenzelm@24815
   756
    val (intrs', elims', induct, ctxt2) = declare_rules kind rec_name coind no_ind
berghofe@23762
   757
      cnames intrs intr_names intr_atts elims raw_induct ctxt1;
berghofe@21048
   758
wenzelm@21526
   759
    val names = map #1 cnames_syn;
berghofe@21048
   760
    val result =
berghofe@21048
   761
      {preds = preds,
berghofe@21048
   762
       intrs = intrs',
berghofe@21048
   763
       elims = elims',
berghofe@21048
   764
       raw_induct = rulify raw_induct,
berghofe@23762
   765
       induct = induct};
wenzelm@21367
   766
berghofe@23762
   767
    val ctxt3 = ctxt2
wenzelm@21526
   768
      |> Context.proof_map (put_inductives names ({names = names, coind = coind}, result))
wenzelm@21526
   769
      |> LocalTheory.declaration (fn phi =>
wenzelm@21526
   770
        let
berghofe@23762
   771
          val names' = map (LocalTheory.target_name ctxt2 o Morphism.name phi) names;
wenzelm@22667
   772
          val result' = morph_result phi result;
wenzelm@21526
   773
        in put_inductives names' ({names = names', coind = coind}, result') end);
berghofe@23762
   774
  in (result, ctxt3) end;
berghofe@5094
   775
wenzelm@6424
   776
wenzelm@10735
   777
(* external interfaces *)
berghofe@5094
   778
wenzelm@24815
   779
fun gen_add_inductive_i mk_def (flags as {verbose, kind, alt_name, coind, no_elim, no_ind})
berghofe@23762
   780
    cnames_syn pnames pre_intros monos ctxt =
berghofe@5094
   781
  let
berghofe@21024
   782
    val thy = ProofContext.theory_of ctxt;
wenzelm@6424
   783
    val _ = Theory.requires thy "Inductive" (coind_prefix coind ^ "inductive definitions");
berghofe@5094
   784
berghofe@21766
   785
    fun is_abbrev ((name, atts), t) =
berghofe@21766
   786
      can (Logic.strip_assums_concl #> Logic.dest_equals) t andalso
berghofe@21766
   787
      (name = "" andalso null atts orelse
berghofe@21766
   788
       error "Abbreviations may not have names or attributes");
berghofe@21766
   789
berghofe@21766
   790
    fun expand_atom tab (t as Free xT) =
berghofe@21766
   791
          the_default t (AList.lookup op = tab xT)
berghofe@21766
   792
      | expand_atom tab t = t;
berghofe@21766
   793
    fun expand [] r = r
berghofe@21766
   794
      | expand tab r = Envir.beta_norm (Term.map_aterms (expand_atom tab) r);
berghofe@21766
   795
berghofe@24744
   796
    val (_, ctxt') = Variable.add_fixes (map (fst o fst) cnames_syn) ctxt;
berghofe@21766
   797
berghofe@21766
   798
    fun prep_abbrevs [] abbrevs' abbrevs'' = (rev abbrevs', rev abbrevs'')
berghofe@21766
   799
      | prep_abbrevs ((_, abbrev) :: abbrevs) abbrevs' abbrevs'' =
berghofe@21766
   800
          let val ((s, T), t) =
berghofe@21766
   801
            LocalDefs.abs_def (snd (LocalDefs.cert_def ctxt' abbrev))
berghofe@24744
   802
          in case find_first (equal s o fst o fst) cnames_syn of
berghofe@21766
   803
              NONE => error ("Head of abbreviation " ^ quote s ^ " undeclared")
berghofe@24744
   804
            | SOME (_, mx) => prep_abbrevs abbrevs
berghofe@21766
   805
                (((s, T), expand abbrevs' t) :: abbrevs')
berghofe@21766
   806
                (((s, mx), expand abbrevs' t) :: abbrevs'') (* FIXME: do not expand *)
berghofe@21766
   807
          end;
berghofe@21766
   808
berghofe@21766
   809
    val (abbrevs, pre_intros') = List.partition is_abbrev pre_intros;
berghofe@21766
   810
    val (abbrevs', abbrevs'') = prep_abbrevs abbrevs [] [];
berghofe@21766
   811
    val _ = (case gen_inter (op = o apsnd fst)
berghofe@21766
   812
      (fold (Term.add_frees o snd) abbrevs' [], abbrevs') of
berghofe@21766
   813
        [] => ()
berghofe@21766
   814
      | xs => error ("Bad abbreviation(s): " ^ commas (map fst xs)));
berghofe@21766
   815
berghofe@24744
   816
    val params = map Free pnames;
berghofe@24744
   817
    val cnames_syn' = filter_out (fn ((s, _), _) =>
berghofe@21766
   818
      exists (equal s o fst o fst) abbrevs') cnames_syn;
berghofe@24744
   819
    val cs = map (Free o fst) cnames_syn';
berghofe@24744
   820
    val cnames_syn'' = map (fn ((s, _), mx) => (s, mx)) cnames_syn';
berghofe@5094
   821
berghofe@21024
   822
    fun close_rule (x, r) = (x, list_all_free (rev (fold_aterms
berghofe@21024
   823
      (fn t as Free (v as (s, _)) =>
berghofe@24744
   824
            if Variable.is_fixed ctxt' s orelse
berghofe@21024
   825
              member op = params t then I else insert op = v
berghofe@21024
   826
        | _ => I) r []), r));
berghofe@5094
   827
berghofe@24744
   828
    val intros = map (close_rule ##> expand abbrevs') pre_intros';
berghofe@21048
   829
  in
wenzelm@24815
   830
    ctxt
wenzelm@24815
   831
    |> mk_def flags cs intros monos params cnames_syn''
wenzelm@24815
   832
    ||> fold (snd oo LocalTheory.abbrev Syntax.default_mode) abbrevs''
berghofe@21048
   833
  end;
berghofe@5094
   834
wenzelm@24721
   835
fun gen_add_inductive mk_def verbose coind cnames_syn pnames_syn intro_srcs raw_monos lthy =
berghofe@5094
   836
  let
wenzelm@24721
   837
    val ((vars, specs), _) = lthy |> Specification.read_specification
wenzelm@24721
   838
      (cnames_syn @ pnames_syn) (map (fn (a, s) => [(a, [s])]) intro_srcs);
wenzelm@24721
   839
    val (cs, ps) = chop (length cnames_syn) vars;
wenzelm@24721
   840
    val intrs = map (apsnd the_single) specs;
wenzelm@24721
   841
    val monos = Attrib.eval_thms lthy raw_monos;
wenzelm@24815
   842
    val flags = {verbose = verbose, kind = Thm.theoremK, alt_name = "",
wenzelm@24815
   843
      coind = coind, no_elim = false, no_ind = false};
wenzelm@24815
   844
  in gen_add_inductive_i mk_def flags cs (map fst ps) intrs monos lthy end;
berghofe@5094
   845
berghofe@23762
   846
val add_inductive_i = gen_add_inductive_i add_ind_def;
berghofe@23762
   847
val add_inductive = gen_add_inductive add_ind_def;
berghofe@23762
   848
wenzelm@24815
   849
fun add_inductive_global flags cnames_syn pnames pre_intros monos =
wenzelm@21526
   850
  TheoryTarget.init NONE #>
wenzelm@24815
   851
  add_inductive_i flags cnames_syn pnames pre_intros monos #>
wenzelm@21526
   852
  (fn (_, lthy) =>
wenzelm@21526
   853
    (#2 (the_inductive (LocalTheory.target_of lthy)
berghofe@24744
   854
      (LocalTheory.target_name lthy (fst (fst (hd cnames_syn))))),
wenzelm@21526
   855
    ProofContext.theory_of (LocalTheory.exit lthy)));
wenzelm@6424
   856
wenzelm@6424
   857
berghofe@22789
   858
(* read off arities of inductive predicates from raw induction rule *)
berghofe@22789
   859
fun arities_of induct =
berghofe@22789
   860
  map (fn (_ $ t $ u) =>
berghofe@22789
   861
      (fst (dest_Const (head_of t)), length (snd (strip_comb u))))
berghofe@22789
   862
    (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
berghofe@22789
   863
berghofe@22789
   864
(* read off parameters of inductive predicate from raw induction rule *)
berghofe@22789
   865
fun params_of induct =
berghofe@22789
   866
  let
berghofe@22789
   867
    val (_ $ t $ u :: _) =
berghofe@22789
   868
      HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct));
berghofe@22789
   869
    val (_, ts) = strip_comb t;
berghofe@22789
   870
    val (_, us) = strip_comb u
berghofe@22789
   871
  in
berghofe@22789
   872
    List.take (ts, length ts - length us)
berghofe@22789
   873
  end;
berghofe@22789
   874
berghofe@22789
   875
val pname_of_intr =
berghofe@22789
   876
  concl_of #> HOLogic.dest_Trueprop #> head_of #> dest_Const #> fst;
berghofe@22789
   877
berghofe@22789
   878
(* partition introduction rules according to predicate name *)
berghofe@22789
   879
fun partition_rules induct intros =
berghofe@22789
   880
  fold_rev (fn r => AList.map_entry op = (pname_of_intr r) (cons r)) intros
berghofe@22789
   881
    (map (rpair [] o fst) (arities_of induct));
berghofe@22789
   882
berghofe@22789
   883
fun unpartition_rules intros xs =
berghofe@22789
   884
  fold_map (fn r => AList.map_entry_yield op = (pname_of_intr r)
berghofe@22789
   885
    (fn x :: xs => (x, xs)) #>> the) intros xs |> fst;
berghofe@22789
   886
berghofe@22789
   887
(* infer order of variables in intro rules from order of quantifiers in elim rule *)
berghofe@22789
   888
fun infer_intro_vars elim arity intros =
berghofe@22789
   889
  let
berghofe@22789
   890
    val thy = theory_of_thm elim;
berghofe@22789
   891
    val _ :: cases = prems_of elim;
berghofe@22789
   892
    val used = map (fst o fst) (Term.add_vars (prop_of elim) []);
berghofe@22789
   893
    fun mtch (t, u) =
berghofe@22789
   894
      let
berghofe@22789
   895
        val params = Logic.strip_params t;
berghofe@22789
   896
        val vars = map (Var o apfst (rpair 0))
berghofe@22789
   897
          (Name.variant_list used (map fst params) ~~ map snd params);
berghofe@22789
   898
        val ts = map (curry subst_bounds (rev vars))
berghofe@22789
   899
          (List.drop (Logic.strip_assums_hyp t, arity));
berghofe@22789
   900
        val us = Logic.strip_imp_prems u;
berghofe@22789
   901
        val tab = fold (Pattern.first_order_match thy) (ts ~~ us)
berghofe@22789
   902
          (Vartab.empty, Vartab.empty);
berghofe@22789
   903
      in
berghofe@22789
   904
        map (Envir.subst_vars tab) vars
berghofe@22789
   905
      end
berghofe@22789
   906
  in
berghofe@22789
   907
    map (mtch o apsnd prop_of) (cases ~~ intros)
berghofe@22789
   908
  end;
berghofe@22789
   909
berghofe@22789
   910
wenzelm@6437
   911
(** package setup **)
wenzelm@6437
   912
wenzelm@6437
   913
(* setup theory *)
wenzelm@6437
   914
wenzelm@8634
   915
val setup =
berghofe@23762
   916
  Method.add_methods [("ind_cases", ind_cases,
berghofe@21024
   917
    "dynamic case analysis on predicates")] #>
berghofe@23762
   918
  Attrib.add_attributes [("mono", Attrib.add_del_args mono_add mono_del,
wenzelm@18728
   919
    "declaration of monotonicity rule")];
wenzelm@6437
   920
wenzelm@6437
   921
wenzelm@6437
   922
(* outer syntax *)
wenzelm@6424
   923
wenzelm@17057
   924
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6424
   925
wenzelm@21367
   926
(* FIXME tmp *)
wenzelm@21367
   927
fun flatten_specification specs = specs |> maps
wenzelm@21367
   928
  (fn (a, (concl, [])) => concl |> map
wenzelm@21367
   929
        (fn ((b, atts), [B]) =>
wenzelm@21367
   930
              if a = "" then ((b, atts), B)
wenzelm@21367
   931
              else if b = "" then ((a, atts), B)
wenzelm@21367
   932
              else error ("Illegal nested case names " ^ quote (NameSpace.append a b))
wenzelm@21367
   933
          | ((b, _), _) => error ("Illegal simultaneous specification " ^ quote b))
wenzelm@21367
   934
    | (a, _) => error ("Illegal local specification parameters for " ^ quote a));
wenzelm@6424
   935
berghofe@23762
   936
fun gen_ind_decl mk_def coind =
wenzelm@22102
   937
  P.opt_target --
wenzelm@21367
   938
  P.fixes -- P.for_fixes --
wenzelm@22102
   939
  Scan.optional (P.$$$ "where" |-- P.!!! SpecParse.specification) [] --
wenzelm@22102
   940
  Scan.optional (P.$$$ "monos" |-- P.!!! SpecParse.xthms1) []
wenzelm@21367
   941
  >> (fn ((((loc, preds), params), specs), monos) =>
wenzelm@21367
   942
    Toplevel.local_theory loc
berghofe@23762
   943
      (fn lthy => lthy |> gen_add_inductive mk_def true coind preds params
berghofe@23762
   944
         (flatten_specification specs) monos |> snd));
berghofe@23762
   945
berghofe@23762
   946
val ind_decl = gen_ind_decl add_ind_def;
wenzelm@6424
   947
wenzelm@6723
   948
val inductiveP =
berghofe@23762
   949
  OuterSyntax.command "inductive" "define inductive predicates" K.thy_decl (ind_decl false);
wenzelm@6723
   950
wenzelm@6723
   951
val coinductiveP =
berghofe@23762
   952
  OuterSyntax.command "coinductive" "define coinductive predicates" K.thy_decl (ind_decl true);
wenzelm@6424
   953
wenzelm@7107
   954
wenzelm@7107
   955
val inductive_casesP =
berghofe@23762
   956
  OuterSyntax.command "inductive_cases"
wenzelm@21367
   957
    "create simplified instances of elimination rules (improper)" K.thy_script
wenzelm@22102
   958
    (P.opt_target -- P.and_list1 SpecParse.spec
wenzelm@21367
   959
      >> (fn (loc, specs) => Toplevel.local_theory loc (snd o inductive_cases specs)));
wenzelm@7107
   960
wenzelm@21367
   961
val _ = OuterSyntax.add_keywords ["monos"];
wenzelm@7107
   962
val _ = OuterSyntax.add_parsers [inductiveP, coinductiveP, inductive_casesP];
wenzelm@6424
   963
berghofe@5094
   964
end;
wenzelm@6424
   965
wenzelm@6424
   966
end;