src/ZF/Tools/inductive_package.ML
author wenzelm
Thu Oct 30 16:55:29 2014 +0100 (2014-10-30)
changeset 58838 59203adfc33f
parent 58028 e4250d370657
child 58936 7fbe4436952d
permissions -rw-r--r--
eliminated aliases;
wenzelm@12191
     1
(*  Title:      ZF/Tools/inductive_package.ML
paulson@6051
     2
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
paulson@6051
     3
paulson@6051
     4
Fixedpoint definition module -- for Inductive/Coinductive Definitions
paulson@6051
     5
paulson@6051
     6
The functor will be instantiated for normal sums/products (inductive defs)
paulson@6051
     7
                         and non-standard sums/products (coinductive defs)
paulson@6051
     8
paulson@6051
     9
Sums are used only for mutual recursion;
paulson@6051
    10
Products are used only to derive "streamlined" induction rules for relations
paulson@6051
    11
*)
paulson@6051
    12
paulson@6051
    13
type inductive_result =
paulson@6051
    14
   {defs       : thm list,             (*definitions made in thy*)
paulson@6051
    15
    bnd_mono   : thm,                  (*monotonicity for the lfp definition*)
paulson@6051
    16
    dom_subset : thm,                  (*inclusion of recursive set in dom*)
paulson@6051
    17
    intrs      : thm list,             (*introduction rules*)
paulson@6051
    18
    elim       : thm,                  (*case analysis theorem*)
paulson@6051
    19
    induct     : thm,                  (*main induction rule*)
paulson@6051
    20
    mutual_induct : thm};              (*mutual induction rule*)
paulson@6051
    21
paulson@6051
    22
paulson@6051
    23
