src/HOL/Tools/inductive_package.ML
author berghofe
Fri Oct 13 18:27:27 2006 +0200 (2006-10-13)
changeset 21024 63ab84bb64d1
parent 20901 437ca370dbd7
child 21048 e57e91f72831
permissions -rw-r--r--
Completely rewrote inductive definition package. Now allows to
define n-ary predicates directly (rather than sets of n-tuples),
using generalized fixpoint theory for arbitrary complete lattices.
berghofe@5094
     1
(*  Title:      HOL/Tools/inductive_package.ML
berghofe@5094
     2
    ID:         $Id$
berghofe@5094
     3
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
wenzelm@10735
     4
    Author:     Stefan Berghofer, TU Muenchen
wenzelm@10735
     5
    Author:     Markus Wenzel, TU Muenchen
berghofe@5094
     6
wenzelm@6424
     7
(Co)Inductive Definition module for HOL.
berghofe@5094
     8
berghofe@5094
     9
Features:
wenzelm@6424
    10
  * least or greatest fixedpoints
wenzelm@6424
    11
  * mutually recursive definitions
wenzelm@6424
    12
  * definitions involving arbitrary monotone operators
wenzelm@6424
    13
  * automatically proves introduction and elimination rules
berghofe@5094
    14
berghofe@5094
    15
  Introduction rules have the form
berghofe@21024
    16
  [| M Pj ti, ..., Q x, ... |] ==> Pk t
berghofe@5094
    17
  where M is some monotone operator (usually the identity)
berghofe@21024
    18
  Q x is any side condition on the free variables
berghofe@5094
    19
  ti, t are any terms
berghofe@21024
    20
  Pj, Pk are two of the predicates being defined in mutual recursion
berghofe@5094
    21
*)
berghofe@5094
    22
berghofe@5094
    23
signature INDUCTIVE_PACKAGE =
berghofe@5094
    24
sig
wenzelm@6424
    25
  val quiet_mode: bool ref
paulson@13626
    26
  val trace: bool ref
berghofe@21024
    27
  type inductive_result
berghofe@21024
    28
  type inductive_info
berghofe@21024
    29
  val get_inductive: Context.generic -> string -> inductive_info option
berghofe@21024
    30
  val the_mk_cases: Context.generic -> string -> string -> thm
berghofe@21024
    31
  val print_inductives: Context.generic -> unit
wenzelm@18728
    32
  val mono_add: attribute
wenzelm@18728
    33
  val mono_del: attribute
berghofe@21024
    34
  val get_monos: Context.generic -> thm list
wenzelm@10910
    35
  val inductive_forall_name: string
wenzelm@10910
    36
  val inductive_forall_def: thm
wenzelm@10910
    37
  val rulify: thm -> thm
wenzelm@15703
    38
  val inductive_cases: ((bstring * Attrib.src list) * string list) list -> theory -> theory
wenzelm@18728
    39
  val inductive_cases_i: ((bstring * attribute list) * term list) list -> theory -> theory
berghofe@21024
    40
  val add_inductive_i: bool -> bstring -> bool -> bool -> bool -> (string * typ option * mixfix) list ->
berghofe@21024
    41
    (string * typ option) list -> ((bstring * Attrib.src list) * term) list -> thm list ->
berghofe@21024
    42
      local_theory -> local_theory * inductive_result
berghofe@21024
    43
  val add_inductive: bool -> bool -> (string * string option * mixfix) list ->
berghofe@21024
    44
    (string * string option * mixfix) list ->
berghofe@21024
    45
    ((bstring * Attrib.src list) * string) list -> (thmref * Attrib.src list) list ->
berghofe@21024
    46
    local_theory -> local_theory * inductive_result
wenzelm@18708
    47
  val setup: theory -> theory
berghofe@5094
    48
end;
berghofe@5094
    49
wenzelm@6424
    50
structure InductivePackage: INDUCTIVE_PACKAGE =
berghofe@5094
    51
struct
berghofe@5094
    52
wenzelm@9598
    53
wenzelm@10729
    54
(** theory context references **)
wenzelm@10729
    55
nipkow@15525
    56
val mono_name = "Orderings.mono";
avigad@17010
    57
val gfp_name = "FixedPoint.gfp";
avigad@17010
    58
val lfp_name = "FixedPoint.lfp";
wenzelm@10735
    59
wenzelm@11991
    60
val inductive_forall_name = "HOL.induct_forall";
wenzelm@11991
    61
val inductive_forall_def = thm "induct_forall_def";
wenzelm@11991
    62
val inductive_conj_name = "HOL.induct_conj";
wenzelm@11991
    63
val inductive_conj_def = thm "induct_conj_def";
wenzelm@11991
    64
val inductive_conj = thms "induct_conj";
wenzelm@11991
    65
val inductive_atomize = thms "induct_atomize";
wenzelm@18463
    66
val inductive_rulify = thms "induct_rulify";
wenzelm@18463
    67
val inductive_rulify_fallback = thms "induct_rulify_fallback";
wenzelm@10729
    68
berghofe@21024
    69
val notTrueE = TrueI RSN (2, notE);
berghofe@21024
    70
val notFalseI = Seq.hd (atac 1 notI);
berghofe@21024
    71
val simp_thms' = map (fn s => mk_meta_eq (the (find_first
berghofe@21024
    72
  (equal (term_of (read_cterm HOL.thy (s, propT))) o prop_of) simp_thms)))
berghofe@21024
    73
  ["(~True) = False", "(~False) = True",
berghofe@21024
    74
   "(True --> ?P) = ?P", "(False --> ?P) = True",
berghofe@21024
    75
   "(?P & True) = ?P", "(True & ?P) = ?P"];
berghofe@21024
    76
wenzelm@10729
    77
wenzelm@10729
    78
wenzelm@10735
    79
(** theory data **)
berghofe@7710
    80
berghofe@21024
    81
type inductive_result =
berghofe@21024
    82
  {preds: term list, defs: thm list, elims: thm list, raw_induct: thm,
berghofe@21024
    83
   induct: thm, intrs: thm list, mk_cases: string -> thm, mono: thm, unfold: thm};
berghofe@7710
    84
berghofe@21024
    85
type inductive_info =
berghofe@21024
    86
  {names: string list, coind: bool} * inductive_result;
berghofe@21024
    87
berghofe@21024
    88
structure InductiveData = GenericDataFun
wenzelm@16432
    89
(struct
berghofe@21024
    90
  val name = "HOL/inductive2";
berghofe@7710
    91
  type T = inductive_info Symtab.table * thm list;
berghofe@7710
    92
berghofe@7710
    93
  val empty = (Symtab.empty, []);
wenzelm@16432
    94
  val extend = I;
wenzelm@16432
    95
  fun merge _ ((tab1, monos1), (tab2, monos2)) =
wenzelm@11502
    96
    (Symtab.merge (K true) (tab1, tab2), Drule.merge_rules (monos1, monos2));
berghofe@7710
    97
berghofe@21024
    98
  fun print generic (tab, monos) =
wenzelm@16364
    99
    [Pretty.strs ("(co)inductives:" ::
berghofe@21024
   100
      map #1 (NameSpace.extern_table
berghofe@21024
   101
        (Sign.const_space (Context.theory_of generic), tab))),  (* FIXME? *)
berghofe@21024
   102
     Pretty.big_list "monotonicity rules:"
berghofe@21024
   103
        (map (ProofContext.pretty_thm (Context.proof_of generic)) monos)]
