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