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