src/HOL/Codatatype/Tools/bnf_wrap.ML
author blanchet
Thu Sep 20 17:35:49 2012 +0200 (2012-09-20)
changeset 49484 0194a18f80cf
parent 49478 416ad6e2343b
child 49486 64cc57c0d0fe
permissions -rw-r--r--
finished "disc_coiter_iff" etc. generation
blanchet@49074
     1
(*  Title:      HOL/Codatatype/Tools/bnf_wrap.ML
blanchet@49017
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@49017
     3
    Copyright   2012
blanchet@49017
     4
blanchet@49074
     5
Wrapping existing datatypes.
blanchet@49017
     6
*)
blanchet@49017
     7
blanchet@49074
     8
signature BNF_WRAP =
blanchet@49017
     9
sig
blanchet@49121
    10
  val mk_half_pairss: 'a list -> ('a * 'a) list list
blanchet@49203
    11
  val mk_ctr: typ list -> term -> term
blanchet@49484
    12
  val mk_disc_or_sel: typ list -> term -> term
blanchet@49437
    13
  val base_name_of_ctr: term -> string
blanchet@49199
    14
  val wrap_datatype: ({prems: thm list, context: Proof.context} -> tactic) list list ->
blanchet@49280
    15
    ((bool * term list) * term) *
blanchet@49280
    16
      (binding list * (binding list list * (binding * term) list list)) -> local_theory ->
blanchet@49484
    17
    (term list * term list list * thm list * thm list * thm list * thm list list * thm list *
blanchet@49484
    18
     thm list list) * local_theory
blanchet@49278
    19
  val parse_wrap_options: bool parser
blanchet@49286
    20
  val parse_bound_term: (binding * string) parser
blanchet@49017
    21
end;
blanchet@49017
    22
blanchet@49074
    23
structure BNF_Wrap : BNF_WRAP =
blanchet@49017
    24
struct
blanchet@49017
    25
blanchet@49017
    26
open BNF_Util
blanchet@49074
    27
open BNF_Wrap_Tactics
blanchet@49017
    28
blanchet@49223
    29
val isN = "is_";
blanchet@49223
    30
val unN = "un_";
blanchet@49223
    31
fun mk_unN 1 1 suf = unN ^ suf
blanchet@49223
    32
  | mk_unN _ l suf = unN ^ suf ^ string_of_int l;
blanchet@49046
    33
blanchet@49054
    34
val case_congN = "case_cong";
blanchet@49116
    35
val case_eqN = "case_eq";
blanchet@49054
    36
val casesN = "cases";
blanchet@49118
    37
val collapseN = "collapse";
blanchet@49122
    38
val disc_excludeN = "disc_exclude";
blanchet@49054
    39
val disc_exhaustN = "disc_exhaust";
blanchet@49054
    40
val discsN = "discs";
blanchet@49054
    41
val distinctN = "distinct";
blanchet@49075
    42
val exhaustN = "exhaust";
blanchet@49075
    43
val injectN = "inject";
blanchet@49075
    44
val nchotomyN = "nchotomy";
blanchet@49054
    45
val selsN = "sels";
blanchet@49054
    46
val splitN = "split";
blanchet@49054
    47
val split_asmN = "split_asm";
blanchet@49054
    48
val weak_case_cong_thmsN = "weak_case_cong";
blanchet@49019
    49
blanchet@49336
    50
val std_binding = @{binding _};
blanchet@49300
    51
blanchet@49300
    52
val induct_simp_attrs = @{attributes [induct_simp]};
blanchet@49300
    53
val cong_attrs = @{attributes [cong]};
blanchet@49300
    54
val iff_attrs = @{attributes [iff]};
blanchet@49300
    55
val safe_elim_attrs = @{attributes [elim!]};
blanchet@49300
    56
val simp_attrs = @{attributes [simp]};
blanchet@49046
    57
blanchet@49056
    58
fun pad_list x n xs = xs @ replicate (n - length xs) x;
blanchet@49056
    59
blanchet@49259
    60
fun unflat_lookup eq ys zs = map (map (fn x => nth zs (find_index (curry eq x) ys)));
blanchet@49258
    61
blanchet@49048
    62
fun mk_half_pairss' _ [] = []
blanchet@49056
    63
  | mk_half_pairss' indent (y :: ys) =
