src/HOL/Tools/old_inductive_package.ML
author paulson
Tue May 22 17:56:06 2007 +0200 (2007-05-22)
changeset 23075 69e30a7e8880
parent 22846 fb79144af9a3
child 23419 8c30dd4b3b22
permissions -rw-r--r--
Some hacks for SPASS format
berghofe@21023
     1
(*  Title:      HOL/Tools/old_inductive_package.ML
berghofe@21023
     2
    ID:         $Id$
berghofe@21023
     3
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
berghofe@21023
     4
    Author:     Stefan Berghofer, TU Muenchen
berghofe@21023
     5
    Author:     Markus Wenzel, TU Muenchen
berghofe@21023
     6
berghofe@21023
     7
(Co)Inductive Definition module for HOL.
berghofe@21023
     8
berghofe@21023
     9
Features:
berghofe@21023
    10
  * least or greatest fixedpoints
berghofe@21023
    11
  * user-specified product and sum constructions
berghofe@21023
    12
  * mutually recursive definitions
berghofe@21023
    13
  * definitions involving arbitrary monotone operators
berghofe@21023
    14
  * automatically proves introduction and elimination rules
berghofe@21023
    15
berghofe@21023
    16
The recursive sets must *already* be declared as constants in the
berghofe@21023
    17
current theory!
berghofe@21023
    18
berghofe@21023
    19
  Introduction rules have the form
berghofe@21023
    20
  [| ti:M(Sj), ..., P(x), ... |] ==> t: Sk
berghofe@21023
    21
  where M is some monotone operator (usually the identity)
berghofe@21023
    22
  P(x) is any side condition on the free variables
berghofe@21023
    23
  ti, t are any terms
berghofe@21023
    24
  Sj, Sk are two of the sets being defined in mutual recursion
berghofe@21023
    25
berghofe@21023
    26
Sums are used only for mutual recursion.  Products are used only to
berghofe@21023
    27
derive "streamlined" induction rules for relations.
berghofe@21023
    28
*)
berghofe@21023
    29
berghofe@21023
    30
signature OLD_INDUCTIVE_PACKAGE =
berghofe@21023
    31
sig
berghofe@21023
    32
  val quiet_mode: bool ref
berghofe@21023
    33
  val trace: bool ref
berghofe@21023
    34
  val unify_consts: theory -> term list -> term list -> term list * term list
berghofe@21023
    35
  val split_rule_vars: term list -> thm -> thm
berghofe@21023
    36
  val get_inductive: theory -> string -> ({names: string list, coind: bool} *
berghofe@21023
    37
    {defs: thm list, elims: thm list, raw_induct: thm, induct: thm,
berghofe@21023
    38
     intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm}) option
berghofe@21023
    39
  val the_mk_cases: theory -> string -> string -> thm
berghofe@21023
    40
  val mono_add: attribute
berghofe@21023
    41
  val mono_del: attribute
berghofe@21023
    42
  val get_monos: theory -> thm list
berghofe@21023
    43
  val inductive_forall_name: string
berghofe@21023
    44
  val inductive_forall_def: thm
berghofe@21023
    45
  val rulify: thm -> thm
berghofe@21023
    46
  val inductive_cases: ((bstring * Attrib.src list) * string list) list -> theory -> theory
berghofe@21023
    47
  val inductive_cases_i: ((bstring * attribute list) * term list) list -> theory -> theory
berghofe@21023
    48
  val add_inductive_i: bool -> bool -> bstring -> bool -> bool -> bool -> term list ->
berghofe@21023
    49
    ((bstring * term) * attribute list) list -> thm list -> theory -> theory *
berghofe@21023
    50
      {defs: thm list, elims: thm list, raw_induct: thm, induct: thm,
berghofe@21023
    51
       intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm}
berghofe@21023
    52
  val add_inductive: bool -> bool -> string list ->
berghofe@21023
    53
    ((bstring * string) * Attrib.src list) list -> (thmref * Attrib.src list) list ->
berghofe@21023
    54
    theory -> theory *
berghofe@21023
    55
      {defs: thm list, elims: thm list, raw_induct: thm, induct: thm,
berghofe@21023
    56
       intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm}
berghofe@21023
    57
  val setup: theory -> theory
berghofe@21023
    58
end;
berghofe@21023
    59
berghofe@21023
    60
structure OldInductivePackage: OLD_INDUCTIVE_PACKAGE =
berghofe@21023
    61
struct
berghofe@21023
    62
berghofe@21023
    63
berghofe@21023
    64
(** theory context references **)
berghofe@21023
    65
berghofe@21023
    66
val mono_name = "Orderings.mono";
berghofe@21023
    67
val gfp_name = "FixedPoint.gfp";
berghofe@21023
    68
val lfp_name = "FixedPoint.lfp";
berghofe@21023
    69
val vimage_name = "Set.vimage";
berghofe@21023
    70
val Const _ $ (vimage_f $ _) $ _ = HOLogic.dest_Trueprop (Thm.concl_of vimageD);
berghofe@21023
    71
berghofe@21023
    72
val inductive_forall_name = "HOL.induct_forall";
berghofe@21023
    73
val inductive_forall_def = thm "induct_forall_def";
berghofe@21023
    74
val inductive_conj_name = "HOL.induct_conj";
berghofe@21023
    75
val inductive_conj_def = thm "induct_conj_def";
berghofe@21023
    76
val inductive_conj = thms "induct_conj";
berghofe@21023
    77
val inductive_atomize = thms "induct_atomize";
berghofe@21023
    78
val inductive_rulify = thms "induct_rulify";
berghofe@21023
    79
val inductive_rulify_fallback = thms "induct_rulify_fallback";
berghofe@21023
    80
berghofe@21023
    81
berghofe@21023
    82
berghofe@21023
    83
(** theory data **)
berghofe@21023
    84
berghofe@21023
    85
type inductive_info =
berghofe@21023
    86
  {names: string list, coind: bool} * {defs: thm list, elims: thm list, raw_induct: thm,
berghofe@21023
    87
    induct: thm, intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm};
berghofe@21023
    88
berghofe@21023
    89
structure InductiveData = TheoryDataFun
wenzelm@22846
    90
(
berghofe@21023
    91
  type T = inductive_info Symtab.table * thm list;
berghofe@21023
    92
  val empty = (Symtab.empty, []);
berghofe@21023
    93
  val copy = I;
berghofe@21023
    94
  val extend = I;
berghofe@21023
    95
  fun merge _ ((tab1, monos1), (tab2, monos2)) =
berghofe@21023
    96
    (Symtab.merge (K true) (tab1, tab2), Drule.merge_rules (monos1, monos2));
wenzelm@22846
    97
);
berghofe@21023
    98
berghofe@21023
    99
val get_inductive = Symtab.lookup o #1 o InductiveData.get;
berghofe@21023
   100
berghofe@21023
   101
fun the_inductive thy name =
berghofe@21023
   102
  (case get_inductive thy name of
berghofe@21023
   103
    NONE => error ("Unknown (co)inductive set " ^ quote name)
berghofe@21023
   104
  | SOME info => info);
berghofe@21023
   105
berghofe@21023
   106
