src/HOL/BNF/Tools/bnf_ctr_sugar.ML
author blanchet
Tue Oct 01 14:05:25 2013 +0200 (2013-10-01)
changeset 54006 9fe1bd54d437
parent 53925 9008c4806198
permissions -rw-r--r--
renamed theory file
blanchet@51797
     1
(*  Title:      HOL/BNF/Tools/bnf_ctr_sugar.ML
blanchet@49017
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@49017
     3
    Copyright   2012
blanchet@49017
     4
blanchet@51797
     5
Wrapping existing freely generated type's constructors.
blanchet@49017
     6
*)
blanchet@49017
     7
blanchet@54006
     8
signature CTR_SUGAR =
blanchet@49017
     9
sig
blanchet@51840
    10
  type ctr_sugar =
blanchet@51839
    11
    {ctrs: term list,
blanchet@52375
    12
     casex: term,
blanchet@51839
    13
     discs: term list,
blanchet@51819
    14
     selss: term list list,
blanchet@51819
    15
     exhaust: thm,
blanchet@52375
    16
     nchotomy: thm,
blanchet@51819
    17
     injects: thm list,
blanchet@51819
    18
     distincts: thm list,
blanchet@51819
    19
     case_thms: thm list,
blanchet@52375
    20
     case_cong: thm,
blanchet@52375
    21
     weak_case_cong: thm,
blanchet@52375
    22
     split: thm,
blanchet@52375
    23
     split_asm: thm,
blanchet@51819
    24
     disc_thmss: thm list list,
blanchet@51819
    25
     discIs: thm list,
blanchet@53475
    26
     sel_thmss: thm list list,
blanchet@53475
    27
     disc_exhausts: thm list,
blanchet@53916
    28
     sel_exhausts: thm list,
blanchet@53475
    29
     collapses: thm list,
blanchet@53475
    30
     expands: thm list,
blanchet@53917
    31
     sel_splits: thm list,
blanchet@53917
    32
     sel_split_asms: thm list,
blanchet@53857
    33
     case_conv_ifs: thm list};
blanchet@51809
    34
blanchet@51840
    35
  val morph_ctr_sugar: morphism -> ctr_sugar -> ctr_sugar
blanchet@53867
    36
  val ctr_sugar_of: Proof.context -> string -> ctr_sugar option
blanchet@53906
    37
  val ctr_sugars_of: Proof.context -> ctr_sugar list
blanchet@51823
    38
blanchet@49633
    39
  val rep_compat_prefix: string
blanchet@49633
    40
blanchet@49585
    41
  val mk_half_pairss: 'a list * 'a list -> ('a * 'a) list list
blanchet@49585
    42
  val join_halves: int -> 'a list list -> 'a list list -> 'a list * 'a list list list
blanchet@49585
    43
blanchet@49203
    44
  val mk_ctr: typ list -> term -> term
blanchet@53864
    45
  val mk_case: typ list -> typ -> term -> term
blanchet@49484
    46
  val mk_disc_or_sel: typ list -> term -> term
blanchet@49622
    47
  val name_of_ctr: term -> string
blanchet@51777
    48
  val name_of_disc: term -> string
blanchet@53888
    49
  val dest_ctr: Proof.context -> string -> term -> term * term list
blanchet@53870
    50
  val dest_case: Proof.context -> string -> typ list -> term -> (term list * term list) option
blanchet@49585
    51
blanchet@51781
    52
  val wrap_free_constructors: ({prems: thm list, context: Proof.context} -> tactic) list list ->
blanchet@52968
    53
    (((bool * bool) * term list) * binding) *
blanchet@49280
    54
      (binding list * (binding list list * (binding * term) list list)) -> local_theory ->
blanchet@51840
    55
    ctr_sugar * local_theory
blanchet@52823
    56
  val parse_wrap_free_constructors_options: (bool * bool) parser
blanchet@49286
    57
  val parse_bound_term: (binding * string) parser
blanchet@49017
    58
end;
blanchet@49017
    59
blanchet@54006
    60
structure Ctr_Sugar : CTR_SUGAR =
blanchet@49017
    61
struct
blanchet@49017
    62
blanchet@49017
    63
open BNF_Util
blanchet@54006
    64
open Ctr_Sugar_Tactics
blanchet@49017
    65
blanchet@51840
    66
type ctr_sugar =
blanchet@51839
    67
  {ctrs: term list,
blanchet@52375
    68
   casex: term,
blanchet@51839
    69
   discs: term list,
blanchet@51819
    70
   selss: term list list,
blanchet@51819
    71
   exhaust: thm,
blanchet@52375
    72
   nchotomy: thm,
blanchet@51819
    73
   injects: thm list,
blanchet@51819
    74
   distincts: thm list,
blanchet@51819
    75
   case_thms: thm list,
blanchet@52375
    76
   case_cong: thm,
blanchet@52375
    77
   weak_case_cong: thm,
blanchet@52375
    78
   split: thm,
blanchet@52375
    79
   split_asm: thm,
blanchet@51819
    80
   disc_thmss: thm list list,
blanchet@51819
    81
   discIs: thm list,
blanchet@53475
    82
   sel_thmss: thm list list,
blanchet@53475
    83
   disc_exhausts: thm list,
blanchet@53916
    84
   sel_exhausts: thm list,
blanchet@53475
    85
   collapses: thm list,
blanchet@53475
    86
   expands: thm list,
blanchet@53917
    87
   sel_splits: thm list,
blanchet@53917
    88
   sel_split_asms: thm list,
blanchet@53857
    89
   case_conv_ifs: thm list};
blanchet@51809
    90
blanchet@53906
    91
fun eq_ctr_sugar ({ctrs = ctrs1, casex = case1, discs = discs1, selss = selss1, ...} : ctr_sugar,
blanchet@53906
    92
    {ctrs = ctrs2, casex = case2, discs = discs2, selss = selss2, ...} : ctr_sugar) =
blanchet@53906
    93
  ctrs1 = ctrs2 andalso case1 = case2 andalso discs1 = discs2 andalso selss1 = selss2;
blanchet@53906
    94
blanchet@52375
    95
fun morph_ctr_sugar phi {ctrs, casex, discs, selss, exhaust, nchotomy, injects, distincts,
blanchet@53475
    96
    case_thms, case_cong, weak_case_cong, split, split_asm, disc_thmss, discIs, sel_thmss,
blanchet@53917
    97
    disc_exhausts, sel_exhausts, collapses, expands, sel_splits, sel_split_asms, case_conv_ifs} =
blanchet@51839
    98
  {ctrs = map (Morphism.term phi) ctrs,
blanchet@52375
    99
   casex = Morphism.term phi casex,
blanchet@51839
   100
   discs = map (Morphism.term phi) discs,
blanchet@51823
   101
   selss = map (map (Morphism.term phi)) selss,
blanchet@51823
   102
   exhaust = Morphism.thm phi exhaust,
blanchet@52375
   103
   nchotomy = Morphism.thm phi nchotomy,
blanchet@51823
   104
   injects = map (Morphism.thm phi) injects,
blanchet@51823
   105
   distincts = map (Morphism.thm phi) distincts,
blanchet@51823
   106
   case_thms = map (Morphism.thm phi) case_thms,
blanchet@52375
   107
   case_cong = Morphism.thm phi case_cong,
blanchet@52375
   108
   weak_case_cong = Morphism.thm phi weak_case_cong,
blanchet@52375
   109
   split = Morphism.thm phi split,
blanchet@52375
   110
   split_asm = Morphism.thm phi split_asm,
blanchet@51823
   111
   disc_thmss = map (map (Morphism.thm phi)) disc_thmss,
blanchet@51823
   112
   discIs = map (Morphism.thm phi) discIs,
blanchet@53475
   113
   sel_thmss = map (map (Morphism.thm phi)) sel_thmss,
blanchet@53475
   114
   disc_exhausts = map (Morphism.thm phi) disc_exhausts,
blanchet@53916
   115
   sel_exhausts = map (Morphism.thm phi) sel_exhausts,
blanchet@53475
   116
   collapses = map (Morphism.thm phi) collapses,
blanchet@53475
   117
   expands = map (Morphism.thm phi) expands,
blanchet@53917
   118
   sel_splits = map (Morphism.thm phi) sel_splits,
blanchet@53917
   119
   sel_split_asms = map (Morphism.thm phi) sel_split_asms,
blanchet@53857
   120
   case_conv_ifs = map (Morphism.thm phi) case_conv_ifs};
blanchet@51823
   121
blanchet@53906
   122
val transfer_ctr_sugar =
blanchet@53906
   123
  morph_ctr_sugar o Morphism.thm_morphism o Thm.transfer o Proof_Context.theory_of;
