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