blanchet@49056
    64
    indent @ fold_rev (cons o single o pair y) ys (mk_half_pairss' ([] :: indent) ys);
blanchet@49027
    65
blanchet@49048
    66
fun mk_half_pairss ys = mk_half_pairss' [[]] ys;
blanchet@49027
    67
blanchet@49280
    68
fun mk_undefined T = Const (@{const_name undefined}, T);
blanchet@49055
    69
blanchet@49203
    70
fun mk_ctr Ts ctr =
blanchet@49203
    71
  let val Type (_, Ts0) = body_type (fastype_of ctr) in
blanchet@49203
    72
    Term.subst_atomic_types (Ts0 ~~ Ts) ctr
blanchet@49203
    73
  end;
blanchet@49203
    74
blanchet@49484
    75
fun mk_disc_or_sel Ts t =
blanchet@49484
    76
  Term.subst_atomic_types (snd (Term.dest_Type (domain_type (fastype_of t))) ~~ Ts) t;
blanchet@49484
    77
blanchet@49300
    78
fun base_name_of_ctr c =
blanchet@49300
    79
  Long_Name.base_name (case head_of c of
blanchet@49300
    80
      Const (s, _) => s
blanchet@49300
    81
    | Free (s, _) => s
blanchet@49300
    82
    | _ => error "Cannot extract name of constructor");
blanchet@49046
    83
blanchet@49437
    84
fun eta_expand_arg xs f_xs = fold_rev Term.lambda xs f_xs;
blanchet@49437
    85
blanchet@49278
    86
fun prepare_wrap_datatype prep_term (((no_dests, raw_ctrs), raw_case),
blanchet@49336
    87
    (raw_disc_bindings, (raw_sel_bindingss, raw_sel_defaultss))) no_defs_lthy =
blanchet@49017
    88
  let
blanchet@49019
    89
    (* TODO: sanity checks on arguments *)
blanchet@49113
    90
    (* TODO: case syntax *)
blanchet@49025
    91
blanchet@49280
    92
    val n = length raw_ctrs;
blanchet@49054
    93
    val ks = 1 upto n;
blanchet@49054
    94
blanchet@49121
    95
    val _ = if n > 0 then () else error "No constructors specified";
blanchet@49121
    96
blanchet@49280
    97
    val ctrs0 = map (prep_term no_defs_lthy) raw_ctrs;
blanchet@49280
    98
    val case0 = prep_term no_defs_lthy raw_case;
blanchet@49280
    99
    val sel_defaultss =
blanchet@49280
   100
      pad_list [] n (map (map (apsnd (prep_term no_defs_lthy))) raw_sel_defaultss);
blanchet@49280
   101
blanchet@49300
   102
    val Type (dataT_name, As0) = body_type (fastype_of (hd ctrs0));
blanchet@49302
   103
    val data_b = Binding.qualified_name dataT_name;
blanchet@49055
   104
blanchet@49055
   105
    val (As, B) =
blanchet@49055
   106
      no_defs_lthy
blanchet@49298
   107
      |> mk_TFrees' (map Type.sort_of_atyp As0)
blanchet@49055
   108
      ||> the_single o fst o mk_TFrees 1;
blanchet@49055
   109
blanchet@49300
   110
    val dataT = Type (dataT_name, As);
blanchet@49055
   111
    val ctrs = map (mk_ctr As) ctrs0;
blanchet@49055
   112
    val ctr_Tss = map (binder_types o fastype_of) ctrs;
blanchet@49055
   113
blanchet@49055
   114
    val ms = map length ctr_Tss;
blanchet@49055
   115
traytel@49434
   116
    val raw_disc_bindings' = pad_list Binding.empty n raw_disc_bindings;
blanchet@49120
   117
blanchet@49174
   118
    fun can_really_rely_on_disc k =
traytel@49434
   119
      not (Binding.eq_name (nth raw_disc_bindings' (k - 1), Binding.empty)) orelse
traytel@49434
   120
      nth ms (k - 1) = 0;
blanchet@49174
   121
    fun can_rely_on_disc k =
blanchet@49174
   122
      can_really_rely_on_disc k orelse (k = 1 andalso not (can_really_rely_on_disc 2));
blanchet@49336
   123
    fun can_omit_disc_binding k m =
blanchet@49174
   124
      n = 1 orelse m = 0 orelse (n = 2 andalso can_rely_on_disc (3 - k));
blanchet@49120
   125
blanchet@49336
   126
    val std_disc_binding =
blanchet@49302
   127
      Binding.qualify false (Binding.name_of data_b) o Binding.name o prefix isN o base_name_of_ctr;
blanchet@49120
   128
blanchet@49336
   129
    val disc_bindings =
blanchet@49336
   130
      raw_disc_bindings'
blanchet@49120
   131
      |> map4 (fn k => fn m => fn ctr => fn disc =>
blanchet@49302
   132
        Option.map (Binding.qualify false (Binding.name_of data_b))
traytel@49434
   133
          (if Binding.eq_name (disc, Binding.empty) then
blanchet@49336
   134
             if can_omit_disc_binding k m then NONE else SOME (std_disc_binding ctr)
blanchet@49336
   135
           else if Binding.eq_name (disc, std_binding) then
blanchet@49336
   136
             SOME (std_disc_binding ctr)
blanchet@49302
   137
           else
blanchet@49302
   138
             SOME disc)) ks ms ctrs0;
blanchet@49056
   139
blanchet@49336
   140
    val no_discs = map is_none disc_bindings;
blanchet@49137
   141
    val no_discs_at_all = forall I no_discs;
blanchet@49116
   142
blanchet@49336
   143
    fun std_sel_binding m l = Binding.name o mk_unN m l o base_name_of_ctr;
blanchet@49120
   144
blanchet@49336
   145
    val sel_bindingss =
blanchet@49336
   146
      pad_list [] n raw_sel_bindingss
blanchet@49056
   147
      |> map3 (fn ctr => fn m => map2 (fn l => fn sel =>
blanchet@49302
   148
        Binding.qualify false (Binding.name_of data_b)
traytel@49434
   149
          (if Binding.eq_name (sel, Binding.empty) orelse Binding.eq_name (sel, std_binding) then
blanchet@49336
   150
            std_sel_binding m l ctr
blanchet@49302
   151
          else
traytel@49434
   152
            sel)) (1 upto m) o pad_list Binding.empty m) ctrs0 ms;
blanchet@49020
   153
blanchet@49130
   154
    fun mk_case Ts T =
blanchet@49121
   155
      let
blanchet@49336
   156
        val (bindings, body) = strip_type (fastype_of case0)
blanchet@49336
   157
        val Type (_, Ts0) = List.last bindings
blanchet@49130
   158
      in Term.subst_atomic_types ((body, T) :: (Ts0 ~~ Ts)) case0 end;
blanchet@49022
   159
blanchet@49201
   160
    val casex = mk_case As B;
blanchet@49201
   161
    val case_Ts = map (fn Ts => Ts ---> B) ctr_Tss;
blanchet@49043
   162
blanchet@49364
   163
    val ((((((((xss, xss'), yss), fs), gs), (v, v')), w), (p, p')), names_lthy) = no_defs_lthy |>
blanchet@49364
   164
      mk_Freess' "x" ctr_Tss
blanchet@49025
   165
      ||>> mk_Freess "y" ctr_Tss
blanchet@49201
   166
      ||>> mk_Frees "f" case_Ts
blanchet@49201
   167
      ||>> mk_Frees "g" case_Ts
blanchet@49300
   168
      ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "v") dataT
blanchet@49300
   169
      ||>> yield_singleton (mk_Frees "w") dataT
blanchet@49043
   170
      ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "P") HOLogic.boolT;
blanchet@49043
   171
blanchet@49463
   172
    val q = Free (fst p', mk_pred1T B);
blanchet@49020
   173
blanchet@49210
   174
    fun ap_v t = t $ v;
blanchet@49137
   175
    fun mk_v_eq_v () = HOLogic.mk_eq (v, v);
blanchet@49137
   176
blanchet@49025
   177
    val xctrs = map2 (curry Term.list_comb) ctrs xss;
blanchet@49025
   178
    val yctrs = map2 (curry Term.list_comb) ctrs yss;
blanchet@49032
   179
blanchet@49043
   180
    val xfs = map2 (curry Term.list_comb) fs xss;
blanchet@49043
   181
    val xgs = map2 (curry Term.list_comb) gs xss;
blanchet@49043
   182
blanchet@49437
   183
    val eta_fs = map2 eta_expand_arg xss xfs;
blanchet@49437
   184
    val eta_gs = map2 eta_expand_arg xss xgs;
blanchet@49043
   185
blanchet@49201
   186
    val fcase = Term.list_comb (casex, eta_fs);
blanchet@49201
   187
    val gcase = Term.list_comb (casex, eta_gs);
blanchet@49020
   188
blanchet@49025
   189
    val exist_xs_v_eq_ctrs =
blanchet@49025
   190
      map2 (fn xctr => fn xs => list_exists_free xs (HOLogic.mk_eq (v, xctr))) xctrs xss;
blanchet@49022
   191
blanchet@49278
   192
    val unique_disc_no_def = TrueI; (*arbitrary marker*)
blanchet@49278
   193
    val alternate_disc_no_def = FalseE; (*arbitrary marker*)
blanchet@49116
   194
blanchet@49278
   195
    fun alternate_disc_lhs get_disc k =
blanchet@49116
   196
      HOLogic.mk_not
blanchet@49336
   197
        (case nth disc_bindings (k - 1) of
blanchet@49152
   198
          NONE => nth exist_xs_v_eq_ctrs (k - 1)
blanchet@49278
   199
        | SOME b => get_disc b (k - 1) $ v);
blanchet@49116
   200
blanchet@49285
   201
    val (all_sels_distinct, discs, selss, disc_defs, sel_defs, sel_defss, lthy') =
blanchet@49278
   202
      if no_dests then
blanchet@49285
   203
        (true, [], [], [], [], [], no_defs_lthy)
blanchet@49278
   204
      else
blanchet@49278
   205
        let
blanchet@49463
   206
          fun disc_free b = Free (Binding.name_of b, mk_pred1T dataT);
blanchet@49025
   207
blanchet@49278
   208
          fun disc_spec b exist_xs_v_eq_ctr = mk_Trueprop_eq (disc_free b $ v, exist_xs_v_eq_ctr);
blanchet@49278
   209
blanchet@49278
   210
          fun alternate_disc k = Term.lambda v (alternate_disc_lhs (K o disc_free) (3 - k));
blanchet@49278
   211
blanchet@49364
   212
          fun mk_default T t =
blanchet@49364
   213
            let
blanchet@49364
   214
              val Ts0 = map TFree (Term.add_tfreesT (fastype_of t) []);
blanchet@49364
   215
              val Ts = map TFree (Term.add_tfreesT T []);
blanchet@49364
   216
            in Term.subst_atomic_types (Ts0 ~~ Ts) t end;
blanchet@49364
   217
blanchet@49280
   218
          fun mk_sel_case_args b proto_sels T =
blanchet@49280
   219
            map2 (fn Ts => fn k =>
blanchet@49280
   220
              (case AList.lookup (op =) proto_sels k of
blanchet@49280
   221
                NONE =>
blanchet@49364
   222
                (case AList.lookup Binding.eq_name (rev (nth sel_defaultss (k - 1))) b of
blanchet@49364
   223
                  NONE => fold_rev (Term.lambda o curry Free Name.uu) Ts (mk_undefined T)
blanchet@49364
   224
                | SOME t => mk_default (Ts ---> T) t)
blanchet@49280
   225
              | SOME (xs, x) => fold_rev Term.lambda xs x)) ctr_Tss ks;
blanchet@49258
   226
blanchet@49278
   227
          fun sel_spec b proto_sels =
blanchet@49278
   228
            let
blanchet@49278
   229
              val _ =
blanchet@49278
   230
                (case duplicates (op =) (map fst proto_sels) of
blanchet@49278
   231
                   k :: _ => error ("Duplicate selector name " ^ quote (Binding.name_of b) ^
blanchet@49278
   232
                     " for constructor " ^
blanchet@49278
   233
                     quote (Syntax.string_of_term no_defs_lthy (nth ctrs (k - 1))))
blanchet@49278
   234
                 | [] => ())
blanchet@49278
   235
              val T =
blanchet@49278
   236
                (case distinct (op =) (map (fastype_of o snd o snd) proto_sels) of
blanchet@49278
   237
                  [T] => T
blanchet@49278
   238
                | T :: T' :: _ => error ("Inconsistent range type for selector " ^
blanchet@49278
   239
                    quote (Binding.name_of b) ^ ": " ^ quote (Syntax.string_of_typ no_defs_lthy T) ^
blanchet@49278
   240
                    " vs. " ^ quote (Syntax.string_of_typ no_defs_lthy T')));
blanchet@49278
   241
            in
blanchet@49300
   242
              mk_Trueprop_eq (Free (Binding.name_of b, dataT --> T) $ v,
blanchet@49280
   243
                Term.list_comb (mk_case As T, mk_sel_case_args b proto_sels T) $ v)
blanchet@49278
   244
            end;
blanchet@49116
   245
blanchet@49336
   246
          val sel_bindings = flat sel_bindingss;
blanchet@49336
   247
          val uniq_sel_bindings = distinct Binding.eq_name sel_bindings;
blanchet@49336
   248
          val all_sels_distinct = (length uniq_sel_bindings = length sel_bindings);
blanchet@49285
   249
blanchet@49336
   250
          val sel_binding_index =
blanchet@49336
   251
            if all_sels_distinct then 1 upto length sel_bindings
blanchet@49336
   252
            else map (fn b => find_index (curry Binding.eq_name b) uniq_sel_bindings) sel_bindings;
blanchet@49285
   253
blanchet@49285
   254
          val proto_sels = flat (map3 (fn k => fn xs => map (fn x => (k, (xs, x)))) ks xss xss);
blanchet@49300
   255
          val sel_infos =
blanchet@49336
   256
            AList.group (op =) (sel_binding_index ~~ proto_sels)
blanchet@49285
   257
            |> sort (int_ord o pairself fst)
blanchet@49336
   258
            |> map snd |> curry (op ~~) uniq_sel_bindings;
blanchet@49336
   259
          val sel_bindings = map fst sel_infos;
blanchet@49258
   260
blanchet@49336
   261
          fun unflat_selss xs = unflat_lookup Binding.eq_name sel_bindings xs sel_bindingss;
blanchet@49258
   262
blanchet@49278
   263
          val (((raw_discs, raw_disc_defs), (raw_sels, raw_sel_defs)), (lthy', lthy)) =
blanchet@49278
   264
            no_defs_lthy
blanchet@49278
   265
            |> apfst split_list o fold_map4 (fn k => fn m => fn exist_xs_v_eq_ctr =>
blanchet@49278
   266
              fn NONE =>
blanchet@49278
   267
                 if n = 1 then pair (Term.lambda v (mk_v_eq_v ()), unique_disc_no_def)
blanchet@49278
   268
                 else if m = 0 then pair (Term.lambda v exist_xs_v_eq_ctr, refl)
blanchet@49278
   269
                 else pair (alternate_disc k, alternate_disc_no_def)
blanchet@49278
   270
               | SOME b => Specification.definition (SOME (b, NONE, NoSyn),
blanchet@49278
   271
                   ((Thm.def_binding b, []), disc_spec b exist_xs_v_eq_ctr)) #>> apsnd snd)
blanchet@49336
   272
              ks ms exist_xs_v_eq_ctrs disc_bindings
blanchet@49278
   273
            ||>> apfst split_list o fold_map (fn (b, proto_sels) =>
blanchet@49278
   274
              Specification.definition (SOME (b, NONE, NoSyn),
blanchet@49300
   275
                ((Thm.def_binding b, []), sel_spec b proto_sels)) #>> apsnd snd) sel_infos
blanchet@49278
   276
            ||> `Local_Theory.restore;
blanchet@49022
   277
blanchet@49278
   278
          val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49025
   279
blanchet@49278
   280
          val disc_defs = map (Morphism.thm phi) raw_disc_defs;
blanchet@49281
   281
          val sel_defs = map (Morphism.thm phi) raw_sel_defs;
blanchet@49281
   282
          val sel_defss = unflat_selss sel_defs;
blanchet@49278
   283
blanchet@49278
   284
          val discs0 = map (Morphism.term phi) raw_discs;
blanchet@49278
   285
          val selss0 = unflat_selss (map (Morphism.term phi) raw_sels);
blanchet@49028
   286
blanchet@49278
   287
          val discs = map (mk_disc_or_sel As) discs0;
blanchet@49278
   288
          val selss = map (map (mk_disc_or_sel As)) selss0;
blanchet@49278
   289
        in
blanchet@49285
   290
          (all_sels_distinct, discs, selss, disc_defs, sel_defs, sel_defss, lthy')
blanchet@49278
   291
        end;
blanchet@49025
   292
blanchet@49032
   293
    fun mk_imp_p Qs = Logic.list_implies (Qs, HOLogic.mk_Trueprop p);
blanchet@49029
   294
blanchet@49458
   295
    val exhaust_goal =
blanchet@49032
   296
      let fun mk_prem xctr xs = fold_rev Logic.all xs (mk_imp_p [mk_Trueprop_eq (v, xctr)]) in
blanchet@49121
   297
        fold_rev Logic.all [p, v] (mk_imp_p (map2 mk_prem xctrs xss))
blanchet@49020
   298
      end;
blanchet@49019
   299
blanchet@49484
   300
    val inject_goalss =
blanchet@49017
   301
      let
blanchet@49034
   302
        fun mk_goal _ _ [] [] = []
blanchet@49025
   303
          | mk_goal xctr yctr xs ys =
blanchet@49121
   304
            [fold_rev Logic.all (xs @ ys) (mk_Trueprop_eq (HOLogic.mk_eq (xctr, yctr),
blanchet@49121
   305
              Library.foldr1 HOLogic.mk_conj (map2 (curry HOLogic.mk_eq) xs ys)))];
blanchet@49017
   306
      in
blanchet@49034
   307
        map4 mk_goal xctrs yctrs xss yss
blanchet@49017
   308
      end;
blanchet@49017
   309
blanchet@49484
   310
    val half_distinct_goalss =
blanchet@49121
   311
      let
blanchet@49203
   312
        fun mk_goal ((xs, xc), (xs', xc')) =
blanchet@49121
   313
          fold_rev Logic.all (xs @ xs')
blanchet@49203
   314
            (HOLogic.mk_Trueprop (HOLogic.mk_not (HOLogic.mk_eq (xc, xc'))));
blanchet@49121
   315
      in
blanchet@49121
   316
        map (map mk_goal) (mk_half_pairss (xss ~~ xctrs))
blanchet@49121
   317
      end;
blanchet@49019
   318
blanchet@49458
   319
    val cases_goal =
blanchet@49121
   320
      map3 (fn xs => fn xctr => fn xf =>
blanchet@49201
   321
        fold_rev Logic.all (fs @ xs) (mk_Trueprop_eq (fcase $ xctr, xf))) xss xctrs xfs;
blanchet@49025
   322
blanchet@49484
   323
    val goalss = [exhaust_goal] :: inject_goalss @ half_distinct_goalss @ [cases_goal];
blanchet@49019
   324
blanchet@49019
   325
    fun after_qed thmss lthy =
blanchet@49019
   326
      let
blanchet@49048
   327
        val ([exhaust_thm], (inject_thmss, (half_distinct_thmss, [case_thms]))) =
blanchet@49048
   328
          (hd thmss, apsnd (chop (n * n)) (chop n (tl thmss)));
blanchet@49019
   329
blanchet@49438
   330
        val inject_thms = flat inject_thmss;
blanchet@49438
   331
blanchet@49032
   332
        val exhaust_thm' =
blanchet@49032
   333
          let val Tinst = map (pairself (certifyT lthy)) (map Logic.varifyT_global As ~~ As) in
blanchet@49032
   334
            Drule.instantiate' [] [SOME (certify lthy v)]
blanchet@49032
   335
              (Thm.instantiate (Tinst, []) (Drule.zero_var_indexes exhaust_thm))
blanchet@49032
   336
          end;
blanchet@49032
   337
blanchet@49300
   338
        val exhaust_cases = map base_name_of_ctr ctrs;
blanchet@49300
   339
blanchet@49048
   340
        val other_half_distinct_thmss = map (map (fn thm => thm RS not_sym)) half_distinct_thmss;
blanchet@49048
   341
blanchet@49052
   342
        val (distinct_thmsss', distinct_thmsss) =
blanchet@49048
   343
          map2 (map2 append) (Library.chop_groups n half_distinct_thmss)
blanchet@49052
   344
            (transpose (Library.chop_groups n other_half_distinct_thmss))
blanchet@49052
   345
          |> `transpose;
blanchet@49048
   346
        val distinct_thms = interleave (flat half_distinct_thmss) (flat other_half_distinct_thmss);
blanchet@49019
   347
blanchet@49020
   348
        val nchotomy_thm =
blanchet@49020
   349
          let
blanchet@49020
   350
            val goal =
blanchet@49022
   351
              HOLogic.mk_Trueprop (HOLogic.mk_all (fst v', snd v',
blanchet@49029
   352
                Library.foldr1 HOLogic.mk_disj exist_xs_v_eq_ctrs));
blanchet@49020
   353
          in
blanchet@49020
   354
            Skip_Proof.prove lthy [] [] goal (fn _ => mk_nchotomy_tac n exhaust_thm)
blanchet@49020
   355
          end;
blanchet@49020
   356
blanchet@49484
   357
        val (all_sel_thms, sel_thmss, disc_thmss, disc_thms, discI_thms, disc_exclude_thms,
blanchet@49484
   358
             disc_exhaust_thms, collapse_thms, case_eq_thms) =
blanchet@49278
   359
          if no_dests then
blanchet@49484
   360
            ([], [], [], [], [], [], [], [], [])
blanchet@49116
   361
          else
blanchet@49116
   362
            let
blanchet@49364
   363
              fun make_sel_thm xs' case_thm sel_def =
blanchet@49364
   364
                zero_var_indexes (Drule.gen_all (Drule.rename_bvars' (map (SOME o fst) xs')
blanchet@49364
   365
                    (Drule.forall_intr_vars (case_thm RS (sel_def RS trans)))));
blanchet@49281
   366
blanchet@49281
   367
              fun has_undefined_rhs thm =
blanchet@49281
   368
                (case snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of thm))) of
blanchet@49281
   369
                  Const (@{const_name undefined}, _) => true
blanchet@49281
   370
                | _ => false);
blanchet@49281
   371
blanchet@49364
   372
              val sel_thmss = map3 (map oo make_sel_thm) xss' case_thms sel_defss;
blanchet@49281
   373
blanchet@49281
   374
              val all_sel_thms =
blanchet@49285
   375
                (if all_sels_distinct andalso forall null sel_defaultss then
blanchet@49285
   376
                   flat sel_thmss
blanchet@49285
   377
                 else
blanchet@49364
   378
                   map_product (fn s => fn (xs', c) => make_sel_thm xs' c s) sel_defs
blanchet@49364
   379
                     (xss' ~~ case_thms))
blanchet@49285
   380
                |> filter_out has_undefined_rhs;
blanchet@49278
   381
blanchet@49278
   382
              fun mk_unique_disc_def () =
blanchet@49278
   383
                let
blanchet@49278
   384
                  val m = the_single ms;
blanchet@49278
   385
                  val goal = mk_Trueprop_eq (mk_v_eq_v (), the_single exist_xs_v_eq_ctrs);
blanchet@49278
   386
                in
blanchet@49278
   387
                  Skip_Proof.prove lthy [] [] goal (fn _ => mk_unique_disc_def_tac m exhaust_thm')
blanchet@49278
   388
                  |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49278
   389
                  |> Thm.close_derivation
blanchet@49278
   390
                end;
blanchet@49278
   391
blanchet@49278
   392
              fun mk_alternate_disc_def k =
blanchet@49278
   393
                let
blanchet@49278
   394
                  val goal =
blanchet@49278
   395
                    mk_Trueprop_eq (alternate_disc_lhs (K (nth discs)) (3 - k),
blanchet@49278
   396
                      nth exist_xs_v_eq_ctrs (k - 1));
blanchet@49278
   397
                in
blanchet@49278
   398
                  Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@49278
   399
                    mk_alternate_disc_def_tac ctxt k (nth disc_defs (2 - k))
blanchet@49278
   400
                      (nth distinct_thms (2 - k)) exhaust_thm')
blanchet@49278
   401
                  |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49278
   402
                  |> Thm.close_derivation
blanchet@49278
   403
                end;
blanchet@49028
   404
blanchet@49278
   405
              val has_alternate_disc_def =
blanchet@49278
   406
                exists (fn def => Thm.eq_thm_prop (def, alternate_disc_no_def)) disc_defs;
blanchet@49278
   407
blanchet@49278
   408
              val disc_defs' =
blanchet@49278
   409
                map2 (fn k => fn def =>
blanchet@49278
   410
                  if Thm.eq_thm_prop (def, unique_disc_no_def) then mk_unique_disc_def ()
blanchet@49278
   411
                  else if Thm.eq_thm_prop (def, alternate_disc_no_def) then mk_alternate_disc_def k
blanchet@49278
   412
                  else def) ks disc_defs;
blanchet@49278
   413
blanchet@49278
   414
              val discD_thms = map (fn def => def RS iffD1) disc_defs';
blanchet@49278
   415
              val discI_thms =
blanchet@49278
   416
                map2 (fn m => fn def => funpow m (fn thm => exI RS thm) (def RS iffD2)) ms
blanchet@49278
   417
                  disc_defs';
blanchet@49278
   418
              val not_discI_thms =
blanchet@49278
   419
                map2 (fn m => fn def => funpow m (fn thm => allI RS thm)
blanchet@49463
   420
                    (unfold_defs lthy @{thms not_ex} (def RS @{thm ssubst[of _ _ Not]})))
blanchet@49278
   421
                  ms disc_defs';
blanchet@49278
   422
blanchet@49278
   423
              val (disc_thmss', disc_thmss) =
blanchet@49278
   424
                let
blanchet@49278
   425
                  fun mk_thm discI _ [] = refl RS discI
blanchet@49278
   426
                    | mk_thm _ not_discI [distinct] = distinct RS not_discI;
blanchet@49278
   427
                  fun mk_thms discI not_discI distinctss = map (mk_thm discI not_discI) distinctss;
blanchet@49278
   428
                in
blanchet@49278
   429
                  map3 mk_thms discI_thms not_discI_thms distinct_thmsss' |> `transpose
blanchet@49278
   430
                end;
blanchet@49278
   431
blanchet@49278
   432
              val disc_thms = flat (map2 (fn true => K [] | false => I) no_discs disc_thmss);
blanchet@49028
   433
blanchet@49278
   434
              val disc_exclude_thms =
blanchet@49278
   435
                if has_alternate_disc_def then
blanchet@49278
   436
                  []
blanchet@49278
   437
                else
blanchet@49278
   438
                  let
blanchet@49278
   439
                    fun mk_goal [] = []
blanchet@49278
   440
                      | mk_goal [((_, true), (_, true))] = []
blanchet@49278
   441
                      | mk_goal [(((_, disc), _), ((_, disc'), _))] =
blanchet@49278
   442
                        [Logic.all v (Logic.mk_implies (HOLogic.mk_Trueprop (betapply (disc, v)),
blanchet@49278
   443
                           HOLogic.mk_Trueprop (HOLogic.mk_not (betapply (disc', v)))))];
blanchet@49278
   444
                    fun prove tac goal = Skip_Proof.prove lthy [] [] goal (K tac);
blanchet@49278
   445
blanchet@49300
   446
                    val infos = ms ~~ discD_thms ~~ discs ~~ no_discs;
blanchet@49300
   447
                    val half_pairss = mk_half_pairss infos;
blanchet@49278
   448
blanchet@49484
   449
                    val half_goalss = map mk_goal half_pairss;
blanchet@49278
   450
                    val half_thmss =
blanchet@49278
   451
                      map3 (fn [] => K (K []) | [goal] => fn [((((m, discD), _), _), _)] =>
blanchet@49278
   452
                          fn disc_thm => [prove (mk_half_disc_exclude_tac m discD disc_thm) goal])
blanchet@49484
   453
                        half_goalss half_pairss (flat disc_thmss');
blanchet@49278
   454
blanchet@49484
   455
                    val other_half_goalss = map (mk_goal o map swap) half_pairss;
blanchet@49278
   456
                    val other_half_thmss =
blanchet@49278
   457
                      map2 (map2 (prove o mk_other_half_disc_exclude_tac)) half_thmss
blanchet@49484
   458
                        other_half_goalss;
blanchet@49278
   459
                  in
blanchet@49278
   460
                    interleave (flat half_thmss) (flat other_half_thmss)
blanchet@49278
   461
                  end;
blanchet@49028
   462
blanchet@49278
   463
              val disc_exhaust_thms =
blanchet@49278
   464
                if has_alternate_disc_def orelse no_discs_at_all then
blanchet@49278
   465
                  []
blanchet@49278
   466
                else
blanchet@49278
   467
                  let
blanchet@49278
   468
                    fun mk_prem disc = mk_imp_p [HOLogic.mk_Trueprop (betapply (disc, v))];
blanchet@49278
   469
                    val goal = fold_rev Logic.all [p, v] (mk_imp_p (map mk_prem discs));
blanchet@49278
   470
                  in
blanchet@49278
   471
                    [Skip_Proof.prove lthy [] [] goal (fn _ =>
blanchet@49278
   472
                       mk_disc_exhaust_tac n exhaust_thm discI_thms)]
blanchet@49278
   473
                  end;
blanchet@49025
   474
blanchet@49278
   475
              val collapse_thms =
blanchet@49278
   476
                if no_dests then
blanchet@49278
   477
                  []
blanchet@49278
   478
                else
blanchet@49278
   479
                  let
blanchet@49278
   480
                    fun mk_goal ctr disc sels =
blanchet@49278
   481
                      let
blanchet@49278
   482
                        val prem = HOLogic.mk_Trueprop (betapply (disc, v));
blanchet@49278
   483
                        val concl =
blanchet@49278
   484
                          mk_Trueprop_eq ((null sels ? swap)
blanchet@49278
   485
                            (Term.list_comb (ctr, map ap_v sels), v));
blanchet@49278
   486
                      in
blanchet@49278
   487
                        if prem aconv concl then NONE
blanchet@49278
   488
                        else SOME (Logic.all v (Logic.mk_implies (prem, concl)))
blanchet@49278
   489
                      end;
blanchet@49278
   490
                    val goals = map3 mk_goal ctrs discs selss;
blanchet@49278
   491
                  in
blanchet@49278
   492
                    map4 (fn m => fn discD => fn sel_thms => Option.map (fn goal =>
blanchet@49278
   493
                      Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@49278
   494
                        mk_collapse_tac ctxt m discD sel_thms)
blanchet@49278
   495
                      |> perhaps (try (fn thm => refl RS thm)))) ms discD_thms sel_thmss goals
blanchet@49278
   496
                    |> map_filter I
blanchet@49278
   497
                  end;
blanchet@49278
   498
blanchet@49278
   499
              val case_eq_thms =
blanchet@49278
   500
                if no_dests then
blanchet@49278
   501
                  []
blanchet@49278
   502
                else
blanchet@49278
   503
                  let
blanchet@49278
   504
                    fun mk_body f sels = Term.list_comb (f, map ap_v sels);
blanchet@49278
   505
                    val goal =
blanchet@49278
   506
                      mk_Trueprop_eq (fcase $ v, mk_IfN B (map ap_v discs) (map2 mk_body fs selss));
blanchet@49278
   507
                  in
blanchet@49278
   508
                    [Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@49278
   509
                      mk_case_eq_tac ctxt n exhaust_thm' case_thms disc_thmss' sel_thmss)]
blanchet@49278
   510
                    |> Proof_Context.export names_lthy lthy
blanchet@49278
   511
                  end;
blanchet@49116
   512
            in
blanchet@49484
   513
              (all_sel_thms, sel_thmss, disc_thmss, disc_thms, discI_thms, disc_exclude_thms,
blanchet@49484
   514
               disc_exhaust_thms, collapse_thms, case_eq_thms)
blanchet@49116
   515
            end;
blanchet@49025
   516
blanchet@49033
   517
        val (case_cong_thm, weak_case_cong_thm) =
blanchet@49032
   518
          let
blanchet@49032
   519
            fun mk_prem xctr xs f g =
blanchet@49045
   520
              fold_rev Logic.all xs (Logic.mk_implies (mk_Trueprop_eq (w, xctr),
blanchet@49032
   521
                mk_Trueprop_eq (f, g)));
blanchet@49033
   522
blanchet@49033
   523
            val v_eq_w = mk_Trueprop_eq (v, w);
blanchet@49032
   524
blanchet@49032
   525
            val goal =
blanchet@49033
   526
              Logic.list_implies (v_eq_w :: map4 mk_prem xctrs xss fs gs,
blanchet@49201
   527
                 mk_Trueprop_eq (fcase $ v, gcase $ w));
blanchet@49458
   528
            val weak_goal = Logic.mk_implies (v_eq_w, mk_Trueprop_eq (fcase $ v, fcase $ w));
blanchet@49032
   529
          in
blanchet@49049
   530
            (Skip_Proof.prove lthy [] [] goal (fn _ => mk_case_cong_tac exhaust_thm' case_thms),
blanchet@49458
   531
             Skip_Proof.prove lthy [] [] weak_goal (K (etac arg_cong 1)))
blanchet@49033
   532
            |> pairself (singleton (Proof_Context.export names_lthy lthy))
blanchet@49032
   533
          end;
blanchet@49025
   534
blanchet@49044
   535
        val (split_thm, split_asm_thm) =
blanchet@49043
   536
          let
blanchet@49044
   537
            fun mk_conjunct xctr xs f_xs =
blanchet@49043
   538
              list_all_free xs (HOLogic.mk_imp (HOLogic.mk_eq (v, xctr), q $ f_xs));
blanchet@49044
   539
            fun mk_disjunct xctr xs f_xs =
blanchet@49044
   540
              list_exists_free xs (HOLogic.mk_conj (HOLogic.mk_eq (v, xctr),
blanchet@49044
   541
                HOLogic.mk_not (q $ f_xs)));
blanchet@49044
   542
blanchet@49201
   543
            val lhs = q $ (fcase $ v);
blanchet@49044
   544
blanchet@49043
   545
            val goal =
blanchet@49044
   546
              mk_Trueprop_eq (lhs, Library.foldr1 HOLogic.mk_conj (map3 mk_conjunct xctrs xss xfs));
blanchet@49458
   547
            val asm_goal =
blanchet@49044
   548
              mk_Trueprop_eq (lhs, HOLogic.mk_not (Library.foldr1 HOLogic.mk_disj
blanchet@49044
   549
                (map3 mk_disjunct xctrs xss xfs)));
blanchet@49044
   550
blanchet@49044
   551
            val split_thm =
blanchet@49049
   552
              Skip_Proof.prove lthy [] [] goal
blanchet@49052
   553
                (fn _ => mk_split_tac exhaust_thm' case_thms inject_thmss distinct_thmsss)
blanchet@49044
   554
              |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49044
   555
            val split_asm_thm =
blanchet@49458
   556
              Skip_Proof.prove lthy [] [] asm_goal (fn {context = ctxt, ...} =>
blanchet@49044
   557
                mk_split_asm_tac ctxt split_thm)
blanchet@49044
   558
              |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49043
   559
          in
blanchet@49044
   560
            (split_thm, split_asm_thm)
blanchet@49043
   561
          end;
blanchet@49025
   562
blanchet@49437
   563
        val exhaust_case_names_attr = Attrib.internal (K (Rule_Cases.case_names exhaust_cases));
blanchet@49300
   564
        val cases_type_attr = Attrib.internal (K (Induct.cases_type dataT_name));
blanchet@49300
   565
blanchet@49052
   566
        val notes =
blanchet@49300
   567
          [(case_congN, [case_cong_thm], []),
blanchet@49300
   568
           (case_eqN, case_eq_thms, []),
blanchet@49300
   569
           (casesN, case_thms, simp_attrs),
blanchet@49300
   570
           (collapseN, collapse_thms, simp_attrs),
blanchet@49300
   571
           (discsN, disc_thms, simp_attrs),
blanchet@49300
   572
           (disc_excludeN, disc_exclude_thms, []),
blanchet@49300
   573
           (disc_exhaustN, disc_exhaust_thms, [exhaust_case_names_attr]),
blanchet@49300
   574
           (distinctN, distinct_thms, simp_attrs @ induct_simp_attrs),
blanchet@49300
   575
           (exhaustN, [exhaust_thm], [exhaust_case_names_attr, cases_type_attr]),
blanchet@49438
   576
           (injectN, inject_thms, iff_attrs @ induct_simp_attrs),
blanchet@49300
   577
           (nchotomyN, [nchotomy_thm], []),
blanchet@49300
   578
           (selsN, all_sel_thms, simp_attrs),
blanchet@49300
   579
           (splitN, [split_thm], []),
blanchet@49300
   580
           (split_asmN, [split_asm_thm], []),
blanchet@49300
   581
           (weak_case_cong_thmsN, [weak_case_cong_thm], cong_attrs)]
blanchet@49300
   582
          |> filter_out (null o #2)
blanchet@49300
   583
          |> map (fn (thmN, thms, attrs) =>
blanchet@49302
   584
            ((Binding.qualify true (Binding.name_of data_b) (Binding.name thmN), attrs),
blanchet@49302
   585
             [(thms, [])]));
blanchet@49300
   586
blanchet@49300
   587
        val notes' =
blanchet@49300
   588
          [(map (fn th => th RS notE) distinct_thms, safe_elim_attrs)]
blanchet@49300
   589
          |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
blanchet@49019
   590
      in
blanchet@49484
   591
        ((discs, selss, inject_thms, distinct_thms, case_thms, disc_thmss, discI_thms, sel_thmss),
blanchet@49438
   592
         lthy |> Local_Theory.notes (notes' @ notes) |> snd)
blanchet@49019
   593
      end;
blanchet@49017
   594
  in
blanchet@49121
   595
    (goalss, after_qed, lthy')
blanchet@49017
   596
  end;
blanchet@49017
   597
blanchet@49199
   598
fun wrap_datatype tacss = (fn (goalss, after_qed, lthy) =>
blanchet@49111
   599
  map2 (map2 (Skip_Proof.prove lthy [] [])) goalss tacss
blanchet@49280
   600
  |> (fn thms => after_qed thms lthy)) oo prepare_wrap_datatype (K I);
blanchet@49280
   601
blanchet@49297
   602
val wrap_datatype_cmd = (fn (goalss, after_qed, lthy) =>
blanchet@49297
   603
  Proof.theorem NONE (snd oo after_qed) (map (map (rpair [])) goalss) lthy) oo
blanchet@49297
   604
  prepare_wrap_datatype Syntax.read_term;
blanchet@49297
   605
blanchet@49280
   606
fun parse_bracket_list parser = @{keyword "["} |-- Parse.list parser --|  @{keyword "]"};
blanchet@49111
   607
blanchet@49280
   608
val parse_bindings = parse_bracket_list Parse.binding;
blanchet@49280
   609
val parse_bindingss = parse_bracket_list parse_bindings;
blanchet@49280
   610
blanchet@49280
   611
val parse_bound_term = (Parse.binding --| @{keyword ":"}) -- Parse.term;
blanchet@49280
   612
val parse_bound_terms = parse_bracket_list parse_bound_term;
blanchet@49280
   613
val parse_bound_termss = parse_bracket_list parse_bound_terms;
blanchet@49017
   614
blanchet@49278
   615
val parse_wrap_options =
blanchet@49278
   616
  Scan.optional (@{keyword "("} |-- (@{keyword "no_dests"} >> K true) --| @{keyword ")"}) false;
blanchet@49278
   617
blanchet@49017
   618
val _ =
blanchet@49074
   619
  Outer_Syntax.local_theory_to_proof @{command_spec "wrap_data"} "wraps an existing datatype"
blanchet@49278
   620
    ((parse_wrap_options -- (@{keyword "["} |-- Parse.list Parse.term --| @{keyword "]"}) --
blanchet@49280
   621
      Parse.term -- Scan.optional (parse_bindings -- Scan.optional (parse_bindingss --
blanchet@49280
   622
        Scan.optional parse_bound_termss []) ([], [])) ([], ([], [])))
blanchet@49199
   623
     >> wrap_datatype_cmd);
blanchet@49017
   624
blanchet@49017
   625
end;