blanchet@53867
   124
blanchet@53867
   125
structure Data = Generic_Data
blanchet@53867
   126
(
blanchet@53867
   127
  type T = ctr_sugar Symtab.table;
blanchet@53867
   128
  val empty = Symtab.empty;
blanchet@53867
   129
  val extend = I;
blanchet@53867
   130
  val merge = Symtab.merge eq_ctr_sugar;
blanchet@53867
   131
);
blanchet@53867
   132
blanchet@53867
   133
fun ctr_sugar_of ctxt =
blanchet@53867
   134
  Symtab.lookup (Data.get (Context.Proof ctxt))
blanchet@53906
   135
  #> Option.map (transfer_ctr_sugar ctxt);
blanchet@53906
   136
blanchet@53906
   137
fun ctr_sugars_of ctxt =
blanchet@53906
   138
  Symtab.fold (cons o transfer_ctr_sugar ctxt o snd) (Data.get (Context.Proof ctxt)) [];
blanchet@53867
   139
blanchet@53867
   140
fun register_ctr_sugar key ctr_sugar =
blanchet@53867
   141
  Local_Theory.declaration {syntax = false, pervasive = true}
blanchet@53867
   142
    (fn phi => Data.map (Symtab.default (key, morph_ctr_sugar phi ctr_sugar)));
blanchet@53867
   143
blanchet@49633
   144
val rep_compat_prefix = "new";
blanchet@49633
   145
blanchet@49223
   146
val isN = "is_";
blanchet@49223
   147
val unN = "un_";
blanchet@49223
   148
fun mk_unN 1 1 suf = unN ^ suf
blanchet@49223
   149
  | mk_unN _ l suf = unN ^ suf ^ string_of_int l;
blanchet@49046
   150
blanchet@49594
   151
val caseN = "case";
blanchet@49054
   152
val case_congN = "case_cong";
blanchet@53857
   153
val case_conv_ifN = "case_conv_if";
blanchet@49118
   154
val collapseN = "collapse";
blanchet@49122
   155
val disc_excludeN = "disc_exclude";
blanchet@49054
   156
val disc_exhaustN = "disc_exhaust";
blanchet@53694
   157
val discN = "disc";
blanchet@53700
   158
val discIN = "discI";
blanchet@49054
   159
val distinctN = "distinct";
blanchet@49075
   160
val exhaustN = "exhaust";
blanchet@49486
   161
val expandN = "expand";
blanchet@49075
   162
val injectN = "inject";
blanchet@49075
   163
val nchotomyN = "nchotomy";
blanchet@53694
   164
val selN = "sel";
blanchet@53916
   165
val sel_exhaustN = "sel_exhaust";
blanchet@53917
   166
val sel_splitN = "sel_split";
blanchet@53917
   167
val sel_split_asmN = "sel_split_asm";
blanchet@49054
   168
val splitN = "split";
blanchet@49633
   169
val splitsN = "splits";
blanchet@49054
   170
val split_asmN = "split_asm";
blanchet@49054
   171
val weak_case_cong_thmsN = "weak_case_cong";
blanchet@49019
   172
blanchet@53700
   173
val cong_attrs = @{attributes [cong]};
blanchet@53836
   174
val dest_attrs = @{attributes [dest]};
blanchet@53700
   175
val safe_elim_attrs = @{attributes [elim!]};
blanchet@53700
   176
val iff_attrs = @{attributes [iff]};
blanchet@49300
   177
val induct_simp_attrs = @{attributes [induct_simp]};
blanchet@53808
   178
val nitpick_attrs = @{attributes [nitpick_simp]};
blanchet@49300
   179
val simp_attrs = @{attributes [simp]};
blanchet@53810
   180
val code_nitpick_simp_simp_attrs = Code.add_default_eqn_attrib :: nitpick_attrs @ simp_attrs;
blanchet@49046
   181
blanchet@53040
   182
fun unflat_lookup eq xs ys = map (fn xs' => permute_like eq xs xs' ys);
blanchet@49258
   183
blanchet@49585
   184
fun mk_half_pairss' _ ([], []) = []
blanchet@49591
   185
  | mk_half_pairss' indent (x :: xs, _ :: ys) =