wenzelm@8720
   104
    |> Pretty.chunks |> Pretty.writeln;
wenzelm@16432
   105
end);
berghofe@7710
   106
berghofe@7710
   107
val print_inductives = InductiveData.print;
berghofe@7710
   108
berghofe@7710
   109
berghofe@7710
   110
(* get and put data *)
berghofe@7710
   111
wenzelm@17412
   112
val get_inductive = Symtab.lookup o #1 o InductiveData.get;
berghofe@7710
   113
wenzelm@9598
   114
fun the_inductive thy name =
wenzelm@9598
   115
  (case get_inductive thy name of
berghofe@21024
   116
    NONE => error ("Unknown (co)inductive predicate " ^ quote name)
skalberg@15531
   117
  | SOME info => info);
wenzelm@9598
   118
wenzelm@12400
   119
val the_mk_cases = (#mk_cases o #2) oo the_inductive;
wenzelm@12400
   120
wenzelm@18222
   121
fun put_inductives names info = InductiveData.map (apfst (fn tab =>
wenzelm@18222
   122
  fold (fn name => Symtab.update_new (name, info)) names tab
berghofe@21024
   123
    handle Symtab.DUP dup => error ("Duplicate definition of (co)inductive predicate " ^ quote dup)));
berghofe@7710
   124
wenzelm@8277
   125
berghofe@7710
   126
berghofe@7710
   127
(** monotonicity rules **)
berghofe@7710
   128
wenzelm@9831
   129
val get_monos = #2 o InductiveData.get;
wenzelm@20901
   130
val map_monos = InductiveData.map o Library.apsnd;
wenzelm@8277
   131
berghofe@7710
   132
fun mk_mono thm =
berghofe@7710
   133
  let
berghofe@21024
   134
    fun eq2mono thm' = [(*standard*) (thm' RS (thm' RS eq_to_mono))] @
berghofe@7710
   135
      (case concl_of thm of
berghofe@7710
   136
          (_ $ (_ $ (Const ("Not", _) $ _) $ _)) => []
berghofe@21024
   137
        | _ => [(*standard*) (thm' RS (thm' RS eq_to_mono2))]);
berghofe@7710
   138
    val concl = concl_of thm
berghofe@7710
   139
  in
wenzelm@20872
   140
    if can Logic.dest_equals concl then
berghofe@7710
   141
      eq2mono (thm RS meta_eq_to_obj_eq)
berghofe@7710
   142
    else if can (HOLogic.dest_eq o HOLogic.dest_Trueprop) concl then
berghofe@7710
   143
      eq2mono thm
berghofe@7710
   144
    else [thm]
berghofe@7710
   145
  end;
berghofe@7710
   146
wenzelm@8634
   147
wenzelm@8634
   148
(* attributes *)
berghofe@7710
   149
wenzelm@20901
   150
val mono_add = Thm.declaration_attribute (fn th =>
berghofe@21024
   151
  map_monos (fold Drule.add_rule (mk_mono th)));
wenzelm@20901
   152
wenzelm@20901
   153
val mono_del = Thm.declaration_attribute (fn th =>
berghofe@21024
   154
  map_monos (fold Drule.del_rule (mk_mono th)));
berghofe@7710
   155
berghofe@7710
   156
wenzelm@7107
   157
wenzelm@10735
   158
(** misc utilities **)
wenzelm@6424
   159
berghofe@5662
   160
val quiet_mode = ref false;
paulson@13626
   161
val trace = ref false;  (*for debugging*)
wenzelm@10735
   162
fun message s = if ! quiet_mode then () else writeln s;
wenzelm@10735
   163
fun clean_message s = if ! quick_and_dirty then () else message s;
berghofe@5662
   164
wenzelm@6424
   165
fun coind_prefix true = "co"
wenzelm@6424
   166
  | coind_prefix false = "";
wenzelm@6424
   167
berghofe@21024
   168
fun log b m n = if m >= n then 0 else 1 + log b (b * m) n;
wenzelm@6424
   169
berghofe@21024
   170
fun make_bool_args f g [] i = []
berghofe@21024
   171
  | make_bool_args f g (x :: xs) i =
berghofe@21024
   172
      (if i mod 2 = 0 then f x else g x) :: make_bool_args f g xs (i div 2);
berghofe@21024
   173
berghofe@21024
   174
fun make_bool_args' xs =
berghofe@21024
   175
  make_bool_args (K HOLogic.false_const) (K HOLogic.true_const) xs;
berghofe@21024
   176
berghofe@21024
   177
fun find_arg T x [] = sys_error "find_arg"
berghofe@21024
   178
  | find_arg T x ((p as (_, (SOME _, _))) :: ps) =
berghofe@21024
   179
      apsnd (cons p) (find_arg T x ps)
berghofe@21024
   180
  | find_arg T x ((p as (U, (NONE, y))) :: ps) =
berghofe@21024
   181
      if T = U then (y, (U, (SOME x, y)) :: ps)
berghofe@21024
   182
      else apsnd (cons p) (find_arg T x ps);
berghofe@7020
   183
berghofe@21024
   184
fun make_args Ts xs =
berghofe@21024
   185
  map (fn (T, (NONE, ())) => Const ("arbitrary", T) | (_, (SOME t, ())) => t)
berghofe@21024
   186
    (fold (fn (t, T) => snd o find_arg T t) xs (map (rpair (NONE, ())) Ts));
berghofe@7020
   187
berghofe@21024
   188
fun make_args' Ts xs Us =
berghofe@21024
   189
  fst (fold_map (fn T => find_arg T ()) Us (Ts ~~ map (pair NONE) xs));
berghofe@7020
   190
berghofe@21024
   191
fun dest_predicate cs params t =
berghofe@5094
   192
  let
berghofe@21024
   193
    val k = length params;
berghofe@21024
   194
    val (c, ts) = strip_comb t;
berghofe@21024
   195
    val (xs, ys) = chop k ts;
berghofe@21024
   196
    val i = find_index_eq c cs;
berghofe@21024
   197
  in
berghofe@21024
   198
    if xs = params andalso i >= 0 then
berghofe@21024
   199
      SOME (c, i, ys, chop (length ys)
berghofe@21024
   200
        (List.drop (binder_types (fastype_of c), k)))
berghofe@21024
   201
    else NONE
berghofe@5094
   202
  end;
berghofe@5094
   203
berghofe@21024
   204
fun mk_names a 0 = []
berghofe@21024
   205
  | mk_names a 1 = [a]
berghofe@21024
   206
  | mk_names a n = map (fn i => a ^ string_of_int i) (1 upto n);
berghofe@10988
   207
wenzelm@6424
   208
wenzelm@6424
   209
wenzelm@10729
   210
(** process rules **)
wenzelm@10729
   211
wenzelm@10729
   212
local
berghofe@5094
   213
wenzelm@16432
   214
fun err_in_rule thy name t msg =
wenzelm@16432
   215
  error (cat_lines ["Ill-formed introduction rule " ^ quote name,
wenzelm@16432
   216
    Sign.string_of_term thy t, msg]);
wenzelm@10729
   217
wenzelm@16432
   218
fun err_in_prem thy name t p msg =
wenzelm@16432
   219
  error (cat_lines ["Ill-formed premise", Sign.string_of_term thy p,
wenzelm@16432
   220
    "in introduction rule " ^ quote name, Sign.string_of_term thy t, msg]);
berghofe@5094
   221
berghofe@21024
   222
val bad_concl = "Conclusion of introduction rule must be an inductive predicate";
wenzelm@10729
   223
berghofe@21024
   224
val bad_ind_occ = "Inductive predicate occurs in argument of inductive predicate";
berghofe@21024
   225
berghofe@21024
   226
val bad_app = "Inductive predicate must be applied to parameter(s) ";
paulson@11358
   227
wenzelm@16432
   228
fun atomize_term thy = MetaSimplifier.rewrite_term thy inductive_atomize [];
wenzelm@10729
   229
wenzelm@10729
   230
in
berghofe@5094
   231
berghofe@21024
   232
fun check_rule thy cs params ((name, att), rule) =
wenzelm@10729
   233
  let
berghofe@21024
   234
    val params' = Term.variant_frees rule (Logic.strip_params rule);
berghofe@21024
   235
    val frees = rev (map Free params');
berghofe@21024
   236
    val concl = subst_bounds (frees, Logic.strip_assums_concl rule);
berghofe@21024
   237
    val prems = map (curry subst_bounds frees) (Logic.strip_assums_hyp rule);
wenzelm@16432
   238
    val aprems = map (atomize_term thy) prems;
berghofe@21024
   239
    val arule = list_all_free (params', Logic.list_implies (aprems, concl));
berghofe@21024
   240
berghofe@21024
   241
    fun check_ind err t = case dest_predicate cs params t of
berghofe@21024
   242
        NONE => err (bad_app ^
berghofe@21024
   243
          commas (map (Sign.string_of_term thy) params))
berghofe@21024
   244
      | SOME (_, _, ys, _) =>
berghofe@21024
   245
          if exists (fn c => exists (fn t => Logic.occs (c, t)) ys) cs
berghofe@21024
   246
          then err bad_ind_occ else ();
berghofe@21024
   247
berghofe@21024
   248
    fun check_prem' prem t =
berghofe@21024
   249
      if head_of t mem cs then
berghofe@21024
   250
        check_ind (err_in_prem thy name rule prem) t
berghofe@21024
   251
      else (case t of
berghofe@21024
   252
          Abs (_, _, t) => check_prem' prem t
berghofe@21024
   253
        | t $ u => (check_prem' prem t; check_prem' prem u)
berghofe@21024
   254
        | _ => ());
berghofe@5094
   255
wenzelm@10729
   256
    fun check_prem (prem, aprem) =
berghofe@21024
   257
      if can HOLogic.dest_Trueprop aprem then check_prem' prem prem
wenzelm@16432
   258
      else err_in_prem thy name rule prem "Non-atomic premise";
wenzelm@10729
   259
  in
paulson@11358
   260
    (case concl of
berghofe@21024
   261
       Const ("Trueprop", _) $ t => 
berghofe@21024
   262
         if head_of t mem cs then
berghofe@21024
   263
           (check_ind (err_in_rule thy name rule) t;
berghofe@21024
   264
            List.app check_prem (prems ~~ aprems))
berghofe@21024
   265
         else err_in_rule thy name rule bad_concl
berghofe@21024
   266
     | _ => err_in_rule thy name rule bad_concl);
berghofe@21024
   267
    ((name, att), arule)
wenzelm@10729
   268
  end;
berghofe@5094
   269
wenzelm@18222
   270
val rulify =  (* FIXME norm_hhf *)
wenzelm@18222
   271
  hol_simplify inductive_conj
wenzelm@18463
   272
  #> hol_simplify inductive_rulify
wenzelm@18463
   273
  #> hol_simplify inductive_rulify_fallback
berghofe@21024
   274
  (*#> standard*);
wenzelm@10729
   275
wenzelm@10729
   276
end;
wenzelm@10729
   277
berghofe@5094
   278
wenzelm@6424
   279
berghofe@21024
   280
(** properties of (co)inductive predicates **)
wenzelm@6424
   281
wenzelm@10735
   282
(* prepare cases and induct rules *)
wenzelm@8316
   283
berghofe@21024
   284
fun add_cases_induct no_elim no_induct coind rec_name names elims induct =
wenzelm@8316
   285
  let
berghofe@21024
   286
    fun cases_spec name elim =
berghofe@21024
   287
      LocalTheory.note ((NameSpace.append (Sign.base_name name) "cases",
berghofe@21024
   288
        [Attrib.internal (InductAttrib.cases_set name)]), [elim]) #> snd;
haftmann@18330
   289
    val cases_specs = if no_elim then [] else map2 cases_spec names elims;
wenzelm@8316
   290
wenzelm@18728
   291
    val induct_att = if coind then InductAttrib.coinduct_set else InductAttrib.induct_set;
berghofe@21024
   292
    fun induct_specs ctxt =
berghofe@21024
   293
      if no_induct then ctxt
wenzelm@18463
   294
      else
wenzelm@18463
   295
        let
wenzelm@19874
   296
          val rules = names ~~ ProjectRule.projects ctxt (1 upto length names) induct;
wenzelm@18463
   297
          val inducts = map (RuleCases.save induct o standard o #2) rules;
wenzelm@18463
   298
        in
berghofe@21024
   299
          ctxt |>
berghofe@21024
   300
          LocalTheory.notes (rules |> map (fn (name, th) =>
berghofe@21024
   301
            (("", [Attrib.internal (RuleCases.consumes 1),
berghofe@21024
   302
                Attrib.internal (induct_att name)]), [([th], [])]))) |> snd |>
berghofe@21024
   303
          LocalTheory.note ((NameSpace.append rec_name
berghofe@21024
   304
              (coind_prefix coind ^ "inducts"),
berghofe@21024
   305
            [Attrib.internal (RuleCases.consumes 1)]), inducts) |> snd
wenzelm@18463
   306
        end;
wenzelm@18463
   307
  in Library.apply cases_specs #> induct_specs end;
wenzelm@8316
   308
wenzelm@8316
   309
wenzelm@8316
   310
berghofe@21024
   311
(** proofs for (co)inductive predicates **)
wenzelm@6424
   312
wenzelm@10735
   313
(* prove monotonicity -- NOT subject to quick_and_dirty! *)
berghofe@5094
   314
berghofe@21024
   315
fun prove_mono predT fp_fun monos ctxt =
wenzelm@10735
   316
 (message "  Proving monotonicity ...";
berghofe@21024
   317
  Goal.prove ctxt [] []   (*NO quick_and_dirty here!*)
wenzelm@17985
   318
    (HOLogic.mk_Trueprop
berghofe@21024
   319
      (Const (mono_name, (predT --> predT) --> HOLogic.boolT) $ fp_fun))
wenzelm@17985
   320
    (fn _ => EVERY [rtac monoI 1,
berghofe@21024
   321
      REPEAT (resolve_tac [le_funI, le_boolI'] 1),
berghofe@21024
   322
      REPEAT (FIRST
berghofe@21024
   323
        [atac 1,
berghofe@21024
   324
         resolve_tac (List.concat (map mk_mono monos) @
berghofe@21024
   325
           get_monos (Context.Proof ctxt)) 1,
berghofe@21024
   326
         etac le_funE 1, dtac le_boolD 1])]));
berghofe@5094
   327
wenzelm@6424
   328
wenzelm@10735
   329
(* prove introduction rules *)
berghofe@5094
   330
berghofe@21024
   331
fun prove_intrs coind mono fp_def k intr_ts rec_preds_defs ctxt =
berghofe@5094
   332
  let
wenzelm@10735
   333
    val _ = clean_message "  Proving the introduction rules ...";
berghofe@5094
   334
berghofe@21024
   335
    val unfold = funpow k (fn th => th RS fun_cong)
berghofe@21024
   336
      (mono RS (fp_def RS
berghofe@21024
   337
        (if coind then def_gfp_unfold else def_lfp_unfold)));
berghofe@5094
   338
berghofe@5094
   339
    fun select_disj 1 1 = []
berghofe@5094
   340
      | select_disj _ 1 = [rtac disjI1]
berghofe@5094
   341
      | select_disj n i = (rtac disjI2)::(select_disj (n - 1) (i - 1));
berghofe@5094
   342
berghofe@21024
   343
    val rules = [refl, TrueI, notFalseI, exI, conjI];
berghofe@21024
   344
berghofe@21024
   345
    val intrs = map_index (fn (i, intr) =>
wenzelm@20047
   346
      rulify (SkipProof.prove ctxt [] [] intr (fn _ => EVERY
berghofe@21024
   347
       [rewrite_goals_tac rec_preds_defs,
berghofe@21024
   348
        rtac (unfold RS iffD2) 1,
berghofe@21024
   349
        EVERY1 (select_disj (length intr_ts) (i + 1)),
wenzelm@17985
   350
        (*Not ares_tac, since refl must be tried before any equality assumptions;
wenzelm@17985
   351
          backtracking may occur if the premises have extra variables!*)
berghofe@21024
   352
        DEPTH_SOLVE_1 (resolve_tac rules 1 APPEND assume_tac 1)]))) intr_ts
berghofe@5094
   353
berghofe@5094
   354
  in (intrs, unfold) end;
berghofe@5094
   355
wenzelm@6424
   356
wenzelm@10735
   357
(* prove elimination rules *)
berghofe@5094
   358
berghofe@21024
   359
fun prove_elims cs params intr_ts intr_names unfold rec_preds_defs ctxt =
berghofe@5094
   360
  let
wenzelm@10735
   361
    val _ = clean_message "  Proving the elimination rules ...";
berghofe@5094
   362
berghofe@21024
   363
    val ([pname], ctxt') = Variable.variant_fixes ["P"] ctxt;
berghofe@21024
   364
    val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
berghofe@21024
   365
berghofe@21024
   366
    fun dest_intr r =
berghofe@21024
   367
      (the (dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))),
berghofe@21024
   368
       Logic.strip_assums_hyp r, Logic.strip_params r);
berghofe@21024
   369
berghofe@21024
   370
    val intrs = map dest_intr intr_ts ~~ intr_names;
berghofe@21024
   371
berghofe@21024
   372
    val rules1 = [disjE, exE, FalseE];
berghofe@21024
   373
    val rules2 = [conjE, FalseE, notTrueE];
berghofe@21024
   374
berghofe@21024
   375
    fun prove_elim c =
berghofe@21024
   376
      let
berghofe@21024
   377
        val Ts = List.drop (binder_types (fastype_of c), length params);
berghofe@21024
   378
        val (anames, ctxt'') = Variable.variant_fixes (mk_names "a" (length Ts)) ctxt';
berghofe@21024
   379
        val frees = map Free (anames ~~ Ts);
berghofe@21024
   380
berghofe@21024
   381
        fun mk_elim_prem ((_, _, us, _), ts, params') =
berghofe@21024
   382
          list_all (params',
berghofe@21024
   383
            Logic.list_implies (map (HOLogic.mk_Trueprop o HOLogic.mk_eq)
berghofe@21024
   384
              (frees ~~ us) @ ts, P));
berghofe@21024
   385
        val c_intrs = (List.filter (equal c o #1 o #1 o #1) intrs);
berghofe@21024
   386
        val prems = HOLogic.mk_Trueprop (list_comb (c, params @ frees)) ::
berghofe@21024
   387
           map mk_elim_prem (map #1 c_intrs)
berghofe@21024
   388
      in
berghofe@21024
   389
        SkipProof.prove ctxt'' [] prems P
berghofe@21024
   390
          (fn {prems, ...} => EVERY
berghofe@21024
   391
            [cut_facts_tac [hd prems] 1,
berghofe@21024
   392
             rewrite_goals_tac rec_preds_defs,
berghofe@21024
   393
             dtac (unfold RS iffD1) 1,
berghofe@21024
   394
             REPEAT (FIRSTGOAL (eresolve_tac rules1)),
berghofe@21024
   395
             REPEAT (FIRSTGOAL (eresolve_tac rules2)),
berghofe@21024
   396
             EVERY (map (fn prem =>
berghofe@21024
   397
               DEPTH_SOLVE_1 (ares_tac [rewrite_rule rec_preds_defs prem, conjI] 1)) (tl prems))])
berghofe@21024
   398
          |> rulify
berghofe@21024
   399
          |> singleton (ProofContext.export ctxt'' ctxt)
berghofe@21024
   400
          |> RuleCases.name (map #2 c_intrs)
berghofe@21024
   401
      end
berghofe@21024
   402
berghofe@21024
   403
   in map prove_elim cs end;
berghofe@5094
   404
wenzelm@6424
   405
wenzelm@10735
   406
(* derivation of simplified elimination rules *)
berghofe@5094
   407
wenzelm@11682
   408
local
wenzelm@11682
   409
berghofe@21024
   410
(*cprop should have the form "Si t" where Si is an inductive predicate*)
berghofe@21024
   411
val mk_cases_err = "mk_cases: proposition not an inductive predicate";
wenzelm@9598
   412
wenzelm@11682
   413
(*delete needless equality assumptions*)
wenzelm@11682
   414
val refl_thin = prove_goal HOL.thy "!!P. a = a ==> P ==> P" (fn _ => [assume_tac 1]);
berghofe@21024
   415
val elim_rls = [asm_rl, FalseE, refl_thin, conjE, exE];
wenzelm@11682
   416
val elim_tac = REPEAT o Tactic.eresolve_tac elim_rls;
wenzelm@11682
   417
wenzelm@11682
   418
fun simp_case_tac solved ss i =
wenzelm@11682
   419
  EVERY' [elim_tac, asm_full_simp_tac ss, elim_tac, REPEAT o bound_hyp_subst_tac] i
wenzelm@11682
   420
  THEN_MAYBE (if solved then no_tac else all_tac);
wenzelm@11682
   421
wenzelm@11682
   422
in
wenzelm@9598
   423
wenzelm@9598
   424
fun mk_cases_i elims ss cprop =
wenzelm@7107
   425
  let
wenzelm@7107
   426
    val prem = Thm.assume cprop;
wenzelm@11682
   427
    val tac = ALLGOALS (simp_case_tac false ss) THEN prune_params_tac;
wenzelm@9298
   428
    fun mk_elim rl = Drule.standard (Tactic.rule_by_tactic tac (prem RS rl));
wenzelm@7107
   429
  in
wenzelm@7107
   430
    (case get_first (try mk_elim) elims of
skalberg@15531
   431
      SOME r => r
skalberg@15531
   432
    | NONE => error (Pretty.string_of (Pretty.block
wenzelm@9598
   433
        [Pretty.str mk_cases_err, Pretty.fbrk, Display.pretty_cterm cprop])))
wenzelm@7107
   434
  end;
wenzelm@7107
   435
paulson@6141
   436
fun mk_cases elims s =
wenzelm@16432
   437
  mk_cases_i elims (simpset()) (Thm.read_cterm (Thm.theory_of_thm (hd elims)) (s, propT));
wenzelm@9598
   438
berghofe@21024
   439
fun smart_mk_cases ctxt ss cprop =
wenzelm@9598
   440
  let
berghofe@21024
   441
    val c = #1 (Term.dest_Const (Term.head_of (HOLogic.dest_Trueprop
berghofe@21024
   442
      (Logic.strip_imp_concl (Thm.term_of cprop))))) handle TERM _ => error mk_cases_err;
berghofe@21024
   443
    val (_, {elims, ...}) = the_inductive ctxt c;
wenzelm@9598
   444
  in mk_cases_i elims ss cprop end;
wenzelm@7107
   445
wenzelm@11682
   446
end;
wenzelm@11682
   447
wenzelm@7107
   448
wenzelm@7107
   449
(* inductive_cases(_i) *)
wenzelm@7107
   450
wenzelm@12609
   451
fun gen_inductive_cases prep_att prep_prop args thy =
wenzelm@9598
   452
  let
wenzelm@16432
   453
    val cert_prop = Thm.cterm_of thy o prep_prop (ProofContext.init thy);
berghofe@21024
   454
    val mk_cases = smart_mk_cases (Context.Theory thy) (Simplifier.simpset_of thy) o cert_prop;
wenzelm@12609
   455
wenzelm@12876
   456
    val facts = args |> map (fn ((a, atts), props) =>
wenzelm@12876
   457
     ((a, map (prep_att thy) atts), map (Thm.no_attributes o single o mk_cases) props));
wenzelm@20901
   458
  in thy |> PureThy.note_thmss_i "" facts |> snd end;
berghofe@5094
   459
wenzelm@18728
   460
val inductive_cases = gen_inductive_cases Attrib.attribute ProofContext.read_prop;
wenzelm@12172
   461
val inductive_cases_i = gen_inductive_cases (K I) ProofContext.cert_prop;
wenzelm@7107
   462
wenzelm@6424
   463
wenzelm@9598
   464
(* mk_cases_meth *)
wenzelm@9598
   465
wenzelm@9598
   466
fun mk_cases_meth (ctxt, raw_props) =
wenzelm@9598
   467
  let
wenzelm@9598
   468
    val thy = ProofContext.theory_of ctxt;
wenzelm@15032
   469
    val ss = local_simpset_of ctxt;
wenzelm@16432
   470
    val cprops = map (Thm.cterm_of thy o ProofContext.read_prop ctxt) raw_props;
berghofe@21024
   471
  in Method.erule 0 (map (smart_mk_cases (Context.Theory thy) ss) cprops) end;
wenzelm@9598
   472
wenzelm@9598
   473
val mk_cases_args = Method.syntax (Scan.lift (Scan.repeat1 Args.name));
wenzelm@9598
   474
wenzelm@9598
   475
wenzelm@10735
   476
(* prove induction rule *)
berghofe@5094
   477
berghofe@21024
   478
fun prove_indrule cs argTs bs xs rec_const params intr_ts mono
berghofe@21024
   479
    fp_def rec_preds_defs ctxt =
berghofe@5094
   480
  let
wenzelm@10735
   481
    val _ = clean_message "  Proving the induction rule ...";
wenzelm@20047
   482
    val thy = ProofContext.theory_of ctxt;
berghofe@5094
   483
berghofe@21024
   484
    (* predicates for induction rule *)
berghofe@21024
   485
berghofe@21024
   486
    val (pnames, ctxt') = Variable.variant_fixes (mk_names "P" (length cs)) ctxt;
berghofe@21024
   487
    val preds = map Free (pnames ~~
berghofe@21024
   488
      map (fn c => List.drop (binder_types (fastype_of c), length params) --->
berghofe@21024
   489
        HOLogic.boolT) cs);
berghofe@21024
   490
berghofe@21024
   491
    (* transform an introduction rule into a premise for induction rule *)
berghofe@21024
   492
berghofe@21024
   493
    fun mk_ind_prem r =
berghofe@21024
   494
      let
berghofe@21024
   495
        fun subst s = (case dest_predicate cs params s of
berghofe@21024
   496
            SOME (_, i, ys, (_, Ts)) =>
berghofe@21024
   497
              let
berghofe@21024
   498
                val k = length Ts;
berghofe@21024
   499
                val bs = map Bound (k - 1 downto 0);
berghofe@21024
   500
                val P = list_comb (List.nth (preds, i), ys @ bs);
berghofe@21024
   501
                val Q = list_abs (mk_names "x" k ~~ Ts,
berghofe@21024
   502
                  HOLogic.mk_binop inductive_conj_name (list_comb (s, bs), P))
berghofe@21024
   503
              in (Q, case Ts of [] => SOME (s, P) | _ => NONE) end
berghofe@21024
   504
          | NONE => (case s of
berghofe@21024
   505
              (t $ u) => (fst (subst t) $ fst (subst u), NONE)
berghofe@21024
   506
            | (Abs (a, T, t)) => (Abs (a, T, fst (subst t)), NONE)
berghofe@21024
   507
            | _ => (s, NONE)));
berghofe@7293
   508
berghofe@21024
   509
        fun mk_prem (s, prems) = (case subst s of
berghofe@21024
   510
              (_, SOME (t, u)) => t :: u :: prems
berghofe@21024
   511
            | (t, _) => t :: prems);
berghofe@21024
   512
berghofe@21024
   513
        val SOME (_, i, ys, _) = dest_predicate cs params
berghofe@21024
   514
          (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))
berghofe@21024
   515
berghofe@21024
   516
      in list_all_free (Logic.strip_params r,
berghofe@21024
   517
        Logic.list_implies (map HOLogic.mk_Trueprop (foldr mk_prem
berghofe@21024
   518
          [] (map HOLogic.dest_Trueprop (Logic.strip_assums_hyp r))),
berghofe@21024
   519
            HOLogic.mk_Trueprop (list_comb (List.nth (preds, i), ys))))
berghofe@21024
   520
      end;
berghofe@21024
   521
berghofe@21024
   522
    val ind_prems = map mk_ind_prem intr_ts;
berghofe@21024
   523
berghofe@21024
   524
    (* make conclusions for induction rules *)
berghofe@21024
   525
berghofe@21024
   526
    val Tss = map (binder_types o fastype_of) preds;
berghofe@21024
   527
    val (xnames, ctxt'') =
berghofe@21024
   528
      Variable.variant_fixes (mk_names "x" (length (flat Tss))) ctxt';
berghofe@21024
   529
    val mutual_ind_concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
berghofe@21024
   530
        (map (fn (((xnames, Ts), c), P) =>
berghofe@21024
   531
           let val frees = map Free (xnames ~~ Ts)
berghofe@21024
   532
           in HOLogic.mk_imp
berghofe@21024
   533
             (list_comb (c, params @ frees), list_comb (P, frees))
berghofe@21024
   534
           end) (unflat Tss xnames ~~ Tss ~~ cs ~~ preds)));
berghofe@5094
   535
paulson@13626
   536
    val dummy = if !trace then
wenzelm@17985
   537
                (writeln "ind_prems = ";
wenzelm@17985
   538
                 List.app (writeln o Sign.string_of_term thy) ind_prems)
wenzelm@17985
   539
            else ();
paulson@13626
   540
berghofe@5094
   541
    (* make predicate for instantiation of abstract induction rule *)
berghofe@5094
   542
berghofe@21024
   543
    val ind_pred = fold_rev lambda (bs @ xs) (foldr1 HOLogic.mk_conj
berghofe@21024
   544
      (map_index (fn (i, P) => foldr HOLogic.mk_imp
berghofe@21024
   545
         (list_comb (P, make_args' argTs xs (binder_types (fastype_of P))))
berghofe@21024
   546
         (make_bool_args HOLogic.mk_not I bs i)) preds));
berghofe@5094
   547
berghofe@5094
   548
    val ind_concl = HOLogic.mk_Trueprop
berghofe@21024
   549
      (HOLogic.mk_binrel "Orderings.less_eq" (rec_const, ind_pred));
berghofe@5094
   550
paulson@13626
   551
    val raw_fp_induct = (mono RS (fp_def RS def_lfp_induct));
paulson@13626
   552
paulson@13626
   553
    val dummy = if !trace then
wenzelm@17985
   554
                (writeln "raw_fp_induct = "; print_thm raw_fp_induct)
wenzelm@17985
   555
            else ();
paulson@13626
   556
berghofe@21024
   557
    val induct = SkipProof.prove ctxt'' [] ind_prems ind_concl
wenzelm@20248
   558
      (fn {prems, ...} => EVERY
wenzelm@17985
   559
        [rewrite_goals_tac [inductive_conj_def],
berghofe@21024
   560
         DETERM (rtac raw_fp_induct 1),
berghofe@21024
   561
         REPEAT (resolve_tac [le_funI, le_boolI] 1),
berghofe@21024
   562
         rewrite_goals_tac (map mk_meta_eq [meet_fun_eq, meet_bool_eq] @ simp_thms'),
berghofe@21024
   563
         (*This disjE separates out the introduction rules*)
berghofe@21024
   564
         REPEAT (FIRSTGOAL (eresolve_tac [disjE, exE, FalseE])),
berghofe@5094
   565
         (*Now break down the individual cases.  No disjE here in case
berghofe@5094
   566
           some premise involves disjunction.*)
paulson@13747
   567
         REPEAT (FIRSTGOAL (etac conjE ORELSE' bound_hyp_subst_tac)),
berghofe@21024
   568
         REPEAT (FIRSTGOAL
berghofe@21024
   569
           (resolve_tac [conjI, impI] ORELSE' (etac notE THEN' atac))),
berghofe@21024
   570
         EVERY (map (fn prem => DEPTH_SOLVE_1 (ares_tac [rewrite_rule
berghofe@21024
   571
           (inductive_conj_def :: rec_preds_defs) prem, conjI, refl] 1)) prems)]);
berghofe@5094
   572
berghofe@21024
   573
    val lemma = SkipProof.prove ctxt'' [] []
wenzelm@17985
   574
      (Logic.mk_implies (ind_concl, mutual_ind_concl)) (fn _ => EVERY
berghofe@21024
   575
        [rewrite_goals_tac rec_preds_defs,
berghofe@5094
   576
         REPEAT (EVERY
berghofe@5094
   577
           [REPEAT (resolve_tac [conjI, impI] 1),
berghofe@21024
   578
            REPEAT (eresolve_tac [le_funE, le_boolE] 1),
berghofe@21024
   579
            atac 1,
berghofe@21024
   580
            rewrite_goals_tac simp_thms',
berghofe@21024
   581
            atac 1])])
berghofe@5094
   582
berghofe@21024
   583
  in singleton (ProofContext.export ctxt'' ctxt) (induct RS lemma) end;
berghofe@5094
   584
wenzelm@6424
   585
wenzelm@6424
   586
berghofe@21024
   587
(** specification of (co)inductive predicates **)
wenzelm@10729
   588
berghofe@21024
   589
fun mk_ind_def alt_name coind cs intr_ts monos
berghofe@21024
   590
      params cnames_syn ctxt =
berghofe@5094
   591
  let
wenzelm@10735
   592
    val fp_name = if coind then gfp_name else lfp_name;
berghofe@5094
   593
berghofe@21024
   594
    val argTs = fold (fn c => fn Ts => Ts @
berghofe@21024
   595
      (List.drop (binder_types (fastype_of c), length params) \\ Ts)) cs [];
berghofe@21024
   596
    val k = log 2 1 (length cs);
berghofe@21024
   597
    val predT = replicate k HOLogic.boolT ---> argTs ---> HOLogic.boolT;
berghofe@21024
   598
    val p :: xs = map Free (Variable.variant_frees ctxt intr_ts
berghofe@21024
   599
      (("p", predT) :: (mk_names "x" (length argTs) ~~ argTs)));
berghofe@21024
   600
    val bs = map Free (Variable.variant_frees ctxt (p :: xs @ intr_ts)
berghofe@21024
   601
      (map (rpair HOLogic.boolT) (mk_names "b" k)));
berghofe@21024
   602
berghofe@21024
   603
    fun subst t = (case dest_predicate cs params t of
berghofe@21024
   604
        SOME (_, i, ts, (Ts, Us)) =>
berghofe@21024
   605
          let val zs = map Bound (length Us - 1 downto 0)
berghofe@21024
   606
          in
berghofe@21024
   607
            list_abs (map (pair "z") Us, list_comb (p,
berghofe@21024
   608
              make_bool_args' bs i @ make_args argTs ((ts ~~ Ts) @ (zs ~~ Us))))
berghofe@21024
   609
          end
berghofe@21024
   610
      | NONE => (case t of
berghofe@21024
   611
          t1 $ t2 => subst t1 $ subst t2
berghofe@21024
   612
        | Abs (x, T, u) => Abs (x, T, subst u)
berghofe@21024
   613
        | _ => t));
berghofe@5149
   614
berghofe@5094
   615
    (* transform an introduction rule into a conjunction  *)
berghofe@21024
   616
    (*   [| p_i t; ... |] ==> p_j u                       *)
berghofe@5094
   617
    (* is transformed into                                *)
berghofe@21024
   618
    (*   b_j & x_j = u & p b_j t & ...                    *)
berghofe@5094
   619
berghofe@5094
   620
    fun transform_rule r =
berghofe@5094
   621
      let
berghofe@21024
   622
        val SOME (_, i, ts, (Ts, _)) = dest_predicate cs params
berghofe@21024
   623
          (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))
berghofe@5094
   624
berghofe@21024
   625
      in foldr (fn ((x, T), P) => HOLogic.exists_const T $ (Abs (x, T, P)))
skalberg@15574
   626
        (foldr1 HOLogic.mk_conj
berghofe@21024
   627
          (make_bool_args HOLogic.mk_not I bs i @
berghofe@21024
   628
           map HOLogic.mk_eq (make_args' argTs xs Ts ~~ ts) @
berghofe@21024
   629
           map (subst o HOLogic.dest_Trueprop)
berghofe@21024
   630
             (Logic.strip_assums_hyp r))) (Logic.strip_params r)
berghofe@5094
   631
      end
berghofe@5094
   632
berghofe@5094
   633
    (* make a disjunction of all introduction rules *)
berghofe@5094
   634
berghofe@21024
   635
    val fp_fun = fold_rev lambda (p :: bs @ xs)
berghofe@21024
   636
      (if null intr_ts then HOLogic.false_const
berghofe@21024
   637
       else foldr1 HOLogic.mk_disj (map transform_rule intr_ts));
berghofe@5094
   638
berghofe@21024
   639
    (* add definiton of recursive predicates to theory *)
berghofe@5094
   640
berghofe@14235
   641
    val rec_name = if alt_name = "" then
berghofe@21024
   642
      space_implode "_" (map fst cnames_syn) else alt_name;
berghofe@5094
   643
berghofe@21024
   644
    val ((rec_const, (_, fp_def)), ctxt') = ctxt |>
berghofe@21024
   645
      Variable.add_fixes (map (fst o dest_Free) params) |> snd |>
berghofe@21024
   646
      fold Variable.declare_term intr_ts |>
berghofe@21024
   647
      LocalTheory.def
berghofe@21024
   648
        ((rec_name, case cnames_syn of [(_, syn)] => syn | _ => NoSyn),
berghofe@21024
   649
         (("", []), fold_rev lambda params
berghofe@21024
   650
           (Const (fp_name, (predT --> predT) --> predT) $ fp_fun)));
berghofe@21024
   651
    val fp_def' = Simplifier.rewrite (HOL_basic_ss addsimps [fp_def])
berghofe@21024
   652
      (cterm_of (ProofContext.theory_of ctxt') (list_comb (rec_const, params)));
berghofe@21024
   653
    val specs = if length cs < 2 then [] else
berghofe@21024
   654
      map_index (fn (i, (name_mx, c)) =>
berghofe@21024
   655
        let
berghofe@21024
   656
          val Ts = List.drop (binder_types (fastype_of c), length params);
berghofe@21024
   657
          val xs = map Free (Variable.variant_frees ctxt intr_ts
berghofe@21024
   658
            (mk_names "x" (length Ts) ~~ Ts))
berghofe@21024
   659
        in
berghofe@21024
   660
          (name_mx, (("", []), fold_rev lambda (params @ xs)
berghofe@21024
   661
            (list_comb (rec_const, params @ make_bool_args' bs i @
berghofe@21024
   662
              make_args argTs (xs ~~ Ts)))))
berghofe@21024
   663
        end) (cnames_syn ~~ cs);
berghofe@21024
   664
    val (consts_defs, ctxt'') = fold_map LocalTheory.def specs ctxt';
berghofe@21024
   665
    val preds = (case cs of [_] => [rec_const] | _ => map #1 consts_defs);
berghofe@5094
   666
berghofe@21024
   667
    val mono = prove_mono predT fp_fun monos ctxt''
berghofe@5094
   668
berghofe@21024
   669
  in (ctxt'', rec_name, mono, fp_def', map (#2 o #2) consts_defs,
berghofe@21024
   670
    list_comb (rec_const, params), preds, argTs, bs, xs)
berghofe@21024
   671
  end;
berghofe@5094
   672
berghofe@21024
   673
fun add_ind_def verbose alt_name coind no_elim no_ind cs
berghofe@21024
   674
    intros monos params cnames_syn induct_cases ctxt =
berghofe@9072
   675
  let
wenzelm@10735
   676
    val _ =
berghofe@21024
   677
      if verbose then message ("Proofs for " ^ coind_prefix coind ^ "inductive predicate(s) " ^
berghofe@21024
   678
        commas_quote (map fst cnames_syn)) else ();
berghofe@9072
   679
berghofe@21024
   680
    val ((intr_names, intr_atts), intr_ts) = apfst split_list (split_list intros);
berghofe@21024
   681
berghofe@21024
   682
    val (ctxt1, rec_name, mono, fp_def, rec_preds_defs, rec_const, preds,
berghofe@21024
   683
      argTs, bs, xs) = mk_ind_def alt_name coind cs intr_ts
berghofe@21024
   684
        monos params cnames_syn ctxt;
berghofe@9072
   685
berghofe@21024
   686
    val (intrs, unfold) = prove_intrs coind mono fp_def (length bs + length xs)
berghofe@21024
   687
      intr_ts rec_preds_defs ctxt1;
berghofe@21024
   688
    val elims = ProofContext.export ctxt1 ctxt (if no_elim then [] else
berghofe@21024
   689
      prove_elims cs params intr_ts intr_names unfold rec_preds_defs ctxt1);
berghofe@21024
   690
    val raw_induct = singleton (ProofContext.export ctxt1 ctxt)
berghofe@21024
   691
      (if no_ind then Drule.asm_rl else
berghofe@21024
   692
       if coind then ObjectLogic.rulify (rule_by_tactic
berghofe@21024
   693
         (rewrite_tac [le_fun_def, le_bool_def] THEN
berghofe@21024
   694
           fold_tac rec_preds_defs) (mono RS (fp_def RS def_coinduct)))
berghofe@21024
   695
       else
berghofe@21024
   696
         prove_indrule cs argTs bs xs rec_const params intr_ts mono fp_def
berghofe@21024
   697
           rec_preds_defs ctxt1);
wenzelm@12165
   698
    val induct =
wenzelm@18222
   699
      if coind then
wenzelm@18222
   700
        (raw_induct, [RuleCases.case_names [rec_name],
wenzelm@18234
   701
          RuleCases.case_conclusion (rec_name, induct_cases),
wenzelm@18222
   702
          RuleCases.consumes 1])
wenzelm@18222
   703
      else if no_ind orelse length cs > 1 then
wenzelm@18222
   704
        (raw_induct, [RuleCases.case_names induct_cases, RuleCases.consumes 0])
wenzelm@18222
   705
      else (raw_induct RSN (2, rev_mp), [RuleCases.case_names induct_cases, RuleCases.consumes 1]);
berghofe@5094
   706
berghofe@21024
   707
    val (intrs', ctxt2) =
berghofe@21024
   708
      ctxt1 |>
berghofe@21024
   709
      LocalTheory.notes (map (NameSpace.append rec_name) intr_names ~~ intr_atts ~~
berghofe@21024
   710
        map (single o rpair [] o single) (ProofContext.export ctxt1 ctxt intrs)) |>>
berghofe@21024
   711
      map (hd o snd); (* FIXME? *)
berghofe@21024
   712
    val (((_, (_, elims')), (_, [induct'])), ctxt3) =
berghofe@21024
   713
      ctxt2 |>
berghofe@21024
   714
      LocalTheory.note ((NameSpace.append rec_name "intros", []), intrs') ||>>
berghofe@21024
   715
      LocalTheory.note ((NameSpace.append rec_name "elims",
berghofe@21024
   716
        [Attrib.internal (RuleCases.consumes 1)]), elims) ||>>
berghofe@21024
   717
      LocalTheory.note ((NameSpace.append rec_name (coind_prefix coind ^ "induct"),
berghofe@21024
   718
        map Attrib.internal (#2 induct)), [rulify (#1 induct)])
berghofe@21024
   719
  in (ctxt3, rec_name,
berghofe@21024
   720
    {preds = preds,
berghofe@21024
   721
     defs = fp_def :: rec_preds_defs,
berghofe@21024
   722
     mono = singleton (ProofContext.export ctxt1 ctxt) mono,
berghofe@21024
   723
     unfold = singleton (ProofContext.export ctxt1 ctxt) unfold,
berghofe@13709
   724
     intrs = intrs',
wenzelm@7798
   725
     elims = elims',
wenzelm@7798
   726
     mk_cases = mk_cases elims',
wenzelm@10729
   727
     raw_induct = rulify raw_induct,
wenzelm@7798
   728
     induct = induct'})
berghofe@5094
   729
  end;
berghofe@5094
   730
wenzelm@6424
   731
wenzelm@10735
   732
(* external interfaces *)
berghofe@5094
   733
berghofe@21024
   734
fun add_inductive_i verbose alt_name coind no_elim no_ind cnames_syn pnames pre_intros monos ctxt =
berghofe@5094
   735
  let
berghofe@21024
   736
    val thy = ProofContext.theory_of ctxt;
wenzelm@6424
   737
    val _ = Theory.requires thy "Inductive" (coind_prefix coind ^ "inductive definitions");
berghofe@5094
   738
berghofe@21024
   739
    val frees = fold (Term.add_frees o snd) pre_intros [];
berghofe@21024
   740
    fun type_of s = (case AList.lookup op = frees s of
berghofe@21024
   741
      NONE => error ("No such variable: " ^ s) | SOME T => T);
berghofe@5094
   742
berghofe@21024
   743
    val params = map
berghofe@21024
   744
      (fn (s, SOME T) => Free (s, T) | (s, NONE) => Free (s, type_of s)) pnames;
berghofe@21024
   745
    val cs = map
berghofe@21024
   746
      (fn (s, SOME T, _) => Free (s, T) | (s, NONE, _) => Free (s, type_of s)) cnames_syn;
berghofe@21024
   747
    val cnames_syn' = map (fn (s, _, mx) => (s, mx)) cnames_syn;
berghofe@21024
   748
    val cnames = map (Sign.full_name thy o #1) cnames_syn;
berghofe@5094
   749
berghofe@21024
   750
    fun close_rule (x, r) = (x, list_all_free (rev (fold_aterms
berghofe@21024
   751
      (fn t as Free (v as (s, _)) =>
berghofe@21024
   752
            if Variable.is_fixed ctxt s orelse member op = cs t orelse
berghofe@21024
   753
              member op = params t then I else insert op = v
berghofe@21024
   754
        | _ => I) r []), r));
berghofe@5094
   755
berghofe@21024
   756
    val intros = map (close_rule o check_rule thy cs params) pre_intros;
wenzelm@8401
   757
    val induct_cases = map (#1 o #1) intros;
wenzelm@6437
   758
berghofe@21024
   759
    val (ctxt1, rec_name, result as {elims, induct, ...}) =
berghofe@21024
   760
      add_ind_def verbose alt_name coind no_elim no_ind cs intros monos
berghofe@21024
   761
        params cnames_syn' induct_cases ctxt;
berghofe@21024
   762
    val ctxt2 = ctxt1
berghofe@21024
   763
      |> LocalTheory.declaration
berghofe@21024
   764
        (put_inductives cnames ({names = cnames, coind = coind}, result))
berghofe@21024
   765
      |> add_cases_induct no_elim no_ind coind rec_name cnames elims induct;
berghofe@21024
   766
  in (ctxt2, result) end;
berghofe@5094
   767
berghofe@21024
   768
fun add_inductive verbose coind cnames_syn pnames_syn intro_srcs raw_monos ctxt =
berghofe@5094
   769
  let
berghofe@21024
   770
    val (_, ctxt') = Specification.read_specification (cnames_syn @ pnames_syn) [] ctxt;
berghofe@21024
   771
    val intrs = map (fn spec => apsnd hd (hd (snd (fst
berghofe@21024
   772
      (Specification.read_specification [] [apsnd single spec] ctxt'))))) intro_srcs;
berghofe@21024
   773
    val pnames = map (fn (s, _, _) =>
berghofe@21024
   774
      (s, SOME (ProofContext.infer_type ctxt' s))) pnames_syn;
berghofe@21024
   775
    val cnames_syn' = map (fn (s, _, mx) =>
berghofe@21024
   776
      (s, SOME (ProofContext.infer_type ctxt' s), mx)) cnames_syn;
berghofe@21024
   777
    val (monos, ctxt'') = LocalTheory.theory_result (IsarThy.apply_theorems raw_monos) ctxt;
wenzelm@6424
   778
  in
berghofe@21024
   779
    add_inductive_i verbose "" coind false false cnames_syn' pnames intrs monos ctxt''
berghofe@5094
   780
  end;
berghofe@5094
   781
wenzelm@6424
   782
wenzelm@6424
   783
wenzelm@6437
   784
(** package setup **)
wenzelm@6437
   785
wenzelm@6437
   786
(* setup theory *)
wenzelm@6437
   787
wenzelm@8634
   788
val setup =
wenzelm@18708
   789
  InductiveData.init #>
berghofe@21024
   790
  Method.add_methods [("ind_cases2", mk_cases_meth oo mk_cases_args,
berghofe@21024
   791
    "dynamic case analysis on predicates")] #>
berghofe@21024
   792
  Attrib.add_attributes [("mono2", Attrib.add_del_args mono_add mono_del,
wenzelm@18728
   793
    "declaration of monotonicity rule")];
wenzelm@6437
   794
wenzelm@6437
   795
wenzelm@6437
   796
(* outer syntax *)
wenzelm@6424
   797
wenzelm@17057
   798
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6424
   799
berghofe@21024
   800
fun mk_ind coind ((((loc, preds), params), intrs), monos) =
berghofe@21024
   801
  Toplevel.local_theory loc
berghofe@21024
   802
    (#1 o add_inductive true coind preds params intrs monos);
wenzelm@6424
   803
wenzelm@6424
   804
fun ind_decl coind =
berghofe@21024
   805
  P.opt_locale_target --
berghofe@21024
   806
  P.fixes -- Scan.optional (P.$$$ "for" |-- P.fixes) [] --
wenzelm@9598
   807
  (P.$$$ "intros" |--
berghofe@18787
   808
    P.!!! (Scan.repeat (P.opt_thm_name ":" -- P.prop))) --
wenzelm@12876
   809
  Scan.optional (P.$$$ "monos" |-- P.!!! P.xthms1) []
berghofe@21024
   810
  >> mk_ind coind;
wenzelm@6424
   811
wenzelm@6723
   812
val inductiveP =
berghofe@21024
   813
  OuterSyntax.command "inductive2" "define inductive predicates" K.thy_decl (ind_decl false);
wenzelm@6723
   814
wenzelm@6723
   815
val coinductiveP =
berghofe@21024
   816
  OuterSyntax.command "coinductive2" "define coinductive predicates" K.thy_decl (ind_decl true);
wenzelm@6424
   817
wenzelm@7107
   818
wenzelm@7107
   819
val ind_cases =
wenzelm@12876
   820
  P.and_list1 (P.opt_thm_name ":" -- Scan.repeat1 P.prop)
wenzelm@7107
   821
  >> (Toplevel.theory o inductive_cases);
wenzelm@7107
   822
wenzelm@7107
   823
val inductive_casesP =
berghofe@21024
   824
  OuterSyntax.command "inductive_cases2"
wenzelm@9598
   825
    "create simplified instances of elimination rules (improper)" K.thy_script ind_cases;
wenzelm@7107
   826
wenzelm@12180
   827
val _ = OuterSyntax.add_keywords ["intros", "monos"];
wenzelm@7107
   828
val _ = OuterSyntax.add_parsers [inductiveP, coinductiveP, inductive_casesP];
wenzelm@6424
   829
berghofe@5094
   830
end;
wenzelm@6424
   831
wenzelm@6424
   832
end;
wenzelm@15705
   833