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