src/HOL/Tools/inductive_set.ML
author haftmann
Thu Jul 30 15:20:57 2009 +0200 (2009-07-30)
changeset 32342 3fabf5b5fc83
parent 32287 65d5c5b30747
child 32351 96f9e6402403
permissions -rw-r--r--
path-sensitive tuple combinators carry a "p"(ath) prefix; combinators for standard right-fold tuples
     1 (*  Title:      HOL/Tools/inductive_set.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Wrapper for defining inductive sets using package for inductive predicates,
     5 including infrastructure for converting between predicates and sets.
     6 *)
     7 
     8 signature INDUCTIVE_SET =
     9 sig
    10   val to_set_att: thm list -> attribute
    11   val to_pred_att: thm list -> attribute
    12   val pred_set_conv_att: attribute
    13   val add_inductive_i:
    14     Inductive.inductive_flags ->
    15     ((binding * typ) * mixfix) list ->
    16     (string * typ) list ->
    17     (Attrib.binding * term) list -> thm list ->
    18     local_theory -> Inductive.inductive_result * local_theory
    19   val add_inductive: bool -> bool ->
    20     (binding * string option * mixfix) list ->
    21     (binding * string option * mixfix) list ->
    22     (Attrib.binding * string) list -> (Facts.ref * Attrib.src list) list ->
    23     bool -> local_theory -> Inductive.inductive_result * local_theory
    24   val codegen_preproc: theory -> thm list -> thm list
    25   val setup: theory -> theory
    26 end;
    27 
    28 structure Inductive_Set: INDUCTIVE_SET =
    29 struct
    30 
    31 (**** simplify {(x1, ..., xn). (x1, ..., xn) : S} to S ****)
    32 
    33 val collect_mem_simproc =
    34   Simplifier.simproc (theory "Set") "Collect_mem" ["Collect t"] (fn thy => fn ss =>
    35     fn S as Const ("Collect", Type ("fun", [_, T])) $ t =>
    36          let val (u, Ts, ps) = HOLogic.strip_psplits t
    37          in case u of
    38            (c as Const ("op :", _)) $ q $ S' =>
    39              (case try (HOLogic.strip_ptuple ps) q of
    40                 NONE => NONE
    41               | SOME ts =>
    42                   if not (loose_bvar (S', 0)) andalso
    43                     ts = map Bound (length ps downto 0)
    44                   then
    45                     let val simp = full_simp_tac (Simplifier.inherit_context ss
    46                       (HOL_basic_ss addsimps [split_paired_all, split_conv])) 1
    47                     in
    48                       SOME (Goal.prove (Simplifier.the_context ss) [] []
    49                         (Const ("==", T --> T --> propT) $ S $ S')
    50                         (K (EVERY
    51                           [rtac eq_reflection 1, rtac @{thm subset_antisym} 1,
    52                            rtac subsetI 1, dtac CollectD 1, simp,
    53                            rtac subsetI 1, rtac CollectI 1, simp])))
    54                     end
    55                   else NONE)
    56          | _ => NONE
    57          end
    58      | _ => NONE);
    59 
    60 (***********************************************************************************)
    61 (* simplifies (%x y. (x, y) : S & P x y) to (%x y. (x, y) : S Int {(x, y). P x y}) *)
    62 (* and        (%x y. (x, y) : S | P x y) to (%x y. (x, y) : S Un {(x, y). P x y})  *)
    63 (* used for converting "strong" (co)induction rules                                *)
    64 (***********************************************************************************)
    65 
    66 val anyt = Free ("t", TFree ("'t", []));
    67 
    68 fun strong_ind_simproc tab =
    69   Simplifier.simproc_i @{theory HOL} "strong_ind" [anyt] (fn thy => fn ss => fn t =>
    70     let
    71       fun close p t f =
    72         let val vs = Term.add_vars t []
    73         in Drule.instantiate' [] (rev (map (SOME o cterm_of thy o Var) vs))
    74           (p (fold (Logic.all o Var) vs t) f)
    75         end;
    76       fun mkop "op &" T x = SOME (Const (@{const_name inter}, T --> T --> T), x)
    77         | mkop "op |" T x = SOME (Const (@{const_name union}, T --> T --> T), x)
    78         | mkop _ _ _ = NONE;
    79       fun mk_collect p T t =
    80         let val U = HOLogic.dest_setT T
    81         in HOLogic.Collect_const U $
    82           HOLogic.mk_psplits (HOLogic.flat_tuple_paths p) U HOLogic.boolT t
    83         end;
    84       fun decomp (Const (s, _) $ ((m as Const ("op :",
    85             Type (_, [_, Type (_, [T, _])]))) $ p $ S) $ u) =
    86               mkop s T (m, p, S, mk_collect p T (head_of u))
    87         | decomp (Const (s, _) $ u $ ((m as Const ("op :",
    88             Type (_, [_, Type (_, [T, _])]))) $ p $ S)) =
    89               mkop s T (m, p, mk_collect p T (head_of u), S)
    90         | decomp _ = NONE;
    91       val simp = full_simp_tac (Simplifier.inherit_context ss
    92         (HOL_basic_ss addsimps [mem_Collect_eq, split_conv])) 1;
    93       fun mk_rew t = (case strip_abs_vars t of
    94           [] => NONE
    95         | xs => (case decomp (strip_abs_body t) of
    96             NONE => NONE
    97           | SOME (bop, (m, p, S, S')) =>
    98               SOME (close (Goal.prove (Simplifier.the_context ss) [] [])
    99                 (Logic.mk_equals (t, list_abs (xs, m $ p $ (bop $ S $ S'))))
   100                 (K (EVERY
   101                   [rtac eq_reflection 1, REPEAT (rtac ext 1), rtac iffI 1,
   102                    EVERY [etac conjE 1, rtac IntI 1, simp, simp,
   103                      etac IntE 1, rtac conjI 1, simp, simp] ORELSE
   104                    EVERY [etac disjE 1, rtac UnI1 1, simp, rtac UnI2 1, simp,
   105                      etac UnE 1, rtac disjI1 1, simp, rtac disjI2 1, simp]])))
   106                 handle ERROR _ => NONE))
   107     in
   108       case strip_comb t of
   109         (h as Const (name, _), ts) => (case Symtab.lookup tab name of
   110           SOME _ =>
   111             let val rews = map mk_rew ts
   112             in
   113               if forall is_none rews then NONE
   114               else SOME (fold (fn th1 => fn th2 => combination th2 th1)
   115                 (map2 (fn SOME r => K r | NONE => reflexive o cterm_of thy)
   116                    rews ts) (reflexive (cterm_of thy h)))
   117             end
   118         | NONE => NONE)
   119       | _ => NONE
   120     end);
   121 
   122 (* only eta contract terms occurring as arguments of functions satisfying p *)
   123 fun eta_contract p =
   124   let
   125     fun eta b (Abs (a, T, body)) =
   126           (case eta b body of
   127              body' as (f $ Bound 0) =>
   128                if loose_bvar1 (f, 0) orelse not b then Abs (a, T, body')
   129                else incr_boundvars ~1 f
   130            | body' => Abs (a, T, body'))
   131       | eta b (t $ u) = eta b t $ eta (p (head_of t)) u
   132       | eta b t = t
   133   in eta false end;
   134 
   135 fun eta_contract_thm p =
   136   Conv.fconv_rule (Conv.then_conv (Thm.beta_conversion true, fn ct =>
   137     Thm.transitive (Thm.eta_conversion ct)
   138       (Thm.symmetric (Thm.eta_conversion
   139         (cterm_of (theory_of_cterm ct) (eta_contract p (term_of ct)))))));
   140 
   141 
   142 (***********************************************************)
   143 (* rules for converting between predicate and set notation *)
   144 (*                                                         *)
   145 (* rules for converting predicates to sets have the form   *)
   146 (* P (%x y. (x, y) : s) = (%x y. (x, y) : S s)             *)
   147 (*                                                         *)
   148 (* rules for converting sets to predicates have the form   *)
   149 (* S {(x, y). p x y} = {(x, y). P p x y}                   *)
   150 (*                                                         *)
   151 (* where s and p are parameters                            *)
   152 (***********************************************************)
   153 
   154 structure PredSetConvData = GenericDataFun
   155 (
   156   type T =
   157     {(* rules for converting predicates to sets *)
   158      to_set_simps: thm list,
   159      (* rules for converting sets to predicates *)
   160      to_pred_simps: thm list,
   161      (* arities of functions of type t set => ... => u set *)
   162      set_arities: (typ * (int list list option list * int list list option)) list Symtab.table,
   163      (* arities of functions of type (t => ... => bool) => u => ... => bool *)
   164      pred_arities: (typ * (int list list option list * int list list option)) list Symtab.table};
   165   val empty = {to_set_simps = [], to_pred_simps = [],
   166     set_arities = Symtab.empty, pred_arities = Symtab.empty};
   167   val extend = I;
   168   fun merge _
   169     ({to_set_simps = to_set_simps1, to_pred_simps = to_pred_simps1,
   170       set_arities = set_arities1, pred_arities = pred_arities1},
   171      {to_set_simps = to_set_simps2, to_pred_simps = to_pred_simps2,
   172       set_arities = set_arities2, pred_arities = pred_arities2}) : T =
   173     {to_set_simps = Thm.merge_thms (to_set_simps1, to_set_simps2),
   174      to_pred_simps = Thm.merge_thms (to_pred_simps1, to_pred_simps2),
   175      set_arities = Symtab.merge_list op = (set_arities1, set_arities2),
   176      pred_arities = Symtab.merge_list op = (pred_arities1, pred_arities2)};
   177 );
   178 
   179 fun name_type_of (Free p) = SOME p
   180   | name_type_of (Const p) = SOME p
   181   | name_type_of _ = NONE;
   182 
   183 fun map_type f (Free (s, T)) = Free (s, f T)
   184   | map_type f (Var (ixn, T)) = Var (ixn, f T)
   185   | map_type f _ = error "map_type";
   186 
   187 fun find_most_specific is_inst f eq xs T =
   188   find_first (fn U => is_inst (T, f U)
   189     andalso forall (fn U' => eq (f U, f U') orelse not
   190       (is_inst (T, f U') andalso is_inst (f U', f U)))
   191         xs) xs;
   192 
   193 fun lookup_arity thy arities (s, T) = case Symtab.lookup arities s of
   194     NONE => NONE
   195   | SOME xs => find_most_specific (Sign.typ_instance thy) fst (op =) xs T;
   196 
   197 fun lookup_rule thy f rules = find_most_specific
   198   (swap #> Pattern.matches thy) (f #> fst) (op aconv) rules;
   199 
   200 fun infer_arities thy arities (optf, t) fs = case strip_comb t of
   201     (Abs (s, T, u), []) => infer_arities thy arities (NONE, u) fs
   202   | (Abs _, _) => infer_arities thy arities (NONE, Envir.beta_norm t) fs
   203   | (u, ts) => (case Option.map (lookup_arity thy arities) (name_type_of u) of
   204       SOME (SOME (_, (arity, _))) =>
   205         (fold (infer_arities thy arities) (arity ~~ List.take (ts, length arity)) fs
   206            handle Subscript => error "infer_arities: bad term")
   207     | _ => fold (infer_arities thy arities) (map (pair NONE) ts)
   208       (case optf of
   209          NONE => fs
   210        | SOME f => AList.update op = (u, the_default f
   211            (Option.map (curry op inter f) (AList.lookup op = fs u))) fs));
   212 
   213 
   214 (**************************************************************)
   215 (*    derive the to_pred equation from the to_set equation    *)
   216 (*                                                            *)
   217 (* 1. instantiate each set parameter with {(x, y). p x y}     *)
   218 (* 2. apply %P. {(x, y). P x y} to both sides of the equation *)
   219 (* 3. simplify                                                *)
   220 (**************************************************************)
   221 
   222 fun mk_to_pred_inst thy fs =
   223   map (fn (x, ps) =>
   224     let
   225       val U = HOLogic.dest_setT (fastype_of x);
   226       val x' = map_type (K (HOLogic.strip_ptupleT ps U ---> HOLogic.boolT)) x
   227     in
   228       (cterm_of thy x,
   229        cterm_of thy (HOLogic.Collect_const U $
   230          HOLogic.mk_psplits ps U HOLogic.boolT x'))
   231     end) fs;
   232 
   233 fun mk_to_pred_eq p fs optfs' T thm =
   234   let
   235     val thy = theory_of_thm thm;
   236     val insts = mk_to_pred_inst thy fs;
   237     val thm' = Thm.instantiate ([], insts) thm;
   238     val thm'' = (case optfs' of
   239         NONE => thm' RS sym
   240       | SOME fs' =>
   241           let
   242             val (_, U) = split_last (binder_types T);
   243             val Ts = HOLogic.strip_ptupleT fs' U;
   244             (* FIXME: should cterm_instantiate increment indexes? *)
   245             val arg_cong' = Thm.incr_indexes (Thm.maxidx_of thm + 1) arg_cong;
   246             val (arg_cong_f, _) = arg_cong' |> cprop_of |> Drule.strip_imp_concl |>
   247               Thm.dest_comb |> snd |> Drule.strip_comb |> snd |> hd |> Thm.dest_comb
   248           in
   249             thm' RS (Drule.cterm_instantiate [(arg_cong_f,
   250               cterm_of thy (Abs ("P", Ts ---> HOLogic.boolT,
   251                 HOLogic.Collect_const U $ HOLogic.mk_psplits fs' U
   252                   HOLogic.boolT (Bound 0))))] arg_cong' RS sym)
   253           end)
   254   in
   255     Simplifier.simplify (HOL_basic_ss addsimps [mem_Collect_eq, split_conv]
   256       addsimprocs [collect_mem_simproc]) thm'' |>
   257         zero_var_indexes |> eta_contract_thm (equal p)
   258   end;
   259 
   260 
   261 (**** declare rules for converting predicates to sets ****)
   262 
   263 fun add ctxt thm (tab as {to_set_simps, to_pred_simps, set_arities, pred_arities}) =
   264   case prop_of thm of
   265     Const ("Trueprop", _) $ (Const ("op =", Type (_, [T, _])) $ lhs $ rhs) =>
   266       (case body_type T of
   267          Type ("bool", []) =>
   268            let
   269              val thy = Context.theory_of ctxt;
   270              fun factors_of t fs = case strip_abs_body t of
   271                  Const ("op :", _) $ u $ S =>
   272                    if is_Free S orelse is_Var S then
   273                      let val ps = HOLogic.flat_tuple_paths u
   274                      in (SOME ps, (S, ps) :: fs) end
   275                    else (NONE, fs)
   276                | _ => (NONE, fs);
   277              val (h, ts) = strip_comb lhs
   278              val (pfs, fs) = fold_map factors_of ts [];
   279              val ((h', ts'), fs') = (case rhs of
   280                  Abs _ => (case strip_abs_body rhs of
   281                      Const ("op :", _) $ u $ S =>
   282                        (strip_comb S, SOME (HOLogic.flat_tuple_paths u))
   283                    | _ => error "member symbol on right-hand side expected")
   284                | _ => (strip_comb rhs, NONE))
   285            in
   286              case (name_type_of h, name_type_of h') of
   287                (SOME (s, T), SOME (s', T')) =>
   288                  if exists (fn (U, _) =>
   289                    Sign.typ_instance thy (T', U) andalso
   290                    Sign.typ_instance thy (U, T'))
   291                      (Symtab.lookup_list set_arities s')
   292                  then
   293                    (warning ("Ignoring conversion rule for operator " ^ s'); tab)
   294                  else
   295                    {to_set_simps = thm :: to_set_simps,
   296                     to_pred_simps =
   297                       mk_to_pred_eq h fs fs' T' thm :: to_pred_simps,
   298                     set_arities = Symtab.insert_list op = (s',
   299                       (T', (map (AList.lookup op = fs) ts', fs'))) set_arities,
   300                     pred_arities = Symtab.insert_list op = (s,
   301                       (T, (pfs, fs'))) pred_arities}
   302              | _ => error "set / predicate constant expected"
   303            end
   304        | _ => error "equation between predicates expected")
   305   | _ => error "equation expected";
   306 
   307 val pred_set_conv_att = Thm.declaration_attribute
   308   (fn thm => fn ctxt => PredSetConvData.map (add ctxt thm) ctxt);
   309 
   310 
   311 (**** convert theorem in set notation to predicate notation ****)
   312 
   313 fun is_pred tab t =
   314   case Option.map (Symtab.lookup tab o fst) (name_type_of t) of
   315     SOME (SOME _) => true | _ => false;
   316 
   317 fun to_pred_simproc rules =
   318   let val rules' = map mk_meta_eq rules
   319   in
   320     Simplifier.simproc_i @{theory HOL} "to_pred" [anyt]
   321       (fn thy => K (lookup_rule thy (prop_of #> Logic.dest_equals) rules'))
   322   end;
   323 
   324 fun to_pred_proc thy rules t = case lookup_rule thy I rules t of
   325     NONE => NONE
   326   | SOME (lhs, rhs) =>
   327       SOME (Envir.subst_term
   328         (Pattern.match thy (lhs, t) (Vartab.empty, Vartab.empty)) rhs);
   329 
   330 fun to_pred thms ctxt thm =
   331   let
   332     val thy = Context.theory_of ctxt;
   333     val {to_pred_simps, set_arities, pred_arities, ...} =
   334       fold (add ctxt) thms (PredSetConvData.get ctxt);
   335     val fs = filter (is_Var o fst)
   336       (infer_arities thy set_arities (NONE, prop_of thm) []);
   337     (* instantiate each set parameter with {(x, y). p x y} *)
   338     val insts = mk_to_pred_inst thy fs
   339   in
   340     thm |>
   341     Thm.instantiate ([], insts) |>
   342     Simplifier.full_simplify (HOL_basic_ss addsimprocs
   343       [to_pred_simproc (mem_Collect_eq :: split_conv :: to_pred_simps)]) |>
   344     eta_contract_thm (is_pred pred_arities) |>
   345     RuleCases.save thm
   346   end;
   347 
   348 val to_pred_att = Thm.rule_attribute o to_pred;
   349     
   350 
   351 (**** convert theorem in predicate notation to set notation ****)
   352 
   353 fun to_set thms ctxt thm =
   354   let
   355     val thy = Context.theory_of ctxt;
   356     val {to_set_simps, pred_arities, ...} =
   357       fold (add ctxt) thms (PredSetConvData.get ctxt);
   358     val fs = filter (is_Var o fst)
   359       (infer_arities thy pred_arities (NONE, prop_of thm) []);
   360     (* instantiate each predicate parameter with %x y. (x, y) : s *)
   361     val insts = map (fn (x, ps) =>
   362       let
   363         val Ts = binder_types (fastype_of x);
   364         val T = HOLogic.mk_ptupleT ps Ts;
   365         val x' = map_type (K (HOLogic.mk_setT T)) x
   366       in
   367         (cterm_of thy x,
   368          cterm_of thy (list_abs (map (pair "x") Ts, HOLogic.mk_mem
   369            (HOLogic.mk_ptuple ps T (map Bound (length ps downto 0)), x'))))
   370       end) fs
   371   in
   372     thm |>
   373     Thm.instantiate ([], insts) |>
   374     Simplifier.full_simplify (HOL_basic_ss addsimps to_set_simps
   375         addsimprocs [strong_ind_simproc pred_arities, collect_mem_simproc]) |>
   376     RuleCases.save thm
   377   end;
   378 
   379 val to_set_att = Thm.rule_attribute o to_set;
   380 
   381 
   382 (**** preprocessor for code generator ****)
   383 
   384 fun codegen_preproc thy =
   385   let
   386     val {to_pred_simps, set_arities, pred_arities, ...} =
   387       PredSetConvData.get (Context.Theory thy);
   388     fun preproc thm =
   389       if exists_Const (fn (s, _) => case Symtab.lookup set_arities s of
   390           NONE => false
   391         | SOME arities => exists (fn (_, (xs, _)) =>
   392             forall is_none xs) arities) (prop_of thm)
   393       then
   394         thm |>
   395         Simplifier.full_simplify (HOL_basic_ss addsimprocs
   396           [to_pred_simproc (mem_Collect_eq :: split_conv :: to_pred_simps)]) |>
   397         eta_contract_thm (is_pred pred_arities)
   398       else thm
   399   in map preproc end;
   400 
   401 fun code_ind_att optmod = to_pred_att [] #> InductiveCodegen.add optmod NONE;
   402 
   403 
   404 (**** definition of inductive sets ****)
   405 
   406 fun add_ind_set_def
   407     {quiet_mode, verbose, kind, alt_name, coind, no_elim, no_ind, skip_mono, fork_mono}
   408     cs intros monos params cnames_syn ctxt =
   409   let
   410     val thy = ProofContext.theory_of ctxt;
   411     val {set_arities, pred_arities, to_pred_simps, ...} =
   412       PredSetConvData.get (Context.Proof ctxt);
   413     fun infer (Abs (_, _, t)) = infer t
   414       | infer (Const ("op :", _) $ t $ u) =
   415           infer_arities thy set_arities (SOME (HOLogic.flat_tuple_paths t), u)
   416       | infer (t $ u) = infer t #> infer u
   417       | infer _ = I;
   418     val new_arities = filter_out
   419       (fn (x as Free (_, T), _) => x mem params andalso length (binder_types T) > 1
   420         | _ => false) (fold (snd #> infer) intros []);
   421     val params' = map (fn x => (case AList.lookup op = new_arities x of
   422         SOME fs =>
   423           let
   424             val T = HOLogic.dest_setT (fastype_of x);
   425             val Ts = HOLogic.strip_ptupleT fs T;
   426             val x' = map_type (K (Ts ---> HOLogic.boolT)) x
   427           in
   428             (x, (x',
   429               (HOLogic.Collect_const T $
   430                  HOLogic.mk_psplits fs T HOLogic.boolT x',
   431                list_abs (map (pair "x") Ts, HOLogic.mk_mem
   432                  (HOLogic.mk_ptuple fs T (map Bound (length fs downto 0)),
   433                   x)))))
   434           end
   435        | NONE => (x, (x, (x, x))))) params;
   436     val (params1, (params2, params3)) =
   437       params' |> map snd |> split_list ||> split_list;
   438     val paramTs = map fastype_of params;
   439 
   440     (* equations for converting sets to predicates *)
   441     val ((cs', cs_info), eqns) = cs |> map (fn c as Free (s, T) =>
   442       let
   443         val fs = the_default [] (AList.lookup op = new_arities c);
   444         val (Us, U) = split_last (binder_types T);
   445         val _ = Us = paramTs orelse error (Pretty.string_of (Pretty.chunks
   446           [Pretty.str "Argument types",
   447            Pretty.block (Pretty.commas (map (Syntax.pretty_typ ctxt) Us)),
   448            Pretty.str ("of " ^ s ^ " do not agree with types"),
   449            Pretty.block (Pretty.commas (map (Syntax.pretty_typ ctxt) paramTs)),
   450            Pretty.str "of declared parameters"]));
   451         val Ts = HOLogic.strip_ptupleT fs U;
   452         val c' = Free (s ^ "p",
   453           map fastype_of params1 @ Ts ---> HOLogic.boolT)
   454       in
   455         ((c', (fs, U, Ts)),
   456          (list_comb (c, params2),
   457           HOLogic.Collect_const U $ HOLogic.mk_psplits fs U HOLogic.boolT
   458             (list_comb (c', params1))))
   459       end) |> split_list |>> split_list;
   460     val eqns' = eqns @
   461       map (prop_of #> HOLogic.dest_Trueprop #> HOLogic.dest_eq)
   462         (mem_Collect_eq :: split_conv :: to_pred_simps);
   463 
   464     (* predicate version of the introduction rules *)
   465     val intros' =
   466       map (fn (name_atts, t) => (name_atts,
   467         t |>
   468         map_aterms (fn u =>
   469           (case AList.lookup op = params' u of
   470              SOME (_, (u', _)) => u'
   471            | NONE => u)) |>
   472         Pattern.rewrite_term thy [] [to_pred_proc thy eqns'] |>
   473         eta_contract (member op = cs' orf is_pred pred_arities))) intros;
   474     val cnames_syn' = map (fn (b, _) => (Binding.suffix_name "p" b, NoSyn)) cnames_syn;
   475     val monos' = map (to_pred [] (Context.Proof ctxt)) monos;
   476     val ({preds, intrs, elims, raw_induct, ...}, ctxt1) =
   477       Inductive.add_ind_def
   478         {quiet_mode = quiet_mode, verbose = verbose, kind = kind, alt_name = Binding.empty,
   479           coind = coind, no_elim = no_elim, no_ind = no_ind,
   480           skip_mono = skip_mono, fork_mono = fork_mono}
   481         cs' intros' monos' params1 cnames_syn' ctxt;
   482 
   483     (* define inductive sets using previously defined predicates *)
   484     val (defs, ctxt2) = fold_map (LocalTheory.define Thm.internalK)
   485       (map (fn ((c_syn, (fs, U, _)), p) => (c_syn, (Attrib.empty_binding,
   486          fold_rev lambda params (HOLogic.Collect_const U $
   487            HOLogic.mk_psplits fs U HOLogic.boolT (list_comb (p, params3))))))
   488          (cnames_syn ~~ cs_info ~~ preds)) ctxt1;
   489 
   490     (* prove theorems for converting predicate to set notation *)
   491     val ctxt3 = fold
   492       (fn (((p, c as Free (s, _)), (fs, U, Ts)), (_, (_, def))) => fn ctxt =>
   493         let val conv_thm =
   494           Goal.prove ctxt (map (fst o dest_Free) params) []
   495             (HOLogic.mk_Trueprop (HOLogic.mk_eq
   496               (list_comb (p, params3),
   497                list_abs (map (pair "x") Ts, HOLogic.mk_mem
   498                  (HOLogic.mk_ptuple fs U (map Bound (length fs downto 0)),
   499                   list_comb (c, params))))))
   500             (K (REPEAT (rtac ext 1) THEN simp_tac (HOL_basic_ss addsimps
   501               [def, mem_Collect_eq, split_conv]) 1))
   502         in
   503           ctxt |> LocalTheory.note kind ((Binding.name (s ^ "p_" ^ s ^ "_eq"),
   504             [Attrib.internal (K pred_set_conv_att)]),
   505               [conv_thm]) |> snd
   506         end) (preds ~~ cs ~~ cs_info ~~ defs) ctxt2;
   507 
   508     (* convert theorems to set notation *)
   509     val rec_name =
   510       if Binding.is_empty alt_name then
   511         Binding.name (space_implode "_" (map (Binding.name_of o fst) cnames_syn))
   512       else alt_name;
   513     val cnames = map (LocalTheory.full_name ctxt3 o #1) cnames_syn;  (* FIXME *)
   514     val (intr_names, intr_atts) = split_list (map fst intros);
   515     val raw_induct' = to_set [] (Context.Proof ctxt3) raw_induct;
   516     val (intrs', elims', induct, ctxt4) =
   517       Inductive.declare_rules kind rec_name coind no_ind cnames
   518       (map (to_set [] (Context.Proof ctxt3)) intrs) intr_names intr_atts
   519       (map (fn th => (to_set [] (Context.Proof ctxt3) th,
   520          map fst (fst (RuleCases.get th)))) elims)
   521       raw_induct' ctxt3
   522   in
   523     ({intrs = intrs', elims = elims', induct = induct,
   524       raw_induct = raw_induct', preds = map fst defs},
   525      ctxt4)
   526   end;
   527 
   528 val add_inductive_i = Inductive.gen_add_inductive_i add_ind_set_def;
   529 val add_inductive = Inductive.gen_add_inductive add_ind_set_def;
   530 
   531 val mono_add_att = to_pred_att [] #> Inductive.mono_add;
   532 val mono_del_att = to_pred_att [] #> Inductive.mono_del;
   533 
   534 
   535 (** package setup **)
   536 
   537 (* setup theory *)
   538 
   539 val setup =
   540   Attrib.setup @{binding pred_set_conv} (Scan.succeed pred_set_conv_att)
   541     "declare rules for converting between predicate and set notation" #>
   542   Attrib.setup @{binding to_set} (Attrib.thms >> to_set_att) "convert rule to set notation" #>
   543   Attrib.setup @{binding to_pred} (Attrib.thms >> to_pred_att) "convert rule to predicate notation" #>
   544   Attrib.setup @{binding code_ind_set}
   545     (Scan.lift (Scan.option (Args.$$$ "target" |-- Args.colon |-- Args.name) >> code_ind_att))
   546     "introduction rules for executable predicates" #>
   547   Codegen.add_preprocessor codegen_preproc #>
   548   Attrib.setup @{binding mono_set} (Attrib.add_del mono_add_att mono_del_att)
   549     "declaration of monotonicity rule for set operators" #>
   550   Context.theory_map (Simplifier.map_ss (fn ss => ss addsimprocs [collect_mem_simproc]));
   551 
   552 
   553 (* outer syntax *)
   554 
   555 local structure P = OuterParse and K = OuterKeyword in
   556 
   557 val ind_set_decl = Inductive.gen_ind_decl add_ind_set_def;
   558 
   559 val _ =
   560   OuterSyntax.local_theory' "inductive_set" "define inductive sets" K.thy_decl (ind_set_decl false);
   561 
   562 val _ =
   563   OuterSyntax.local_theory' "coinductive_set" "define coinductive sets" K.thy_decl (ind_set_decl true);
   564 
   565 end;
   566 
   567 end;