src/HOL/Tools/inductive_package.ML
author berghofe
Tue Oct 17 09:51:04 2006 +0200 (2006-10-17)
changeset 21048 e57e91f72831
parent 21024 63ab84bb64d1
child 21350 6e58289b6685
permissions -rw-r--r--
Restructured and repaired code dealing with case names
in induction and elimination rules.
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
(** proofs for (co)inductive predicates **)
wenzelm@6424
   281
wenzelm@10735
   282
(* prove monotonicity -- NOT subject to quick_and_dirty! *)
berghofe@5094
   283
berghofe@21024
   284
fun prove_mono predT fp_fun monos ctxt =
wenzelm@10735
   285
 (message "  Proving monotonicity ...";
berghofe@21024
   286
  Goal.prove ctxt [] []   (*NO quick_and_dirty here!*)
wenzelm@17985
   287
    (HOLogic.mk_Trueprop
berghofe@21024
   288
      (Const (mono_name, (predT --> predT) --> HOLogic.boolT) $ fp_fun))
wenzelm@17985
   289
    (fn _ => EVERY [rtac monoI 1,
berghofe@21024
   290
      REPEAT (resolve_tac [le_funI, le_boolI'] 1),
berghofe@21024
   291
      REPEAT (FIRST
berghofe@21024
   292
        [atac 1,
berghofe@21024
   293
         resolve_tac (List.concat (map mk_mono monos) @
berghofe@21024
   294
           get_monos (Context.Proof ctxt)) 1,
berghofe@21024
   295
         etac le_funE 1, dtac le_boolD 1])]));
berghofe@5094
   296
wenzelm@6424
   297
wenzelm@10735
   298
(* prove introduction rules *)
berghofe@5094
   299
berghofe@21024
   300
fun prove_intrs coind mono fp_def k intr_ts rec_preds_defs ctxt =
berghofe@5094
   301
  let
wenzelm@10735
   302
    val _ = clean_message "  Proving the introduction rules ...";
berghofe@5094
   303
berghofe@21024
   304
    val unfold = funpow k (fn th => th RS fun_cong)
berghofe@21024
   305
      (mono RS (fp_def RS
berghofe@21024
   306
        (if coind then def_gfp_unfold else def_lfp_unfold)));
berghofe@5094
   307
berghofe@5094
   308
    fun select_disj 1 1 = []
berghofe@5094
   309
      | select_disj _ 1 = [rtac disjI1]
berghofe@5094
   310
      | select_disj n i = (rtac disjI2)::(select_disj (n - 1) (i - 1));
berghofe@5094
   311
berghofe@21024
   312
    val rules = [refl, TrueI, notFalseI, exI, conjI];
berghofe@21024
   313
berghofe@21024
   314
    val intrs = map_index (fn (i, intr) =>
wenzelm@20047
   315
      rulify (SkipProof.prove ctxt [] [] intr (fn _ => EVERY
berghofe@21024
   316
       [rewrite_goals_tac rec_preds_defs,
berghofe@21024
   317
        rtac (unfold RS iffD2) 1,
berghofe@21024
   318
        EVERY1 (select_disj (length intr_ts) (i + 1)),
wenzelm@17985
   319
        (*Not ares_tac, since refl must be tried before any equality assumptions;
wenzelm@17985
   320
          backtracking may occur if the premises have extra variables!*)
berghofe@21024
   321
        DEPTH_SOLVE_1 (resolve_tac rules 1 APPEND assume_tac 1)]))) intr_ts
berghofe@5094
   322
berghofe@5094
   323
  in (intrs, unfold) end;
berghofe@5094
   324
wenzelm@6424
   325
wenzelm@10735
   326
(* prove elimination rules *)
berghofe@5094
   327
berghofe@21024
   328
fun prove_elims cs params intr_ts intr_names unfold rec_preds_defs ctxt =
berghofe@5094
   329
  let
wenzelm@10735
   330
    val _ = clean_message "  Proving the elimination rules ...";
berghofe@5094
   331
berghofe@21024
   332
    val ([pname], ctxt') = Variable.variant_fixes ["P"] ctxt;
berghofe@21024
   333
    val P = HOLogic.mk_Trueprop (Free (pname, HOLogic.boolT));
berghofe@21024
   334
berghofe@21024
   335
    fun dest_intr r =
berghofe@21024
   336
      (the (dest_predicate cs params (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))),
berghofe@21024
   337
       Logic.strip_assums_hyp r, Logic.strip_params r);
berghofe@21024
   338
berghofe@21024
   339
    val intrs = map dest_intr intr_ts ~~ intr_names;
berghofe@21024
   340
berghofe@21024
   341
    val rules1 = [disjE, exE, FalseE];
berghofe@21024
   342
    val rules2 = [conjE, FalseE, notTrueE];
berghofe@21024
   343
berghofe@21024
   344
    fun prove_elim c =
berghofe@21024
   345
      let
berghofe@21024
   346
        val Ts = List.drop (binder_types (fastype_of c), length params);
berghofe@21024
   347
        val (anames, ctxt'') = Variable.variant_fixes (mk_names "a" (length Ts)) ctxt';
berghofe@21024
   348
        val frees = map Free (anames ~~ Ts);
berghofe@21024
   349
berghofe@21024
   350
        fun mk_elim_prem ((_, _, us, _), ts, params') =
berghofe@21024
   351
          list_all (params',
berghofe@21024
   352
            Logic.list_implies (map (HOLogic.mk_Trueprop o HOLogic.mk_eq)
berghofe@21024
   353
              (frees ~~ us) @ ts, P));
berghofe@21024
   354
        val c_intrs = (List.filter (equal c o #1 o #1 o #1) intrs);
berghofe@21024
   355
        val prems = HOLogic.mk_Trueprop (list_comb (c, params @ frees)) ::
berghofe@21024
   356
           map mk_elim_prem (map #1 c_intrs)
berghofe@21024
   357
      in
berghofe@21048
   358
        (SkipProof.prove ctxt'' [] prems P
berghofe@21024
   359
          (fn {prems, ...} => EVERY
berghofe@21024
   360
            [cut_facts_tac [hd prems] 1,
berghofe@21024
   361
             rewrite_goals_tac rec_preds_defs,
berghofe@21024
   362
             dtac (unfold RS iffD1) 1,
berghofe@21024
   363
             REPEAT (FIRSTGOAL (eresolve_tac rules1)),
berghofe@21024
   364
             REPEAT (FIRSTGOAL (eresolve_tac rules2)),
berghofe@21024
   365
             EVERY (map (fn prem =>
berghofe@21024
   366
               DEPTH_SOLVE_1 (ares_tac [rewrite_rule rec_preds_defs prem, conjI] 1)) (tl prems))])
berghofe@21024
   367
          |> rulify
berghofe@21048
   368
          |> singleton (ProofContext.export ctxt'' ctxt),
berghofe@21048
   369
         map #2 c_intrs)
berghofe@21024
   370
      end
berghofe@21024
   371
berghofe@21024
   372
   in map prove_elim cs end;
berghofe@5094
   373
wenzelm@6424
   374
wenzelm@10735
   375
(* derivation of simplified elimination rules *)
berghofe@5094
   376
wenzelm@11682
   377
local
wenzelm@11682
   378
berghofe@21024
   379
(*cprop should have the form "Si t" where Si is an inductive predicate*)
berghofe@21024
   380
val mk_cases_err = "mk_cases: proposition not an inductive predicate";
wenzelm@9598
   381
wenzelm@11682
   382
(*delete needless equality assumptions*)
wenzelm@11682
   383
val refl_thin = prove_goal HOL.thy "!!P. a = a ==> P ==> P" (fn _ => [assume_tac 1]);
berghofe@21024
   384
val elim_rls = [asm_rl, FalseE, refl_thin, conjE, exE];
wenzelm@11682
   385
val elim_tac = REPEAT o Tactic.eresolve_tac elim_rls;
wenzelm@11682
   386
wenzelm@11682
   387
fun simp_case_tac solved ss i =
wenzelm@11682
   388
  EVERY' [elim_tac, asm_full_simp_tac ss, elim_tac, REPEAT o bound_hyp_subst_tac] i
wenzelm@11682
   389
  THEN_MAYBE (if solved then no_tac else all_tac);
wenzelm@11682
   390
wenzelm@11682
   391
in
wenzelm@9598
   392
wenzelm@9598
   393
fun mk_cases_i elims ss cprop =
wenzelm@7107
   394
  let
wenzelm@7107
   395
    val prem = Thm.assume cprop;
wenzelm@11682
   396
    val tac = ALLGOALS (simp_case_tac false ss) THEN prune_params_tac;
wenzelm@9298
   397
    fun mk_elim rl = Drule.standard (Tactic.rule_by_tactic tac (prem RS rl));
wenzelm@7107
   398
  in
wenzelm@7107
   399
    (case get_first (try mk_elim) elims of
skalberg@15531
   400
      SOME r => r
skalberg@15531
   401
    | NONE => error (Pretty.string_of (Pretty.block
wenzelm@9598
   402
        [Pretty.str mk_cases_err, Pretty.fbrk, Display.pretty_cterm cprop])))
wenzelm@7107
   403
  end;
wenzelm@7107
   404
paulson@6141
   405
fun mk_cases elims s =
wenzelm@16432
   406
  mk_cases_i elims (simpset()) (Thm.read_cterm (Thm.theory_of_thm (hd elims)) (s, propT));
wenzelm@9598
   407
berghofe@21024
   408
fun smart_mk_cases ctxt ss cprop =
wenzelm@9598
   409
  let
berghofe@21024
   410
    val c = #1 (Term.dest_Const (Term.head_of (HOLogic.dest_Trueprop
berghofe@21024
   411
      (Logic.strip_imp_concl (Thm.term_of cprop))))) handle TERM _ => error mk_cases_err;
berghofe@21024
   412
    val (_, {elims, ...}) = the_inductive ctxt c;
wenzelm@9598
   413
  in mk_cases_i elims ss cprop end;
wenzelm@7107
   414
wenzelm@11682
   415
end;
wenzelm@11682
   416
wenzelm@7107
   417
wenzelm@7107
   418
(* inductive_cases(_i) *)
wenzelm@7107
   419
wenzelm@12609
   420
fun gen_inductive_cases prep_att prep_prop args thy =
wenzelm@9598
   421
  let
wenzelm@16432
   422
    val cert_prop = Thm.cterm_of thy o prep_prop (ProofContext.init thy);
berghofe@21024
   423
    val mk_cases = smart_mk_cases (Context.Theory thy) (Simplifier.simpset_of thy) o cert_prop;
wenzelm@12609
   424
wenzelm@12876
   425
    val facts = args |> map (fn ((a, atts), props) =>
wenzelm@12876
   426
     ((a, map (prep_att thy) atts), map (Thm.no_attributes o single o mk_cases) props));
wenzelm@20901
   427
  in thy |> PureThy.note_thmss_i "" facts |> snd end;
berghofe@5094
   428
wenzelm@18728
   429
val inductive_cases = gen_inductive_cases Attrib.attribute ProofContext.read_prop;
wenzelm@12172
   430
val inductive_cases_i = gen_inductive_cases (K I) ProofContext.cert_prop;
wenzelm@7107
   431
wenzelm@6424
   432
wenzelm@9598
   433
(* mk_cases_meth *)
wenzelm@9598
   434
wenzelm@9598
   435
fun mk_cases_meth (ctxt, raw_props) =
wenzelm@9598
   436
  let
wenzelm@9598
   437
    val thy = ProofContext.theory_of ctxt;
wenzelm@15032
   438
    val ss = local_simpset_of ctxt;
wenzelm@16432
   439
    val cprops = map (Thm.cterm_of thy o ProofContext.read_prop ctxt) raw_props;
berghofe@21024
   440
  in Method.erule 0 (map (smart_mk_cases (Context.Theory thy) ss) cprops) end;
wenzelm@9598
   441
wenzelm@9598
   442
val mk_cases_args = Method.syntax (Scan.lift (Scan.repeat1 Args.name));
wenzelm@9598
   443
wenzelm@9598
   444
wenzelm@10735
   445
(* prove induction rule *)
berghofe@5094
   446
berghofe@21024
   447
fun prove_indrule cs argTs bs xs rec_const params intr_ts mono
berghofe@21024
   448
    fp_def rec_preds_defs ctxt =
berghofe@5094
   449
  let
wenzelm@10735
   450
    val _ = clean_message "  Proving the induction rule ...";
wenzelm@20047
   451
    val thy = ProofContext.theory_of ctxt;
berghofe@5094
   452
berghofe@21024
   453
    (* predicates for induction rule *)
berghofe@21024
   454
berghofe@21024
   455
    val (pnames, ctxt') = Variable.variant_fixes (mk_names "P" (length cs)) ctxt;
berghofe@21024
   456
    val preds = map Free (pnames ~~
berghofe@21024
   457
      map (fn c => List.drop (binder_types (fastype_of c), length params) --->
berghofe@21024
   458
        HOLogic.boolT) cs);
berghofe@21024
   459
berghofe@21024
   460
    (* transform an introduction rule into a premise for induction rule *)
berghofe@21024
   461
berghofe@21024
   462
    fun mk_ind_prem r =
berghofe@21024
   463
      let
berghofe@21024
   464
        fun subst s = (case dest_predicate cs params s of
berghofe@21024
   465
            SOME (_, i, ys, (_, Ts)) =>
berghofe@21024
   466
              let
berghofe@21024
   467
                val k = length Ts;
berghofe@21024
   468
                val bs = map Bound (k - 1 downto 0);
berghofe@21024
   469
                val P = list_comb (List.nth (preds, i), ys @ bs);
berghofe@21024
   470
                val Q = list_abs (mk_names "x" k ~~ Ts,
berghofe@21024
   471
                  HOLogic.mk_binop inductive_conj_name (list_comb (s, bs), P))
berghofe@21024
   472
              in (Q, case Ts of [] => SOME (s, P) | _ => NONE) end
berghofe@21024
   473
          | NONE => (case s of
berghofe@21024
   474
              (t $ u) => (fst (subst t) $ fst (subst u), NONE)
berghofe@21024
   475
            | (Abs (a, T, t)) => (Abs (a, T, fst (subst t)), NONE)
berghofe@21024
   476
            | _ => (s, NONE)));
berghofe@7293
   477
berghofe@21024
   478
        fun mk_prem (s, prems) = (case subst s of
berghofe@21024
   479
              (_, SOME (t, u)) => t :: u :: prems
berghofe@21024
   480
            | (t, _) => t :: prems);
berghofe@21024
   481
berghofe@21024
   482
        val SOME (_, i, ys, _) = dest_predicate cs params
berghofe@21024
   483
          (HOLogic.dest_Trueprop (Logic.strip_assums_concl r))
berghofe@21024
   484
berghofe@21024
   485
      in list_all_free (Logic.strip_params r,
berghofe@21024
   486
        Logic.list_implies (map HOLogic.mk_Trueprop (foldr mk_prem
berghofe@21024
   487
          [] (map HOLogic.dest_Trueprop (Logic.strip_assums_hyp r))),
berghofe@21024
   488
            HOLogic.mk_Trueprop (list_comb (List.nth (preds, i), ys))))
berghofe@21024
   489
      end;
berghofe@21024
   490
berghofe@21024
   491
    val ind_prems = map mk_ind_prem intr_ts;
berghofe@21024
   492
berghofe@21024
   493
    (* make conclusions for induction rules *)
berghofe@21024
   494
berghofe@21024
   495
    val Tss = map (binder_types o fastype_of) preds;
berghofe@21024
   496
    val (xnames, ctxt'') =
berghofe@21024
   497
      Variable.variant_fixes (mk_names "x" (length (flat Tss))) ctxt';
berghofe@21024
   498
    val mutual_ind_concl = HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
berghofe@21024
   499
        (map (fn (((xnames, Ts), c), P) =>
berghofe@21024
   500
           let val frees = map Free (xnames ~~ Ts)
berghofe@21024
   501
           in HOLogic.mk_imp
berghofe@21024
   502
             (list_comb (c, params @ frees), list_comb (P, frees))
berghofe@21024
   503
           end) (unflat Tss xnames ~~ Tss ~~ cs ~~ preds)));
berghofe@5094
   504
paulson@13626
   505
    val dummy = if !trace then
wenzelm@17985
   506
                (writeln "ind_prems = ";
wenzelm@17985
   507
                 List.app (writeln o Sign.string_of_term thy) ind_prems)
wenzelm@17985
   508
            else ();
paulson@13626
   509
berghofe@5094
   510
    (* make predicate for instantiation of abstract induction rule *)
berghofe@5094
   511
berghofe@21024
   512
    val ind_pred = fold_rev lambda (bs @ xs) (foldr1 HOLogic.mk_conj
berghofe@21024
   513
      (map_index (fn (i, P) => foldr HOLogic.mk_imp
berghofe@21024
   514
         (list_comb (P, make_args' argTs xs (binder_types (fastype_of P))))
berghofe@21024
   515
         (make_bool_args HOLogic.mk_not I bs i)) preds));
berghofe@5094
   516
berghofe@5094
   517
    val ind_concl = HOLogic.mk_Trueprop
berghofe@21024
   518
      (HOLogic.mk_binrel "Orderings.less_eq" (rec_const, ind_pred));
berghofe@5094
   519
paulson@13626
   520
    val raw_fp_induct = (mono RS (fp_def RS def_lfp_induct));
paulson@13626
   521
paulson@13626
   522
    val dummy = if !trace then
wenzelm@17985
   523
                (writeln "raw_fp_induct = "; print_thm raw_fp_induct)
wenzelm@17985
   524
            else ();
paulson@13626
   525
berghofe@21024
   526
    val induct = SkipProof.prove ctxt'' [] ind_prems ind_concl
wenzelm@20248
   527
      (fn {prems, ...} => EVERY
wenzelm@17985
   528
        [rewrite_goals_tac [inductive_conj_def],
berghofe@21024
   529
         DETERM (rtac raw_fp_induct 1),
berghofe@21024
   530
         REPEAT (resolve_tac [le_funI, le_boolI] 1),
berghofe@21024
   531
         rewrite_goals_tac (map mk_meta_eq [meet_fun_eq, meet_bool_eq] @ simp_thms'),
berghofe@21024
   532
         (*This disjE separates out the introduction rules*)
berghofe@21024
   533
         REPEAT (FIRSTGOAL (eresolve_tac [disjE, exE, FalseE])),
berghofe@5094
   534
         (*Now break down the individual cases.  No disjE here in case
berghofe@5094
   535
           some premise involves disjunction.*)
paulson@13747
   536
         REPEAT (FIRSTGOAL (etac conjE ORELSE' bound_hyp_subst_tac)),
berghofe@21024
   537
         REPEAT (FIRSTGOAL
berghofe@21024
   538
           (resolve_tac [conjI, impI] ORELSE' (etac notE THEN' atac))),
berghofe@21024
   539
         EVERY (map (fn prem => DEPTH_SOLVE_1 (ares_tac [rewrite_rule
berghofe@21024
   540
           (inductive_conj_def :: rec_preds_defs) prem, conjI, refl] 1)) prems)]);
berghofe@5094
   541
berghofe@21024
   542
    val lemma = SkipProof.prove ctxt'' [] []
wenzelm@17985
   543
      (Logic.mk_implies (ind_concl, mutual_ind_concl)) (fn _ => EVERY
berghofe@21024
   544
        [rewrite_goals_tac rec_preds_defs,
berghofe@5094
   545
         REPEAT (EVERY
berghofe@5094
   546
           [REPEAT (resolve_tac [conjI, impI] 1),
berghofe@21024
   547
            REPEAT (eresolve_tac [le_funE, le_boolE] 1),
berghofe@21024
   548
            atac 1,
berghofe@21024
   549
            rewrite_goals_tac simp_thms',
berghofe@21024
   550
            atac 1])])
berghofe@5094
   551
berghofe@21024
   552
  in singleton (ProofContext.export ctxt'' ctxt) (induct RS lemma) end;
berghofe@5094
   553
wenzelm@6424
   554
wenzelm@6424
   555
berghofe@21024
   556
(** specification of (co)inductive predicates **)
wenzelm@10729
   557
berghofe@21024
   558
fun mk_ind_def alt_name coind cs intr_ts monos
berghofe@21024
   559
      params cnames_syn ctxt =
berghofe@5094
   560
  let
wenzelm@10735
   561
    val fp_name = if coind then gfp_name else lfp_name;
berghofe@5094
   562
berghofe@21024
   563
    val argTs = fold (fn c => fn Ts => Ts @
berghofe@21024
   564
      (List.drop (binder_types (fastype_of c), length params) \\ Ts)) cs [];
berghofe@21024
   565
    val k = log 2 1 (length cs);
berghofe@21024
   566
    val predT = replicate k HOLogic.boolT ---> argTs ---> HOLogic.boolT;
berghofe@21024
   567
    val p :: xs = map Free (Variable.variant_frees ctxt intr_ts
berghofe@21024
   568
      (("p", predT) :: (mk_names "x" (length argTs) ~~ argTs)));
berghofe@21024
   569
    val bs = map Free (Variable.variant_frees ctxt (p :: xs @ intr_ts)
berghofe@21024
   570
      (map (rpair HOLogic.boolT) (mk_names "b" k)));
berghofe@21024
   571
berghofe@21024
   572
    fun subst t = (case dest_predicate cs params t of
berghofe@21024
   573
        SOME (_, i, ts, (Ts, Us)) =>
berghofe@21024
   574
          let val zs = map Bound (length Us - 1 downto 0)
berghofe@21024
   575
          in
berghofe@21024
   576
            list_abs (map (pair "z") Us, list_comb (p,
berghofe@21024
   577
              make_bool_args' bs i @ make_args argTs ((ts ~~ Ts) @ (zs ~~ Us))))
berghofe@21024
   578
          end
berghofe@21024
   579
      | NONE => (case t of
berghofe@21024
   580
          t1 $ t2 => subst t1 $ subst t2
berghofe@21024
   581
        | Abs (x, T, u) => Abs (x, T, subst u)
berghofe@21024
   582
        | _ => t));
berghofe@5149
   583
berghofe@5094
   584
    (* transform an introduction rule into a conjunction  *)
berghofe@21024
   585
    (*   [| p_i t; ... |] ==> p_j u                       *)
berghofe@5094
   586
    (* is transformed into                                *)
berghofe@21024
   587
    (*   b_j & x_j = u & p b_j t & ...                    *)
berghofe@5094
   588
berghofe@5094
   589
    fun transform_rule r =
berghofe@5094
   590
      let
berghofe@21024
   591
        val SOME (_, i, ts, (Ts, _)) = dest_predicate cs params
berghofe@21048
   592
          (HOLogic.dest_Trueprop (Logic.strip_assums_concl r));
berghofe@21048
   593
        val ps = make_bool_args HOLogic.mk_not I bs i @
berghofe@21048
   594
          map HOLogic.mk_eq (make_args' argTs xs Ts ~~ ts) @
berghofe@21048
   595
          map (subst o HOLogic.dest_Trueprop)
berghofe@21048
   596
            (Logic.strip_assums_hyp r)
berghofe@21024
   597
      in foldr (fn ((x, T), P) => HOLogic.exists_const T $ (Abs (x, T, P)))
berghofe@21048
   598
        (if null ps then HOLogic.true_const else foldr1 HOLogic.mk_conj ps)
berghofe@21048
   599
        (Logic.strip_params r)
berghofe@5094
   600
      end
berghofe@5094
   601
berghofe@5094
   602
    (* make a disjunction of all introduction rules *)
berghofe@5094
   603
berghofe@21024
   604
    val fp_fun = fold_rev lambda (p :: bs @ xs)
berghofe@21024
   605
      (if null intr_ts then HOLogic.false_const
berghofe@21024
   606
       else foldr1 HOLogic.mk_disj (map transform_rule intr_ts));
berghofe@5094
   607
berghofe@21024
   608
    (* add definiton of recursive predicates to theory *)
berghofe@5094
   609
berghofe@14235
   610
    val rec_name = if alt_name = "" then
berghofe@21024
   611
      space_implode "_" (map fst cnames_syn) else alt_name;
berghofe@5094
   612
berghofe@21024
   613
    val ((rec_const, (_, fp_def)), ctxt') = ctxt |>
berghofe@21024
   614
      Variable.add_fixes (map (fst o dest_Free) params) |> snd |>
berghofe@21024
   615
      fold Variable.declare_term intr_ts |>
berghofe@21024
   616
      LocalTheory.def
berghofe@21024
   617
        ((rec_name, case cnames_syn of [(_, syn)] => syn | _ => NoSyn),
berghofe@21024
   618
         (("", []), fold_rev lambda params
berghofe@21024
   619
           (Const (fp_name, (predT --> predT) --> predT) $ fp_fun)));
berghofe@21024
   620
    val fp_def' = Simplifier.rewrite (HOL_basic_ss addsimps [fp_def])
berghofe@21024
   621
      (cterm_of (ProofContext.theory_of ctxt') (list_comb (rec_const, params)));
berghofe@21024
   622
    val specs = if length cs < 2 then [] else
berghofe@21024
   623
      map_index (fn (i, (name_mx, c)) =>
berghofe@21024
   624
        let
berghofe@21024
   625
          val Ts = List.drop (binder_types (fastype_of c), length params);
berghofe@21024
   626
          val xs = map Free (Variable.variant_frees ctxt intr_ts
berghofe@21024
   627
            (mk_names "x" (length Ts) ~~ Ts))
berghofe@21024
   628
        in
berghofe@21024
   629
          (name_mx, (("", []), fold_rev lambda (params @ xs)
berghofe@21024
   630
            (list_comb (rec_const, params @ make_bool_args' bs i @
berghofe@21024
   631
              make_args argTs (xs ~~ Ts)))))
berghofe@21024
   632
        end) (cnames_syn ~~ cs);
berghofe@21024
   633
    val (consts_defs, ctxt'') = fold_map LocalTheory.def specs ctxt';
berghofe@21024
   634
    val preds = (case cs of [_] => [rec_const] | _ => map #1 consts_defs);
berghofe@5094
   635
berghofe@21024
   636
    val mono = prove_mono predT fp_fun monos ctxt''
berghofe@5094
   637
berghofe@21024
   638
  in (ctxt'', rec_name, mono, fp_def', map (#2 o #2) consts_defs,
berghofe@21024
   639
    list_comb (rec_const, params), preds, argTs, bs, xs)
berghofe@21024
   640
  end;
berghofe@5094
   641
berghofe@21024
   642
fun add_ind_def verbose alt_name coind no_elim no_ind cs
berghofe@21048
   643
    intros monos params cnames_syn ctxt =
berghofe@9072
   644
  let
wenzelm@10735
   645
    val _ =
berghofe@21024
   646
      if verbose then message ("Proofs for " ^ coind_prefix coind ^ "inductive predicate(s) " ^
berghofe@21024
   647
        commas_quote (map fst cnames_syn)) else ();
berghofe@9072
   648
berghofe@21048
   649
    val cnames = map (Sign.full_name (ProofContext.theory_of ctxt) o #1) cnames_syn;
berghofe@21024
   650
    val ((intr_names, intr_atts), intr_ts) = apfst split_list (split_list intros);
berghofe@21024
   651
berghofe@21024
   652
    val (ctxt1, rec_name, mono, fp_def, rec_preds_defs, rec_const, preds,
berghofe@21024
   653
      argTs, bs, xs) = mk_ind_def alt_name coind cs intr_ts
berghofe@21024
   654
        monos params cnames_syn ctxt;
berghofe@9072
   655
berghofe@21024
   656
    val (intrs, unfold) = prove_intrs coind mono fp_def (length bs + length xs)
berghofe@21024
   657
      intr_ts rec_preds_defs ctxt1;
berghofe@21048
   658
    val elims = if no_elim then [] else
berghofe@21048
   659
      cnames ~~ map (apfst (singleton (ProofContext.export ctxt1 ctxt)))
berghofe@21048
   660
        (prove_elims cs params intr_ts intr_names unfold rec_preds_defs ctxt1);
berghofe@21024
   661
    val raw_induct = singleton (ProofContext.export ctxt1 ctxt)
berghofe@21024
   662
      (if no_ind then Drule.asm_rl else
berghofe@21024
   663
       if coind then ObjectLogic.rulify (rule_by_tactic
berghofe@21024
   664
         (rewrite_tac [le_fun_def, le_bool_def] THEN
berghofe@21024
   665
           fold_tac rec_preds_defs) (mono RS (fp_def RS def_coinduct)))
berghofe@21024
   666
       else
berghofe@21024
   667
         prove_indrule cs argTs bs xs rec_const params intr_ts mono fp_def
berghofe@21024
   668
           rec_preds_defs ctxt1);
berghofe@21048
   669
    val induct_cases = map (#1 o #1) intros;
berghofe@21048
   670
    val ind_case_names = RuleCases.case_names induct_cases;
wenzelm@12165
   671
    val induct =
wenzelm@18222
   672
      if coind then
wenzelm@18222
   673
        (raw_induct, [RuleCases.case_names [rec_name],
wenzelm@18234
   674
          RuleCases.case_conclusion (rec_name, induct_cases),
wenzelm@18222
   675
          RuleCases.consumes 1])
wenzelm@18222
   676
      else if no_ind orelse length cs > 1 then
berghofe@21048
   677
        (raw_induct, [ind_case_names, RuleCases.consumes 0])
berghofe@21048
   678
      else (raw_induct RSN (2, rev_mp), [ind_case_names, RuleCases.consumes 1]);
berghofe@5094
   679
berghofe@21024
   680
    val (intrs', ctxt2) =
berghofe@21024
   681
      ctxt1 |>
berghofe@21048
   682
      LocalTheory.notes
berghofe@21048
   683
        (map (fn "" => "" | name => NameSpace.append rec_name name) intr_names ~~
berghofe@21048
   684
         intr_atts ~~
berghofe@21048
   685
         map (single o rpair [] o single) (ProofContext.export ctxt1 ctxt intrs)) |>>
berghofe@21024
   686
      map (hd o snd); (* FIXME? *)
berghofe@21048
   687
    val (((_, elims'), (_, [induct'])), ctxt3) =
berghofe@21024
   688
      ctxt2 |>
berghofe@21024
   689
      LocalTheory.note ((NameSpace.append rec_name "intros", []), intrs') ||>>
berghofe@21048
   690
      fold_map (fn (name, (elim, cases)) =>
berghofe@21048
   691
        LocalTheory.note ((NameSpace.append (Sign.base_name name) "cases",
berghofe@21048
   692
          [Attrib.internal (RuleCases.case_names cases),
berghofe@21048
   693
           Attrib.internal (RuleCases.consumes 1),
berghofe@21048
   694
           Attrib.internal (InductAttrib.cases_set name)]), [elim]) #>
berghofe@21048
   695
        apfst (hd o snd)) elims ||>>
berghofe@21024
   696
      LocalTheory.note ((NameSpace.append rec_name (coind_prefix coind ^ "induct"),
berghofe@21048
   697
        map Attrib.internal (#2 induct)), [rulify (#1 induct)]);
berghofe@21048
   698
berghofe@21048
   699
    val induct_att = if coind then InductAttrib.coinduct_set else InductAttrib.induct_set;
berghofe@21048
   700
    val ctxt4 = if no_ind then ctxt3 else
berghofe@21048
   701
      let val inducts = cnames ~~ ProjectRule.projects ctxt (1 upto length cnames) induct'
berghofe@21048
   702
      in
berghofe@21048
   703
        ctxt3 |>
berghofe@21048
   704
        LocalTheory.notes (inducts |> map (fn (name, th) => (("",
berghofe@21048
   705
          [Attrib.internal ind_case_names,
berghofe@21048
   706
           Attrib.internal (RuleCases.consumes 1),
berghofe@21048
   707
           Attrib.internal (induct_att name)]), [([th], [])]))) |> snd |>
berghofe@21048
   708
        LocalTheory.note ((NameSpace.append rec_name (coind_prefix coind ^ "inducts"),
berghofe@21048
   709
          [Attrib.internal ind_case_names,
berghofe@21048
   710
           Attrib.internal (RuleCases.consumes 1)]), map snd inducts) |> snd
berghofe@21048
   711
      end;
berghofe@21048
   712
berghofe@21048
   713
    val result =
berghofe@21048
   714
      {preds = preds,
berghofe@21048
   715
       defs = fp_def :: rec_preds_defs,
berghofe@21048
   716
       mono = singleton (ProofContext.export ctxt1 ctxt) mono,
berghofe@21048
   717
       unfold = singleton (ProofContext.export ctxt1 ctxt) unfold,
berghofe@21048
   718
       intrs = intrs',
berghofe@21048
   719
       elims = elims',
berghofe@21048
   720
       mk_cases = mk_cases elims',
berghofe@21048
   721
       raw_induct = rulify raw_induct,
berghofe@21048
   722
       induct = induct'}
berghofe@21048
   723
      
berghofe@21048
   724
  in
berghofe@21048
   725
    (LocalTheory.declaration
berghofe@21048
   726
       (put_inductives cnames ({names = cnames, coind = coind}, result)) ctxt4,
berghofe@21048
   727
     result)
berghofe@5094
   728
  end;
berghofe@5094
   729
wenzelm@6424
   730
wenzelm@10735
   731
(* external interfaces *)
berghofe@5094
   732
berghofe@21024
   733
fun add_inductive_i verbose alt_name coind no_elim no_ind cnames_syn pnames pre_intros monos ctxt =
berghofe@5094
   734
  let
berghofe@21024
   735
    val thy = ProofContext.theory_of ctxt;
wenzelm@6424
   736
    val _ = Theory.requires thy "Inductive" (coind_prefix coind ^ "inductive definitions");
berghofe@5094
   737
berghofe@21024
   738
    val frees = fold (Term.add_frees o snd) pre_intros [];
berghofe@21024
   739
    fun type_of s = (case AList.lookup op = frees s of
berghofe@21024
   740
      NONE => error ("No such variable: " ^ s) | SOME T => T);
berghofe@5094
   741
berghofe@21024
   742
    val params = map
berghofe@21024
   743
      (fn (s, SOME T) => Free (s, T) | (s, NONE) => Free (s, type_of s)) pnames;
berghofe@21024
   744
    val cs = map
berghofe@21024
   745
      (fn (s, SOME T, _) => Free (s, T) | (s, NONE, _) => Free (s, type_of s)) cnames_syn;
berghofe@21024
   746
    val cnames_syn' = map (fn (s, _, mx) => (s, mx)) cnames_syn;
berghofe@5094
   747
berghofe@21024
   748
    fun close_rule (x, r) = (x, list_all_free (rev (fold_aterms
berghofe@21024
   749
      (fn t as Free (v as (s, _)) =>
berghofe@21024
   750
            if Variable.is_fixed ctxt s orelse member op = cs t orelse
berghofe@21024
   751
              member op = params t then I else insert op = v
berghofe@21024
   752
        | _ => I) r []), r));
berghofe@5094
   753
berghofe@21024
   754
    val intros = map (close_rule o check_rule thy cs params) pre_intros;
berghofe@21048
   755
  in
berghofe@21048
   756
    add_ind_def verbose alt_name coind no_elim no_ind cs intros monos
berghofe@21048
   757
      params cnames_syn' ctxt
berghofe@21048
   758
  end;
berghofe@5094
   759
berghofe@21024
   760
fun add_inductive verbose coind cnames_syn pnames_syn intro_srcs raw_monos ctxt =
berghofe@5094
   761
  let
berghofe@21024
   762
    val (_, ctxt') = Specification.read_specification (cnames_syn @ pnames_syn) [] ctxt;
berghofe@21024
   763
    val intrs = map (fn spec => apsnd hd (hd (snd (fst
berghofe@21024
   764
      (Specification.read_specification [] [apsnd single spec] ctxt'))))) intro_srcs;
berghofe@21024
   765
    val pnames = map (fn (s, _, _) =>
berghofe@21024
   766
      (s, SOME (ProofContext.infer_type ctxt' s))) pnames_syn;
berghofe@21024
   767
    val cnames_syn' = map (fn (s, _, mx) =>
berghofe@21024
   768
      (s, SOME (ProofContext.infer_type ctxt' s), mx)) cnames_syn;
berghofe@21024
   769
    val (monos, ctxt'') = LocalTheory.theory_result (IsarThy.apply_theorems raw_monos) ctxt;
wenzelm@6424
   770
  in
berghofe@21024
   771
    add_inductive_i verbose "" coind false false cnames_syn' pnames intrs monos ctxt''
berghofe@5094
   772
  end;
berghofe@5094
   773
wenzelm@6424
   774
wenzelm@6424
   775
wenzelm@6437
   776
(** package setup **)
wenzelm@6437
   777
wenzelm@6437
   778
(* setup theory *)
wenzelm@6437
   779
wenzelm@8634
   780
val setup =
wenzelm@18708
   781
  InductiveData.init #>
berghofe@21024
   782
  Method.add_methods [("ind_cases2", mk_cases_meth oo mk_cases_args,
berghofe@21024
   783
    "dynamic case analysis on predicates")] #>
berghofe@21024
   784
  Attrib.add_attributes [("mono2", Attrib.add_del_args mono_add mono_del,
wenzelm@18728
   785
    "declaration of monotonicity rule")];
wenzelm@6437
   786
wenzelm@6437
   787
wenzelm@6437
   788
(* outer syntax *)
wenzelm@6424
   789
wenzelm@17057
   790
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6424
   791
berghofe@21024
   792
fun mk_ind coind ((((loc, preds), params), intrs), monos) =
berghofe@21024
   793
  Toplevel.local_theory loc
berghofe@21024
   794
    (#1 o add_inductive true coind preds params intrs monos);
wenzelm@6424
   795
wenzelm@6424
   796
fun ind_decl coind =
berghofe@21024
   797
  P.opt_locale_target --
berghofe@21024
   798
  P.fixes -- Scan.optional (P.$$$ "for" |-- P.fixes) [] --
wenzelm@9598
   799
  (P.$$$ "intros" |--
berghofe@18787
   800
    P.!!! (Scan.repeat (P.opt_thm_name ":" -- P.prop))) --
wenzelm@12876
   801
  Scan.optional (P.$$$ "monos" |-- P.!!! P.xthms1) []
berghofe@21024
   802
  >> mk_ind coind;
wenzelm@6424
   803
wenzelm@6723
   804
val inductiveP =
berghofe@21024
   805
  OuterSyntax.command "inductive2" "define inductive predicates" K.thy_decl (ind_decl false);
wenzelm@6723
   806
wenzelm@6723
   807
val coinductiveP =
berghofe@21024
   808
  OuterSyntax.command "coinductive2" "define coinductive predicates" K.thy_decl (ind_decl true);
wenzelm@6424
   809
wenzelm@7107
   810
wenzelm@7107
   811
val ind_cases =
wenzelm@12876
   812
  P.and_list1 (P.opt_thm_name ":" -- Scan.repeat1 P.prop)
wenzelm@7107
   813
  >> (Toplevel.theory o inductive_cases);
wenzelm@7107
   814
wenzelm@7107
   815
val inductive_casesP =
berghofe@21024
   816
  OuterSyntax.command "inductive_cases2"
wenzelm@9598
   817
    "create simplified instances of elimination rules (improper)" K.thy_script ind_cases;
wenzelm@7107
   818
wenzelm@12180
   819
val _ = OuterSyntax.add_keywords ["intros", "monos"];
wenzelm@7107
   820
val _ = OuterSyntax.add_parsers [inductiveP, coinductiveP, inductive_casesP];
wenzelm@6424
   821
berghofe@5094
   822
end;
wenzelm@6424
   823
wenzelm@6424
   824
end;
wenzelm@15705
   825