val the_mk_cases = (#mk_cases o #2) oo the_inductive;
berghofe@21023
   107
berghofe@21023
   108
fun put_inductives names info = InductiveData.map (apfst (fn tab =>
berghofe@21023
   109
  fold (fn name => Symtab.update_new (name, info)) names tab
berghofe@21023
   110
    handle Symtab.DUP dup => error ("Duplicate definition of (co)inductive set " ^ quote dup)));
berghofe@21023
   111
berghofe@21023
   112
berghofe@21023
   113
berghofe@21023
   114
(** monotonicity rules **)
berghofe@21023
   115
berghofe@21023
   116
val get_monos = #2 o InductiveData.get;
berghofe@21023
   117
val map_monos = InductiveData.map o Library.apsnd;
berghofe@21023
   118
berghofe@21023
   119
fun mk_mono thm =
berghofe@21023
   120
  let
berghofe@21023
   121
    fun eq2mono thm' = [standard (thm' RS (thm' RS eq_to_mono))] @
berghofe@21023
   122
      (case concl_of thm of
berghofe@21023
   123
          (_ $ (_ $ (Const ("Not", _) $ _) $ _)) => []
berghofe@21023
   124
        | _ => [standard (thm' RS (thm' RS eq_to_mono2))]);
berghofe@21023
   125
    val concl = concl_of thm
berghofe@21023
   126
  in
berghofe@21023
   127
    if can Logic.dest_equals concl then
berghofe@21023
   128
      eq2mono (thm RS meta_eq_to_obj_eq)
berghofe@21023
   129
    else if can (HOLogic.dest_eq o HOLogic.dest_Trueprop) concl then
berghofe@21023
   130
      eq2mono thm
berghofe@21023
   131
    else [thm]
berghofe@21023
   132
  end;
berghofe@21023
   133
berghofe@21023
   134
berghofe@21023
   135
(* attributes *)
berghofe@21023
   136
berghofe@21023
   137
val mono_add = Thm.declaration_attribute (fn th =>
berghofe@21023
   138
  Context.mapping (map_monos (fold Drule.add_rule (mk_mono th))) I);
berghofe@21023
   139
berghofe@21023
   140
val mono_del = Thm.declaration_attribute (fn th =>
berghofe@21023
   141
  Context.mapping (map_monos (fold Drule.del_rule (mk_mono th))) I);
berghofe@21023
   142
berghofe@21023
   143
berghofe@21023
   144
berghofe@21023
   145
(** misc utilities **)
berghofe@21023
   146
berghofe@21023
   147
val quiet_mode = ref false;
berghofe@21023
   148
val trace = ref false;  (*for debugging*)
berghofe@21023
   149
fun message s = if ! quiet_mode then () else writeln s;
berghofe@21023
   150
fun clean_message s = if ! quick_and_dirty then () else message s;
berghofe@21023
   151
berghofe@21023
   152
fun coind_prefix true = "co"
berghofe@21023
   153
  | coind_prefix false = "";
berghofe@21023
   154
berghofe@21023
   155
berghofe@21023
   156
(*the following code ensures that each recursive set always has the
berghofe@21023
   157
  same type in all introduction rules*)
berghofe@21023
   158
fun unify_consts thy cs intr_ts =
berghofe@21023
   159
  (let
berghofe@21023
   160
    val add_term_consts_2 = fold_aterms (fn Const c => insert (op =) c | _ => I);
berghofe@21023
   161
    fun varify (t, (i, ts)) =
haftmann@21116
   162
      let val t' = map_types (Logic.incr_tvar (i + 1)) (snd (Type.varify [] t))
berghofe@21023
   163
      in (maxidx_of_term t', t'::ts) end;
berghofe@21023
   164
    val (i, cs') = foldr varify (~1, []) cs;
berghofe@21023
   165
    val (i', intr_ts') = foldr varify (i, []) intr_ts;
berghofe@21023
   166
    val rec_consts = fold add_term_consts_2 cs' [];
berghofe@21023
   167
    val intr_consts = fold add_term_consts_2 intr_ts' [];
berghofe@21023
   168
    fun unify (cname, cT) =
haftmann@21116
   169
      let val consts = map snd (filter (fn (c, _) => c = cname) intr_consts)
berghofe@21023
   170
      in fold (Sign.typ_unify thy) ((replicate (length consts) cT) ~~ consts) end;
berghofe@21023
   171
    val (env, _) = fold unify rec_consts (Vartab.empty, i');
berghofe@21023
   172
    val subst = Type.freeze o map_types (Envir.norm_type env)
berghofe@21023
   173
berghofe@21023
   174
  in (map subst cs', map subst intr_ts')
berghofe@21023
   175
  end) handle Type.TUNIFY =>
berghofe@21023
   176
    (warning "Occurrences of recursive constant have non-unifiable types"; (cs, intr_ts));
berghofe@21023
   177
berghofe@21023
   178
berghofe@21023
   179
(*make injections used in mutually recursive definitions*)
berghofe@21023
   180
fun mk_inj cs sumT c x =
berghofe@21023
   181
  let
berghofe@21023
   182
    fun mk_inj' T n i =
berghofe@21023
   183
      if n = 1 then x else
berghofe@21023
   184
      let val n2 = n div 2;
berghofe@21023
   185
          val Type (_, [T1, T2]) = T
berghofe@21023
   186
      in
berghofe@21023
   187
        if i <= n2 then
berghofe@21023
   188
          Const ("Sum_Type.Inl", T1 --> T) $ (mk_inj' T1 n2 i)
berghofe@21023
   189
        else
berghofe@21023
   190
          Const ("Sum_Type.Inr", T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
berghofe@21023
   191
      end
berghofe@21023
   192
  in mk_inj' sumT (length cs) (1 + find_index_eq c cs)
berghofe@21023
   193
  end;
berghofe@21023
   194
berghofe@21023
   195
(*make "vimage" terms for selecting out components of mutually rec.def*)
berghofe@21023
   196
fun mk_vimage cs sumT t c = if length cs < 2 then t else
berghofe@21023
   197
  let
berghofe@21023
   198
    val cT = HOLogic.dest_setT (fastype_of c);
berghofe@21023
   199
    val vimageT = [cT --> sumT, HOLogic.mk_setT sumT] ---> HOLogic.mk_setT cT
berghofe@21023
   200
  in
berghofe@21023
   201
    Const (vimage_name, vimageT) $
berghofe@21023
   202
      Abs ("y", cT, mk_inj cs sumT c (Bound 0)) $ t
berghofe@21023
   203
  end;
berghofe@21023
   204
berghofe@21023
   205
(** proper splitting **)
berghofe@21023
   206
berghofe@21023
   207
fun prod_factors p (Const ("Pair", _) $ t $ u) =
berghofe@21023
   208
      p :: prod_factors (1::p) t @ prod_factors (2::p) u
berghofe@21023
   209
  | prod_factors p _ = [];
berghofe@21023
   210
berghofe@21023
   211
fun mg_prod_factors ts (t $ u) fs = if t mem ts then
berghofe@21023
   212
        let val f = prod_factors [] u
berghofe@21023
   213
        in AList.update (op =) (t, f inter (AList.lookup (op =) fs t) |> the_default f) fs end
berghofe@21023
   214
      else mg_prod_factors ts u (mg_prod_factors ts t fs)
berghofe@21023
   215
  | mg_prod_factors ts (Abs (_, _, t)) fs = mg_prod_factors ts t fs
berghofe@21023
   216
  | mg_prod_factors ts _ fs = fs;
berghofe@21023
   217
berghofe@21023
   218
fun prodT_factors p ps (T as Type ("*", [T1, T2])) =
berghofe@21023
   219
      if p mem ps then prodT_factors (1::p) ps T1 @ prodT_factors (2::p) ps T2
berghofe@21023
   220
      else [T]
berghofe@21023
   221
  | prodT_factors _ _ T = [T];
berghofe@21023
   222
berghofe@21023
   223
fun ap_split p ps (Type ("*", [T1, T2])) T3 u =
berghofe@21023
   224
      if p mem ps then HOLogic.split_const (T1, T2, T3) $
berghofe@21023
   225
        Abs ("v", T1, ap_split (2::p) ps T2 T3 (ap_split (1::p) ps T1
berghofe@21023
   226
          (prodT_factors (2::p) ps T2 ---> T3) (incr_boundvars 1 u) $ Bound 0))
berghofe@21023
   227
      else u
berghofe@21023
   228
  | ap_split _ _ _ _ u =  u;
berghofe@21023
   229
berghofe@21023
   230
fun mk_tuple p ps (Type ("*", [T1, T2])) (tms as t::_) =
berghofe@21023
   231
      if p mem ps then HOLogic.mk_prod (mk_tuple (1::p) ps T1 tms,
berghofe@21023
   232
        mk_tuple (2::p) ps T2 (Library.drop (length (prodT_factors (1::p) ps T1), tms)))
berghofe@21023
   233
      else t
berghofe@21023
   234
  | mk_tuple _ _ _ (t::_) = t;
berghofe@21023
   235
berghofe@21023
   236
fun split_rule_var' ((t as Var (v, Type ("fun", [T1, T2])), ps), rl) =
berghofe@21023
   237
      let val T' = prodT_factors [] ps T1 ---> T2
berghofe@21023
   238
          val newt = ap_split [] ps T1 T2 (Var (v, T'))
berghofe@21023
   239
          val cterm = Thm.cterm_of (Thm.theory_of_thm rl)
berghofe@21023
   240
      in
berghofe@21023
   241
          instantiate ([], [(cterm t, cterm newt)]) rl
berghofe@21023
   242
      end
berghofe@21023
   243
  | split_rule_var' (_, rl) = rl;
berghofe@21023
   244
berghofe@21023
   245
val remove_split = rewrite_rule [split_conv RS eq_reflection];
berghofe@21023
   246
berghofe@21023
   247
fun split_rule_vars vs rl = standard (remove_split (foldr split_rule_var'
berghofe@21023
   248
  rl (mg_prod_factors vs (Thm.prop_of rl) [])));
berghofe@21023
   249
berghofe@21023
   250
fun split_rule vs rl = standard (remove_split (foldr split_rule_var'
berghofe@21023
   251
  rl (List.mapPartial (fn (t as Var ((a, _), _)) =>
berghofe@21023
   252
      Option.map (pair t) (AList.lookup (op =) vs a)) (term_vars (Thm.prop_of rl)))));
berghofe@21023
   253
berghofe@21023
   254
berghofe@21023
   255
(** process rules **)
berghofe@21023
   256
berghofe@21023
   257
local
berghofe@21023
   258
berghofe@21023
   259
fun err_in_rule thy name t msg =
berghofe@21023
   260
  error (cat_lines ["Ill-formed introduction rule " ^ quote name,
berghofe@21023
   261
    Sign.string_of_term thy t, msg]);
berghofe@21023
   262
berghofe@21023
   263
fun err_in_prem thy name t p msg =
berghofe@21023
   264
  error (cat_lines ["Ill-formed premise", Sign.string_of_term thy p,
berghofe@21023
   265
    "in introduction rule " ^ quote name, Sign.string_of_term thy t, msg]);
berghofe@21023
   266
berghofe@21023
   267
val bad_concl = "Conclusion of introduction rule must have form \"t : S_i\"";
berghofe@21023
   268
berghofe@21023
   269
val all_not_allowed =
berghofe@21023
   270
    "Introduction rule must not have a leading \"!!\" quantifier";
berghofe@21023
   271
berghofe@21023
   272
fun atomize_term thy = MetaSimplifier.rewrite_term thy inductive_atomize [];
berghofe@21023
   273
berghofe@21023
   274
in
berghofe@21023
   275
berghofe@21023
   276
fun check_rule thy cs ((name, rule), att) =
berghofe@21023
   277
  let
berghofe@21023
   278
    val concl = Logic.strip_imp_concl rule;
berghofe@21023
   279
    val prems = Logic.strip_imp_prems rule;
berghofe@21023
   280
    val aprems = map (atomize_term thy) prems;
berghofe@21023
   281
    val arule = Logic.list_implies (aprems, concl);
berghofe@21023
   282
berghofe@21023
   283
    fun check_prem (prem, aprem) =
berghofe@21023
   284
      if can HOLogic.dest_Trueprop aprem then ()
berghofe@21023
   285
      else err_in_prem thy name rule prem "Non-atomic premise";
berghofe@21023
   286
  in
berghofe@21023
   287
    (case concl of
berghofe@21023
   288
      Const ("Trueprop", _) $ (Const ("op :", _) $ t $ u) =>
berghofe@21023
   289
        if u mem cs then
berghofe@21023
   290
          if exists (Logic.occs o rpair t) cs then
berghofe@21023
   291
            err_in_rule thy name rule "Recursion term on left of member symbol"
berghofe@21023
   292
          else List.app check_prem (prems ~~ aprems)
berghofe@21023
   293
        else err_in_rule thy name rule bad_concl
berghofe@21023
   294
      | Const ("all", _) $ _ => err_in_rule thy name rule all_not_allowed
berghofe@21023
   295
      | _ => err_in_rule thy name rule bad_concl);
berghofe@21023
   296
    ((name, arule), att)
berghofe@21023
   297
  end;
berghofe@21023
   298
berghofe@21023
   299
val rulify =  (* FIXME norm_hhf *)
berghofe@21023
   300
  hol_simplify inductive_conj
berghofe@21023
   301
  #> hol_simplify inductive_rulify
berghofe@21023
   302
  #> hol_simplify inductive_rulify_fallback
berghofe@21023
   303
  #> standard;
berghofe@21023
   304
berghofe@21023
   305
end;
berghofe@21023
   306
berghofe@21023
   307
berghofe@21023
   308
berghofe@21023
   309
(** properties of (co)inductive sets **)
berghofe@21023
   310
berghofe@21023
   311
(* elimination rules *)
berghofe@21023
   312
berghofe@21023
   313
fun mk_elims cs cTs params intr_ts intr_names =
berghofe@21023
   314
  let
berghofe@21023
   315
    val used = foldr add_term_names [] intr_ts;
berghofe@21023
   316
    val [aname, pname] = Name.variant_list used ["a", "P"];
berghofe@21023
   317
    val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
berghofe@21023
   318
berghofe@21023
   319
    fun dest_intr r =
berghofe@21023
   320
      let val Const ("op :", _) $ t $ u =
berghofe@21023
   321
        HOLogic.dest_Trueprop (Logic.strip_imp_concl r)
berghofe@21023
   322
      in (u, t, Logic.strip_imp_prems r) end;
berghofe@21023
   323
berghofe@21023
   324
    val intrs = map dest_intr intr_ts ~~ intr_names;
berghofe@21023
   325
berghofe@21023
   326
    fun mk_elim (c, T) =
berghofe@21023
   327
      let
berghofe@21023
   328
        val a = Free (aname, T);
berghofe@21023
   329
berghofe@21023
   330
        fun mk_elim_prem (_, t, ts) =
berghofe@21023
   331
          list_all_free (map dest_Free ((foldr add_term_frees [] (t::ts)) \\ params),
berghofe@21023
   332
            Logic.list_implies (HOLogic.mk_Trueprop (HOLogic.mk_eq (a, t)) :: ts, P));
berghofe@21023
   333
        val c_intrs = (List.filter (equal c o #1 o #1) intrs);
berghofe@21023
   334
      in
berghofe@21023
   335
        (Logic.list_implies (HOLogic.mk_Trueprop (HOLogic.mk_mem (a, c)) ::
berghofe@21023
   336
          map mk_elim_prem (map #1 c_intrs), P), map #2 c_intrs)
berghofe@21023
   337
      end
berghofe@21023
   338
  in
berghofe@21023
   339
    map mk_elim (cs ~~ cTs)
berghofe@21023
   340
  end;
berghofe@21023
   341
berghofe@21023
   342
berghofe@21023
   343
(* premises and conclusions of induction rules *)
berghofe@21023
   344
berghofe@21023
   345
fun mk_indrule cs cTs params intr_ts =
berghofe@21023
   346
  let
berghofe@21023
   347
    val used = foldr add_term_names [] intr_ts;
berghofe@21023
   348
berghofe@21023
   349
    (* predicates for induction rule *)
berghofe@21023
   350
berghofe@21023
   351
    val preds = map Free (Name.variant_list used (if length cs < 2 then ["P"] else
berghofe@21023
   352
      map (fn i => "P" ^ string_of_int i) (1 upto length cs)) ~~
berghofe@21023
   353
        map (fn T => T --> HOLogic.boolT) cTs);
berghofe@21023
   354
berghofe@21023
   355
    (* transform an introduction rule into a premise for induction rule *)
berghofe@21023
   356
berghofe@21023
   357
    fun mk_ind_prem r =
berghofe@21023
   358
      let
berghofe@21023
   359
        val frees = map dest_Free ((add_term_frees (r, [])) \\ params);
berghofe@21023
   360
berghofe@21023
   361
        val pred_of = AList.lookup (op aconv) (cs ~~ preds);
berghofe@21023
   362
berghofe@21023
   363
        fun subst (s as ((m as Const ("op :", T)) $ t $ u)) =
berghofe@21023
   364
              (case pred_of u of
berghofe@21023
   365
                  NONE => (m $ fst (subst t) $ fst (subst u), NONE)
berghofe@21023
   366
                | SOME P => (HOLogic.mk_binop inductive_conj_name (s, P $ t), SOME (s, P $ t)))
berghofe@21023
   367
          | subst s =
berghofe@21023
   368
              (case pred_of s of
berghofe@21023
   369
                  SOME P => (HOLogic.mk_binop "op Int"
berghofe@21023
   370
                    (s, HOLogic.Collect_const (HOLogic.dest_setT
berghofe@21023
   371
                      (fastype_of s)) $ P), NONE)
berghofe@21023
   372
                | NONE => (case s of
berghofe@21023
   373
                     (t $ u) => (fst (subst t) $ fst (subst u), NONE)
berghofe@21023
   374
                   | (Abs (a, T, t)) => (Abs (a, T, fst (subst t)), NONE)
berghofe@21023
   375
                   | _ => (s, NONE)));
berghofe@21023
   376
berghofe@21023
   377
        fun mk_prem (s, prems) = (case subst s of
berghofe@21023
   378
              (_, SOME (t, u)) => t :: u :: prems
berghofe@21023
   379
            | (t, _) => t :: prems);
berghofe@21023
   380
berghofe@21023
   381
        val Const ("op :", _) $ t $ u =
berghofe@21023
   382
          HOLogic.dest_Trueprop (Logic.strip_imp_concl r)
berghofe@21023
   383
berghofe@21023
   384
      in list_all_free (frees,
berghofe@21023
   385
           Logic.list_implies (map HOLogic.mk_Trueprop (foldr mk_prem
berghofe@21023
   386
             [] (map HOLogic.dest_Trueprop (Logic.strip_imp_prems r))),
berghofe@21023
   387
               HOLogic.mk_Trueprop (valOf (pred_of u) $ t)))
berghofe@21023
   388
      end;
berghofe@21023
   389
berghofe@21023
   390
    val ind_prems = map mk_ind_prem intr_ts;
berghofe@21023
   391
wenzelm@21395
   392
    val factors = fold (mg_prod_factors preds) ind_prems [];
berghofe@21023
   393
berghofe@21023
   394
    (* make conclusions for induction rules *)
berghofe@21023
   395
berghofe@21023
   396
    fun mk_ind_concl ((c, P), (ts, x)) =
berghofe@21023
   397
      let val T = HOLogic.dest_setT (fastype_of c);
berghofe@21023
   398
          val ps = AList.lookup (op =) factors P |> the_default [];
berghofe@21023
   399
          val Ts = prodT_factors [] ps T;
berghofe@21023
   400
          val (frees, x') = foldr (fn (T', (fs, s)) =>
berghofe@21023
   401
            ((Free (s, T'))::fs, Symbol.bump_string s)) ([], x) Ts;
berghofe@21023
   402
          val tuple = mk_tuple [] ps T frees;
berghofe@21023
   403
      in ((HOLogic.mk_binop "op -->"
berghofe@21023
   404
        (HOLogic.mk_mem (tuple, c), P $ tuple))::ts, x')
berghofe@21023
   405
      end;
berghofe@21023
   406
berghofe@21023
   407
    val mutual_ind_concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
berghofe@21023
   408
        (fst (foldr mk_ind_concl ([], "xa") (cs ~~ preds))))
berghofe@21023
   409
berghofe@21023
   410
  in (preds, ind_prems, mutual_ind_concl,
berghofe@21023
   411
    map (apfst (fst o dest_Free)) factors)
berghofe@21023
   412
  end;
berghofe@21023
   413
berghofe@21023
   414
berghofe@21023
   415
(* prepare cases and induct rules *)
berghofe@21023
   416
berghofe@21023
   417
fun add_cases_induct no_elim no_induct coind names elims induct =
berghofe@21023
   418
  let
berghofe@21023
   419
    fun cases_spec name elim thy =
berghofe@21023
   420
      thy
berghofe@21023
   421
      |> Theory.parent_path
berghofe@21023
   422
      |> Theory.add_path (Sign.base_name name)
berghofe@21023
   423
      |> PureThy.add_thms [(("cases", elim), [InductAttrib.cases_set name])] |> snd
berghofe@21023
   424
      |> Theory.restore_naming thy;
berghofe@21023
   425
    val cases_specs = if no_elim then [] else map2 cases_spec names elims;
berghofe@21023
   426
berghofe@21023
   427
    val induct_att = if coind then InductAttrib.coinduct_set else InductAttrib.induct_set;
berghofe@21023
   428
    fun induct_specs thy =
berghofe@21023
   429
      if no_induct then thy
berghofe@21023
   430
      else
berghofe@21023
   431
        let
berghofe@21023
   432
          val ctxt = ProofContext.init thy;
berghofe@21023
   433
          val rules = names ~~ ProjectRule.projects ctxt (1 upto length names) induct;
berghofe@21023
   434
          val inducts = map (RuleCases.save induct o standard o #2) rules;
berghofe@21023
   435
        in
berghofe@21023
   436
          thy
berghofe@21023
   437
          |> PureThy.add_thms (rules |> map (fn (name, th) =>
berghofe@21023
   438
            (("", th), [RuleCases.consumes 1, induct_att name]))) |> snd
berghofe@21023
   439
          |> PureThy.add_thmss
berghofe@21023
   440
            [((coind_prefix coind ^ "inducts", inducts), [RuleCases.consumes 1])] |> snd
berghofe@21023
   441
        end;
berghofe@21023
   442
  in Library.apply cases_specs #> induct_specs end;
berghofe@21023
   443
berghofe@21023
   444
berghofe@21023
   445
berghofe@21023
   446
(** proofs for (co)inductive sets **)
berghofe@21023
   447
berghofe@21023
   448
(* prove monotonicity -- NOT subject to quick_and_dirty! *)
berghofe@21023
   449
berghofe@21023
   450
fun prove_mono setT fp_fun monos thy =
berghofe@21023
   451
 (message "  Proving monotonicity ...";
berghofe@21023
   452
  Goal.prove_global thy [] []   (*NO quick_and_dirty here!*)
berghofe@21023
   453
    (HOLogic.mk_Trueprop
berghofe@21023
   454
      (Const (mono_name, (setT --> setT) --> HOLogic.boolT) $ fp_fun))
berghofe@21023
   455
    (fn _ => EVERY [rtac monoI 1,
berghofe@21023
   456
      REPEAT (ares_tac (List.concat (map mk_mono monos) @ get_monos thy) 1)]));
berghofe@21023
   457
berghofe@21023
   458
berghofe@21023
   459
(* prove introduction rules *)
berghofe@21023
   460
berghofe@21023
   461
fun prove_intrs coind mono fp_def intr_ts rec_sets_defs ctxt =
berghofe@21023
   462
  let
berghofe@21023
   463
    val _ = clean_message "  Proving the introduction rules ...";
berghofe@21023
   464
berghofe@21023
   465
    val unfold = standard' (mono RS (fp_def RS
berghofe@21023
   466
      (if coind then def_gfp_unfold else def_lfp_unfold)));
berghofe@21023
   467
berghofe@21023
   468
    fun select_disj 1 1 = []
berghofe@21023
   469
      | select_disj _ 1 = [rtac disjI1]
berghofe@21023
   470
      | select_disj n i = (rtac disjI2)::(select_disj (n - 1) (i - 1));
berghofe@21023
   471
berghofe@21023
   472
    val intrs = (1 upto (length intr_ts) ~~ intr_ts) |> map (fn (i, intr) =>
berghofe@21023
   473
      rulify (SkipProof.prove ctxt [] [] intr (fn _ => EVERY
berghofe@21023
   474
       [rewrite_goals_tac rec_sets_defs,
berghofe@21023
   475
        stac unfold 1,
berghofe@21023
   476
        REPEAT (resolve_tac [vimageI2, CollectI] 1),
berghofe@21023
   477
        (*Now 1-2 subgoals: the disjunction, perhaps equality.*)
berghofe@21023
   478
        EVERY1 (select_disj (length intr_ts) i),
berghofe@21023
   479
        (*Not ares_tac, since refl must be tried before any equality assumptions;
berghofe@21023
   480
          backtracking may occur if the premises have extra variables!*)
berghofe@21023
   481
        DEPTH_SOLVE_1 (resolve_tac [refl, exI, conjI] 1 APPEND assume_tac 1),
berghofe@21023
   482
        (*Now solve the equations like Inl 0 = Inl ?b2*)
berghofe@21023
   483
        REPEAT (rtac refl 1)])))
berghofe@21023
   484
berghofe@21023
   485
  in (intrs, unfold) end;
berghofe@21023
   486
berghofe@21023
   487
berghofe@21023
   488
(* prove elimination rules *)
berghofe@21023
   489
berghofe@21023
   490
fun prove_elims cs cTs params intr_ts intr_names unfold rec_sets_defs ctxt =
berghofe@21023
   491
  let
berghofe@21023
   492
    val _ = clean_message "  Proving the elimination rules ...";
berghofe@21023
   493
berghofe@21023
   494
    val rules1 = [CollectE, disjE, make_elim vimageD, exE, FalseE];
berghofe@21023
   495
    val rules2 = [conjE, Inl_neq_Inr, Inr_neq_Inl] @ map make_elim [Inl_inject, Inr_inject];
berghofe@21023
   496
  in
berghofe@21023
   497
    mk_elims cs cTs params intr_ts intr_names |> map (fn (t, cases) =>
berghofe@21023
   498
      SkipProof.prove ctxt [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
berghofe@21023
   499
        (fn {prems, ...} => EVERY
berghofe@21023
   500
          [cut_facts_tac [hd prems] 1,
berghofe@21023
   501
           rewrite_goals_tac rec_sets_defs,
berghofe@21023
   502
           dtac (unfold RS subst) 1,
berghofe@21023
   503
           REPEAT (FIRSTGOAL (eresolve_tac rules1)),
berghofe@21023
   504
           REPEAT (FIRSTGOAL (eresolve_tac rules2)),
berghofe@21023
   505
           EVERY (map (fn prem =>
berghofe@21023
   506
             DEPTH_SOLVE_1 (ares_tac [rewrite_rule rec_sets_defs prem, conjI] 1)) (tl prems))])
berghofe@21023
   507
        |> rulify
berghofe@21023
   508
        |> RuleCases.name cases)
berghofe@21023
   509
  end;
berghofe@21023
   510
berghofe@21023
   511
berghofe@21023
   512
(* derivation of simplified elimination rules *)
berghofe@21023
   513
berghofe@21023
   514
local
berghofe@21023
   515
berghofe@21023
   516
(*cprop should have the form t:Si where Si is an inductive set*)
berghofe@21023
   517
val mk_cases_err = "mk_cases: proposition not of form \"t : S_i\"";
berghofe@21023
   518
berghofe@21023
   519
(*delete needless equality assumptions*)
berghofe@21023
   520
val refl_thin = prove_goal HOL.thy "!!P. a = a ==> P ==> P" (fn _ => [assume_tac 1]);
berghofe@21023
   521
val elim_rls = [asm_rl, FalseE, refl_thin, conjE, exE, Pair_inject];
berghofe@21023
   522
val elim_tac = REPEAT o Tactic.eresolve_tac elim_rls;
berghofe@21023
   523
berghofe@21023
   524
fun simp_case_tac solved ss i =
berghofe@21023
   525
  EVERY' [elim_tac, asm_full_simp_tac ss, elim_tac, REPEAT o bound_hyp_subst_tac] i
berghofe@21023
   526
  THEN_MAYBE (if solved then no_tac else all_tac);
berghofe@21023
   527
berghofe@21023
   528
in
berghofe@21023
   529
berghofe@21023
   530
fun mk_cases_i elims ss cprop =
berghofe@21023
   531
  let
berghofe@21023
   532
    val prem = Thm.assume cprop;
berghofe@21023
   533
    val tac = ALLGOALS (simp_case_tac false ss) THEN prune_params_tac;
berghofe@21023
   534
    fun mk_elim rl = Drule.standard (Tactic.rule_by_tactic tac (prem RS rl));
berghofe@21023
   535
  in
berghofe@21023
   536
    (case get_first (try mk_elim) elims of
berghofe@21023
   537
      SOME r => r
berghofe@21023
   538
    | NONE => error (Pretty.string_of (Pretty.block
berghofe@21023
   539
        [Pretty.str mk_cases_err, Pretty.fbrk, Display.pretty_cterm cprop])))
berghofe@21023
   540
  end;
berghofe@21023
   541
berghofe@21023
   542
fun mk_cases elims s =
berghofe@21023
   543
  mk_cases_i elims (simpset()) (Thm.read_cterm (Thm.theory_of_thm (hd elims)) (s, propT));
berghofe@21023
   544
berghofe@21023
   545
fun smart_mk_cases thy ss cprop =
berghofe@21023
   546
  let
berghofe@21023
   547
    val c = #1 (Term.dest_Const (Term.head_of (#2 (HOLogic.dest_mem (HOLogic.dest_Trueprop
berghofe@21023
   548
      (Logic.strip_imp_concl (Thm.term_of cprop))))))) handle TERM _ => error mk_cases_err;
berghofe@21023
   549
    val (_, {elims, ...}) = the_inductive thy c;
berghofe@21023
   550
  in mk_cases_i elims ss cprop end;
berghofe@21023
   551
berghofe@21023
   552
end;
berghofe@21023
   553
berghofe@21023
   554
berghofe@21023
   555
(* inductive_cases(_i) *)
berghofe@21023
   556
berghofe@21023
   557
fun gen_inductive_cases prep_att prep_prop args thy =
berghofe@21023
   558
  let
berghofe@21023
   559
    val cert_prop = Thm.cterm_of thy o prep_prop (ProofContext.init thy);
berghofe@21023
   560
    val mk_cases = smart_mk_cases thy (Simplifier.simpset_of thy) o cert_prop;
berghofe@21023
   561
berghofe@21023
   562
    val facts = args |> map (fn ((a, atts), props) =>
berghofe@21023
   563
     ((a, map (prep_att thy) atts), map (Thm.no_attributes o single o mk_cases) props));
berghofe@21023
   564
  in thy |> PureThy.note_thmss_i "" facts |> snd end;
berghofe@21023
   565
berghofe@21023
   566
val inductive_cases = gen_inductive_cases Attrib.attribute ProofContext.read_prop;
berghofe@21023
   567
val inductive_cases_i = gen_inductive_cases (K I) ProofContext.cert_prop;
berghofe@21023
   568
berghofe@21023
   569
berghofe@21023
   570
(* mk_cases_meth *)
berghofe@21023
   571
haftmann@21879
   572
fun mk_cases_meth (raw_props, ctxt) =
berghofe@21023
   573
  let
berghofe@21023
   574
    val thy = ProofContext.theory_of ctxt;
berghofe@21023
   575
    val ss = local_simpset_of ctxt;
berghofe@21023
   576
    val cprops = map (Thm.cterm_of thy o ProofContext.read_prop ctxt) raw_props;
berghofe@21023
   577
  in Method.erule 0 (map (smart_mk_cases thy ss) cprops) end;
berghofe@21023
   578
berghofe@21023
   579
val mk_cases_args = Method.syntax (Scan.lift (Scan.repeat1 Args.name));
berghofe@21023
   580
berghofe@21023
   581
berghofe@21023
   582
(* prove induction rule *)
berghofe@21023
   583
berghofe@21023
   584
fun prove_indrule cs cTs sumT rec_const params intr_ts mono
berghofe@21023
   585
    fp_def rec_sets_defs ctxt =
berghofe@21023
   586
  let
berghofe@21023
   587
    val _ = clean_message "  Proving the induction rule ...";
berghofe@21023
   588
    val thy = ProofContext.theory_of ctxt;
berghofe@21023
   589
berghofe@21023
   590
    val sum_case_rewrites =
berghofe@21023
   591
      (if Context.theory_name thy = "Datatype" then
berghofe@21023
   592
        PureThy.get_thms thy (Name "sum.cases")
berghofe@21023
   593
      else
berghofe@21023
   594
        (case ThyInfo.lookup_theory "Datatype" of
berghofe@21023
   595
          NONE => []
berghofe@21023
   596
        | SOME thy' =>
berghofe@21023
   597
            if Theory.subthy (thy', thy) then
berghofe@21023
   598
              PureThy.get_thms thy' (Name "sum.cases")
berghofe@21023
   599
            else []))
berghofe@21023
   600
      |> map mk_meta_eq;
berghofe@21023
   601
berghofe@21023
   602
    val (preds, ind_prems, mutual_ind_concl, factors) =
berghofe@21023
   603
      mk_indrule cs cTs params intr_ts;
berghofe@21023
   604
berghofe@21023
   605
    val dummy = if !trace then
berghofe@21023
   606
                (writeln "ind_prems = ";
berghofe@21023
   607
                 List.app (writeln o Sign.string_of_term thy) ind_prems)
berghofe@21023
   608
            else ();
berghofe@21023
   609
berghofe@21023
   610
    (* make predicate for instantiation of abstract induction rule *)
berghofe@21023
   611
berghofe@21023
   612
    fun mk_ind_pred _ [P] = P
berghofe@21023
   613
      | mk_ind_pred T Ps =
berghofe@21023
   614
         let val n = (length Ps) div 2;
berghofe@21023
   615
             val Type (_, [T1, T2]) = T
berghofe@21023
   616
         in Const ("Datatype.sum.sum_case",
berghofe@21023
   617
           [T1 --> HOLogic.boolT, T2 --> HOLogic.boolT, T] ---> HOLogic.boolT) $
berghofe@21023
   618
             mk_ind_pred T1 (Library.take (n, Ps)) $ mk_ind_pred T2 (Library.drop (n, Ps))
berghofe@21023
   619
         end;
berghofe@21023
   620
berghofe@21023
   621
    val ind_pred = mk_ind_pred sumT preds;
berghofe@21023
   622
berghofe@21023
   623
    val ind_concl = HOLogic.mk_Trueprop
berghofe@21023
   624
      (HOLogic.all_const sumT $ Abs ("x", sumT, HOLogic.mk_binop "op -->"
berghofe@21023
   625
        (HOLogic.mk_mem (Bound 0, rec_const), ind_pred $ Bound 0)));
berghofe@21023
   626
berghofe@21023
   627
    (* simplification rules for vimage and Collect *)
berghofe@21023
   628
berghofe@21023
   629
    val vimage_simps = if length cs < 2 then [] else
berghofe@21023
   630
      map (fn c => standard (SkipProof.prove ctxt [] []
berghofe@21023
   631
        (HOLogic.mk_Trueprop (HOLogic.mk_eq
berghofe@21023
   632
          (mk_vimage cs sumT (HOLogic.Collect_const sumT $ ind_pred) c,
berghofe@21023
   633
           HOLogic.Collect_const (HOLogic.dest_setT (fastype_of c)) $
berghofe@21023
   634
             List.nth (preds, find_index_eq c cs))))
berghofe@21023
   635
        (fn _ => EVERY
berghofe@21023
   636
          [rtac vimage_Collect 1, rewrite_goals_tac sum_case_rewrites, rtac refl 1]))) cs;
berghofe@21023
   637
berghofe@21023
   638
    val raw_fp_induct = (mono RS (fp_def RS def_lfp_induct_set));
berghofe@21023
   639
berghofe@21023
   640
    val dummy = if !trace then
berghofe@21023
   641
                (writeln "raw_fp_induct = "; print_thm raw_fp_induct)
berghofe@21023
   642
            else ();
berghofe@21023
   643
berghofe@21023
   644
    val induct = standard (SkipProof.prove ctxt [] ind_prems ind_concl
berghofe@21023
   645
      (fn {prems, ...} => EVERY
berghofe@21023
   646
        [rewrite_goals_tac [inductive_conj_def],
berghofe@21023
   647
         rtac (impI RS allI) 1,
berghofe@21023
   648
         DETERM (etac raw_fp_induct 1),
berghofe@21023
   649
         rewrite_goals_tac (map mk_meta_eq (vimage_Int::Int_Collect::vimage_simps)),
berghofe@21023
   650
         fold_goals_tac rec_sets_defs,
berghofe@21023
   651
         (*This CollectE and disjE separates out the introduction rules*)
berghofe@21023
   652
         REPEAT (FIRSTGOAL (eresolve_tac [CollectE, disjE, exE, FalseE])),
berghofe@21023
   653
         (*Now break down the individual cases.  No disjE here in case
berghofe@21023
   654
           some premise involves disjunction.*)
berghofe@21023
   655
         REPEAT (FIRSTGOAL (etac conjE ORELSE' bound_hyp_subst_tac)),
berghofe@21023
   656
         rewrite_goals_tac sum_case_rewrites,
berghofe@21023
   657
         EVERY (map (fn prem =>
berghofe@21023
   658
           DEPTH_SOLVE_1 (ares_tac [rewrite_rule [inductive_conj_def] prem, conjI, refl] 1)) prems)]));
berghofe@21023
   659
berghofe@21023
   660
    val lemma = standard (SkipProof.prove ctxt [] []
berghofe@21023
   661
      (Logic.mk_implies (ind_concl, mutual_ind_concl)) (fn _ => EVERY
berghofe@21023
   662
        [rewrite_goals_tac rec_sets_defs,
berghofe@21023
   663
         REPEAT (EVERY
berghofe@21023
   664
           [REPEAT (resolve_tac [conjI, impI] 1),
berghofe@21023
   665
            TRY (dtac vimageD 1), etac allE 1, dtac mp 1, atac 1,
berghofe@21023
   666
            rewrite_goals_tac sum_case_rewrites,
berghofe@21023
   667
            atac 1])]))
berghofe@21023
   668
berghofe@21023
   669
  in standard (split_rule factors (induct RS lemma)) end;
berghofe@21023
   670
berghofe@21023
   671
berghofe@21023
   672
berghofe@21023
   673
(** specification of (co)inductive sets **)
berghofe@21023
   674
berghofe@21023
   675
fun cond_declare_consts declare_consts cs paramTs cnames =
berghofe@21023
   676
  if declare_consts then
berghofe@21023
   677
    Theory.add_consts_i (map (fn (c, n) => (Sign.base_name n, paramTs ---> fastype_of c, NoSyn)) (cs ~~ cnames))
berghofe@21023
   678
  else I;
berghofe@21023
   679
berghofe@21023
   680
fun mk_ind_def declare_consts alt_name coind cs intr_ts monos thy
berghofe@21023
   681
      params paramTs cTs cnames =
berghofe@21023
   682
  let
berghofe@21023
   683
    val sumT = fold_bal (fn (T, U) => Type ("+", [T, U])) cTs;
berghofe@21023
   684
    val setT = HOLogic.mk_setT sumT;
berghofe@21023
   685
berghofe@21023
   686
    val fp_name = if coind then gfp_name else lfp_name;
berghofe@21023
   687
berghofe@21023
   688
    val used = foldr add_term_names [] intr_ts;
berghofe@21023
   689
    val [sname, xname] = Name.variant_list used ["S", "x"];
berghofe@21023
   690
berghofe@21023
   691
    (* transform an introduction rule into a conjunction  *)
berghofe@21023
   692
    (*   [| t : ... S_i ... ; ... |] ==> u : S_j          *)
berghofe@21023
   693
    (* is transformed into                                *)
berghofe@21023
   694
    (*   x = Inj_j u & t : ... Inj_i -`` S ... & ...      *)
berghofe@21023
   695
berghofe@21023
   696
    fun transform_rule r =
berghofe@21023
   697
      let
berghofe@21023
   698
        val frees = map dest_Free ((add_term_frees (r, [])) \\ params);
berghofe@21023
   699
        val subst = subst_free
berghofe@21023
   700
          (cs ~~ (map (mk_vimage cs sumT (Free (sname, setT))) cs));
berghofe@21023
   701
        val Const ("op :", _) $ t $ u =
berghofe@21023
   702
          HOLogic.dest_Trueprop (Logic.strip_imp_concl r)
berghofe@21023
   703
berghofe@21023
   704
      in foldr (fn ((x, T), P) => HOLogic.mk_exists (x, T, P))
berghofe@21023
   705
        (foldr1 HOLogic.mk_conj
berghofe@21023
   706
          (((HOLogic.eq_const sumT) $ Free (xname, sumT) $ (mk_inj cs sumT u t))::
berghofe@21023
   707
            (map (subst o HOLogic.dest_Trueprop)
berghofe@21023
   708
              (Logic.strip_imp_prems r)))) frees
berghofe@21023
   709
      end
berghofe@21023
   710
berghofe@21023
   711
    (* make a disjunction of all introduction rules *)
berghofe@21023
   712
berghofe@21023
   713
    val fp_fun = absfree (sname, setT, (HOLogic.Collect_const sumT) $
berghofe@21023
   714
      absfree (xname, sumT, if null intr_ts then HOLogic.false_const
berghofe@21023
   715
        else foldr1 HOLogic.mk_disj (map transform_rule intr_ts)));
berghofe@21023
   716
berghofe@21023
   717
    (* add definiton of recursive sets to theory *)
berghofe@21023
   718
berghofe@21023
   719
    val rec_name = if alt_name = "" then
berghofe@21023
   720
      space_implode "_" (map Sign.base_name cnames) else alt_name;
berghofe@21023
   721
    val full_rec_name = if length cs < 2 then hd cnames
berghofe@21023
   722
      else Sign.full_name thy rec_name;
berghofe@21023
   723
berghofe@21023
   724
    val rec_const = list_comb
berghofe@21023
   725
      (Const (full_rec_name, paramTs ---> setT), params);
berghofe@21023
   726
berghofe@21023
   727
    val fp_def_term = Logic.mk_equals (rec_const,
berghofe@21023
   728
      Const (fp_name, (setT --> setT) --> setT) $ fp_fun);
berghofe@21023
   729
berghofe@21023
   730
    val def_terms = fp_def_term :: (if length cs < 2 then [] else
berghofe@21023
   731
      map (fn c => Logic.mk_equals (c, mk_vimage cs sumT rec_const c)) cs);
berghofe@21023
   732
berghofe@21023
   733
    val ([fp_def :: rec_sets_defs], thy') =
berghofe@21023
   734
      thy
berghofe@21023
   735
      |> cond_declare_consts declare_consts cs paramTs cnames
berghofe@21023
   736
      |> (if length cs < 2 then I
berghofe@21023
   737
          else Theory.add_consts_i [(rec_name, paramTs ---> setT, NoSyn)])
berghofe@21023
   738
      |> Theory.add_path rec_name
berghofe@21023
   739
      |> PureThy.add_defss_i false [(("defs", def_terms), [])];
berghofe@21023
   740
berghofe@21023
   741
    val mono = prove_mono setT fp_fun monos thy'
berghofe@21023
   742
berghofe@21023
   743
  in (thy', rec_name, mono, fp_def, rec_sets_defs, rec_const, sumT) end;
berghofe@21023
   744
berghofe@21023
   745
fun add_ind_def verbose declare_consts alt_name coind no_elim no_ind cs
berghofe@21023
   746
    intros monos thy params paramTs cTs cnames induct_cases =
berghofe@21023
   747
  let
berghofe@21023
   748
    val _ =
berghofe@21023
   749
      if verbose then message ("Proofs for " ^ coind_prefix coind ^ "inductive set(s) " ^
berghofe@21023
   750
        commas_quote (map Sign.base_name cnames)) else ();
berghofe@21023
   751
berghofe@21023
   752
    val ((intr_names, intr_ts), intr_atts) = apfst split_list (split_list intros);
berghofe@21023
   753
berghofe@21023
   754
    val (thy1, rec_name, mono, fp_def, rec_sets_defs, rec_const, sumT) =
berghofe@21023
   755
      mk_ind_def declare_consts alt_name coind cs intr_ts monos thy
berghofe@21023
   756
        params paramTs cTs cnames;
berghofe@21023
   757
    val ctxt1 = ProofContext.init thy1;
berghofe@21023
   758
berghofe@21023
   759
    val (intrs, unfold) = prove_intrs coind mono fp_def intr_ts rec_sets_defs ctxt1;
berghofe@21023
   760
    val elims = if no_elim then [] else
berghofe@21023
   761
      prove_elims cs cTs params intr_ts intr_names unfold rec_sets_defs ctxt1;
berghofe@21023
   762
    val raw_induct = if no_ind then Drule.asm_rl else
berghofe@21023
   763
      if coind then standard (rule_by_tactic
berghofe@21023
   764
        (rewrite_tac [mk_meta_eq vimage_Un] THEN
berghofe@21023
   765
          fold_tac rec_sets_defs) (mono RS (fp_def RS def_Collect_coinduct)))
berghofe@21023
   766
      else
berghofe@21023
   767
        prove_indrule cs cTs sumT rec_const params intr_ts mono fp_def
berghofe@21023
   768
          rec_sets_defs ctxt1;
berghofe@21023
   769
    val induct =
berghofe@21023
   770
      if coind then
berghofe@21023
   771
        (raw_induct, [RuleCases.case_names [rec_name],
berghofe@21023
   772
          RuleCases.case_conclusion (rec_name, induct_cases),
berghofe@21023
   773
          RuleCases.consumes 1])
berghofe@21023
   774
      else if no_ind orelse length cs > 1 then
berghofe@21023
   775
        (raw_induct, [RuleCases.case_names induct_cases, RuleCases.consumes 0])
berghofe@21023
   776
      else (raw_induct RSN (2, rev_mp), [RuleCases.case_names induct_cases, RuleCases.consumes 1]);
berghofe@21023
   777
berghofe@21023
   778
    val (intrs', thy2) =
berghofe@21023
   779
      thy1
berghofe@21023
   780
      |> PureThy.add_thms ((intr_names ~~ intrs) ~~ intr_atts);
berghofe@21023
   781
    val (([_, elims'], [induct']), thy3) =
berghofe@21023
   782
      thy2
berghofe@21023
   783
      |> PureThy.add_thmss
berghofe@21023
   784
        [(("intros", intrs'), []),
berghofe@21023
   785
          (("elims", elims), [RuleCases.consumes 1])]
berghofe@21023
   786
      ||>> PureThy.add_thms
berghofe@21023
   787
        [((coind_prefix coind ^ "induct", rulify (#1 induct)), #2 induct)];
berghofe@21023
   788
  in (thy3,
berghofe@21023
   789
    {defs = fp_def :: rec_sets_defs,
berghofe@21023
   790
     mono = mono,
berghofe@21023
   791
     unfold = unfold,
berghofe@21023
   792
     intrs = intrs',
berghofe@21023
   793
     elims = elims',
berghofe@21023
   794
     mk_cases = mk_cases elims',
berghofe@21023
   795
     raw_induct = rulify raw_induct,
berghofe@21023
   796
     induct = induct'})
berghofe@21023
   797
  end;
berghofe@21023
   798
berghofe@21023
   799
berghofe@21023
   800
(* external interfaces *)
berghofe@21023
   801
berghofe@21023
   802
fun try_term f msg thy t =
wenzelm@21395
   803
  (case try f t of
berghofe@21023
   804
    SOME x => x
berghofe@21023
   805
  | NONE => error (msg ^ Sign.string_of_term thy t));
berghofe@21023
   806
berghofe@21023
   807
fun add_inductive_i verbose declare_consts alt_name coind no_elim no_ind cs pre_intros monos thy =
berghofe@21023
   808
  let
berghofe@21023
   809
    val _ = Theory.requires thy "Inductive" (coind_prefix coind ^ "inductive definitions");
berghofe@21023
   810
berghofe@21023
   811
    (*parameters should agree for all mutually recursive components*)
berghofe@21023
   812
    val (_, params) = strip_comb (hd cs);
berghofe@21023
   813
    val paramTs = map (try_term (snd o dest_Free) "Parameter in recursive\
berghofe@21023
   814
      \ component is not a free variable: " thy) params;
berghofe@21023
   815
berghofe@21023
   816
    val cTs = map (try_term (HOLogic.dest_setT o fastype_of)
berghofe@21023
   817
      "Recursive component not of type set: " thy) cs;
berghofe@21023
   818
berghofe@21023
   819
    val cnames = map (try_term (fst o dest_Const o head_of)
berghofe@21023
   820
      "Recursive set not previously declared as constant: " thy) cs;
berghofe@21023
   821
berghofe@21023
   822
    val save_thy = thy
berghofe@21023
   823
      |> Theory.copy |> cond_declare_consts declare_consts cs paramTs cnames;
berghofe@21023
   824
    val intros = map (check_rule save_thy cs) pre_intros;
berghofe@21023
   825
    val induct_cases = map (#1 o #1) intros;
berghofe@21023
   826
berghofe@21023
   827
    val (thy1, result as {elims, induct, ...}) =
berghofe@21023
   828
      add_ind_def verbose declare_consts alt_name coind no_elim no_ind cs intros monos
berghofe@21023
   829
        thy params paramTs cTs cnames induct_cases;
berghofe@21023
   830
    val thy2 = thy1
berghofe@21023
   831
      |> put_inductives cnames ({names = cnames, coind = coind}, result)
berghofe@21023
   832
      |> add_cases_induct no_elim no_ind coind cnames elims induct
berghofe@21023
   833
      |> Theory.parent_path;
berghofe@21023
   834
  in (thy2, result) end;
berghofe@21023
   835
berghofe@21023
   836
fun add_inductive verbose coind c_strings intro_srcs raw_monos thy =
berghofe@21023
   837
  let
berghofe@21023
   838
    val cs = map (Sign.read_term thy) c_strings;
berghofe@21023
   839
berghofe@21023
   840
    val intr_names = map (fst o fst) intro_srcs;
berghofe@21023
   841
    fun read_rule s = Thm.read_cterm thy (s, propT)
berghofe@21023
   842
      handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s);
berghofe@21023
   843
    val intr_ts = map (Thm.term_of o read_rule o snd o fst) intro_srcs;
berghofe@21023
   844
    val intr_atts = map (map (Attrib.attribute thy) o snd) intro_srcs;
berghofe@21023
   845
    val (cs', intr_ts') = unify_consts thy cs intr_ts;
berghofe@21023
   846
wenzelm@21350
   847
    val (monos, thy') = thy |> IsarCmd.apply_theorems raw_monos;
berghofe@21023
   848
  in
berghofe@21023
   849
    add_inductive_i verbose false "" coind false false cs'
berghofe@21023
   850
      ((intr_names ~~ intr_ts') ~~ intr_atts) monos thy'
berghofe@21023
   851
  end;
berghofe@21023
   852
berghofe@21023
   853
berghofe@21023
   854
berghofe@21023
   855
(** package setup **)
berghofe@21023
   856
berghofe@21023
   857
(* setup theory *)
berghofe@21023
   858
berghofe@21023
   859
val setup =
berghofe@21023
   860
  Method.add_methods [("ind_cases", mk_cases_meth oo mk_cases_args,
berghofe@21023
   861
    "dynamic case analysis on sets")] #>
berghofe@21023
   862
  Attrib.add_attributes [("mono", Attrib.add_del_args mono_add mono_del,
berghofe@21023
   863
    "declaration of monotonicity rule")];
berghofe@21023
   864
berghofe@21023
   865
berghofe@21023
   866
(* outer syntax *)
berghofe@21023
   867
berghofe@21023
   868
local structure P = OuterParse and K = OuterKeyword in
berghofe@21023
   869
berghofe@21023
   870
fun mk_ind coind ((sets, intrs), monos) =
berghofe@21023
   871
  #1 o add_inductive true coind sets (map P.triple_swap intrs) monos;
berghofe@21023
   872
berghofe@21023
   873
fun ind_decl coind =
berghofe@21023
   874
  Scan.repeat1 P.term --
berghofe@21023
   875
  (P.$$$ "intros" |--
wenzelm@22101
   876
    P.!!! (Scan.repeat (SpecParse.opt_thm_name ":" -- P.prop))) --
wenzelm@22101
   877
  Scan.optional (P.$$$ "monos" |-- P.!!! SpecParse.xthms1) []
berghofe@21023
   878
  >> (Toplevel.theory o mk_ind coind);
berghofe@21023
   879
berghofe@21023
   880
val inductiveP =
berghofe@21023
   881
  OuterSyntax.command "inductive" "define inductive sets" K.thy_decl (ind_decl false);
berghofe@21023
   882
berghofe@21023
   883
val coinductiveP =
berghofe@21023
   884
  OuterSyntax.command "coinductive" "define coinductive sets" K.thy_decl (ind_decl true);
berghofe@21023
   885
berghofe@21023
   886
berghofe@21023
   887
val ind_cases =
wenzelm@22101
   888
  P.and_list1 (SpecParse.opt_thm_name ":" -- Scan.repeat1 P.prop)
berghofe@21023
   889
  >> (Toplevel.theory o inductive_cases);
berghofe@21023
   890
berghofe@21023
   891
val inductive_casesP =
berghofe@21023
   892
  OuterSyntax.command "inductive_cases"
berghofe@21023
   893
    "create simplified instances of elimination rules (improper)" K.thy_script ind_cases;
berghofe@21023
   894
berghofe@21023
   895
val _ = OuterSyntax.add_keywords ["intros", "monos"];
berghofe@21023
   896
val _ = OuterSyntax.add_parsers [inductiveP, coinductiveP, inductive_casesP];
berghofe@21023
   897
berghofe@21023
   898
end;
berghofe@21023
   899
berghofe@21023
   900
end;
berghofe@21023
   901