src/HOL/Tools/inductive_package.ML
author wenzelm
Tue Jan 16 00:32:38 2001 +0100 (2001-01-16)
changeset 10910 058775a575db
parent 10804 306aee77eadd
child 10988 e0016a009c17
permissions -rw-r--r--
export inductive_forall_name, inductive_forall_def, rulify;
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@10735
     4
    Author:     Stefan Berghofer, TU Muenchen
wenzelm@10735
     5
    Author:     Markus Wenzel, TU Muenchen
berghofe@5094
     6
    Copyright   1994  University of Cambridge
wenzelm@9598
     7
                1998  TU Muenchen
berghofe@5094
     8
wenzelm@6424
     9
(Co)Inductive Definition module for HOL.
berghofe@5094
    10
berghofe@5094
    11
Features:
wenzelm@6424
    12
  * least or greatest fixedpoints
wenzelm@6424
    13
  * user-specified product and sum constructions
wenzelm@6424
    14
  * mutually recursive definitions
wenzelm@6424
    15
  * definitions involving arbitrary monotone operators
wenzelm@6424
    16
  * automatically proves introduction and elimination rules
berghofe@5094
    17
wenzelm@6424
    18
The recursive sets must *already* be declared as constants in the
wenzelm@6424
    19
current theory!
berghofe@5094
    20
berghofe@5094
    21
  Introduction rules have the form
wenzelm@8316
    22
  [| ti:M(Sj), ..., P(x), ... |] ==> t: Sk
berghofe@5094
    23
  where M is some monotone operator (usually the identity)
berghofe@5094
    24
  P(x) is any side condition on the free variables
berghofe@5094
    25
  ti, t are any terms
berghofe@5094
    26
  Sj, Sk are two of the sets being defined in mutual recursion
berghofe@5094
    27
wenzelm@6424
    28
Sums are used only for mutual recursion.  Products are used only to
wenzelm@6424
    29
derive "streamlined" induction rules for relations.
berghofe@5094
    30
*)
berghofe@5094
    31
berghofe@5094
    32
signature INDUCTIVE_PACKAGE =
berghofe@5094
    33
sig
wenzelm@6424
    34
  val quiet_mode: bool ref
berghofe@7020
    35
  val unify_consts: Sign.sg -> term list -> term list -> term list * term list
berghofe@9116
    36
  val get_inductive: theory -> string -> ({names: string list, coind: bool} *
berghofe@9116
    37
    {defs: thm list, elims: thm list, raw_induct: thm, induct: thm,
berghofe@9116
    38
     intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm}) option
wenzelm@6437
    39
  val print_inductives: theory -> unit
berghofe@7710
    40
  val mono_add_global: theory attribute
berghofe@7710
    41
  val mono_del_global: theory attribute
berghofe@7710
    42
  val get_monos: theory -> thm list
wenzelm@10910
    43
  val inductive_forall_name: string
wenzelm@10910
    44
  val inductive_forall_def: thm
wenzelm@10910
    45
  val rulify: thm -> thm
wenzelm@10735
    46
  val inductive_cases: ((bstring * Args.src list) * string list) * Comment.text
wenzelm@10735
    47
    -> theory -> theory
wenzelm@10735
    48
  val inductive_cases_i: ((bstring * theory attribute list) * term list) * Comment.text
wenzelm@10735
    49
    -> theory -> theory
wenzelm@6424
    50
  val add_inductive_i: bool -> bool -> bstring -> bool -> bool -> bool -> term list ->
wenzelm@6521
    51
    theory attribute list -> ((bstring * term) * theory attribute list) list ->
wenzelm@6521
    52
      thm list -> thm list -> theory -> theory *
wenzelm@6424
    53
      {defs: thm list, elims: thm list, raw_induct: thm, induct: thm,
wenzelm@6437
    54
       intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm}
wenzelm@6521
    55
  val add_inductive: bool -> bool -> string list -> Args.src list ->
wenzelm@6521
    56
    ((bstring * string) * Args.src list) list -> (xstring * Args.src list) list ->
wenzelm@6521
    57
      (xstring * Args.src list) list -> theory -> theory *
wenzelm@6424
    58
      {defs: thm list, elims: thm list, raw_induct: thm, induct: thm,
wenzelm@6437
    59
       intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm}
wenzelm@6437
    60
  val setup: (theory -> theory) list
berghofe@5094
    61
end;
berghofe@5094
    62
wenzelm@6424
    63
structure InductivePackage: INDUCTIVE_PACKAGE =
berghofe@5094
    64
struct
berghofe@5094
    65
wenzelm@9598
    66
wenzelm@10729
    67
(** theory context references **)
wenzelm@10729
    68
wenzelm@10735
    69
val mono_name = "Ord.mono";
wenzelm@10735
    70
val gfp_name = "Gfp.gfp";
wenzelm@10735
    71
val lfp_name = "Lfp.lfp";
wenzelm@10735
    72
val vimage_name = "Inverse_Image.vimage";
wenzelm@10735
    73
val Const _ $ (vimage_f $ _) $ _ = HOLogic.dest_Trueprop (Thm.concl_of vimageD);
wenzelm@10735
    74
wenzelm@10910
    75
val inductive_forall_name = "Inductive.forall";
wenzelm@10910
    76
val inductive_forall_def = thm "forall_def";
wenzelm@10735
    77
val inductive_conj_name = "Inductive.conj";
wenzelm@10729
    78
val inductive_conj_def = thm "conj_def";
wenzelm@10729
    79
val inductive_conj = thms "inductive_conj";
wenzelm@10729
    80
val inductive_atomize = thms "inductive_atomize";
wenzelm@10729
    81
val inductive_rulify1 = thms "inductive_rulify1";
wenzelm@10729
    82
val inductive_rulify2 = thms "inductive_rulify2";
wenzelm@10729
    83
wenzelm@10729
    84
wenzelm@10729
    85
wenzelm@10735
    86
(** theory data **)
berghofe@7710
    87
berghofe@7710
    88
(* data kind 'HOL/inductive' *)
berghofe@7710
    89
berghofe@7710
    90
type inductive_info =
berghofe@7710
    91
  {names: string list, coind: bool} * {defs: thm list, elims: thm list, raw_induct: thm,
berghofe@7710
    92
    induct: thm, intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm};
berghofe@7710
    93
berghofe@7710
    94
structure InductiveArgs =
berghofe@7710
    95
struct
berghofe@7710
    96
  val name = "HOL/inductive";
berghofe@7710
    97
  type T = inductive_info Symtab.table * thm list;
berghofe@7710
    98
berghofe@7710
    99
  val empty = (Symtab.empty, []);
berghofe@7710
   100
  val copy = I;
berghofe@7710
   101
  val prep_ext = I;
berghofe@7710
   102
  fun merge ((tab1, monos1), (tab2, monos2)) = (Symtab.merge (K true) (tab1, tab2),
berghofe@7710
   103
    Library.generic_merge Thm.eq_thm I I monos1 monos2);
berghofe@7710
   104
berghofe@7710
   105
  fun print sg (tab, monos) =