(*Functor's result signature*)
paulson@6051
    24
signature INDUCTIVE_PACKAGE =
wenzelm@12132
    25
sig
paulson@6051
    26
  (*Insert definitions for the recursive sets, which
paulson@6051
    27
     must *already* be declared as constants in parent theory!*)
wenzelm@12132
    28
  val add_inductive_i: bool -> term list * term ->
haftmann@29579
    29
    ((binding * term) * attribute list) list ->
wenzelm@12132
    30
    thm list * thm list * thm list * thm list -> theory -> theory * inductive_result
wenzelm@12132
    31
  val add_inductive: string list * string ->
wenzelm@58011
    32
    ((binding * string) * Token.src list) list ->
wenzelm@58011
    33
    (Facts.ref * Token.src list) list * (Facts.ref * Token.src list) list *
wenzelm@58011
    34
    (Facts.ref * Token.src list) list * (Facts.ref * Token.src list) list ->
wenzelm@12132
    35
    theory -> theory * inductive_result
wenzelm@12132
    36
end;
paulson@6051
    37
paulson@6051
    38
paulson@6051
    39
(*Declares functions to add fixedpoint/constructor defs to a theory.
paulson@6051
    40
  Recursive sets must *already* be declared as constants.*)
wenzelm@12132
    41
functor Add_inductive_def_Fun
wenzelm@12132
    42
    (structure Fp: FP and Pr : PR and CP: CARTPROD and Su : SU val coind: bool)
paulson@6051
    43
 : INDUCTIVE_PACKAGE =
paulson@6051
    44
struct
wenzelm@12183
    45
wenzelm@12227
    46
val co_prefix = if coind then "co" else "";
wenzelm@12227
    47
wenzelm@7695
    48
wenzelm@7695
    49
(* utils *)
wenzelm@7695
    50
wenzelm@7695
    51
(*make distinct individual variables a1, a2, a3, ..., an. *)
wenzelm@7695
    52
fun mk_frees a [] = []
wenzelm@12902
    53
  | mk_frees a (T::Ts) = Free(a,T) :: mk_frees (Symbol.bump_string a) Ts;
wenzelm@7695
    54
wenzelm@7695
    55
wenzelm@7695
    56
(* add_inductive(_i) *)
wenzelm@7695
    57
paulson@6051
    58
(*internal version, accepting terms*)
wenzelm@12132
    59
fun add_inductive_i verbose (rec_tms, dom_sum)
wenzelm@28083
    60
  raw_intr_specs (monos, con_defs, type_intrs, type_elims) thy =
wenzelm@12132
    61
let
wenzelm@56249
    62
  val _ = Theory.requires thy (Context.theory_name @{theory}) "(co)inductive definitions";
wenzelm@42361
    63
  val ctxt = Proof_Context.init_global thy;
paulson@6051
    64
wenzelm@30223
    65
  val intr_specs = map (apfst (apfst Binding.name_of)) raw_intr_specs;
wenzelm@12191
    66
  val (intr_names, intr_tms) = split_list (map fst intr_specs);
wenzelm@33368
    67
  val case_names = Rule_Cases.case_names intr_names;
paulson@6051
    68
paulson@6051
    69
  (*recT and rec_params should agree for all mutually recursive components*)
paulson@6051
    70
  val rec_hds = map head_of rec_tms;
paulson@6051
    71
wenzelm@57877
    72
  val dummy = rec_hds |> forall (fn t => is_Const t orelse
wenzelm@57877
    73
      error ("Recursive set not previously declared as constant: " ^
wenzelm@57877
    74
                   Syntax.string_of_term ctxt t));
paulson@6051
    75
paulson@6051
    76
  (*Now we know they are all Consts, so get their names, type and params*)
paulson@6051
    77
  val rec_names = map (#1 o dest_Const) rec_hds
paulson@6051
    78
  and (Const(_,recT),rec_params) = strip_comb (hd rec_tms);
paulson@6051
    79
wenzelm@30364
    80
  val rec_base_names = map Long_Name.base_name rec_names;
wenzelm@57877
    81
  val dummy = rec_base_names |> forall (fn a => Symbol_Pos.is_identifier a orelse
wenzelm@57877
    82
    error ("Base name of recursive set not an identifier: " ^ a));
paulson@6051
    83
paulson@6051
    84
  local (*Checking the introduction rules*)
wenzelm@41449
    85
    val intr_sets = map (#2 o Ind_Syntax.rule_concl_msg thy) intr_tms;
paulson@6051
    86
    fun intr_ok set =
haftmann@36692
    87
        case head_of set of Const(a,recT) => member (op =) rec_names a | _ => false;
paulson@6051
    88
  in
wenzelm@57877
    89
    val dummy = intr_sets |> forall (fn t => intr_ok t orelse
wenzelm@57877
    90
      error ("Conclusion of rule does not name a recursive set: " ^
wenzelm@57877
    91
                Syntax.string_of_term ctxt t));
paulson@6051
    92
  end;
paulson@6051
    93
wenzelm@57877
    94
  val dummy = rec_params |> forall (fn t => is_Free t orelse
wenzelm@57877
    95
      error ("Param in recursion term not a free variable: " ^
wenzelm@57877
    96
               Syntax.string_of_term ctxt t));
paulson@6051
    97
paulson@6051
    98
  (*** Construct the fixedpoint definition ***)
wenzelm@44121
    99
  val mk_variant = singleton (Name.variant_list (List.foldr Misc_Legacy.add_term_names [] intr_tms));
paulson@6051
   100
paulson@6051
   101
  val z' = mk_variant"z" and X' = mk_variant"X" and w' = mk_variant"w";
paulson@6051
   102
haftmann@38522
   103
  fun dest_tprop (Const(@{const_name Trueprop},_) $ P) = P
wenzelm@12132
   104
    | dest_tprop Q = error ("Ill-formed premise of introduction rule: " ^
wenzelm@26189
   105
                            Syntax.string_of_term ctxt Q);
paulson@6051
   106
paulson@6051
   107
  (*Makes a disjunct from an introduction rule*)
paulson@6051
   108
  fun fp_part intr = (*quantify over rule's free vars except parameters*)
wenzelm@16855
   109
    let val prems = map dest_tprop (Logic.strip_imp_prems intr)
wenzelm@41449
   110
        val dummy = List.app (fn rec_hd => List.app (Ind_Syntax.chk_prem rec_hd) prems) rec_hds
wenzelm@44121
   111
        val exfrees = subtract (op =) rec_params (Misc_Legacy.term_frees intr)
wenzelm@41449
   112
        val zeq = FOLogic.mk_eq (Free(z', Ind_Syntax.iT), #1 (Ind_Syntax.rule_concl intr))
wenzelm@30190
   113
    in List.foldr FOLogic.mk_exists
wenzelm@32765
   114
             (Balanced_Tree.make FOLogic.mk_conj (zeq::prems)) exfrees
paulson@6051
   115
    end;
paulson@6051
   116
paulson@6051
   117
  (*The Part(A,h) terms -- compose injections to make h*)
wenzelm@41449
   118
  fun mk_Part (Bound 0) = Free(X', Ind_Syntax.iT) (*no mutual rec, no Part needed*)
wenzelm@41449
   119
    | mk_Part h = @{const Part} $ Free(X', Ind_Syntax.iT) $ Abs (w', Ind_Syntax.iT, h);
paulson@6051
   120
paulson@6051
   121
  (*Access to balanced disjoint sums via injections*)
wenzelm@23419
   122
  val parts = map mk_Part
wenzelm@32765
   123
    (Balanced_Tree.accesses {left = fn t => Su.inl $ t, right = fn t => Su.inr $ t, init = Bound 0}
wenzelm@23419
   124
      (length rec_tms));
paulson@6051
   125
paulson@6051
   126
  (*replace each set by the corresponding Part(A,h)*)
paulson@6051
   127
  val part_intrs = map (subst_free (rec_tms ~~ parts) o fp_part) intr_tms;
paulson@6051
   128
wenzelm@41449
   129
  val fp_abs =
wenzelm@44241
   130
    absfree (X', Ind_Syntax.iT)
wenzelm@44241
   131
        (Ind_Syntax.mk_Collect (z', dom_sum,
wenzelm@41449
   132
            Balanced_Tree.make FOLogic.mk_disj part_intrs));
paulson@6051
   133
paulson@6051
   134
  val fp_rhs = Fp.oper $ dom_sum $ fp_abs
paulson@6051
   135
wenzelm@22567
   136
  val dummy = List.app (fn rec_hd => (Logic.occs (rec_hd, fp_rhs) andalso
wenzelm@22567
   137
                             error "Illegal occurrence of recursion operator"; ()))
wenzelm@12132
   138
           rec_hds;
paulson@6051
   139
paulson@6051
   140
  (*** Make the new theory ***)
paulson@6051
   141
paulson@6051
   142
  (*A key definition:
paulson@6051
   143
    If no mutual recursion then it equals the one recursive set.
paulson@6051
   144
    If mutual recursion then it differs from all the recursive sets. *)
paulson@6051
   145
  val big_rec_base_name = space_implode "_" rec_base_names;
wenzelm@42361
   146
  val big_rec_name = Proof_Context.intern_const ctxt big_rec_base_name;
paulson@6051
   147
wenzelm@12132
   148
wenzelm@21962
   149
  val _ =
wenzelm@21962
   150
    if verbose then
wenzelm@21962
   151
      writeln ((if coind then "Coind" else "Ind") ^ "uctive definition " ^ quote big_rec_name)
wenzelm@21962
   152
    else ();
paulson@6051
   153
paulson@6051
   154
  (*Big_rec... is the union of the mutually recursive sets*)
paulson@6051
   155
  val big_rec_tm = list_comb(Const(big_rec_name,recT), rec_params);
paulson@6051
   156
paulson@6051
   157
  (*The individual sets must already be declared*)
wenzelm@37781
   158
  val axpairs = map Misc_Legacy.mk_defpair
wenzelm@12132
   159
        ((big_rec_tm, fp_rhs) ::
wenzelm@12132
   160
         (case parts of
wenzelm@12132
   161
             [_] => []                        (*no mutual recursion*)
wenzelm@12132
   162
           | _ => rec_tms ~~          (*define the sets as Parts*)
wenzelm@41449
   163
                  map (subst_atomic [(Free (X', Ind_Syntax.iT), big_rec_tm)]) parts));
paulson@6051
   164
paulson@6051
   165
  (*tracing: print the fixedpoint definition*)
paulson@6051
   166
  val dummy = if !Ind_Syntax.trace then
wenzelm@26189
   167
              writeln (cat_lines (map (Syntax.string_of_term ctxt o #2) axpairs))
wenzelm@12132
   168
          else ()
paulson@6051
   169
paulson@6051
   170
  (*add definitions of the inductive sets*)
haftmann@18377
   171
  val (_, thy1) =
haftmann@18377
   172
    thy
wenzelm@24712
   173
    |> Sign.add_path big_rec_base_name
wenzelm@39557
   174
    |> Global_Theory.add_defs false (map (Thm.no_attributes o apfst Binding.name) axpairs);
wenzelm@26189
   175
wenzelm@42361
   176
  val ctxt1 = Proof_Context.init_global thy1;
paulson@6051
   177
paulson@6051
   178
paulson@6051
   179
  (*fetch fp definitions from the theory*)
wenzelm@12132
   180
  val big_rec_def::part_rec_defs =
wenzelm@37781
   181
    map (Misc_Legacy.get_def thy1)
wenzelm@12132
   182
        (case rec_names of [_] => rec_names
wenzelm@12132
   183
                         | _   => big_rec_base_name::rec_names);
paulson@6051
   184
paulson@6051
   185
paulson@6051
   186
  (********)
paulson@6051
   187
  val dummy = writeln "  Proving monotonicity...";
paulson@6051
   188
wenzelm@12132
   189
  val bnd_mono =
wenzelm@20342
   190
    Goal.prove_global thy1 [] [] (FOLogic.mk_Trueprop (Fp.bnd_mono $ dom_sum $ fp_abs))
wenzelm@17985
   191
      (fn _ => EVERY
wenzelm@58838
   192
        [resolve_tac [@{thm Collect_subset} RS @{thm bnd_monoI}] 1,
wenzelm@24893
   193
         REPEAT (ares_tac (@{thms basic_monos} @ monos) 1)]);
paulson@6051
   194
wenzelm@35021
   195
  val dom_subset = Drule.export_without_context (big_rec_def RS Fp.subs);
paulson@6051
   196
wenzelm@35021
   197
  val unfold = Drule.export_without_context ([big_rec_def, bnd_mono] MRS Fp.Tarski);
paulson@6051
   198
paulson@6051
   199
  (********)
paulson@6051
   200
  val dummy = writeln "  Proving the introduction rules...";
paulson@6051
   201
wenzelm@12132
   202
  (*Mutual recursion?  Helps to derive subset rules for the
paulson@6051
   203
    individual sets.*)
paulson@6051
   204
  val Part_trans =
paulson@6051
   205
      case rec_names of
wenzelm@12132
   206
           [_] => asm_rl
wenzelm@35021
   207
         | _   => Drule.export_without_context (@{thm Part_subset} RS @{thm subset_trans});
paulson@6051
   208
paulson@6051
   209
  (*To type-check recursive occurrences of the inductive sets, possibly
paulson@6051
   210
    enclosed in some monotonic operator M.*)
wenzelm@12132
   211
  val rec_typechecks =
wenzelm@12132
   212
     [dom_subset] RL (asm_rl :: ([Part_trans] RL monos))
wenzelm@24893
   213
     RL [@{thm subsetD}];
paulson@6051
   214
paulson@6051
   215
  (*Type-checking is hardest aspect of proof;
paulson@6051
   216
    disjIn selects the correct disjunct after unfolding*)
wenzelm@54742
   217
  fun intro_tacsf disjIn ctxt =
wenzelm@17985
   218
    [DETERM (stac unfold 1),
wenzelm@24893
   219
     REPEAT (resolve_tac [@{thm Part_eqI}, @{thm CollectI}] 1),
paulson@6051
   220
     (*Now 2-3 subgoals: typechecking, the disjunction, perhaps equality.*)
wenzelm@58838
   221
     resolve_tac [disjIn] 2,
paulson@6051
   222
     (*Not ares_tac, since refl must be tried before equality assumptions;
paulson@6051
   223
       backtracking may occur if the premises have extra variables!*)
wenzelm@35409
   224
     DEPTH_SOLVE_1 (resolve_tac [@{thm refl}, @{thm exI}, @{thm conjI}] 2 APPEND assume_tac 2),
paulson@6051
   225
     (*Now solve the equations like Tcons(a,f) = Inl(?b4)*)
wenzelm@54742
   226
     rewrite_goals_tac ctxt con_defs,
wenzelm@58838
   227
     REPEAT (resolve_tac @{thms refl} 2),
paulson@6051
   228
     (*Typechecking; this can fail*)
wenzelm@56491
   229
     if !Ind_Syntax.trace then print_tac ctxt "The type-checking subgoal:"
paulson@6051
   230
     else all_tac,
paulson@6051
   231
     REPEAT (FIRSTGOAL (        dresolve_tac rec_typechecks
wenzelm@30595
   232
                        ORELSE' eresolve_tac (asm_rl :: @{thm PartE} :: @{thm SigmaE2} ::
wenzelm@12132
   233
                                              type_elims)
wenzelm@51798
   234
                        ORELSE' hyp_subst_tac ctxt1)),
wenzelm@56491
   235
     if !Ind_Syntax.trace then print_tac ctxt "The subgoal after monos, type_elims:"
paulson@6051
   236
     else all_tac,
wenzelm@30595
   237
     DEPTH_SOLVE (swap_res_tac (@{thm SigmaI} :: @{thm subsetI} :: type_intrs) 1)];
paulson@6051
   238
paulson@6051
   239
  (*combines disjI1 and disjI2 to get the corresponding nested disjunct...*)
wenzelm@32765
   240
  val mk_disj_rls = Balanced_Tree.accesses
wenzelm@26189
   241
    {left = fn rl => rl RS @{thm disjI1},
wenzelm@26189
   242
     right = fn rl => rl RS @{thm disjI2},
wenzelm@26189
   243
     init = @{thm asm_rl}};
paulson@6051
   244
wenzelm@17985
   245
  val intrs =
wenzelm@17985
   246
    (intr_tms, map intro_tacsf (mk_disj_rls (length intr_tms)))
wenzelm@17985
   247
    |> ListPair.map (fn (t, tacs) =>
wenzelm@20342
   248
      Goal.prove_global thy1 [] [] t
wenzelm@54742
   249
        (fn {context = ctxt, ...} => EVERY (rewrite_goals_tac ctxt part_rec_defs :: tacs ctxt)));
paulson@6051
   250
paulson@6051
   251
  (********)
paulson@6051
   252
  val dummy = writeln "  Proving the elimination rule...";
paulson@6051
   253
paulson@6051
   254
  (*Breaks down logical connectives in the monotonic function*)
wenzelm@52087
   255
  fun basic_elim_tac ctxt =
paulson@6051
   256
      REPEAT (SOMEGOAL (eresolve_tac (Ind_Syntax.elim_rls @ Su.free_SEs)
wenzelm@52087
   257
                ORELSE' bound_hyp_subst_tac ctxt))
wenzelm@54742
   258
      THEN prune_params_tac ctxt
wenzelm@12132
   259
          (*Mutual recursion: collapse references to Part(D,h)*)
wenzelm@54742
   260
      THEN (PRIMITIVE (fold_rule ctxt part_rec_defs));
paulson@6051
   261
paulson@6051
   262
  (*Elimination*)
wenzelm@52145
   263
  val elim =
wenzelm@52145
   264
    rule_by_tactic ctxt1 (basic_elim_tac ctxt1) (unfold RS Ind_Syntax.equals_CollectD)
paulson@6051
   265
paulson@6051
   266
  (*Applies freeness of the given constructors, which *must* be unfolded by
wenzelm@12132
   267
      the given defs.  Cannot simply use the local con_defs because
wenzelm@12132
   268
      con_defs=[] for inference systems.
wenzelm@12175
   269
    Proposition A should have the form t:Si where Si is an inductive set*)
wenzelm@36541
   270
  fun make_cases ctxt A =
wenzelm@36546
   271
    rule_by_tactic ctxt
wenzelm@52087
   272
      (basic_elim_tac ctxt THEN ALLGOALS (asm_full_simp_tac ctxt) THEN basic_elim_tac ctxt)
wenzelm@12175
   273
      (Thm.assume A RS elim)
wenzelm@35021
   274
      |> Drule.export_without_context_open;
paulson@6051
   275
paulson@6051
   276
  fun induction_rules raw_induct thy =
paulson@6051
   277
   let
paulson@6051
   278
     val dummy = writeln "  Proving the induction rule...";
paulson@6051
   279
paulson@6051
   280
     (*** Prove the main induction rule ***)
paulson@6051
   281
paulson@6051
   282
     val pred_name = "P";            (*name for predicate variables*)
paulson@6051
   283
paulson@6051
   284
     (*Used to make induction rules;
wenzelm@12132
   285
        ind_alist = [(rec_tm1,pred1),...] associates predicates with rec ops
wenzelm@12132
   286
        prem is a premise of an intr rule*)
wenzelm@26189
   287
     fun add_induct_prem ind_alist (prem as Const (@{const_name Trueprop}, _) $
wenzelm@26189
   288
                      (Const (@{const_name mem}, _) $ t $ X), iprems) =
haftmann@17314
   289
          (case AList.lookup (op aconv) ind_alist X of
skalberg@15531
   290
               SOME pred => prem :: FOLogic.mk_Trueprop (pred $ t) :: iprems
skalberg@15531
   291
             | NONE => (*possibly membership in M(rec_tm), for M monotone*)
wenzelm@12132
   292
                 let fun mk_sb (rec_tm,pred) =
wenzelm@26189
   293
                             (rec_tm, @{const Collect} $ rec_tm $ pred)
wenzelm@12132
   294
                 in  subst_free (map mk_sb ind_alist) prem :: iprems  end)
paulson@6051
   295
       | add_induct_prem ind_alist (prem,iprems) = prem :: iprems;
paulson@6051
   296
paulson@6051
   297
     (*Make a premise of the induction rule.*)
paulson@6051
   298
     fun induct_prem ind_alist intr =
wenzelm@46215
   299
       let val xs = subtract (op =) rec_params (Misc_Legacy.term_frees intr)
wenzelm@30190
   300
           val iprems = List.foldr (add_induct_prem ind_alist) []
skalberg@15574
   301
                              (Logic.strip_imp_prems intr)
wenzelm@12132
   302
           val (t,X) = Ind_Syntax.rule_concl intr
haftmann@17314
   303
           val (SOME pred) = AList.lookup (op aconv) ind_alist X
wenzelm@12132
   304
           val concl = FOLogic.mk_Trueprop (pred $ t)
wenzelm@46215
   305
       in fold_rev Logic.all xs (Logic.list_implies (iprems,concl)) end
paulson@6051
   306
       handle Bind => error"Recursion term not found in conclusion";
paulson@6051
   307
paulson@6051
   308
     (*Minimizes backtracking by delivering the correct premise to each goal.
paulson@6051
   309
       Intro rules with extra Vars in premises still cause some backtracking *)
paulson@6051
   310
     fun ind_tac [] 0 = all_tac
wenzelm@12132
   311
       | ind_tac(prem::prems) i =
wenzelm@35409
   312
             DEPTH_SOLVE_1 (ares_tac [prem, @{thm refl}] i) THEN ind_tac prems (i-1);
paulson@6051
   313
paulson@6051
   314
     val pred = Free(pred_name, Ind_Syntax.iT --> FOLogic.oT);
paulson@6051
   315
wenzelm@12132
   316
     val ind_prems = map (induct_prem (map (rpair pred) rec_tms))
wenzelm@12132
   317
                         intr_tms;
paulson@6051
   318
wenzelm@32091
   319
     val dummy =
wenzelm@32091
   320
      if ! Ind_Syntax.trace then
wenzelm@32091
   321
        writeln (cat_lines
wenzelm@32091
   322
          (["ind_prems:"] @ map (Syntax.string_of_term ctxt1) ind_prems @
wenzelm@32091
   323
           ["raw_induct:", Display.string_of_thm ctxt1 raw_induct]))
wenzelm@32091
   324
      else ();
paulson@6051
   325
paulson@6051
   326
wenzelm@12132
   327
     (*We use a MINIMAL simpset. Even FOL_ss contains too many simpules.
paulson@6051
   328
       If the premises get simplified, then the proofs could fail.*)
wenzelm@45625
   329
     val min_ss =
wenzelm@54895
   330
           (empty_simpset (Proof_Context.init_global thy)
wenzelm@45625
   331
             |> Simplifier.set_mksimps (K (map mk_eq o ZF_atomize o gen_all)))
wenzelm@12132
   332
           setSolver (mk_solver "minimal"
wenzelm@51717
   333
                      (fn ctxt => resolve_tac (triv_rls @ Simplifier.prems_of ctxt)
wenzelm@12132
   334
                                   ORELSE' assume_tac
wenzelm@58838
   335
                                   ORELSE' eresolve_tac @{thms FalseE}));
paulson@6051
   336
wenzelm@12132
   337
     val quant_induct =
wenzelm@20342
   338
       Goal.prove_global thy1 [] ind_prems
wenzelm@17985
   339
         (FOLogic.mk_Trueprop (Ind_Syntax.mk_all_imp (big_rec_tm, pred)))
wenzelm@54742
   340
         (fn {context = ctxt, prems} => EVERY
wenzelm@54742
   341
           [rewrite_goals_tac ctxt part_rec_defs,
wenzelm@58838
   342
            resolve_tac [@{thm impI} RS @{thm allI}] 1,
wenzelm@58838
   343
            DETERM (eresolve_tac [raw_induct] 1),
wenzelm@17985
   344
            (*Push Part inside Collect*)
wenzelm@24893
   345
            full_simp_tac (min_ss addsimps [@{thm Part_Collect}]) 1,
wenzelm@17985
   346
            (*This CollectE and disjE separates out the introduction rules*)
wenzelm@26189
   347
            REPEAT (FIRSTGOAL (eresolve_tac [@{thm CollectE}, @{thm disjE}])),
wenzelm@17985
   348
            (*Now break down the individual cases.  No disjE here in case
wenzelm@17985
   349
              some premise involves disjunction.*)
wenzelm@26189
   350
            REPEAT (FIRSTGOAL (eresolve_tac [@{thm CollectE}, @{thm exE}, @{thm conjE}]
wenzelm@51798
   351
                               ORELSE' (bound_hyp_subst_tac ctxt1))),
wenzelm@54742
   352
            ind_tac (rev (map (rewrite_rule ctxt part_rec_defs) prems)) (length prems)]);
paulson@6051
   353
wenzelm@32091
   354
     val dummy =
wenzelm@32091
   355
      if ! Ind_Syntax.trace then
wenzelm@32091
   356
        writeln ("quant_induct:\n" ^ Display.string_of_thm ctxt1 quant_induct)
wenzelm@32091
   357
      else ();
paulson@6051
   358
paulson@6051
   359
paulson@6051
   360
     (*** Prove the simultaneous induction rule ***)
paulson@6051
   361
paulson@6051
   362
     (*Make distinct predicates for each inductive set*)
paulson@6051
   363
paulson@6051
   364
     (*The components of the element type, several if it is a product*)
paulson@6051
   365
     val elem_type = CP.pseudo_type dom_sum;
paulson@6051
   366
     val elem_factors = CP.factors elem_type;
paulson@6051
   367
     val elem_frees = mk_frees "za" elem_factors;
paulson@6051
   368
     val elem_tuple = CP.mk_tuple Pr.pair elem_type elem_frees;
paulson@6051
   369
paulson@6051
   370
     (*Given a recursive set and its domain, return the "fsplit" predicate
paulson@6051
   371
       and a conclusion for the simultaneous induction rule.
paulson@6051
   372
       NOTE.  This will not work for mutually recursive predicates.  Previously
paulson@6051
   373
       a summand 'domt' was also an argument, but this required the domain of
paulson@6051
   374
       mutual recursion to invariably be a disjoint sum.*)
wenzelm@12132
   375
     fun mk_predpair rec_tm =
paulson@6051
   376
       let val rec_name = (#1 o dest_Const o head_of) rec_tm
wenzelm@30364
   377
           val pfree = Free(pred_name ^ "_" ^ Long_Name.base_name rec_name,
wenzelm@12132
   378
                            elem_factors ---> FOLogic.oT)
wenzelm@12132
   379
           val qconcl =
wenzelm@30190
   380
             List.foldr FOLogic.mk_all
skalberg@15574
   381
               (FOLogic.imp $
wenzelm@26189
   382
                (@{const mem} $ elem_tuple $ rec_tm)
skalberg@15574
   383
                      $ (list_comb (pfree, elem_frees))) elem_frees
wenzelm@12132
   384
       in  (CP.ap_split elem_type FOLogic.oT pfree,
wenzelm@12132
   385
            qconcl)
paulson@6051
   386
       end;
paulson@6051
   387
paulson@6051
   388
     val (preds,qconcls) = split_list (map mk_predpair rec_tms);
paulson@6051
   389
paulson@6051
   390
     (*Used to form simultaneous induction lemma*)
wenzelm@12132
   391
     fun mk_rec_imp (rec_tm,pred) =
wenzelm@26189
   392
         FOLogic.imp $ (@{const mem} $ Bound 0 $ rec_tm) $
wenzelm@12132
   393
                          (pred $ Bound 0);
paulson@6051
   394
paulson@6051
   395
     (*To instantiate the main induction rule*)
wenzelm@12132
   396
     val induct_concl =
wenzelm@12132
   397
         FOLogic.mk_Trueprop
wenzelm@12132
   398
           (Ind_Syntax.mk_all_imp
wenzelm@12132
   399
            (big_rec_tm,
wenzelm@12132
   400
             Abs("z", Ind_Syntax.iT,
wenzelm@32765
   401
                 Balanced_Tree.make FOLogic.mk_conj
wenzelm@12132
   402
                 (ListPair.map mk_rec_imp (rec_tms, preds)))))
paulson@6051
   403
     and mutual_induct_concl =
wenzelm@32765
   404
      FOLogic.mk_Trueprop (Balanced_Tree.make FOLogic.mk_conj qconcls);
paulson@6051
   405
wenzelm@12132
   406
     val dummy = if !Ind_Syntax.trace then
wenzelm@12132
   407
                 (writeln ("induct_concl = " ^
wenzelm@26189
   408
                           Syntax.string_of_term ctxt1 induct_concl);
wenzelm@12132
   409
                  writeln ("mutual_induct_concl = " ^
wenzelm@26189
   410
                           Syntax.string_of_term ctxt1 mutual_induct_concl))
wenzelm@12132
   411
             else ();
paulson@6051
   412
paulson@6051
   413
wenzelm@26189
   414
     val lemma_tac = FIRST' [eresolve_tac [@{thm asm_rl}, @{thm conjE}, @{thm PartE}, @{thm mp}],
wenzelm@26189
   415
                             resolve_tac [@{thm allI}, @{thm impI}, @{thm conjI}, @{thm Part_eqI}],
wenzelm@26189
   416
                             dresolve_tac [@{thm spec}, @{thm mp}, Pr.fsplitD]];
paulson@6051
   417
paulson@6051
   418
     val need_mutual = length rec_names > 1;
paulson@6051
   419
paulson@6051
   420
     val lemma = (*makes the link between the two induction rules*)
paulson@6051
   421
       if need_mutual then
wenzelm@12132
   422
          (writeln "  Proving the mutual induction rule...";
wenzelm@20342
   423
           Goal.prove_global thy1 [] []
wenzelm@17985
   424
             (Logic.mk_implies (induct_concl, mutual_induct_concl))
wenzelm@54742
   425
             (fn {context = ctxt, ...} => EVERY
wenzelm@54742
   426
               [rewrite_goals_tac ctxt part_rec_defs,
wenzelm@54742
   427
                REPEAT (rewrite_goals_tac ctxt [Pr.split_eq] THEN lemma_tac 1)]))
wenzelm@26189
   428
       else (writeln "  [ No mutual induction rule needed ]"; @{thm TrueI});
paulson@6051
   429
wenzelm@32091
   430
     val dummy =
wenzelm@32091
   431
      if ! Ind_Syntax.trace then
wenzelm@32091
   432
        writeln ("lemma: " ^ Display.string_of_thm ctxt1 lemma)
wenzelm@32091
   433
      else ();
paulson@6051
   434
paulson@6051
   435
paulson@6051
   436
     (*Mutual induction follows by freeness of Inl/Inr.*)
paulson@6051
   437
wenzelm@12132
   438
     (*Simplification largely reduces the mutual induction rule to the
paulson@6051
   439
       standard rule*)
wenzelm@12132
   440
     val mut_ss =
wenzelm@12132
   441
         min_ss addsimps [Su.distinct, Su.distinct', Su.inl_iff, Su.inr_iff];
paulson@6051
   442
paulson@6051
   443
     val all_defs = con_defs @ part_rec_defs;
paulson@6051
   444
paulson@6051
   445
     (*Removes Collects caused by M-operators in the intro rules.  It is very
paulson@6051
   446
       hard to simplify
wenzelm@12132
   447
         list({v: tf. (v : t --> P_t(v)) & (v : f --> P_f(v))})
paulson@6051
   448
       where t==Part(tf,Inl) and f==Part(tf,Inr) to  list({v: tf. P_t(v)}).
paulson@6051
   449
       Instead the following rules extract the relevant conjunct.
paulson@6051
   450
     *)
wenzelm@24893
   451
     val cmonos = [@{thm subset_refl} RS @{thm Collect_mono}] RL monos
wenzelm@24893
   452
                   RLN (2,[@{thm rev_subsetD}]);
paulson@6051
   453
paulson@6051
   454
     (*Minimizes backtracking by delivering the correct premise to each goal*)
wenzelm@54742
   455
     fun mutual_ind_tac _ [] 0 = all_tac
wenzelm@54742
   456
       | mutual_ind_tac ctxt (prem::prems) i =
wenzelm@12132
   457
           DETERM
wenzelm@12132
   458
            (SELECT_GOAL
wenzelm@12132
   459
               (
wenzelm@12132
   460
                (*Simplify the assumptions and goal by unfolding Part and
wenzelm@12132
   461
                  using freeness of the Sum constructors; proves all but one
wenzelm@12132
   462
                  conjunct by contradiction*)
wenzelm@54742
   463
                rewrite_goals_tac ctxt all_defs  THEN
wenzelm@24893
   464
                simp_tac (mut_ss addsimps [@{thm Part_iff}]) 1  THEN
wenzelm@12132
   465
                IF_UNSOLVED (*simp_tac may have finished it off!*)
wenzelm@12132
   466
                  ((*simplify assumptions*)
wenzelm@12132
   467
                   (*some risk of excessive simplification here -- might have
wenzelm@12132
   468
                     to identify the bare minimum set of rewrites*)
wenzelm@12132
   469
                   full_simp_tac
wenzelm@26287
   470
                      (mut_ss addsimps @{thms conj_simps} @ @{thms imp_simps} @ @{thms quant_simps}) 1
wenzelm@12132
   471
                   THEN
wenzelm@12132
   472
                   (*unpackage and use "prem" in the corresponding place*)
wenzelm@58838
   473
                   REPEAT (resolve_tac @{thms impI} 1)  THEN
wenzelm@58838
   474
                   resolve_tac [rewrite_rule ctxt all_defs prem] 1  THEN
wenzelm@12132
   475
                   (*prem must not be REPEATed below: could loop!*)
wenzelm@35409
   476
                   DEPTH_SOLVE (FIRSTGOAL (ares_tac [@{thm impI}] ORELSE'
wenzelm@35409
   477
                                           eresolve_tac (@{thm conjE} :: @{thm mp} :: cmonos))))
wenzelm@12132
   478
               ) i)
wenzelm@54742
   479
            THEN mutual_ind_tac ctxt prems (i-1);
paulson@6051
   480
wenzelm@12132
   481
     val mutual_induct_fsplit =
paulson@6051
   482
       if need_mutual then
wenzelm@20342
   483
         Goal.prove_global thy1 [] (map (induct_prem (rec_tms~~preds)) intr_tms)
wenzelm@17985
   484
           mutual_induct_concl
wenzelm@54742
   485
           (fn {context = ctxt, prems} => EVERY
wenzelm@58838
   486
             [resolve_tac [quant_induct RS lemma] 1,
wenzelm@54742
   487
              mutual_ind_tac ctxt (rev prems) (length prems)])
wenzelm@35409
   488
       else @{thm TrueI};
paulson@6051
   489
paulson@6051
   490
     (** Uncurrying the predicate in the ordinary induction rule **)
paulson@6051
   491
paulson@6051
   492
     (*instantiate the variable to a tuple, if it is non-trivial, in order to
paulson@6051
   493
       allow the predicate to be "opened up".
paulson@6051
   494
       The name "x.1" comes from the "RS spec" !*)
wenzelm@12132
   495
     val inst =
wenzelm@12132
   496
         case elem_frees of [_] => I
wenzelm@43333
   497
            | _ => Drule.instantiate_normalize ([], [(cterm_of thy1 (Var(("x",1), Ind_Syntax.iT)),
wenzelm@20342
   498
                                      cterm_of thy1 elem_tuple)]);
paulson@6051
   499
paulson@6051
   500
     (*strip quantifier and the implication*)
wenzelm@35409
   501
     val induct0 = inst (quant_induct RS @{thm spec} RSN (2, @{thm rev_mp}));
paulson@6051
   502
wenzelm@26189
   503
     val Const (@{const_name Trueprop}, _) $ (pred_var $ _) = concl_of induct0
paulson@6051
   504
wenzelm@54742
   505
     val induct =
wenzelm@54742
   506
       CP.split_rule_var (Proof_Context.init_global thy)
wenzelm@54742
   507
        (pred_var, elem_type-->FOLogic.oT, induct0)
wenzelm@54742
   508
       |> Drule.export_without_context
wenzelm@54742
   509
     and mutual_induct = CP.remove_split (Proof_Context.init_global thy) mutual_induct_fsplit
wenzelm@8438
   510
haftmann@18377
   511
     val ([induct', mutual_induct'], thy') =
haftmann@18377
   512
       thy
wenzelm@39557
   513
       |> Global_Theory.add_thms [((Binding.name (co_prefix ^ "induct"), induct),
wenzelm@24861
   514
             [case_names, Induct.induct_pred big_rec_name]),
haftmann@29579
   515
           ((Binding.name "mutual_induct", mutual_induct), [case_names])];
wenzelm@12227
   516
    in ((thy', induct'), mutual_induct')
paulson@6051
   517
    end;  (*of induction_rules*)
paulson@6051
   518
wenzelm@35021
   519
  val raw_induct = Drule.export_without_context ([big_rec_def, bnd_mono] MRS Fp.induct)
paulson@6051
   520
wenzelm@12227
   521
  val ((thy2, induct), mutual_induct) =
wenzelm@12227
   522
    if not coind then induction_rules raw_induct thy1
haftmann@18377
   523
    else
haftmann@18377
   524
      (thy1
wenzelm@39557
   525
      |> Global_Theory.add_thms [((Binding.name (co_prefix ^ "induct"), raw_induct), [])]
wenzelm@35409
   526
      |> apfst hd |> Library.swap, @{thm TrueI})
paulson@6051
   527
  and defs = big_rec_def :: part_rec_defs
paulson@6051
   528
paulson@6051
   529
haftmann@18377
   530
  val (([bnd_mono', dom_subset', elim'], [defs', intrs']), thy3) =
wenzelm@8438
   531
    thy2
wenzelm@12183
   532
    |> IndCases.declare big_rec_name make_cases
wenzelm@39557
   533
    |> Global_Theory.add_thms
haftmann@29579
   534
      [((Binding.name "bnd_mono", bnd_mono), []),
haftmann@29579
   535
       ((Binding.name "dom_subset", dom_subset), []),
haftmann@29579
   536
       ((Binding.name "cases", elim), [case_names, Induct.cases_pred big_rec_name])]
wenzelm@39557
   537
    ||>> (Global_Theory.add_thmss o map Thm.no_attributes)
haftmann@29579
   538
        [(Binding.name "defs", defs),
haftmann@29579
   539
         (Binding.name "intros", intrs)];
haftmann@18377
   540
  val (intrs'', thy4) =
haftmann@18377
   541
    thy3
wenzelm@39557
   542
    |> Global_Theory.add_thms ((map Binding.name intr_names ~~ intrs') ~~ map #2 intr_specs)
wenzelm@24712
   543
    ||> Sign.parent_path;
wenzelm@8438
   544
  in
wenzelm@12132
   545
    (thy4,
wenzelm@8438
   546
      {defs = defs',
wenzelm@8438
   547
       bnd_mono = bnd_mono',
wenzelm@8438
   548
       dom_subset = dom_subset',
wenzelm@12132
   549
       intrs = intrs'',
wenzelm@8438
   550
       elim = elim',
wenzelm@8438
   551
       induct = induct,
wenzelm@8438
   552
       mutual_induct = mutual_induct})
wenzelm@8438
   553
  end;
paulson@6051
   554
wenzelm@12132
   555
(*source version*)
wenzelm@12132
   556
fun add_inductive (srec_tms, sdom_sum) intr_srcs
wenzelm@12132
   557
    (raw_monos, raw_con_defs, raw_type_intrs, raw_type_elims) thy =
wenzelm@12132
   558
  let
wenzelm@42361
   559
    val ctxt = Proof_Context.init_global thy;
wenzelm@39288
   560
    val read_terms = map (Syntax.parse_term ctxt #> Type.constraint Ind_Syntax.iT)
wenzelm@24726
   561
      #> Syntax.check_terms ctxt;
wenzelm@24726
   562
wenzelm@56031
   563
    val intr_atts = map (map (Attrib.attribute_cmd ctxt) o snd) intr_srcs;
wenzelm@17937
   564
    val sintrs = map fst intr_srcs ~~ intr_atts;
wenzelm@24726
   565
    val rec_tms = read_terms srec_tms;
wenzelm@24726
   566
    val dom_sum = singleton read_terms sdom_sum;
wenzelm@24726
   567
    val intr_tms = Syntax.read_props ctxt (map (snd o fst) sintrs);
wenzelm@17937
   568
    val intr_specs = (map (fst o fst) sintrs ~~ intr_tms) ~~ map snd sintrs;
wenzelm@24726
   569
    val monos = Attrib.eval_thms ctxt raw_monos;
wenzelm@24726
   570
    val con_defs = Attrib.eval_thms ctxt raw_con_defs;
wenzelm@24726
   571
    val type_intrs = Attrib.eval_thms ctxt raw_type_intrs;
wenzelm@24726
   572
    val type_elims = Attrib.eval_thms ctxt raw_type_elims;
wenzelm@12132
   573
  in
haftmann@18418
   574
    thy
wenzelm@24726
   575
    |> add_inductive_i true (rec_tms, dom_sum) intr_specs (monos, con_defs, type_intrs, type_elims)
haftmann@18418
   576
  end;
wenzelm@12132
   577
wenzelm@12132
   578
wenzelm@12132
   579
(* outer syntax *)
wenzelm@12132
   580
wenzelm@12132
   581
fun mk_ind (((((doms, intrs), monos), con_defs), type_intrs), type_elims) =
wenzelm@36960
   582
  #1 o add_inductive doms (map Parse.triple_swap intrs) (monos, con_defs, type_intrs, type_elims);
wenzelm@12132
   583
wenzelm@12132
   584
val ind_decl =
wenzelm@46949
   585
  (@{keyword "domains"} |-- Parse.!!! (Parse.enum1 "+" Parse.term --
wenzelm@46949
   586
      ((@{keyword "\<subseteq>"} || @{keyword "<="}) |-- Parse.term))) --
wenzelm@46949
   587
  (@{keyword "intros"} |--
wenzelm@36960
   588
    Parse.!!! (Scan.repeat1 (Parse_Spec.opt_thm_name ":" -- Parse.prop))) --
wenzelm@58028
   589
  Scan.optional (@{keyword "monos"} |-- Parse.!!! Parse.xthms1) [] --
wenzelm@58028
   590
  Scan.optional (@{keyword "con_defs"} |-- Parse.!!! Parse.xthms1) [] --
wenzelm@58028
   591
  Scan.optional (@{keyword "type_intros"} |-- Parse.!!! Parse.xthms1) [] --
wenzelm@58028
   592
  Scan.optional (@{keyword "type_elims"} |-- Parse.!!! Parse.xthms1) []
wenzelm@12132
   593
  >> (Toplevel.theory o mk_ind);
wenzelm@12132
   594
wenzelm@36960
   595
val _ =
wenzelm@46961
   596
  Outer_Syntax.command
wenzelm@46961
   597
    (if coind then @{command_spec "coinductive"} else @{command_spec "inductive"})
wenzelm@46961
   598
    ("define " ^ co_prefix ^ "inductive sets") ind_decl;
wenzelm@12132
   599
paulson@6051
   600
end;
wenzelm@12132
   601