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