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