wenzelm@8720
   106
    [Pretty.strs ("(co)inductives:" :: map #1 (Sign.cond_extern_table sg Sign.constK tab)),
wenzelm@10008
   107
     Pretty.big_list "monotonicity rules:" (map (Display.pretty_thm_sg sg) monos)]
wenzelm@8720
   108
    |> Pretty.chunks |> Pretty.writeln;
berghofe@7710
   109
end;
berghofe@7710
   110
berghofe@7710
   111
structure InductiveData = TheoryDataFun(InductiveArgs);
berghofe@7710
   112
val print_inductives = InductiveData.print;
berghofe@7710
   113
berghofe@7710
   114
berghofe@7710
   115
(* get and put data *)
berghofe@7710
   116
berghofe@9116
   117
fun get_inductive thy name = Symtab.lookup (fst (InductiveData.get thy), name);
berghofe@7710
   118
wenzelm@9598
   119
fun the_inductive thy name =
wenzelm@9598
   120
  (case get_inductive thy name of
wenzelm@9598
   121
    None => error ("Unknown (co)inductive set " ^ quote name)
wenzelm@9598
   122
  | Some info => info);
wenzelm@9598
   123
berghofe@7710
   124
fun put_inductives names info thy =
berghofe@7710
   125
  let
berghofe@7710
   126
    fun upd ((tab, monos), name) = (Symtab.update_new ((name, info), tab), monos);
berghofe@7710
   127
    val tab_monos = foldl upd (InductiveData.get thy, names)
berghofe@7710
   128
      handle Symtab.DUP name => error ("Duplicate definition of (co)inductive set " ^ quote name);
berghofe@7710
   129
  in InductiveData.put tab_monos thy end;
berghofe@7710
   130
wenzelm@8277
   131
berghofe@7710
   132
berghofe@7710
   133
(** monotonicity rules **)
berghofe@7710
   134
wenzelm@9831
   135
val get_monos = #2 o InductiveData.get;
wenzelm@9831
   136
fun map_monos f = InductiveData.map (Library.apsnd f);
wenzelm@8277
   137
berghofe@7710
   138
fun mk_mono thm =
berghofe@7710
   139
  let
berghofe@7710
   140
    fun eq2mono thm' = [standard (thm' RS (thm' RS eq_to_mono))] @
berghofe@7710
   141
      (case concl_of thm of
berghofe@7710
   142
          (_ $ (_ $ (Const ("Not", _) $ _) $ _)) => []
berghofe@7710
   143
        | _ => [standard (thm' RS (thm' RS eq_to_mono2))]);
berghofe@7710
   144
    val concl = concl_of thm
berghofe@7710
   145
  in
berghofe@7710
   146
    if Logic.is_equals concl then
berghofe@7710
   147
      eq2mono (thm RS meta_eq_to_obj_eq)
berghofe@7710
   148
    else if can (HOLogic.dest_eq o HOLogic.dest_Trueprop) concl then
berghofe@7710
   149
      eq2mono thm
berghofe@7710
   150
    else [thm]
berghofe@7710
   151
  end;
berghofe@7710
   152
wenzelm@8634
   153
wenzelm@8634
   154
(* attributes *)
berghofe@7710
   155
wenzelm@9831
   156
fun mono_add_global (thy, thm) = (map_monos (Drule.add_rules (mk_mono thm)) thy, thm);
wenzelm@9831
   157
fun mono_del_global (thy, thm) = (map_monos (Drule.del_rules (mk_mono thm)) thy, thm);
berghofe@7710
   158
berghofe@7710
   159
val mono_attr =
wenzelm@8634
   160
 (Attrib.add_del_args mono_add_global mono_del_global,
wenzelm@8634
   161
  Attrib.add_del_args Attrib.undef_local_attribute Attrib.undef_local_attribute);
berghofe@7710
   162
berghofe@7710
   163
wenzelm@7107
   164
wenzelm@10735
   165
(** misc utilities **)
wenzelm@6424
   166
berghofe@5662
   167
val quiet_mode = ref false;
wenzelm@10735
   168
fun message s = if ! quiet_mode then () else writeln s;
wenzelm@10735
   169
fun clean_message s = if ! quick_and_dirty then () else message s;
berghofe@5662
   170
wenzelm@6424
   171
fun coind_prefix true = "co"
wenzelm@6424
   172
  | coind_prefix false = "";
wenzelm@6424
   173
wenzelm@6424
   174
wenzelm@10735
   175
(*the following code ensures that each recursive set always has the
wenzelm@10735
   176
  same type in all introduction rules*)
berghofe@7020
   177
fun unify_consts sign cs intr_ts =
berghofe@7020
   178
  (let
berghofe@7020
   179
    val {tsig, ...} = Sign.rep_sg sign;
berghofe@7020
   180
    val add_term_consts_2 =
berghofe@7020
   181
      foldl_aterms (fn (cs, Const c) => c ins cs | (cs, _) => cs);
berghofe@7020
   182
    fun varify (t, (i, ts)) =
berghofe@7020
   183
      let val t' = map_term_types (incr_tvar (i + 1)) (Type.varify (t, []))
berghofe@7020
   184
      in (maxidx_of_term t', t'::ts) end;
berghofe@7020
   185
    val (i, cs') = foldr varify (cs, (~1, []));
berghofe@7020
   186
    val (i', intr_ts') = foldr varify (intr_ts, (i, []));
berghofe@7020
   187
    val rec_consts = foldl add_term_consts_2 ([], cs');
berghofe@7020
   188
    val intr_consts = foldl add_term_consts_2 ([], intr_ts');
berghofe@7020
   189
    fun unify (env, (cname, cT)) =
berghofe@7020
   190
      let val consts = map snd (filter (fn c => fst c = cname) intr_consts)
berghofe@7020
   191
      in foldl (fn ((env', j'), Tp) => (Type.unify tsig j' env' Tp))
berghofe@7020
   192
          (env, (replicate (length consts) cT) ~~ consts)
berghofe@7020
   193
      end;
berghofe@8410
   194
    val (env, _) = foldl unify ((Vartab.empty, i'), rec_consts);
berghofe@8410
   195
    fun typ_subst_TVars_2 env T = let val T' = typ_subst_TVars_Vartab env T
berghofe@7020
   196
      in if T = T' then T else typ_subst_TVars_2 env T' end;
berghofe@7020
   197
    val subst = fst o Type.freeze_thaw o
berghofe@7020
   198
      (map_term_types (typ_subst_TVars_2 env))
berghofe@7020
   199
berghofe@7020
   200
  in (map subst cs', map subst intr_ts')
berghofe@7020
   201
  end) handle Type.TUNIFY =>
berghofe@7020
   202
    (warning "Occurrences of recursive constant have non-unifiable types"; (cs, intr_ts));
berghofe@7020
   203
berghofe@7020
   204
wenzelm@10735
   205
(*make injections used in mutually recursive definitions*)
berghofe@5094
   206
fun mk_inj cs sumT c x =
berghofe@5094
   207
  let
berghofe@5094
   208
    fun mk_inj' T n i =
berghofe@5094
   209
      if n = 1 then x else
berghofe@5094
   210
      let val n2 = n div 2;
berghofe@5094
   211
          val Type (_, [T1, T2]) = T
berghofe@5094
   212
      in
berghofe@5094
   213
        if i <= n2 then
berghofe@5094
   214
          Const ("Inl", T1 --> T) $ (mk_inj' T1 n2 i)
berghofe@5094
   215
        else
berghofe@5094
   216
          Const ("Inr", T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
berghofe@5094
   217
      end
berghofe@5094
   218
  in mk_inj' sumT (length cs) (1 + find_index_eq c cs)
berghofe@5094
   219
  end;
berghofe@5094
   220
wenzelm@10735
   221
(*make "vimage" terms for selecting out components of mutually rec.def*)
berghofe@5094
   222
fun mk_vimage cs sumT t c = if length cs < 2 then t else
berghofe@5094
   223
  let
berghofe@5094
   224
    val cT = HOLogic.dest_setT (fastype_of c);
berghofe@5094
   225
    val vimageT = [cT --> sumT, HOLogic.mk_setT sumT] ---> HOLogic.mk_setT cT
berghofe@5094
   226
  in
berghofe@5094
   227
    Const (vimage_name, vimageT) $
berghofe@5094
   228
      Abs ("y", cT, mk_inj cs sumT c (Bound 0)) $ t
berghofe@5094
   229
  end;
berghofe@5094
   230
wenzelm@6424
   231
wenzelm@6424
   232
wenzelm@10729
   233
(** process rules **)
wenzelm@10729
   234
wenzelm@10729
   235
local
berghofe@5094
   236
wenzelm@10729
   237
fun err_in_rule sg name t msg =
wenzelm@10729
   238
  error (cat_lines ["Ill-formed introduction rule " ^ quote name, Sign.string_of_term sg t, msg]);
wenzelm@10729
   239
wenzelm@10729
   240
fun err_in_prem sg name t p msg =
wenzelm@10729
   241
  error (cat_lines ["Ill-formed premise", Sign.string_of_term sg p,
wenzelm@10729
   242
    "in introduction rule " ^ quote name, Sign.string_of_term sg t, msg]);
berghofe@5094
   243
wenzelm@10729
   244
val bad_concl = "Conclusion of introduction rule must have form \"t : S_i\"";
wenzelm@10729
   245
wenzelm@10729
   246
val atomize_cterm = InductMethod.rewrite_cterm inductive_atomize;
wenzelm@10729
   247
fun full_simplify rews = Simplifier.full_simplify (HOL_basic_ss addsimps rews);
wenzelm@10729
   248
wenzelm@10729
   249
in
berghofe@5094
   250
wenzelm@10729
   251
fun check_rule sg cs ((name, rule), att) =
wenzelm@10729
   252
  let
wenzelm@10729
   253
    val concl = Logic.strip_imp_concl rule;
wenzelm@10729
   254
    val prems = Logic.strip_imp_prems rule;
wenzelm@10729
   255
    val aprems = prems |> map (Thm.term_of o atomize_cterm o Thm.cterm_of sg);
wenzelm@10729
   256
    val arule = Logic.list_implies (aprems, concl);
berghofe@5094
   257
wenzelm@10729
   258
    fun check_prem (prem, aprem) =
wenzelm@10729
   259
      if can HOLogic.dest_Trueprop aprem then ()
wenzelm@10729
   260
      else err_in_prem sg name rule prem "Non-atomic premise";
wenzelm@10729
   261
  in
wenzelm@10729
   262
    (case HOLogic.dest_Trueprop concl of
wenzelm@10729
   263
      (Const ("op :", _) $ t $ u) =>
wenzelm@10729
   264
        if u mem cs then
wenzelm@10729
   265
          if exists (Logic.occs o rpair t) cs then
wenzelm@10729
   266
            err_in_rule sg name rule "Recursion term on left of member symbol"
wenzelm@10729
   267
          else seq check_prem (prems ~~ aprems)
wenzelm@10729
   268
        else err_in_rule sg name rule bad_concl
wenzelm@10729
   269
      | _ => err_in_rule sg name rule bad_concl);
wenzelm@10729
   270
    ((name, arule), att)
wenzelm@10729
   271
  end;
berghofe@5094
   272
wenzelm@10729
   273
val rulify =
wenzelm@10804
   274
  standard o Tactic.norm_hhf o
wenzelm@10729
   275
  full_simplify inductive_rulify2 o full_simplify inductive_rulify1 o
wenzelm@10729
   276
  full_simplify inductive_conj;
wenzelm@10729
   277
wenzelm@10729
   278
end;
wenzelm@10729
   279
berghofe@5094
   280
wenzelm@6424
   281
wenzelm@10735
   282
(** properties of (co)inductive sets **)
berghofe@5094
   283
wenzelm@10735
   284
(* elimination rules *)
berghofe@5094
   285
wenzelm@8375
   286
fun mk_elims cs cTs params intr_ts intr_names =
berghofe@5094
   287
  let
berghofe@5094
   288
    val used = foldr add_term_names (intr_ts, []);
berghofe@5094
   289
    val [aname, pname] = variantlist (["a", "P"], used);
berghofe@5094
   290
    val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
berghofe@5094
   291
berghofe@5094
   292
    fun dest_intr r =
berghofe@5094
   293
      let val Const ("op :", _) $ t $ u =
berghofe@5094
   294
        HOLogic.dest_Trueprop (Logic.strip_imp_concl r)
berghofe@5094
   295
      in (u, t, Logic.strip_imp_prems r) end;
berghofe@5094
   296
wenzelm@8380
   297
    val intrs = map dest_intr intr_ts ~~ intr_names;
berghofe@5094
   298
berghofe@5094
   299
    fun mk_elim (c, T) =
berghofe@5094
   300
      let
berghofe@5094
   301
        val a = Free (aname, T);
berghofe@5094
   302
berghofe@5094
   303
        fun mk_elim_prem (_, t, ts) =
berghofe@5094
   304
          list_all_free (map dest_Free ((foldr add_term_frees (t::ts, [])) \\ params),
berghofe@5094
   305
            Logic.list_implies (HOLogic.mk_Trueprop (HOLogic.mk_eq (a, t)) :: ts, P));
wenzelm@8375
   306
        val c_intrs = (filter (equal c o #1 o #1) intrs);
berghofe@5094
   307
      in
wenzelm@8375
   308
        (Logic.list_implies (HOLogic.mk_Trueprop (HOLogic.mk_mem (a, c)) ::
wenzelm@8375
   309
          map mk_elim_prem (map #1 c_intrs), P), map #2 c_intrs)
berghofe@5094
   310
      end
berghofe@5094
   311
  in
berghofe@5094
   312
    map mk_elim (cs ~~ cTs)
berghofe@5094
   313
  end;
wenzelm@9598
   314
wenzelm@6424
   315
wenzelm@10735
   316
(* premises and conclusions of induction rules *)
berghofe@5094
   317
berghofe@5094
   318
fun mk_indrule cs cTs params intr_ts =
berghofe@5094
   319
  let
berghofe@5094
   320
    val used = foldr add_term_names (intr_ts, []);
berghofe@5094
   321
berghofe@5094
   322
    (* predicates for induction rule *)
berghofe@5094
   323
berghofe@5094
   324
    val preds = map Free (variantlist (if length cs < 2 then ["P"] else
berghofe@5094
   325
      map (fn i => "P" ^ string_of_int i) (1 upto length cs), used) ~~
berghofe@5094
   326
        map (fn T => T --> HOLogic.boolT) cTs);
berghofe@5094
   327
berghofe@5094
   328
    (* transform an introduction rule into a premise for induction rule *)
berghofe@5094
   329
berghofe@5094
   330
    fun mk_ind_prem r =
berghofe@5094
   331
      let
berghofe@5094
   332
        val frees = map dest_Free ((add_term_frees (r, [])) \\ params);
berghofe@5094
   333
berghofe@7710
   334
        val pred_of = curry (Library.gen_assoc (op aconv)) (cs ~~ preds);
berghofe@5094
   335
berghofe@7710
   336
        fun subst (s as ((m as Const ("op :", T)) $ t $ u)) =
berghofe@7710
   337
              (case pred_of u of
berghofe@7710
   338
                  None => (m $ fst (subst t) $ fst (subst u), None)
wenzelm@10735
   339
                | Some P => (HOLogic.mk_binop inductive_conj_name (s, P $ t), Some (s, P $ t)))
berghofe@7710
   340
          | subst s =
berghofe@7710
   341
              (case pred_of s of
berghofe@7710
   342
                  Some P => (HOLogic.mk_binop "op Int"
berghofe@7710
   343
                    (s, HOLogic.Collect_const (HOLogic.dest_setT
berghofe@7710
   344
                      (fastype_of s)) $ P), None)
berghofe@7710
   345
                | None => (case s of
berghofe@7710
   346
                     (t $ u) => (fst (subst t) $ fst (subst u), None)
berghofe@7710
   347
                   | (Abs (a, T, t)) => (Abs (a, T, fst (subst t)), None)
berghofe@7710
   348
                   | _ => (s, None)));
berghofe@7710
   349
berghofe@7710
   350
        fun mk_prem (s, prems) = (case subst s of
berghofe@7710
   351
              (_, Some (t, u)) => t :: u :: prems
berghofe@7710
   352
            | (t, _) => t :: prems);
wenzelm@9598
   353
berghofe@5094
   354
        val Const ("op :", _) $ t $ u =
berghofe@5094
   355
          HOLogic.dest_Trueprop (Logic.strip_imp_concl r)
berghofe@5094
   356
berghofe@5094
   357
      in list_all_free (frees,
berghofe@7710
   358
           Logic.list_implies (map HOLogic.mk_Trueprop (foldr mk_prem
berghofe@5094
   359
             (map HOLogic.dest_Trueprop (Logic.strip_imp_prems r), [])),
berghofe@7710
   360
               HOLogic.mk_Trueprop (the (pred_of u) $ t)))
berghofe@5094
   361
      end;
berghofe@5094
   362
berghofe@5094
   363
    val ind_prems = map mk_ind_prem intr_ts;
berghofe@5094
   364
berghofe@5094
   365
    (* make conclusions for induction rules *)
berghofe@5094
   366
berghofe@5094
   367
    fun mk_ind_concl ((c, P), (ts, x)) =
berghofe@5094
   368
      let val T = HOLogic.dest_setT (fastype_of c);
berghofe@5094
   369
          val Ts = HOLogic.prodT_factors T;
berghofe@5094
   370
          val (frees, x') = foldr (fn (T', (fs, s)) =>
berghofe@5094
   371
            ((Free (s, T'))::fs, bump_string s)) (Ts, ([], x));
berghofe@5094
   372
          val tuple = HOLogic.mk_tuple T frees;
berghofe@5094
   373
      in ((HOLogic.mk_binop "op -->"
berghofe@5094
   374
        (HOLogic.mk_mem (tuple, c), P $ tuple))::ts, x')
berghofe@5094
   375
      end;
berghofe@5094
   376
berghofe@7710
   377
    val mutual_ind_concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
berghofe@5094
   378
        (fst (foldr mk_ind_concl (cs ~~ preds, ([], "xa")))))
berghofe@5094
   379
berghofe@5094
   380
  in (preds, ind_prems, mutual_ind_concl)
berghofe@5094
   381
  end;
berghofe@5094
   382
wenzelm@6424
   383
wenzelm@10735
   384
(* prepare cases and induct rules *)
wenzelm@8316
   385
wenzelm@8316
   386
(*
wenzelm@8316
   387
  transform mutual rule:
wenzelm@8316
   388
    HH ==> (x1:A1 --> P1 x1) & ... & (xn:An --> Pn xn)
wenzelm@8316
   389
  into i-th projection:
wenzelm@8316
   390
    xi:Ai ==> HH ==> Pi xi
wenzelm@8316
   391
*)
wenzelm@8316
   392
wenzelm@8316
   393
fun project_rules [name] rule = [(name, rule)]
wenzelm@8316
   394
  | project_rules names mutual_rule =
wenzelm@8316
   395
      let
wenzelm@8316
   396
        val n = length names;
wenzelm@8316
   397
        fun proj i =
wenzelm@8316
   398
          (if i < n then (fn th => th RS conjunct1) else I)
wenzelm@8316
   399
            (Library.funpow (i - 1) (fn th => th RS conjunct2) mutual_rule)
wenzelm@8316
   400
            RS mp |> Thm.permute_prems 0 ~1 |> Drule.standard;
wenzelm@8316
   401
      in names ~~ map proj (1 upto n) end;
wenzelm@8316
   402
wenzelm@8375
   403
fun add_cases_induct no_elim no_ind names elims induct induct_cases =
wenzelm@8316
   404
  let
wenzelm@9405
   405
    fun cases_spec (name, elim) thy =
wenzelm@9405
   406
      thy
wenzelm@9405
   407
      |> Theory.add_path (Sign.base_name name)
wenzelm@10279
   408
      |> (#1 o PureThy.add_thms [(("cases", elim), [InductAttrib.cases_set_global name])])
wenzelm@9405
   409
      |> Theory.parent_path;
wenzelm@8375
   410
    val cases_specs = if no_elim then [] else map2 cases_spec (names, elims);
wenzelm@8316
   411
wenzelm@9405
   412
    fun induct_spec (name, th) = (#1 o PureThy.add_thms
wenzelm@10279
   413
      [(("", th), [RuleCases.case_names induct_cases, InductAttrib.induct_set_global name])]);
wenzelm@8401
   414
    val induct_specs = if no_ind then [] else map induct_spec (project_rules names induct);
wenzelm@9405
   415
  in Library.apply (cases_specs @ induct_specs) end;
wenzelm@8316
   416
wenzelm@8316
   417
wenzelm@8316
   418
wenzelm@10735
   419
(** proofs for (co)inductive sets **)
wenzelm@6424
   420
wenzelm@10735
   421
(* prove monotonicity -- NOT subject to quick_and_dirty! *)
berghofe@5094
   422
berghofe@5094
   423
fun prove_mono setT fp_fun monos thy =
wenzelm@10735
   424
 (message "  Proving monotonicity ...";
wenzelm@10735
   425
  Goals.prove_goalw_cterm []      (*NO SkipProof.prove_goalw_cterm here!*)
wenzelm@10735
   426
    (Thm.cterm_of (Theory.sign_of thy) (HOLogic.mk_Trueprop
berghofe@5094
   427
      (Const (mono_name, (setT --> setT) --> HOLogic.boolT) $ fp_fun)))
wenzelm@10735
   428
    (fn _ => [rtac monoI 1, REPEAT (ares_tac (get_monos thy @ flat (map mk_mono monos)) 1)]));
berghofe@5094
   429
wenzelm@6424
   430
wenzelm@10735
   431
(* prove introduction rules *)
berghofe@5094
   432
berghofe@5094
   433
fun prove_intrs coind mono fp_def intr_ts con_defs rec_sets_defs thy =
berghofe@5094
   434
  let
wenzelm@10735
   435
    val _ = clean_message "  Proving the introduction rules ...";
berghofe@5094
   436
berghofe@5094
   437
    val unfold = standard (mono RS (fp_def RS
nipkow@10186
   438
      (if coind then def_gfp_unfold else def_lfp_unfold)));
berghofe@5094
   439
berghofe@5094
   440
    fun select_disj 1 1 = []
berghofe@5094
   441
      | select_disj _ 1 = [rtac disjI1]
berghofe@5094
   442
      | select_disj n i = (rtac disjI2)::(select_disj (n - 1) (i - 1));
berghofe@5094
   443
wenzelm@10735
   444
    val intrs = map (fn (i, intr) => SkipProof.prove_goalw_cterm thy rec_sets_defs
wenzelm@10735
   445
      (Thm.cterm_of (Theory.sign_of thy) intr) (fn prems =>
berghofe@5094
   446
       [(*insert prems and underlying sets*)
berghofe@5094
   447
       cut_facts_tac prems 1,
berghofe@5094
   448
       stac unfold 1,
berghofe@5094
   449
       REPEAT (resolve_tac [vimageI2, CollectI] 1),
berghofe@5094
   450
       (*Now 1-2 subgoals: the disjunction, perhaps equality.*)
berghofe@5094
   451
       EVERY1 (select_disj (length intr_ts) i),
berghofe@5094
   452
       (*Not ares_tac, since refl must be tried before any equality assumptions;
berghofe@5094
   453
         backtracking may occur if the premises have extra variables!*)
wenzelm@10735
   454
       DEPTH_SOLVE_1 (resolve_tac [refl, exI, conjI] 1 APPEND assume_tac 1),
berghofe@5094
   455
       (*Now solve the equations like Inl 0 = Inl ?b2*)
berghofe@5094
   456
       rewrite_goals_tac con_defs,
wenzelm@10729
   457
       REPEAT (rtac refl 1)])
wenzelm@10729
   458
      |> rulify) (1 upto (length intr_ts) ~~ intr_ts)
berghofe@5094
   459
berghofe@5094
   460
  in (intrs, unfold) end;
berghofe@5094
   461
wenzelm@6424
   462
wenzelm@10735
   463
(* prove elimination rules *)
berghofe@5094
   464
wenzelm@8375
   465
fun prove_elims cs cTs params intr_ts intr_names unfold rec_sets_defs thy =
berghofe@5094
   466
  let
wenzelm@10735
   467
    val _ = clean_message "  Proving the elimination rules ...";
berghofe@5094
   468
berghofe@7710
   469
    val rules1 = [CollectE, disjE, make_elim vimageD, exE];
wenzelm@10735
   470
    val rules2 = [conjE, Inl_neq_Inr, Inr_neq_Inl] @ map make_elim [Inl_inject, Inr_inject];
wenzelm@8375
   471
  in
wenzelm@10735
   472
    map (fn (t, cases) => SkipProof.prove_goalw_cterm thy rec_sets_defs
wenzelm@10735
   473
      (Thm.cterm_of (Theory.sign_of thy) t) (fn prems =>
berghofe@5094
   474
        [cut_facts_tac [hd prems] 1,
berghofe@5094
   475
         dtac (unfold RS subst) 1,
berghofe@5094
   476
         REPEAT (FIRSTGOAL (eresolve_tac rules1)),
berghofe@5094
   477
         REPEAT (FIRSTGOAL (eresolve_tac rules2)),
wenzelm@10735
   478
         EVERY (map (fn prem => DEPTH_SOLVE_1 (ares_tac [prem, conjI] 1)) (tl prems))])
wenzelm@10729
   479
      |> rulify
wenzelm@8375
   480
      |> RuleCases.name cases)
wenzelm@8375
   481
      (mk_elims cs cTs params intr_ts intr_names)
wenzelm@8375
   482
  end;
berghofe@5094
   483
wenzelm@6424
   484
wenzelm@10735
   485
(* derivation of simplified elimination rules *)
berghofe@5094
   486
berghofe@5094
   487
(*Applies freeness of the given constructors, which *must* be unfolded by
wenzelm@9598
   488
  the given defs.  Cannot simply use the local con_defs because con_defs=[]
wenzelm@10735
   489
  for inference systems. (??) *)
berghofe@5094
   490
wenzelm@7107
   491
(*cprop should have the form t:Si where Si is an inductive set*)
wenzelm@9598
   492
wenzelm@10735
   493
val mk_cases_err = "mk_cases: proposition not of form \"t : S_i\"";
wenzelm@9598
   494
wenzelm@9598
   495
fun mk_cases_i elims ss cprop =
wenzelm@7107
   496
  let
wenzelm@7107
   497
    val prem = Thm.assume cprop;
wenzelm@9598
   498
    val tac = ALLGOALS (InductMethod.simp_case_tac false ss) THEN prune_params_tac;
wenzelm@9298
   499
    fun mk_elim rl = Drule.standard (Tactic.rule_by_tactic tac (prem RS rl));
wenzelm@7107
   500
  in
wenzelm@7107
   501
    (case get_first (try mk_elim) elims of
wenzelm@7107
   502
      Some r => r
wenzelm@7107
   503
    | None => error (Pretty.string_of (Pretty.block
wenzelm@9598
   504
        [Pretty.str mk_cases_err, Pretty.fbrk, Display.pretty_cterm cprop])))
wenzelm@7107
   505
  end;
wenzelm@7107
   506
paulson@6141
   507
fun mk_cases elims s =
wenzelm@9598
   508
  mk_cases_i elims (simpset()) (Thm.read_cterm (Thm.sign_of_thm (hd elims)) (s, propT));
wenzelm@9598
   509
wenzelm@9598
   510
fun smart_mk_cases thy ss cprop =
wenzelm@9598
   511
  let
wenzelm@9598
   512
    val c = #1 (Term.dest_Const (Term.head_of (#2 (HOLogic.dest_mem (HOLogic.dest_Trueprop
wenzelm@9598
   513
      (Logic.strip_imp_concl (Thm.term_of cprop))))))) handle TERM _ => error mk_cases_err;
wenzelm@9598
   514
    val (_, {elims, ...}) = the_inductive thy c;
wenzelm@9598
   515
  in mk_cases_i elims ss cprop end;
wenzelm@7107
   516
wenzelm@7107
   517
wenzelm@7107
   518
(* inductive_cases(_i) *)
wenzelm@7107
   519
wenzelm@7107
   520
fun gen_inductive_cases prep_att prep_const prep_prop
wenzelm@9598
   521
    (((name, raw_atts), raw_props), comment) thy =
wenzelm@9598
   522
  let
wenzelm@9598
   523
    val ss = Simplifier.simpset_of thy;
wenzelm@9598
   524
    val sign = Theory.sign_of thy;
wenzelm@9598
   525
    val cprops = map (Thm.cterm_of sign o prep_prop (ProofContext.init thy)) raw_props;
wenzelm@9598
   526
    val atts = map (prep_att thy) raw_atts;
wenzelm@9598
   527
    val thms = map (smart_mk_cases thy ss) cprops;
wenzelm@9598
   528
  in thy |> IsarThy.have_theorems_i [(((name, atts), map Thm.no_attributes thms), comment)] end;
berghofe@5094
   529
wenzelm@7107
   530
val inductive_cases =
wenzelm@7107
   531
  gen_inductive_cases Attrib.global_attribute Sign.intern_const ProofContext.read_prop;
wenzelm@7107
   532
wenzelm@7107
   533
val inductive_cases_i = gen_inductive_cases (K I) (K I) ProofContext.cert_prop;
wenzelm@7107
   534
wenzelm@6424
   535
wenzelm@9598
   536
(* mk_cases_meth *)
wenzelm@9598
   537
wenzelm@9598
   538
fun mk_cases_meth (ctxt, raw_props) =
wenzelm@9598
   539
  let
wenzelm@9598
   540
    val thy = ProofContext.theory_of ctxt;
wenzelm@9598
   541
    val ss = Simplifier.get_local_simpset ctxt;
wenzelm@9598
   542
    val cprops = map (Thm.cterm_of (Theory.sign_of thy) o ProofContext.read_prop ctxt) raw_props;
wenzelm@10743
   543
  in Method.erule 0 (map (smart_mk_cases thy ss) cprops) end;
wenzelm@9598
   544
wenzelm@9598
   545
val mk_cases_args = Method.syntax (Scan.lift (Scan.repeat1 Args.name));
wenzelm@9598
   546
wenzelm@9598
   547
wenzelm@10735
   548
(* prove induction rule *)
berghofe@5094
   549
berghofe@5094
   550
fun prove_indrule cs cTs sumT rec_const params intr_ts mono
berghofe@5094
   551
    fp_def rec_sets_defs thy =
berghofe@5094
   552
  let
wenzelm@10735
   553
    val _ = clean_message "  Proving the induction rule ...";
berghofe@5094
   554
wenzelm@6394
   555
    val sign = Theory.sign_of thy;
berghofe@5094
   556
berghofe@7293
   557
    val sum_case_rewrites = (case ThyInfo.lookup_theory "Datatype" of
berghofe@7293
   558
        None => []
berghofe@7293
   559
      | Some thy' => map mk_meta_eq (PureThy.get_thms thy' "sum.cases"));
berghofe@7293
   560
berghofe@5094
   561
    val (preds, ind_prems, mutual_ind_concl) = mk_indrule cs cTs params intr_ts;
berghofe@5094
   562
berghofe@5094
   563
    (* make predicate for instantiation of abstract induction rule *)
berghofe@5094
   564
berghofe@5094
   565
    fun mk_ind_pred _ [P] = P
berghofe@5094
   566
      | mk_ind_pred T Ps =
berghofe@5094
   567
         let val n = (length Ps) div 2;
berghofe@5094
   568
             val Type (_, [T1, T2]) = T
berghofe@7293
   569
         in Const ("Datatype.sum.sum_case",
berghofe@5094
   570
           [T1 --> HOLogic.boolT, T2 --> HOLogic.boolT, T] ---> HOLogic.boolT) $
berghofe@5094
   571
             mk_ind_pred T1 (take (n, Ps)) $ mk_ind_pred T2 (drop (n, Ps))
berghofe@5094
   572
         end;
berghofe@5094
   573
berghofe@5094
   574
    val ind_pred = mk_ind_pred sumT preds;
berghofe@5094
   575
berghofe@5094
   576
    val ind_concl = HOLogic.mk_Trueprop
berghofe@5094
   577
      (HOLogic.all_const sumT $ Abs ("x", sumT, HOLogic.mk_binop "op -->"
berghofe@5094
   578
        (HOLogic.mk_mem (Bound 0, rec_const), ind_pred $ Bound 0)));
berghofe@5094
   579
berghofe@5094
   580
    (* simplification rules for vimage and Collect *)
berghofe@5094
   581
berghofe@5094
   582
    val vimage_simps = if length cs < 2 then [] else
wenzelm@10735
   583
      map (fn c => SkipProof.prove_goalw_cterm thy [] (Thm.cterm_of sign
berghofe@5094
   584
        (HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@5094
   585
          (mk_vimage cs sumT (HOLogic.Collect_const sumT $ ind_pred) c,
berghofe@5094
   586
           HOLogic.Collect_const (HOLogic.dest_setT (fastype_of c)) $
berghofe@5094
   587
             nth_elem (find_index_eq c cs, preds)))))
wenzelm@10735
   588
        (fn _ => [rtac vimage_Collect 1, rewrite_goals_tac sum_case_rewrites, rtac refl 1])) cs;
berghofe@5094
   589
wenzelm@10735
   590
    val induct = SkipProof.prove_goalw_cterm thy [inductive_conj_def] (Thm.cterm_of sign
berghofe@5094
   591
      (Logic.list_implies (ind_prems, ind_concl))) (fn prems =>
berghofe@5094
   592
        [rtac (impI RS allI) 1,
nipkow@10202
   593
         DETERM (etac (mono RS (fp_def RS def_lfp_induct)) 1),
berghofe@7710
   594
         rewrite_goals_tac (map mk_meta_eq (vimage_Int::Int_Collect::vimage_simps)),
berghofe@5094
   595
         fold_goals_tac rec_sets_defs,
berghofe@5094
   596
         (*This CollectE and disjE separates out the introduction rules*)
berghofe@7710
   597
         REPEAT (FIRSTGOAL (eresolve_tac [CollectE, disjE, exE])),
berghofe@5094
   598
         (*Now break down the individual cases.  No disjE here in case
berghofe@5094
   599
           some premise involves disjunction.*)
berghofe@7710
   600
         REPEAT (FIRSTGOAL (etac conjE ORELSE' hyp_subst_tac)),
berghofe@7293
   601
         rewrite_goals_tac sum_case_rewrites,
berghofe@5094
   602
         EVERY (map (fn prem =>
berghofe@5149
   603
           DEPTH_SOLVE_1 (ares_tac [prem, conjI, refl] 1)) prems)]);
berghofe@5094
   604
wenzelm@10735
   605
    val lemma = SkipProof.prove_goalw_cterm thy rec_sets_defs (Thm.cterm_of sign
berghofe@5094
   606
      (Logic.mk_implies (ind_concl, mutual_ind_concl))) (fn prems =>
berghofe@5094
   607
        [cut_facts_tac prems 1,
berghofe@5094
   608
         REPEAT (EVERY
berghofe@5094
   609
           [REPEAT (resolve_tac [conjI, impI] 1),
berghofe@5094
   610
            TRY (dtac vimageD 1), etac allE 1, dtac mp 1, atac 1,
berghofe@7293
   611
            rewrite_goals_tac sum_case_rewrites,
berghofe@5094
   612
            atac 1])])
berghofe@5094
   613
wenzelm@10729
   614
  in standard (split_rule (induct RS lemma)) end;
berghofe@5094
   615
wenzelm@6424
   616
wenzelm@6424
   617
wenzelm@10735
   618
(** specification of (co)inductive sets **)
berghofe@5094
   619
wenzelm@10729
   620
fun cond_declare_consts declare_consts cs paramTs cnames =
wenzelm@10729
   621
  if declare_consts then
wenzelm@10729
   622
    Theory.add_consts_i (map (fn (c, n) => (n, paramTs ---> fastype_of c, NoSyn)) (cs ~~ cnames))
wenzelm@10729
   623
  else I;
wenzelm@10729
   624
berghofe@9072
   625
fun mk_ind_def declare_consts alt_name coind cs intr_ts monos con_defs thy
berghofe@9072
   626
      params paramTs cTs cnames =
berghofe@5094
   627
  let
berghofe@5094
   628
    val sumT = fold_bal (fn (T, U) => Type ("+", [T, U])) cTs;
berghofe@5094
   629
    val setT = HOLogic.mk_setT sumT;
berghofe@5094
   630
wenzelm@10735
   631
    val fp_name = if coind then gfp_name else lfp_name;
berghofe@5094
   632
berghofe@5149
   633
    val used = foldr add_term_names (intr_ts, []);
berghofe@5149
   634
    val [sname, xname] = variantlist (["S", "x"], used);
berghofe@5149
   635
berghofe@5094
   636
    (* transform an introduction rule into a conjunction  *)
berghofe@5094
   637
    (*   [| t : ... S_i ... ; ... |] ==> u : S_j          *)
berghofe@5094
   638
    (* is transformed into                                *)
berghofe@5094
   639
    (*   x = Inj_j u & t : ... Inj_i -`` S ... & ...      *)
berghofe@5094
   640
berghofe@5094
   641
    fun transform_rule r =
berghofe@5094
   642
      let
berghofe@5094
   643
        val frees = map dest_Free ((add_term_frees (r, [])) \\ params);
berghofe@5149
   644
        val subst = subst_free
berghofe@5149
   645
          (cs ~~ (map (mk_vimage cs sumT (Free (sname, setT))) cs));
berghofe@5094
   646
        val Const ("op :", _) $ t $ u =
berghofe@5094
   647
          HOLogic.dest_Trueprop (Logic.strip_imp_concl r)
berghofe@5094
   648
berghofe@5094
   649
      in foldr (fn ((x, T), P) => HOLogic.mk_exists (x, T, P))
berghofe@7710
   650
        (frees, foldr1 HOLogic.mk_conj
berghofe@5149
   651
          (((HOLogic.eq_const sumT) $ Free (xname, sumT) $ (mk_inj cs sumT u t))::
berghofe@5094
   652
            (map (subst o HOLogic.dest_Trueprop)
berghofe@5094
   653
              (Logic.strip_imp_prems r))))
berghofe@5094
   654
      end
berghofe@5094
   655
berghofe@5094
   656
    (* make a disjunction of all introduction rules *)
berghofe@5094
   657
berghofe@5149
   658
    val fp_fun = absfree (sname, setT, (HOLogic.Collect_const sumT) $
berghofe@7710
   659
      absfree (xname, sumT, foldr1 HOLogic.mk_disj (map transform_rule intr_ts)));
berghofe@5094
   660
berghofe@5094
   661
    (* add definiton of recursive sets to theory *)
berghofe@5094
   662
berghofe@5094
   663
    val rec_name = if alt_name = "" then space_implode "_" cnames else alt_name;
wenzelm@6394
   664
    val full_rec_name = Sign.full_name (Theory.sign_of thy) rec_name;
berghofe@5094
   665
berghofe@5094
   666
    val rec_const = list_comb
berghofe@5094
   667
      (Const (full_rec_name, paramTs ---> setT), params);
berghofe@5094
   668
berghofe@5094
   669
    val fp_def_term = Logic.mk_equals (rec_const,
wenzelm@10735
   670
      Const (fp_name, (setT --> setT) --> setT) $ fp_fun);
berghofe@5094
   671
berghofe@5094
   672
    val def_terms = fp_def_term :: (if length cs < 2 then [] else
berghofe@5094
   673
      map (fn c => Logic.mk_equals (c, mk_vimage cs sumT rec_const c)) cs);
berghofe@5094
   674
wenzelm@8433
   675
    val (thy', [fp_def :: rec_sets_defs]) =
wenzelm@8433
   676
      thy
wenzelm@10729
   677
      |> cond_declare_consts declare_consts cs paramTs cnames
wenzelm@8433
   678
      |> (if length cs < 2 then I
wenzelm@8433
   679
          else Theory.add_consts_i [(rec_name, paramTs ---> setT, NoSyn)])
wenzelm@8433
   680
      |> Theory.add_path rec_name
wenzelm@9315
   681
      |> PureThy.add_defss_i false [(("defs", def_terms), [])];
berghofe@5094
   682
berghofe@9072
   683
    val mono = prove_mono setT fp_fun monos thy'
berghofe@5094
   684
wenzelm@10735
   685
  in (thy', mono, fp_def, rec_sets_defs, rec_const, sumT) end;
berghofe@5094
   686
berghofe@9072
   687
fun add_ind_def verbose declare_consts alt_name coind no_elim no_ind cs
berghofe@9072
   688
    atts intros monos con_defs thy params paramTs cTs cnames induct_cases =
berghofe@9072
   689
  let
wenzelm@10735
   690
    val _ =
wenzelm@10735
   691
      if verbose then message ("Proofs for " ^ coind_prefix coind ^ "inductive set(s) " ^
wenzelm@10735
   692
        commas_quote cnames) else ();
berghofe@9072
   693
berghofe@9072
   694
    val ((intr_names, intr_ts), intr_atts) = apfst split_list (split_list intros);
berghofe@9072
   695
wenzelm@9939
   696
    val (thy1, mono, fp_def, rec_sets_defs, rec_const, sumT) =
berghofe@9072
   697
      mk_ind_def declare_consts alt_name coind cs intr_ts monos con_defs thy
berghofe@9072
   698
        params paramTs cTs cnames;
berghofe@9072
   699
berghofe@5094
   700
    val (intrs, unfold) = prove_intrs coind mono fp_def intr_ts con_defs
wenzelm@9939
   701
      rec_sets_defs thy1;
berghofe@5094
   702
    val elims = if no_elim then [] else
wenzelm@9939
   703
      prove_elims cs cTs params intr_ts intr_names unfold rec_sets_defs thy1;
wenzelm@8312
   704
    val raw_induct = if no_ind then Drule.asm_rl else
berghofe@5094
   705
      if coind then standard (rule_by_tactic
oheimb@5553
   706
        (rewrite_tac [mk_meta_eq vimage_Un] THEN
berghofe@5094
   707
          fold_tac rec_sets_defs) (mono RS (fp_def RS def_Collect_coinduct)))
berghofe@5094
   708
      else
berghofe@5094
   709
        prove_indrule cs cTs sumT rec_const params intr_ts mono fp_def
wenzelm@9939
   710
          rec_sets_defs thy1;
berghofe@5108
   711
    val induct = if coind orelse no_ind orelse length cs > 1 then raw_induct
berghofe@5094
   712
      else standard (raw_induct RSN (2, rev_mp));
berghofe@5094
   713
wenzelm@9939
   714
    val (thy2, intrs') =
wenzelm@9939
   715
      thy1 |> PureThy.add_thms ((intr_names ~~ intrs) ~~ intr_atts);
wenzelm@10735
   716
    val (thy3, ([intrs'', elims'], [induct'])) =
wenzelm@10735
   717
      thy2
wenzelm@10735
   718
      |> PureThy.add_thmss [(("intros", intrs'), atts), (("elims", elims), [])]
wenzelm@10735
   719
      |>>> PureThy.add_thms
wenzelm@10735
   720
        [((coind_prefix coind ^ "induct", rulify induct), [RuleCases.case_names induct_cases])]
wenzelm@8433
   721
      |>> Theory.parent_path;
wenzelm@9939
   722
  in (thy3,
wenzelm@10735
   723
    {defs = fp_def :: rec_sets_defs,
berghofe@5094
   724
     mono = mono,
berghofe@5094
   725
     unfold = unfold,
wenzelm@9939
   726
     intrs = intrs'',
wenzelm@7798
   727
     elims = elims',
wenzelm@7798
   728
     mk_cases = mk_cases elims',
wenzelm@10729
   729
     raw_induct = rulify raw_induct,
wenzelm@7798
   730
     induct = induct'})
berghofe@5094
   731
  end;
berghofe@5094
   732
wenzelm@6424
   733
wenzelm@10735
   734
(* external interfaces *)
berghofe@5094
   735
wenzelm@10735
   736
fun try_term f msg sign t =
wenzelm@10735
   737
  (case Library.try f t of
wenzelm@10735
   738
    Some x => x
wenzelm@10735
   739
  | None => error (msg ^ Sign.string_of_term sign t));
berghofe@5094
   740
berghofe@5094
   741
fun add_inductive_i verbose declare_consts alt_name coind no_elim no_ind cs
wenzelm@10729
   742
    atts pre_intros monos con_defs thy =
berghofe@5094
   743
  let
wenzelm@6424
   744
    val _ = Theory.requires thy "Inductive" (coind_prefix coind ^ "inductive definitions");
wenzelm@6394
   745
    val sign = Theory.sign_of thy;
berghofe@5094
   746
berghofe@5094
   747
    (*parameters should agree for all mutually recursive components*)
berghofe@5094
   748
    val (_, params) = strip_comb (hd cs);
wenzelm@10735
   749
    val paramTs = map (try_term (snd o dest_Free) "Parameter in recursive\
berghofe@5094
   750
      \ component is not a free variable: " sign) params;
berghofe@5094
   751
wenzelm@10735
   752
    val cTs = map (try_term (HOLogic.dest_setT o fastype_of)
berghofe@5094
   753
      "Recursive component not of type set: " sign) cs;
berghofe@5094
   754
wenzelm@10735
   755
    val full_cnames = map (try_term (fst o dest_Const o head_of)
berghofe@5094
   756
      "Recursive set not previously declared as constant: " sign) cs;
wenzelm@6437
   757
    val cnames = map Sign.base_name full_cnames;
berghofe@5094
   758
wenzelm@10729
   759
    val save_sign =
wenzelm@10729
   760
      thy |> Theory.copy |> cond_declare_consts declare_consts cs paramTs cnames |> Theory.sign_of;
wenzelm@10729
   761
    val intros = map (check_rule save_sign cs) pre_intros;
wenzelm@8401
   762
    val induct_cases = map (#1 o #1) intros;
wenzelm@6437
   763
wenzelm@9405
   764
    val (thy1, result as {elims, induct, ...}) =
wenzelm@10735
   765
      add_ind_def verbose declare_consts alt_name coind no_elim no_ind cs atts intros monos
wenzelm@8401
   766
        con_defs thy params paramTs cTs cnames induct_cases;
wenzelm@8307
   767
    val thy2 = thy1
wenzelm@8307
   768
      |> put_inductives full_cnames ({names = full_cnames, coind = coind}, result)
wenzelm@9405
   769
      |> add_cases_induct no_elim (no_ind orelse coind) full_cnames elims induct induct_cases;
wenzelm@6437
   770
  in (thy2, result) end;
berghofe@5094
   771
wenzelm@6521
   772
fun add_inductive verbose coind c_strings srcs intro_srcs raw_monos raw_con_defs thy =
berghofe@5094
   773
  let
wenzelm@6394
   774
    val sign = Theory.sign_of thy;
wenzelm@8100
   775
    val cs = map (term_of o Thm.read_cterm sign o rpair HOLogic.termT) c_strings;
wenzelm@6424
   776
wenzelm@6521
   777
    val atts = map (Attrib.global_attribute thy) srcs;
wenzelm@6424
   778
    val intr_names = map (fst o fst) intro_srcs;
wenzelm@9405
   779
    fun read_rule s = Thm.read_cterm sign (s, propT)
wenzelm@9405
   780
      handle ERROR => error ("The error(s) above occurred for " ^ s);
wenzelm@9405
   781
    val intr_ts = map (Thm.term_of o read_rule o snd o fst) intro_srcs;
wenzelm@6424
   782
    val intr_atts = map (map (Attrib.global_attribute thy) o snd) intro_srcs;
berghofe@7020
   783
    val (cs', intr_ts') = unify_consts sign cs intr_ts;
berghofe@5094
   784
wenzelm@6424
   785
    val ((thy', con_defs), monos) = thy
wenzelm@6424
   786
      |> IsarThy.apply_theorems raw_monos
wenzelm@6424
   787
      |> apfst (IsarThy.apply_theorems raw_con_defs);
wenzelm@6424
   788
  in
berghofe@7020
   789
    add_inductive_i verbose false "" coind false false cs'
berghofe@7020
   790
      atts ((intr_names ~~ intr_ts') ~~ intr_atts) monos con_defs thy'
berghofe@5094
   791
  end;
berghofe@5094
   792
wenzelm@6424
   793
wenzelm@6424
   794
wenzelm@6437
   795
(** package setup **)
wenzelm@6437
   796
wenzelm@6437
   797
(* setup theory *)
wenzelm@6437
   798
wenzelm@8634
   799
val setup =
wenzelm@8634
   800
 [InductiveData.init,
wenzelm@9625
   801
  Method.add_methods [("ind_cases", mk_cases_meth oo mk_cases_args,
wenzelm@9598
   802
    "dynamic case analysis on sets")],
wenzelm@9893
   803
  Attrib.add_attributes [("mono", mono_attr, "declaration of monotonicity rule")]];
wenzelm@6437
   804
wenzelm@6437
   805
wenzelm@6437
   806
(* outer syntax *)
wenzelm@6424
   807
wenzelm@6723
   808
local structure P = OuterParse and K = OuterSyntax.Keyword in
wenzelm@6424
   809
wenzelm@6521
   810
fun mk_ind coind (((sets, (atts, intrs)), monos), con_defs) =
wenzelm@6723
   811
  #1 o add_inductive true coind sets atts (map P.triple_swap intrs) monos con_defs;
wenzelm@6424
   812
wenzelm@6424
   813
fun ind_decl coind =
wenzelm@6729
   814
  (Scan.repeat1 P.term --| P.marg_comment) --
wenzelm@9598
   815
  (P.$$$ "intros" |--
wenzelm@7152
   816
    P.!!! (P.opt_attribs -- Scan.repeat1 (P.opt_thm_name ":" -- P.prop --| P.marg_comment))) --
wenzelm@6729
   817
  Scan.optional (P.$$$ "monos" |-- P.!!! P.xthms1 --| P.marg_comment) [] --
wenzelm@6729
   818
  Scan.optional (P.$$$ "con_defs" |-- P.!!! P.xthms1 --| P.marg_comment) []
wenzelm@6424
   819
  >> (Toplevel.theory o mk_ind coind);
wenzelm@6424
   820
wenzelm@6723
   821
val inductiveP =
wenzelm@6723
   822
  OuterSyntax.command "inductive" "define inductive sets" K.thy_decl (ind_decl false);
wenzelm@6723
   823
wenzelm@6723
   824
val coinductiveP =
wenzelm@6723
   825
  OuterSyntax.command "coinductive" "define coinductive sets" K.thy_decl (ind_decl true);
wenzelm@6424
   826
wenzelm@7107
   827
wenzelm@7107
   828
val ind_cases =
wenzelm@9625
   829
  P.opt_thm_name ":" -- Scan.repeat1 P.prop -- P.marg_comment
wenzelm@7107
   830
  >> (Toplevel.theory o inductive_cases);
wenzelm@7107
   831
wenzelm@7107
   832
val inductive_casesP =
wenzelm@9804
   833
  OuterSyntax.command "inductive_cases"
wenzelm@9598
   834
    "create simplified instances of elimination rules (improper)" K.thy_script ind_cases;
wenzelm@7107
   835
wenzelm@9643
   836
val _ = OuterSyntax.add_keywords ["intros", "monos", "con_defs"];
wenzelm@7107
   837
val _ = OuterSyntax.add_parsers [inductiveP, coinductiveP, inductive_casesP];
wenzelm@6424
   838
berghofe@5094
   839
end;
wenzelm@6424
   840
wenzelm@6424
   841
end;