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