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