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