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