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