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