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