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