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