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