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