blanchet@49585
   186
    indent @ fold_rev (cons o single o pair x) ys (mk_half_pairss' ([] :: indent) (xs, ys));
blanchet@49486
   187
blanchet@49585
   188
fun mk_half_pairss p = mk_half_pairss' [[]] p;
blanchet@49027
   189
blanchet@49486
   190
fun join_halves n half_xss other_half_xss =
blanchet@49486
   191
  let
blanchet@49486
   192
    val xsss =
blanchet@49486
   193
      map2 (map2 append) (Library.chop_groups n half_xss)
blanchet@49486
   194
        (transpose (Library.chop_groups n other_half_xss))
blanchet@49668
   195
    val xs = splice (flat half_xss) (flat other_half_xss);
blanchet@49585
   196
  in (xs, xsss) end;
blanchet@49027
   197
blanchet@49280
   198
fun mk_undefined T = Const (@{const_name undefined}, T);
blanchet@49055
   199
blanchet@49500
   200
fun mk_ctr Ts t =
blanchet@49500
   201
  let val Type (_, Ts0) = body_type (fastype_of t) in
blanchet@49500
   202
    Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@49203
   203
  end;
blanchet@49203
   204
blanchet@49536
   205
fun mk_case Ts T t =
blanchet@49536
   206
  let val (Type (_, Ts0), body) = strip_type (fastype_of t) |>> List.last in
blanchet@49536
   207
    Term.subst_atomic_types ((body, T) :: (Ts0 ~~ Ts)) t
blanchet@49536
   208
  end;
blanchet@49536
   209
blanchet@53864
   210
fun mk_disc_or_sel Ts t =
blanchet@53864
   211
  Term.subst_atomic_types (snd (Term.dest_Type (domain_type (fastype_of t))) ~~ Ts) t;
blanchet@53864
   212
blanchet@51777
   213
fun name_of_const what t =
blanchet@51777
   214
  (case head_of t of
blanchet@49622
   215
    Const (s, _) => s
blanchet@49622
   216
  | Free (s, _) => s
blanchet@51777
   217
  | _ => error ("Cannot extract name of " ^ what));
blanchet@51777
   218
blanchet@51777
   219
val name_of_ctr = name_of_const "constructor";
blanchet@51777
   220
blanchet@51777
   221
val notN = "not_";
blanchet@51777
   222
val eqN = "eq_";
blanchet@51777
   223
val neqN = "neq_";
blanchet@51777
   224
blanchet@51777
   225
fun name_of_disc t =
blanchet@51777
   226
  (case head_of t of
blanchet@51777
   227
    Abs (_, _, @{const Not} $ (t' $ Bound 0)) =>
blanchet@51777
   228
    Long_Name.map_base_name (prefix notN) (name_of_disc t')
blanchet@51777
   229
  | Abs (_, _, Const (@{const_name HOL.eq}, _) $ Bound 0 $ t') =>
blanchet@51777
   230
    Long_Name.map_base_name (prefix eqN) (name_of_disc t')
blanchet@51777
   231
  | Abs (_, _, @{const Not} $ (Const (@{const_name HOL.eq}, _) $ Bound 0 $ t')) =>
blanchet@51777
   232
    Long_Name.map_base_name (prefix neqN) (name_of_disc t')
blanchet@51777
   233
  | t' => name_of_const "destructor" t');
blanchet@49622
   234
blanchet@49622
   235
val base_name_of_ctr = Long_Name.base_name o name_of_ctr;
blanchet@49046
   236
blanchet@53888
   237
fun dest_ctr ctxt s t =
blanchet@53888
   238
  let
blanchet@53888
   239
    val (f, args) = Term.strip_comb t;
blanchet@53888
   240
  in
blanchet@53888
   241
    (case ctr_sugar_of ctxt s of
blanchet@53888
   242
      SOME {ctrs, ...} =>
blanchet@53888
   243
      (case find_first (can (fo_match ctxt f)) ctrs of
blanchet@53888
   244
        SOME f' => (f', args)
blanchet@53888
   245
      | NONE => raise Fail "dest_ctr")
blanchet@53888
   246
    | NONE => raise Fail "dest_ctr")
blanchet@53888
   247
  end;
blanchet@53888
   248
blanchet@53870
   249
fun dest_case ctxt s Ts t =
blanchet@53870
   250
  (case Term.strip_comb t of
blanchet@53870
   251
    (Const (c, _), args as _ :: _) =>
blanchet@53870
   252
    (case ctr_sugar_of ctxt s of
blanchet@53870
   253
      SOME {casex = Const (case_name, _), discs = discs0, selss = selss0, ...} =>
blanchet@53870
   254
      if case_name = c then
blanchet@53924
   255
        let val n = length discs0 in
blanchet@53924
   256
          if n < length args then
blanchet@53924
   257
            let
blanchet@53924
   258
              val (branches, obj :: leftovers) = chop n args;
blanchet@53924
   259
              val discs = map (mk_disc_or_sel Ts) discs0;
blanchet@53924
   260
              val selss = map (map (mk_disc_or_sel Ts)) selss0;
blanchet@53924
   261
              val conds = map (rapp obj) discs;
blanchet@53924
   262
              val branch_argss = map (fn sels => map (rapp obj) sels @ leftovers) selss;
blanchet@53924
   263
              val branches' = map2 (curry Term.betapplys) branches branch_argss;
blanchet@53924
   264
            in
blanchet@53924
   265
              SOME (conds, branches')
blanchet@53924
   266
            end
blanchet@53924
   267
          else
blanchet@53924
   268
            NONE
blanchet@53870
   269
        end
blanchet@53870
   270
      else
blanchet@53870
   271
        NONE
blanchet@53870
   272
    | _ => NONE)
blanchet@53870
   273
  | _ => NONE);
blanchet@53870
   274
blanchet@49437
   275
fun eta_expand_arg xs f_xs = fold_rev Term.lambda xs f_xs;
blanchet@49437
   276
blanchet@52969
   277
fun prepare_wrap_free_constructors prep_term ((((no_discs_sels, rep_compat), raw_ctrs),
blanchet@52968
   278
    raw_case_binding), (raw_disc_bindings, (raw_sel_bindingss, raw_sel_defaultss))) no_defs_lthy =
blanchet@49017
   279
  let
blanchet@49019
   280
    (* TODO: sanity checks on arguments *)
blanchet@49025
   281
blanchet@49280
   282
    val n = length raw_ctrs;
blanchet@49054
   283
    val ks = 1 upto n;
blanchet@49054
   284
blanchet@49121
   285
    val _ = if n > 0 then () else error "No constructors specified";
blanchet@49121
   286
blanchet@49280
   287
    val ctrs0 = map (prep_term no_defs_lthy) raw_ctrs;
blanchet@49280
   288
    val sel_defaultss =
blanchet@49280
   289
      pad_list [] n (map (map (apsnd (prep_term no_defs_lthy))) raw_sel_defaultss);
blanchet@49280
   290
blanchet@53908
   291
    val Type (fcT_name, As0) = body_type (fastype_of (hd ctrs0));
blanchet@53908
   292
    val fc_b_name = Long_Name.base_name fcT_name;
blanchet@53908
   293
    val fc_b = Binding.name fc_b_name;
blanchet@49055
   294
blanchet@49633
   295
    fun qualify mandatory =
blanchet@53908
   296
      Binding.qualify mandatory fc_b_name o (rep_compat ? Binding.qualify false rep_compat_prefix);
blanchet@49633
   297
blanchet@53268
   298
    fun dest_TFree_or_TVar (TFree p) = p
blanchet@53268
   299
      | dest_TFree_or_TVar (TVar ((s, _), S)) = (s, S)
blanchet@53268
   300
      | dest_TFree_or_TVar _ = error "Invalid type argument";
blanchet@52965
   301
blanchet@53268
   302
    val (unsorted_As, B) =
blanchet@49055
   303
      no_defs_lthy
blanchet@53268
   304
      |> variant_tfrees (map (fst o dest_TFree_or_TVar) As0)
blanchet@49055
   305
      ||> the_single o fst o mk_TFrees 1;
blanchet@49055
   306
blanchet@53268
   307
    val As = map2 (resort_tfree o snd o dest_TFree_or_TVar) As0 unsorted_As;
blanchet@53268
   308
blanchet@53908
   309
    val fcT = Type (fcT_name, As);
blanchet@49055
   310
    val ctrs = map (mk_ctr As) ctrs0;
blanchet@49055
   311
    val ctr_Tss = map (binder_types o fastype_of) ctrs;
blanchet@49055
   312
blanchet@49055
   313
    val ms = map length ctr_Tss;
blanchet@49055
   314
blanchet@51790
   315
    val raw_disc_bindings' = pad_list Binding.empty n raw_disc_bindings;
blanchet@49120
   316
blanchet@53925
   317
    fun can_definitely_rely_on_disc k = not (Binding.is_empty (nth raw_disc_bindings' (k - 1)));
blanchet@51790
   318
    fun can_rely_on_disc k =
blanchet@51790
   319
      can_definitely_rely_on_disc k orelse (k = 1 andalso not (can_definitely_rely_on_disc 2));
blanchet@53925
   320
    fun should_omit_disc_binding k = n = 1 orelse (n = 2 andalso can_rely_on_disc (3 - k));
blanchet@51790
   321
blanchet@51790
   322
    fun is_disc_binding_valid b =
blanchet@51790
   323
      not (Binding.is_empty b orelse Binding.eq_name (b, equal_binding));
blanchet@51787
   324
blanchet@52322
   325
    val standard_disc_binding = Binding.name o prefix isN o base_name_of_ctr;
blanchet@49120
   326
blanchet@49336
   327
    val disc_bindings =
blanchet@49336
   328
      raw_disc_bindings'
blanchet@49120
   329
      |> map4 (fn k => fn m => fn ctr => fn disc =>
blanchet@51790
   330
        qualify false
blanchet@51787
   331
          (if Binding.is_empty disc then
blanchet@51790
   332
             if should_omit_disc_binding k then disc else standard_disc_binding ctr
blanchet@51790
   333
           else if Binding.eq_name (disc, equal_binding) then
blanchet@51790
   334
             if m = 0 then disc
blanchet@51790
   335
             else error "Cannot use \"=\" syntax for discriminating nonnullary constructor"
blanchet@51790
   336
           else if Binding.eq_name (disc, standard_binding) then
blanchet@51790
   337
             standard_disc_binding ctr
blanchet@49302
   338
           else
blanchet@51790
   339
             disc)) ks ms ctrs0;
blanchet@49056
   340
blanchet@51787
   341
    fun standard_sel_binding m l = Binding.name o mk_unN m l o base_name_of_ctr;
blanchet@49120
   342
blanchet@49336
   343
    val sel_bindingss =
blanchet@49336
   344
      pad_list [] n raw_sel_bindingss
blanchet@49056
   345
      |> map3 (fn ctr => fn m => map2 (fn l => fn sel =>
blanchet@49633
   346
        qualify false
blanchet@51790
   347
          (if Binding.is_empty sel orelse Binding.eq_name (sel, standard_binding) then
blanchet@51787
   348
            standard_sel_binding m l ctr
blanchet@49302
   349
          else
traytel@49434
   350
            sel)) (1 upto m) o pad_list Binding.empty m) ctrs0 ms;
blanchet@49020
   351
blanchet@49201
   352
    val case_Ts = map (fn Ts => Ts ---> B) ctr_Tss;
blanchet@49043
   353
blanchet@52968
   354
    val ((((((((xss, xss'), yss), fs), gs), [u', v']), [w]), (p, p')), names_lthy) = no_defs_lthy |>
blanchet@49364
   355
      mk_Freess' "x" ctr_Tss
blanchet@49025
   356
      ||>> mk_Freess "y" ctr_Tss
blanchet@49201
   357
      ||>> mk_Frees "f" case_Ts
blanchet@49201
   358
      ||>> mk_Frees "g" case_Ts
blanchet@53908
   359
      ||>> (apfst (map (rpair fcT)) oo Variable.variant_fixes) [fc_b_name, fc_b_name ^ "'"]
blanchet@52968
   360
      ||>> mk_Frees "z" [B]
blanchet@49043
   361
      ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "P") HOLogic.boolT;
blanchet@49043
   362
blanchet@49498
   363
    val u = Free u';
blanchet@49498
   364
    val v = Free v';
blanchet@49463
   365
    val q = Free (fst p', mk_pred1T B);
blanchet@49020
   366
blanchet@49025
   367
    val xctrs = map2 (curry Term.list_comb) ctrs xss;
blanchet@49025
   368
    val yctrs = map2 (curry Term.list_comb) ctrs yss;
blanchet@49032
   369
blanchet@49043
   370
    val xfs = map2 (curry Term.list_comb) fs xss;
blanchet@49043
   371
    val xgs = map2 (curry Term.list_comb) gs xss;
blanchet@49043
   372
blanchet@52968
   373
    (* TODO: Eta-expension is for compatibility with the old datatype package (but it also provides
blanchet@52968
   374
       nicer names). Consider removing. *)
blanchet@52968
   375
    val eta_fs = map2 eta_expand_arg xss xfs;
blanchet@52968
   376
    val eta_gs = map2 eta_expand_arg xss xgs;
blanchet@52968
   377
blanchet@52968
   378
    val case_binding =
blanchet@52968
   379
      qualify false
blanchet@52968
   380
        (if Binding.is_empty raw_case_binding orelse
blanchet@52968
   381
            Binding.eq_name (raw_case_binding, standard_binding) then
blanchet@53908
   382
           Binding.suffix_name ("_" ^ caseN) fc_b
blanchet@52968
   383
         else
blanchet@52968
   384
           raw_case_binding);
blanchet@52968
   385
blanchet@52968
   386
    fun mk_case_disj xctr xf xs =
blanchet@52968
   387
      list_exists_free xs (HOLogic.mk_conj (HOLogic.mk_eq (u, xctr), HOLogic.mk_eq (w, xf)));
blanchet@52968
   388
blanchet@53925
   389
    val case_rhs = fold_rev (fold_rev Term.lambda) [fs, [u]]
blanchet@53925
   390
      (Const (@{const_name The}, (B --> HOLogic.boolT) --> B) $
blanchet@53925
   391
         Term.lambda w (Library.foldr1 HOLogic.mk_disj (map3 mk_case_disj xctrs xfs xss)));
blanchet@52968
   392
blanchet@52968
   393
    val ((raw_case, (_, raw_case_def)), (lthy', lthy)) = no_defs_lthy
blanchet@52968
   394
      |> Local_Theory.define ((case_binding, NoSyn), ((Thm.def_binding case_binding, []), case_rhs))
blanchet@52968
   395
      ||> `Local_Theory.restore;
blanchet@52968
   396
blanchet@52968
   397
    val phi = Proof_Context.export_morphism lthy lthy';
blanchet@52968
   398
blanchet@52968
   399
    val case_def = Morphism.thm phi raw_case_def;
blanchet@52968
   400
blanchet@52968
   401
    val case0 = Morphism.term phi raw_case;
blanchet@52968
   402
    val casex = mk_case As B case0;
blanchet@52968
   403
blanchet@51759
   404
    val fcase = Term.list_comb (casex, fs);
blanchet@51759
   405
blanchet@51759
   406
    val ufcase = fcase $ u;
blanchet@51759
   407
    val vfcase = fcase $ v;
blanchet@51759
   408
blanchet@51759
   409
    val eta_fcase = Term.list_comb (casex, eta_fs);
blanchet@51759
   410
    val eta_gcase = Term.list_comb (casex, eta_gs);
blanchet@49020
   411
blanchet@51759
   412
    val eta_ufcase = eta_fcase $ u;
blanchet@51759
   413
    val eta_vgcase = eta_gcase $ v;
blanchet@49486
   414
blanchet@49591
   415
    fun mk_uu_eq () = HOLogic.mk_eq (u, u);
blanchet@49486
   416
blanchet@49591
   417
    val uv_eq = mk_Trueprop_eq (u, v);
blanchet@49486
   418
blanchet@49486
   419
    val exist_xs_u_eq_ctrs =
blanchet@49486
   420
      map2 (fn xctr => fn xs => list_exists_free xs (HOLogic.mk_eq (u, xctr))) xctrs xss;
blanchet@49022
   421
blanchet@51743
   422
    val unique_disc_no_def = TrueI; (*arbitrary marker*)
blanchet@51743
   423
    val alternate_disc_no_def = FalseE; (*arbitrary marker*)
blanchet@51743
   424
blanchet@49486
   425
    fun alternate_disc_lhs get_udisc k =
blanchet@49116
   426
      HOLogic.mk_not
blanchet@51790
   427
        (let val b = nth disc_bindings (k - 1) in
blanchet@51790
   428
           if is_disc_binding_valid b then get_udisc b (k - 1) else nth exist_xs_u_eq_ctrs (k - 1)
blanchet@51790
   429
         end);
blanchet@49116
   430
blanchet@53917
   431
    val (all_sels_distinct, discs, selss, disc_defs, sel_defs, sel_defss, lthy') =
blanchet@52969
   432
      if no_discs_sels then
blanchet@53917
   433
        (true, [], [], [], [], [], lthy)
blanchet@49278
   434
      else
blanchet@49278
   435
        let
blanchet@53908
   436
          fun disc_free b = Free (Binding.name_of b, mk_pred1T fcT);
blanchet@49025
   437
blanchet@49486
   438
          fun disc_spec b exist_xs_u_eq_ctr = mk_Trueprop_eq (disc_free b $ u, exist_xs_u_eq_ctr);
blanchet@49278
   439
blanchet@49500
   440
          fun alternate_disc k =
blanchet@49500
   441
            Term.lambda u (alternate_disc_lhs (K o rapp u o disc_free) (3 - k));
blanchet@49278
   442
blanchet@49280
   443
          fun mk_sel_case_args b proto_sels T =
blanchet@49280
   444
            map2 (fn Ts => fn k =>
blanchet@49280
   445
              (case AList.lookup (op =) proto_sels k of
blanchet@49280
   446
                NONE =>
blanchet@49364
   447
                (case AList.lookup Binding.eq_name (rev (nth sel_defaultss (k - 1))) b of
blanchet@49364
   448
                  NONE => fold_rev (Term.lambda o curry Free Name.uu) Ts (mk_undefined T)
blanchet@52968
   449
                | SOME t => t |> Type.constraint (Ts ---> T) |> Syntax.check_term lthy)
blanchet@49280
   450
              | SOME (xs, x) => fold_rev Term.lambda xs x)) ctr_Tss ks;
blanchet@49258
   451
blanchet@49278
   452
          fun sel_spec b proto_sels =
blanchet@49278
   453
            let
blanchet@49278
   454
              val _ =
blanchet@49278
   455
                (case duplicates (op =) (map fst proto_sels) of
blanchet@49278
   456
                   k :: _ => error ("Duplicate selector name " ^ quote (Binding.name_of b) ^
blanchet@49278
   457
                     " for constructor " ^
blanchet@52968
   458
                     quote (Syntax.string_of_term lthy (nth ctrs (k - 1))))
blanchet@49278
   459
                 | [] => ())
blanchet@49278
   460
              val T =
blanchet@49278
   461
                (case distinct (op =) (map (fastype_of o snd o snd) proto_sels) of
blanchet@49278
   462
                  [T] => T
blanchet@49278
   463
                | T :: T' :: _ => error ("Inconsistent range type for selector " ^
blanchet@52968
   464
                    quote (Binding.name_of b) ^ ": " ^ quote (Syntax.string_of_typ lthy T) ^ " vs. "
blanchet@52968
   465
                    ^ quote (Syntax.string_of_typ lthy T')));
blanchet@49278
   466
            in
blanchet@53908
   467
              mk_Trueprop_eq (Free (Binding.name_of b, fcT --> T) $ u,
blanchet@49536
   468
                Term.list_comb (mk_case As T case0, mk_sel_case_args b proto_sels T) $ u)
blanchet@49278
   469
            end;
blanchet@49116
   470
blanchet@49336
   471
          val sel_bindings = flat sel_bindingss;
blanchet@49336
   472
          val uniq_sel_bindings = distinct Binding.eq_name sel_bindings;
blanchet@49336
   473
          val all_sels_distinct = (length uniq_sel_bindings = length sel_bindings);
blanchet@49285
   474
blanchet@49336
   475
          val sel_binding_index =
blanchet@49336
   476
            if all_sels_distinct then 1 upto length sel_bindings
blanchet@49336
   477
            else map (fn b => find_index (curry Binding.eq_name b) uniq_sel_bindings) sel_bindings;
blanchet@49285
   478
blanchet@49285
   479
          val proto_sels = flat (map3 (fn k => fn xs => map (fn x => (k, (xs, x)))) ks xss xss);
blanchet@49300
   480
          val sel_infos =
blanchet@49336
   481
            AList.group (op =) (sel_binding_index ~~ proto_sels)
blanchet@49285
   482
            |> sort (int_ord o pairself fst)
blanchet@49336
   483
            |> map snd |> curry (op ~~) uniq_sel_bindings;
blanchet@49336
   484
          val sel_bindings = map fst sel_infos;
blanchet@49258
   485
blanchet@49336
   486
          fun unflat_selss xs = unflat_lookup Binding.eq_name sel_bindings xs sel_bindingss;
blanchet@49258
   487
blanchet@49278
   488
          val (((raw_discs, raw_disc_defs), (raw_sels, raw_sel_defs)), (lthy', lthy)) =
blanchet@52968
   489
            lthy
blanchet@51809
   490
            |> apfst split_list o fold_map3 (fn k => fn exist_xs_u_eq_ctr => fn b =>
blanchet@51790
   491
                if Binding.is_empty b then
blanchet@51790
   492
                  if n = 1 then pair (Term.lambda u (mk_uu_eq ()), unique_disc_no_def)
blanchet@51790
   493
                  else pair (alternate_disc k, alternate_disc_no_def)
blanchet@51790
   494
                else if Binding.eq_name (b, equal_binding) then
blanchet@51790
   495
                  pair (Term.lambda u exist_xs_u_eq_ctr, refl)
blanchet@51790
   496
                else
blanchet@51790
   497
                  Specification.definition (SOME (b, NONE, NoSyn),
blanchet@51790
   498
                    ((Thm.def_binding b, []), disc_spec b exist_xs_u_eq_ctr)) #>> apsnd snd)
blanchet@51809
   499
              ks exist_xs_u_eq_ctrs disc_bindings
blanchet@49278
   500
            ||>> apfst split_list o fold_map (fn (b, proto_sels) =>
blanchet@49278
   501
              Specification.definition (SOME (b, NONE, NoSyn),
blanchet@49300
   502
                ((Thm.def_binding b, []), sel_spec b proto_sels)) #>> apsnd snd) sel_infos
blanchet@49278
   503
            ||> `Local_Theory.restore;
blanchet@49022
   504
blanchet@49278
   505
          val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49025
   506
blanchet@49278
   507
          val disc_defs = map (Morphism.thm phi) raw_disc_defs;
blanchet@49281
   508
          val sel_defs = map (Morphism.thm phi) raw_sel_defs;
blanchet@49281
   509
          val sel_defss = unflat_selss sel_defs;
blanchet@49278
   510
blanchet@49278
   511
          val discs0 = map (Morphism.term phi) raw_discs;
blanchet@49278
   512
          val selss0 = unflat_selss (map (Morphism.term phi) raw_sels);
blanchet@49028
   513
blanchet@49278
   514
          val discs = map (mk_disc_or_sel As) discs0;
blanchet@49278
   515
          val selss = map (map (mk_disc_or_sel As)) selss0;
blanchet@49278
   516
        in
blanchet@53917
   517
          (all_sels_distinct, discs, selss, disc_defs, sel_defs, sel_defss, lthy')
blanchet@49278
   518
        end;
blanchet@49025
   519
blanchet@49032
   520
    fun mk_imp_p Qs = Logic.list_implies (Qs, HOLogic.mk_Trueprop p);
blanchet@49029
   521
blanchet@49458
   522
    val exhaust_goal =
blanchet@49486
   523
      let fun mk_prem xctr xs = fold_rev Logic.all xs (mk_imp_p [mk_Trueprop_eq (u, xctr)]) in
blanchet@49486
   524
        fold_rev Logic.all [p, u] (mk_imp_p (map2 mk_prem xctrs xss))
blanchet@49020
   525
      end;
blanchet@49019
   526
blanchet@49484
   527
    val inject_goalss =
blanchet@49017
   528
      let
blanchet@49034
   529
        fun mk_goal _ _ [] [] = []
blanchet@49025
   530
          | mk_goal xctr yctr xs ys =
blanchet@49121
   531
            [fold_rev Logic.all (xs @ ys) (mk_Trueprop_eq (HOLogic.mk_eq (xctr, yctr),
blanchet@49121
   532
              Library.foldr1 HOLogic.mk_conj (map2 (curry HOLogic.mk_eq) xs ys)))];
blanchet@49017
   533
      in
blanchet@49034
   534
        map4 mk_goal xctrs yctrs xss yss
blanchet@49017
   535
      end;
blanchet@49017
   536
blanchet@49484
   537
    val half_distinct_goalss =
blanchet@49121
   538
      let
blanchet@49203
   539
        fun mk_goal ((xs, xc), (xs', xc')) =
blanchet@49121
   540
          fold_rev Logic.all (xs @ xs')
blanchet@49203
   541
            (HOLogic.mk_Trueprop (HOLogic.mk_not (HOLogic.mk_eq (xc, xc'))));
blanchet@49121
   542
      in
blanchet@49585
   543
        map (map mk_goal) (mk_half_pairss (`I (xss ~~ xctrs)))
blanchet@49121
   544
      end;
blanchet@49019
   545
blanchet@52968
   546
    val goalss = [exhaust_goal] :: inject_goalss @ half_distinct_goalss;
blanchet@49019
   547
blanchet@49019
   548
    fun after_qed thmss lthy =
blanchet@49019
   549
      let
blanchet@52968
   550
        val ([exhaust_thm], (inject_thmss, half_distinct_thmss)) = (hd thmss, chop n (tl thmss));
blanchet@49019
   551
blanchet@49438
   552
        val inject_thms = flat inject_thmss;
blanchet@49438
   553
blanchet@53210
   554
        val rho_As = map (pairself (certifyT lthy)) (map Logic.varifyT_global As ~~ As);
blanchet@49486
   555
blanchet@49486
   556
        fun inst_thm t thm =
blanchet@49486
   557
          Drule.instantiate' [] [SOME (certify lthy t)]
blanchet@53210
   558
            (Thm.instantiate (rho_As, []) (Drule.zero_var_indexes thm));
blanchet@49486
   559
blanchet@49486
   560
        val uexhaust_thm = inst_thm u exhaust_thm;
blanchet@49032
   561
blanchet@49300
   562
        val exhaust_cases = map base_name_of_ctr ctrs;
blanchet@49300
   563
blanchet@49048
   564
        val other_half_distinct_thmss = map (map (fn thm => thm RS not_sym)) half_distinct_thmss;
blanchet@49048
   565
blanchet@49486
   566
        val (distinct_thms, (distinct_thmsss', distinct_thmsss)) =
blanchet@49585
   567
          join_halves n half_distinct_thmss other_half_distinct_thmss ||> `transpose;
blanchet@49019
   568
blanchet@49020
   569
        val nchotomy_thm =
blanchet@49020
   570
          let
blanchet@49020
   571
            val goal =
blanchet@49486
   572
              HOLogic.mk_Trueprop (HOLogic.mk_all (fst u', snd u',
blanchet@49486
   573
                Library.foldr1 HOLogic.mk_disj exist_xs_u_eq_ctrs));
blanchet@49020
   574
          in
wenzelm@51551
   575
            Goal.prove_sorry lthy [] [] goal (fn _ => mk_nchotomy_tac n exhaust_thm)
traytel@49667
   576
            |> Thm.close_derivation
blanchet@49020
   577
          end;
blanchet@49020
   578
blanchet@52968
   579
        val case_thms =
blanchet@52968
   580
          let
blanchet@52968
   581
            val goals =
blanchet@52968
   582
              map3 (fn xctr => fn xf => fn xs =>
blanchet@52968
   583
                fold_rev Logic.all (fs @ xs) (mk_Trueprop_eq (fcase $ xctr, xf))) xctrs xfs xss;
blanchet@52968
   584
          in
blanchet@52968
   585
            map4 (fn k => fn goal => fn injects => fn distinctss =>
blanchet@52968
   586
                Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@52968
   587
                  mk_case_tac ctxt n k case_def injects distinctss)
blanchet@52968
   588
                |> Thm.close_derivation)
blanchet@52968
   589
              ks goals inject_thmss distinct_thmsss
blanchet@52968
   590
          end;
blanchet@52968
   591
blanchet@53917
   592
        val (case_cong_thm, weak_case_cong_thm) =
blanchet@53917
   593
          let
blanchet@53917
   594
            fun mk_prem xctr xs xf xg =
blanchet@53917
   595
              fold_rev Logic.all xs (Logic.mk_implies (mk_Trueprop_eq (v, xctr),
blanchet@53917
   596
                mk_Trueprop_eq (xf, xg)));
blanchet@53917
   597
blanchet@53917
   598
            val goal =
blanchet@53917
   599
              Logic.list_implies (uv_eq :: map4 mk_prem xctrs xss xfs xgs,
blanchet@53917
   600
                 mk_Trueprop_eq (eta_ufcase, eta_vgcase));
blanchet@53917
   601
            val weak_goal = Logic.mk_implies (uv_eq, mk_Trueprop_eq (ufcase, vfcase));
blanchet@53917
   602
          in
blanchet@53917
   603
            (Goal.prove_sorry lthy [] [] goal (fn _ => mk_case_cong_tac lthy uexhaust_thm case_thms),
blanchet@53917
   604
             Goal.prove_sorry lthy [] [] weak_goal (K (etac arg_cong 1)))
blanchet@53917
   605
            |> pairself (Thm.close_derivation #> singleton (Proof_Context.export names_lthy lthy))
blanchet@53917
   606
          end;
blanchet@53917
   607
blanchet@53917
   608
        val split_lhs = q $ ufcase;
blanchet@53917
   609
blanchet@53917
   610
        fun mk_split_conjunct xctr xs f_xs =
blanchet@53917
   611
          list_all_free xs (HOLogic.mk_imp (HOLogic.mk_eq (u, xctr), q $ f_xs));
blanchet@53917
   612
        fun mk_split_disjunct xctr xs f_xs =
blanchet@53917
   613
          list_exists_free xs (HOLogic.mk_conj (HOLogic.mk_eq (u, xctr),
blanchet@53917
   614
            HOLogic.mk_not (q $ f_xs)));
blanchet@53917
   615
blanchet@53917
   616
        fun mk_split_goal xctrs xss xfs =
blanchet@53917
   617
          mk_Trueprop_eq (split_lhs, Library.foldr1 HOLogic.mk_conj
blanchet@53917
   618
            (map3 mk_split_conjunct xctrs xss xfs));
blanchet@53917
   619
        fun mk_split_asm_goal xctrs xss xfs =
blanchet@53917
   620
          mk_Trueprop_eq (split_lhs, HOLogic.mk_not (Library.foldr1 HOLogic.mk_disj
blanchet@53917
   621
            (map3 mk_split_disjunct xctrs xss xfs)));
blanchet@53917
   622
blanchet@53917
   623
        fun prove_split selss goal =
blanchet@53917
   624
          Goal.prove_sorry lthy [] [] goal (fn _ =>
blanchet@53917
   625
            mk_split_tac lthy uexhaust_thm case_thms selss inject_thmss distinct_thmsss)
blanchet@53917
   626
          |> Thm.close_derivation
blanchet@53917
   627
          |> singleton (Proof_Context.export names_lthy lthy);
blanchet@53917
   628
blanchet@53917
   629
        fun prove_split_asm asm_goal split_thm =
blanchet@53917
   630
          Goal.prove_sorry lthy [] [] asm_goal (fn {context = ctxt, ...} =>
blanchet@53917
   631
            mk_split_asm_tac ctxt split_thm)
blanchet@53917
   632
          |> Thm.close_derivation
blanchet@53917
   633
          |> singleton (Proof_Context.export names_lthy lthy);
blanchet@53917
   634
blanchet@53917
   635
        val (split_thm, split_asm_thm) =
blanchet@53917
   636
          let
blanchet@53917
   637
            val goal = mk_split_goal xctrs xss xfs;
blanchet@53917
   638
            val asm_goal = mk_split_asm_goal xctrs xss xfs;
blanchet@53917
   639
blanchet@53917
   640
            val thm = prove_split (replicate n []) goal;
blanchet@53917
   641
            val asm_thm = prove_split_asm asm_goal thm;
blanchet@53917
   642
          in
blanchet@53917
   643
            (thm, asm_thm)
blanchet@53917
   644
          end;
blanchet@53917
   645
blanchet@53704
   646
        val (all_sel_thms, sel_thmss, disc_thmss, nontriv_disc_thms, discI_thms, nontriv_discI_thms,
blanchet@53916
   647
             disc_exclude_thms, disc_exhaust_thms, sel_exhaust_thms, all_collapse_thms,
blanchet@53917
   648
             safe_collapse_thms, expand_thms, sel_split_thms, sel_split_asm_thms,
blanchet@53917
   649
             case_conv_if_thms) =
blanchet@52969
   650
          if no_discs_sels then
blanchet@53917
   651
            ([], [], [], [], [], [], [], [], [], [], [], [], [], [], [])
blanchet@49116
   652
          else
blanchet@49116
   653
            let
blanchet@53917
   654
              val udiscs = map (rapp u) discs;
blanchet@53917
   655
              val uselss = map (map (rapp u)) selss;
blanchet@53917
   656
              val usel_ctrs = map2 (curry Term.list_comb) ctrs uselss;
blanchet@53917
   657
              val usel_fs = map2 (curry Term.list_comb) fs uselss;
blanchet@53917
   658
blanchet@53917
   659
              val vdiscs = map (rapp v) discs;
blanchet@53917
   660
              val vselss = map (map (rapp v)) selss;
blanchet@53917
   661
blanchet@49364
   662
              fun make_sel_thm xs' case_thm sel_def =
blanchet@49364
   663
                zero_var_indexes (Drule.gen_all (Drule.rename_bvars' (map (SOME o fst) xs')
blanchet@49364
   664
                    (Drule.forall_intr_vars (case_thm RS (sel_def RS trans)))));
blanchet@49281
   665
blanchet@53704
   666
              val sel_thmss = map3 (map oo make_sel_thm) xss' case_thms sel_defss;
blanchet@53704
   667
blanchet@49281
   668
              fun has_undefined_rhs thm =
blanchet@49281
   669
                (case snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of thm))) of
blanchet@49281
   670
                  Const (@{const_name undefined}, _) => true
blanchet@49281
   671
                | _ => false);
blanchet@49281
   672
blanchet@49281
   673
              val all_sel_thms =
blanchet@49285
   674
                (if all_sels_distinct andalso forall null sel_defaultss then
blanchet@49285
   675
                   flat sel_thmss
blanchet@49285
   676
                 else
blanchet@49364
   677
                   map_product (fn s => fn (xs', c) => make_sel_thm xs' c s) sel_defs
blanchet@49364
   678
                     (xss' ~~ case_thms))
blanchet@49285
   679
                |> filter_out has_undefined_rhs;
blanchet@49278
   680
blanchet@49278
   681
              fun mk_unique_disc_def () =
blanchet@49278
   682
                let
blanchet@49278
   683
                  val m = the_single ms;
blanchet@49591
   684
                  val goal = mk_Trueprop_eq (mk_uu_eq (), the_single exist_xs_u_eq_ctrs);
blanchet@49278
   685
                in
wenzelm@51551
   686
                  Goal.prove_sorry lthy [] [] goal (fn _ => mk_unique_disc_def_tac m uexhaust_thm)
blanchet@49692
   687
                  |> Thm.close_derivation
blanchet@49278
   688
                  |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49278
   689
                end;
blanchet@49278
   690
blanchet@49278
   691
              fun mk_alternate_disc_def k =
blanchet@49278
   692
                let
blanchet@49278
   693
                  val goal =
blanchet@49486
   694
                    mk_Trueprop_eq (alternate_disc_lhs (K (nth udiscs)) (3 - k),
blanchet@49486
   695
                      nth exist_xs_u_eq_ctrs (k - 1));
blanchet@49278
   696
                in
wenzelm@51551
   697
                  Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@49278
   698
                    mk_alternate_disc_def_tac ctxt k (nth disc_defs (2 - k))
blanchet@49486
   699
                      (nth distinct_thms (2 - k)) uexhaust_thm)
blanchet@49692
   700
                  |> Thm.close_derivation
blanchet@49278
   701
                  |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49278
   702
                end;
blanchet@49028
   703
blanchet@49278
   704
              val has_alternate_disc_def =
blanchet@49278
   705
                exists (fn def => Thm.eq_thm_prop (def, alternate_disc_no_def)) disc_defs;
blanchet@49278
   706
blanchet@49278
   707
              val disc_defs' =
blanchet@49278
   708
                map2 (fn k => fn def =>
blanchet@49278
   709
                  if Thm.eq_thm_prop (def, unique_disc_no_def) then mk_unique_disc_def ()
blanchet@49278
   710
                  else if Thm.eq_thm_prop (def, alternate_disc_no_def) then mk_alternate_disc_def k
blanchet@49278
   711
                  else def) ks disc_defs;
blanchet@49278
   712
blanchet@49278
   713
              val discD_thms = map (fn def => def RS iffD1) disc_defs';
blanchet@49278
   714
              val discI_thms =
blanchet@49278
   715
                map2 (fn m => fn def => funpow m (fn thm => exI RS thm) (def RS iffD2)) ms
blanchet@49278
   716
                  disc_defs';
blanchet@49278
   717
              val not_discI_thms =
blanchet@49278
   718
                map2 (fn m => fn def => funpow m (fn thm => allI RS thm)
blanchet@49504
   719
                    (unfold_thms lthy @{thms not_ex} (def RS @{thm ssubst[of _ _ Not]})))
blanchet@49278
   720
                  ms disc_defs';
blanchet@49278
   721
blanchet@49278
   722
              val (disc_thmss', disc_thmss) =
blanchet@49278
   723
                let
blanchet@49278
   724
                  fun mk_thm discI _ [] = refl RS discI
blanchet@49278
   725
                    | mk_thm _ not_discI [distinct] = distinct RS not_discI;
blanchet@49278
   726
                  fun mk_thms discI not_discI distinctss = map (mk_thm discI not_discI) distinctss;
blanchet@49278
   727
                in
blanchet@49278
   728
                  map3 mk_thms discI_thms not_discI_thms distinct_thmsss' |> `transpose
blanchet@49278
   729
                end;
blanchet@49278
   730
blanchet@53704
   731
              val nontriv_disc_thms =
blanchet@53704
   732
                flat (map2 (fn b => if is_disc_binding_valid b then I else K [])
blanchet@53704
   733
                  disc_bindings disc_thmss);
blanchet@53704
   734
blanchet@53704
   735
              fun is_discI_boring b =
blanchet@53704
   736
                (n = 1 andalso Binding.is_empty b) orelse Binding.eq_name (b, equal_binding);
blanchet@53704
   737
blanchet@53704
   738
              val nontriv_discI_thms =
blanchet@53704
   739
                flat (map2 (fn b => if is_discI_boring b then K [] else single) disc_bindings
blanchet@53704
   740
                  discI_thms);
blanchet@49028
   741
blanchet@49486
   742
              val (disc_exclude_thms, (disc_exclude_thmsss', disc_exclude_thmsss)) =
blanchet@49486
   743
                let
blanchet@49486
   744
                  fun mk_goal [] = []
blanchet@49486
   745
                    | mk_goal [((_, udisc), (_, udisc'))] =
blanchet@49486
   746
                      [Logic.all u (Logic.mk_implies (HOLogic.mk_Trueprop udisc,
blanchet@49486
   747
                         HOLogic.mk_Trueprop (HOLogic.mk_not udisc')))];
blanchet@49486
   748
traytel@49667
   749
                  fun prove tac goal =
wenzelm@51551
   750
                    Goal.prove_sorry lthy [] [] goal (K tac)
traytel@49667
   751
                    |> Thm.close_derivation;
blanchet@49486
   752
blanchet@49585
   753
                  val half_pairss = mk_half_pairss (`I (ms ~~ discD_thms ~~ udiscs));
blanchet@49486
   754
blanchet@49486
   755
                  val half_goalss = map mk_goal half_pairss;
blanchet@49486
   756
                  val half_thmss =
blanchet@49486
   757
                    map3 (fn [] => K (K []) | [goal] => fn [(((m, discD), _), _)] =>
wenzelm@51798
   758
                        fn disc_thm => [prove (mk_half_disc_exclude_tac lthy m discD disc_thm) goal])
blanchet@49486
   759
                      half_goalss half_pairss (flat disc_thmss');
blanchet@49278
   760
blanchet@49486
   761
                  val other_half_goalss = map (mk_goal o map swap) half_pairss;
blanchet@49486
   762
                  val other_half_thmss =
blanchet@49486
   763
                    map2 (map2 (prove o mk_other_half_disc_exclude_tac)) half_thmss
blanchet@49486
   764
                      other_half_goalss;
blanchet@49486
   765
                in
blanchet@49585
   766
                  join_halves n half_thmss other_half_thmss ||> `transpose
blanchet@49486
   767
                  |>> has_alternate_disc_def ? K []
blanchet@49486
   768
                end;
blanchet@49278
   769
blanchet@49486
   770
              val disc_exhaust_thm =
blanchet@49486
   771
                let
blanchet@49486
   772
                  fun mk_prem udisc = mk_imp_p [HOLogic.mk_Trueprop udisc];
blanchet@49486
   773
                  val goal = fold_rev Logic.all [p, u] (mk_imp_p (map mk_prem udiscs));
blanchet@49486
   774
                in
wenzelm@51551
   775
                  Goal.prove_sorry lthy [] [] goal (fn _ =>
blanchet@49486
   776
                    mk_disc_exhaust_tac n exhaust_thm discI_thms)
traytel@49667
   777
                  |> Thm.close_derivation
blanchet@49486
   778
                end;
blanchet@49028
   779
blanchet@53740
   780
              val (safe_collapse_thms, all_collapse_thms) =
blanchet@49486
   781
                let
blanchet@53916
   782
                  fun mk_goal m ctr udisc usel_ctr =
blanchet@49486
   783
                    let
blanchet@49486
   784
                      val prem = HOLogic.mk_Trueprop udisc;
blanchet@53916
   785
                      val concl = mk_Trueprop_eq ((usel_ctr, u) |> m = 0 ? swap);
blanchet@49486
   786
                    in
blanchet@53740
   787
                      (prem aconv concl, Logic.all u (Logic.mk_implies (prem, concl)))
blanchet@49486
   788
                    end;
blanchet@53916
   789
                  val (trivs, goals) = map4 mk_goal ms ctrs udiscs usel_ctrs |> split_list;
blanchet@53740
   790
                  val thms =
blanchet@53740
   791
                    map5 (fn m => fn discD => fn sel_thms => fn triv => fn goal =>
blanchet@53740
   792
                        Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@53740
   793
                          mk_collapse_tac ctxt m discD sel_thms ORELSE HEADGOAL atac)
blanchet@53740
   794
                        |> Thm.close_derivation
blanchet@53740
   795
                        |> not triv ? perhaps (try (fn thm => refl RS thm)))
blanchet@53740
   796
                      ms discD_thms sel_thmss trivs goals;
blanchet@49486
   797
                in
blanchet@53740
   798
                  (map_filter (fn (true, _) => NONE | (false, thm) => SOME thm) (trivs ~~ thms),
blanchet@53740
   799
                   thms)
blanchet@49486
   800
                end;
blanchet@49025
   801
blanchet@53916
   802
              val swapped_all_collapse_thms =
blanchet@53916
   803
                map2 (fn m => fn thm => if m = 0 then thm else thm RS sym) ms all_collapse_thms;
blanchet@53916
   804
blanchet@53916
   805
              val sel_exhaust_thm =
blanchet@53916
   806
                let
blanchet@53916
   807
                  fun mk_prem usel_ctr = mk_imp_p [mk_Trueprop_eq (u, usel_ctr)];
blanchet@53916
   808
                  val goal = fold_rev Logic.all [p, u] (mk_imp_p (map mk_prem usel_ctrs));
blanchet@53916
   809
                in
blanchet@53916
   810
                  Goal.prove_sorry lthy [] [] goal (fn _ =>
blanchet@53916
   811
                    mk_sel_exhaust_tac n disc_exhaust_thm swapped_all_collapse_thms)
blanchet@53916
   812
                  |> Thm.close_derivation
blanchet@53916
   813
                end;
blanchet@53916
   814
blanchet@53919
   815
              val expand_thm =
blanchet@49486
   816
                let
blanchet@49486
   817
                  fun mk_prems k udisc usels vdisc vsels =
blanchet@49486
   818
                    (if k = n then [] else [mk_Trueprop_eq (udisc, vdisc)]) @
blanchet@49486
   819
                    (if null usels then
blanchet@49486
   820
                       []
blanchet@49486
   821
                     else
blanchet@49486
   822
                       [Logic.list_implies
blanchet@49486
   823
                          (if n = 1 then [] else map HOLogic.mk_Trueprop [udisc, vdisc],
blanchet@49486
   824
                             HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
blanchet@49486
   825
                               (map2 (curry HOLogic.mk_eq) usels vsels)))]);
blanchet@49486
   826
blanchet@49591
   827
                  val goal =
blanchet@49591
   828
                    Library.foldr Logic.list_implies
blanchet@49591
   829
                      (map5 mk_prems ks udiscs uselss vdiscs vselss, uv_eq);
blanchet@49486
   830
                  val uncollapse_thms =
blanchet@53740
   831
                    map2 (fn thm => fn [] => thm | _ => thm RS sym) all_collapse_thms uselss;
blanchet@49486
   832
                in
blanchet@53919
   833
                  Goal.prove_sorry lthy [] [] goal (fn _ =>
blanchet@53919
   834
                    mk_expand_tac lthy n ms (inst_thm u disc_exhaust_thm)
blanchet@53919
   835
                      (inst_thm v disc_exhaust_thm) uncollapse_thms disc_exclude_thmsss
blanchet@53919
   836
                      disc_exclude_thmsss')
blanchet@53919
   837
                  |> Thm.close_derivation
blanchet@53919
   838
                  |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49486
   839
                end;
blanchet@49278
   840
blanchet@53917
   841
              val (sel_split_thm, sel_split_asm_thm) =
blanchet@53917
   842
                let
blanchet@53917
   843
                  val zss = map (K []) xss;
blanchet@53917
   844
                  val goal = mk_split_goal usel_ctrs zss usel_fs;
blanchet@53917
   845
                  val asm_goal = mk_split_asm_goal usel_ctrs zss usel_fs;
blanchet@53917
   846
blanchet@53917
   847
                  val thm = prove_split sel_thmss goal;
blanchet@53917
   848
                  val asm_thm = prove_split_asm asm_goal thm;
blanchet@53917
   849
                in
blanchet@53917
   850
                  (thm, asm_thm)
blanchet@53917
   851
                end;
blanchet@53917
   852
blanchet@53919
   853
              val case_conv_if_thm =
blanchet@49486
   854
                let
blanchet@53917
   855
                  val goal = mk_Trueprop_eq (ufcase, mk_IfN B udiscs usel_fs);
blanchet@49486
   856
                in
blanchet@53919
   857
                  Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@53919
   858
                    mk_case_conv_if_tac ctxt n uexhaust_thm case_thms disc_thmss' sel_thmss)
blanchet@53919
   859
                  |> Thm.close_derivation
blanchet@53919
   860
                  |> singleton (Proof_Context.export names_lthy lthy)
blanchet@49486
   861
                end;
blanchet@49116
   862
            in
blanchet@53704
   863
              (all_sel_thms, sel_thmss, disc_thmss, nontriv_disc_thms, discI_thms,
blanchet@53916
   864
               nontriv_discI_thms, disc_exclude_thms, [disc_exhaust_thm], [sel_exhaust_thm],
blanchet@53919
   865
               all_collapse_thms, safe_collapse_thms, [expand_thm], [sel_split_thm],
blanchet@53919
   866
               [sel_split_asm_thm], [case_conv_if_thm])
blanchet@49116
   867
            end;
blanchet@49025
   868
blanchet@49437
   869
        val exhaust_case_names_attr = Attrib.internal (K (Rule_Cases.case_names exhaust_cases));
blanchet@53908
   870
        val cases_type_attr = Attrib.internal (K (Induct.cases_type fcT_name));
blanchet@49300
   871
blanchet@49052
   872
        val notes =
blanchet@53810
   873
          [(caseN, case_thms, code_nitpick_simp_simp_attrs),
blanchet@49594
   874
           (case_congN, [case_cong_thm], []),
blanchet@53857
   875
           (case_conv_ifN, case_conv_if_thms, []),
blanchet@53740
   876
           (collapseN, safe_collapse_thms, simp_attrs),
blanchet@53704
   877
           (discN, nontriv_disc_thms, simp_attrs),
blanchet@53700
   878
           (discIN, nontriv_discI_thms, []),
blanchet@53836
   879
           (disc_excludeN, disc_exclude_thms, dest_attrs),
blanchet@49300
   880
           (disc_exhaustN, disc_exhaust_thms, [exhaust_case_names_attr]),
blanchet@49300
   881
           (distinctN, distinct_thms, simp_attrs @ induct_simp_attrs),
blanchet@49300
   882
           (exhaustN, [exhaust_thm], [exhaust_case_names_attr, cases_type_attr]),
blanchet@49486
   883
           (expandN, expand_thms, []),
blanchet@49438
   884
           (injectN, inject_thms, iff_attrs @ induct_simp_attrs),
blanchet@49300
   885
           (nchotomyN, [nchotomy_thm], []),
blanchet@53810
   886
           (selN, all_sel_thms, code_nitpick_simp_simp_attrs),
blanchet@53916
   887
           (sel_exhaustN, sel_exhaust_thms, [exhaust_case_names_attr]),
blanchet@53917
   888
           (sel_splitN, sel_split_thms, []),
blanchet@53917
   889
           (sel_split_asmN, sel_split_asm_thms, []),
blanchet@49300
   890
           (splitN, [split_thm], []),
blanchet@49300
   891
           (split_asmN, [split_asm_thm], []),
blanchet@49633
   892
           (splitsN, [split_thm, split_asm_thm], []),
blanchet@49300
   893
           (weak_case_cong_thmsN, [weak_case_cong_thm], cong_attrs)]
blanchet@49300
   894
          |> filter_out (null o #2)
blanchet@49300
   895
          |> map (fn (thmN, thms, attrs) =>
blanchet@49633
   896
            ((qualify true (Binding.name thmN), attrs), [(thms, [])]));
blanchet@49300
   897
blanchet@49300
   898
        val notes' =
blanchet@49300
   899
          [(map (fn th => th RS notE) distinct_thms, safe_elim_attrs)]
blanchet@49300
   900
          |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
blanchet@53867
   901
blanchet@53867
   902
        val ctr_sugar =
blanchet@53867
   903
          {ctrs = ctrs, casex = casex, discs = discs, selss = selss, exhaust = exhaust_thm,
blanchet@53867
   904
           nchotomy = nchotomy_thm, injects = inject_thms, distincts = distinct_thms,
blanchet@53867
   905
           case_thms = case_thms, case_cong = case_cong_thm, weak_case_cong = weak_case_cong_thm,
blanchet@53867
   906
           split = split_thm, split_asm = split_asm_thm, disc_thmss = disc_thmss,
blanchet@53867
   907
           discIs = discI_thms, sel_thmss = sel_thmss, disc_exhausts = disc_exhaust_thms,
blanchet@53916
   908
           sel_exhausts = sel_exhaust_thms, collapses = all_collapse_thms, expands = expand_thms,
blanchet@53917
   909
           sel_splits = sel_split_thms, sel_split_asms = sel_split_asm_thms,
blanchet@53916
   910
           case_conv_ifs = case_conv_if_thms};
blanchet@49019
   911
      in
blanchet@53867
   912
        (ctr_sugar,
blanchet@51819
   913
         lthy
blanchet@51819
   914
         |> not rep_compat ?
blanchet@51819
   915
            (Local_Theory.declaration {syntax = false, pervasive = true}
traytel@51697
   916
               (fn phi => Case_Translation.register
blanchet@51819
   917
                  (Morphism.term phi casex) (map (Morphism.term phi) ctrs)))
blanchet@53867
   918
         |> Local_Theory.notes (notes' @ notes) |> snd
blanchet@53908
   919
         |> register_ctr_sugar fcT_name ctr_sugar)
blanchet@49019
   920
      end;
blanchet@49017
   921
  in
blanchet@49121
   922
    (goalss, after_qed, lthy')
blanchet@49017
   923
  end;
blanchet@49017
   924
blanchet@51781
   925
fun wrap_free_constructors tacss = (fn (goalss, after_qed, lthy) =>
wenzelm@51551
   926
  map2 (map2 (Thm.close_derivation oo Goal.prove_sorry lthy [] [])) goalss tacss
blanchet@51781
   927
  |> (fn thms => after_qed thms lthy)) oo prepare_wrap_free_constructors (K I);
blanchet@49280
   928
blanchet@51781
   929
val wrap_free_constructors_cmd = (fn (goalss, after_qed, lthy) =>
blanchet@49297
   930
  Proof.theorem NONE (snd oo after_qed) (map (map (rpair [])) goalss) lthy) oo
blanchet@51781
   931
  prepare_wrap_free_constructors Syntax.read_term;
blanchet@49297
   932
blanchet@49280
   933
fun parse_bracket_list parser = @{keyword "["} |-- Parse.list parser --|  @{keyword "]"};
blanchet@49111
   934
blanchet@51790
   935
val parse_bindings = parse_bracket_list parse_binding;
blanchet@49280
   936
val parse_bindingss = parse_bracket_list parse_bindings;
blanchet@49280
   937
blanchet@51790
   938
val parse_bound_term = (parse_binding --| @{keyword ":"}) -- Parse.term;
blanchet@49280
   939
val parse_bound_terms = parse_bracket_list parse_bound_term;
blanchet@49280
   940
val parse_bound_termss = parse_bracket_list parse_bound_terms;
blanchet@49017
   941
blanchet@52823
   942
val parse_wrap_free_constructors_options =
blanchet@52969
   943
  Scan.optional (@{keyword "("} |-- Parse.list1 ((@{keyword "no_discs_sels"} >> K (true, false)) ||
blanchet@49633
   944
      (@{keyword "rep_compat"} >> K (false, true))) --| @{keyword ")"}
blanchet@49633
   945
    >> (pairself (exists I) o split_list)) (false, false);
blanchet@49278
   946
blanchet@49017
   947
val _ =
blanchet@51781
   948
  Outer_Syntax.local_theory_to_proof @{command_spec "wrap_free_constructors"}
blanchet@51797
   949
    "wrap an existing freely generated type's constructors"
blanchet@52823
   950
    ((parse_wrap_free_constructors_options -- (@{keyword "["} |-- Parse.list Parse.term --|
blanchet@52823
   951
        @{keyword "]"}) --
blanchet@52968
   952
      parse_binding -- Scan.optional (parse_bindings -- Scan.optional (parse_bindingss --
blanchet@49280
   953
        Scan.optional parse_bound_termss []) ([], [])) ([], ([], [])))
blanchet@51781
   954
     >> wrap_free_constructors_cmd);
blanchet@49017
   955
blanchet@49017
   956
end;