src/HOL/Tools/BNF/bnf_fp_def_sugar.ML
author wenzelm
Fri Mar 06 15:58:56 2015 +0100 (2015-03-06)
changeset 59621 291934bac95e
parent 59582 0fbed69ff081
child 59794 39442248a027
permissions -rw-r--r--
Thm.cterm_of and Thm.ctyp_of operate on local context;
blanchet@55061
     1
(*  Title:      HOL/Tools/BNF/bnf_fp_def_sugar.ML
blanchet@49112
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@57668
     3
    Author:     Martin Desharnais, TU Muenchen
blanchet@57668
     4
    Copyright   2012, 2013, 2014
blanchet@49112
     5
blanchet@49389
     6
Sugared datatype and codatatype constructions.
blanchet@49112
     7
*)
blanchet@49112
     8
blanchet@49636
     9
signature BNF_FP_DEF_SUGAR =
blanchet@49112
    10
sig
desharna@58460
    11
  type fp_ctr_sugar =
desharna@58460
    12
    {ctrXs_Tss: typ list list,
desharna@58460
    13
     ctr_defs: thm list,
desharna@58569
    14
     ctr_sugar: Ctr_Sugar.ctr_sugar,
desharna@58570
    15
     ctr_transfers: thm list,
desharna@58571
    16
     case_transfers: thm list,
desharna@58676
    17
     disc_transfers: thm list,
desharna@58676
    18
     sel_transfers: thm list}
desharna@58458
    19
desharna@58458
    20
  type fp_bnf_sugar =
desharna@58462
    21
    {map_thms: thm list,
desharna@58560
    22
     map_disc_iffs: thm list,
desharna@58672
    23
     map_selss: thm list list,
desharna@58462
    24
     rel_injects: thm list,
desharna@58562
    25
     rel_distincts: thm list,
desharna@58563
    26
     rel_sels: thm list,
desharna@58564
    27
     rel_intros: thm list,
desharna@58565
    28
     rel_cases: thm list,
desharna@58566
    29
     set_thms: thm list,
desharna@58671
    30
     set_selssss: thm list list list list,
desharna@58673
    31
     set_introssss: thm list list list list,
desharna@58568
    32
     set_cases: thm list}
desharna@58458
    33
desharna@58459
    34
  type fp_co_induct_sugar =
desharna@58461
    35
    {co_rec: term,
desharna@58461
    36
     common_co_inducts: thm list,
desharna@58461
    37
     co_inducts: thm list,
desharna@58461
    38
     co_rec_def: thm,
desharna@58459
    39
     co_rec_thms: thm list,
desharna@58459
    40
     co_rec_discs: thm list,
desharna@58572
    41
     co_rec_disc_iffs: thm list,
desharna@58573
    42
     co_rec_selss: thm list list,
desharna@58573
    43
     co_rec_codes: thm list,
desharna@58574
    44
     co_rec_transfers: thm list,
desharna@58734
    45
     co_rec_o_maps: thm list,
desharna@58575
    46
     common_rel_co_inducts: thm list,
desharna@58576
    47
     rel_co_inducts: thm list,
desharna@58577
    48
     common_set_inducts: thm list,
desharna@58577
    49
     set_inducts: thm list}
desharna@58457
    50
blanchet@58180
    51
  type fp_sugar =
blanchet@58180
    52
    {T: typ,
blanchet@58180
    53
     BT: typ,
blanchet@58180
    54
     X: typ,
blanchet@58180
    55
     fp: BNF_Util.fp_kind,
blanchet@58180
    56
     fp_res_index: int,
blanchet@58180
    57
     fp_res: BNF_FP_Util.fp_result,
blanchet@58180
    58
     pre_bnf: BNF_Def.bnf,
desharna@58674
    59
     fp_bnf: BNF_Def.bnf,
blanchet@58180
    60
     absT_info: BNF_Comp.absT_info,
blanchet@58180
    61
     fp_nesting_bnfs: BNF_Def.bnf list,
blanchet@58180
    62
     live_nesting_bnfs: BNF_Def.bnf list,
desharna@58457
    63
     fp_ctr_sugar: fp_ctr_sugar,
desharna@58457
    64
     fp_bnf_sugar: fp_bnf_sugar,
desharna@58457
    65
     fp_co_induct_sugar: fp_co_induct_sugar};
blanchet@58180
    66
blanchet@59276
    67
  val co_induct_of: 'a list -> 'a
blanchet@59276
    68
  val strong_co_induct_of: 'a list -> 'a
blanchet@59276
    69
blanchet@58180
    70
  val morph_fp_sugar: morphism -> fp_sugar -> fp_sugar
blanchet@58180
    71
  val transfer_fp_sugar: theory -> fp_sugar -> fp_sugar
blanchet@58180
    72
  val fp_sugar_of: Proof.context -> string -> fp_sugar option
blanchet@58180
    73
  val fp_sugar_of_global: theory -> string -> fp_sugar option
blanchet@58180
    74
  val fp_sugars_of: Proof.context -> fp_sugar list
blanchet@58180
    75
  val fp_sugars_of_global: theory -> fp_sugar list
wenzelm@58659
    76
  val fp_sugars_interpretation: string ->
blanchet@58180
    77
    (fp_sugar list -> local_theory -> local_theory)-> theory -> theory
blanchet@58188
    78
  val interpret_fp_sugars: (string -> bool) -> fp_sugar list -> local_theory -> local_theory
blanchet@58182
    79
  val register_fp_sugars_raw: fp_sugar list -> local_theory -> local_theory
blanchet@58188
    80
  val register_fp_sugars: (string -> bool) -> fp_sugar list -> local_theory -> local_theory
blanchet@51852
    81
blanchet@59276
    82
  val mk_parametricity_goal: Proof.context -> term list -> term -> term -> term
traytel@53106
    83
blanchet@52868
    84
  val flat_corec_preds_predsss_gettersss: 'a list -> 'a list list list -> 'a list list list ->
blanchet@52868
    85
    'a list
blanchet@58230
    86
  val liveness_of_fp_bnf: int -> BNF_Def.bnf -> bool list
blanchet@57397
    87
  val nesting_bnfs: Proof.context -> typ list list list -> typ list -> BNF_Def.bnf list
blanchet@53746
    88
blanchet@58214
    89
  type lfp_sugar_thms = (thm list * thm * Token.src list) * (thm list list * Token.src list)
blanchet@53746
    90
blanchet@54256
    91
  val morph_lfp_sugar_thms: morphism -> lfp_sugar_thms -> lfp_sugar_thms
blanchet@58115
    92
  val transfer_lfp_sugar_thms: theory -> lfp_sugar_thms -> lfp_sugar_thms
blanchet@54256
    93
blanchet@53746
    94
  type gfp_sugar_thms =
wenzelm@58011
    95
    ((thm list * thm) list * (Token.src list * Token.src list))
desharna@57489
    96
    * thm list list
desharna@57489
    97
    * thm list list
wenzelm@58011
    98
    * (thm list list * Token.src list)
wenzelm@58011
    99
    * (thm list list list * Token.src list)
blanchet@53746
   100
blanchet@54256
   101
  val morph_gfp_sugar_thms: morphism -> gfp_sugar_thms -> gfp_sugar_thms
blanchet@58115
   102
  val transfer_gfp_sugar_thms: theory -> gfp_sugar_thms -> gfp_sugar_thms
blanchet@54256
   103
blanchet@55867
   104
  val mk_co_recs_prelims: BNF_Util.fp_kind -> typ list list list -> typ list -> typ list ->
blanchet@55867
   105
     typ list -> typ list -> int list -> int list list -> term list -> Proof.context ->
blanchet@55867
   106
     (term list
blanchet@55867
   107
      * (typ list list * typ list list list list * term list list * term list list list list) option
blanchet@55862
   108
      * (string * term list * term list list
desharna@58448
   109
         * (((term list list * term list list * term list list list list * term list list list list)
desharna@58448
   110
             * term list list list) * typ list)) option)
blanchet@55862
   111
     * Proof.context
blanchet@55772
   112
  val repair_nullary_single_ctr: typ list list -> typ list list
blanchet@55867
   113
  val mk_corec_p_pred_types: typ list -> int list -> typ list list
blanchet@55867
   114
  val mk_corec_fun_arg_types: typ list list list -> typ list -> typ list -> typ list -> int list ->
traytel@55803
   115
    int list list -> term ->
traytel@55803
   116
    typ list list
traytel@55803
   117
    * (typ list list list list * typ list list list * typ list list list list * typ list)
blanchet@58210
   118
  val define_co_rec_as: BNF_Util.fp_kind -> typ list -> typ -> binding -> term -> local_theory ->
blanchet@58209
   119
    (term * thm) * local_theory
blanchet@55867
   120
  val define_rec:
blanchet@56641
   121
    typ list list * typ list list list list * term list list * term list list list list ->
blanchet@55862
   122
    (string -> binding) -> typ list -> typ list -> term list -> term -> Proof.context ->
blanchet@55864
   123
    (term * thm) * Proof.context
blanchet@55867
   124
  val define_corec: 'a * term list * term list list
desharna@58448
   125
      * (((term list list * term list list * term list list list list * term list list list list)
desharna@58448
   126
          * term list list list) * typ list) -> (string -> binding) -> 'b list -> typ list ->
desharna@58448
   127
    term list -> term -> local_theory -> (term * thm) * local_theory
blanchet@58214
   128
  val mk_induct_attrs: term list list -> Token.src list
blanchet@58283
   129
  val mk_coinduct_attrs: typ list -> term list list -> term list list -> int list list ->
blanchet@58283
   130
    Token.src list * Token.src list
blanchet@58335
   131
  val derive_induct_recs_thms_for_types: (string -> bool) -> BNF_Def.bnf list ->
blanchet@55867
   132
     ('a * typ list list list list * term list list * 'b) option -> thm -> thm list ->
blanchet@55862
   133
     BNF_Def.bnf list -> BNF_Def.bnf list -> typ list -> typ list -> typ list ->
blanchet@55862
   134
     typ list list list -> thm list -> thm list -> thm list -> term list list -> thm list list ->
blanchet@55864
   135
     term list -> thm list -> Proof.context -> lfp_sugar_thms
blanchet@55867
   136
  val derive_coinduct_corecs_thms_for_types: BNF_Def.bnf list ->
desharna@58448
   137
    string * term list * term list list
desharna@58448
   138
      * (((term list list * term list list * term list list list list * term list list list list)
desharna@58448
   139
          * term list list list) * typ list) ->
blanchet@55867
   140
    thm -> thm list -> thm list -> thm list -> BNF_Def.bnf list -> typ list -> typ list ->
traytel@55803
   141
    typ list -> typ list list list -> int list list -> int list list -> int list -> thm list ->
blanchet@55864
   142
    thm list -> (thm -> thm) -> thm list list -> Ctr_Sugar.ctr_sugar list -> term list ->
blanchet@56347
   143
    thm list -> (thm list -> thm list) -> Proof.context -> gfp_sugar_thms
blanchet@55469
   144
blanchet@55575
   145
  val co_datatypes: BNF_Util.fp_kind -> (mixfix list -> binding list -> binding list ->
blanchet@52207
   146
      binding list list -> binding list -> (string * sort) list -> typ list * typ list list ->
traytel@55803
   147
      BNF_Def.bnf list -> BNF_Comp.absT_info list -> local_theory ->
traytel@55803
   148
      BNF_FP_Util.fp_result * local_theory) ->
blanchet@58189
   149
    Ctr_Sugar.ctr_options
blanchet@57206
   150
    * ((((((binding option * (typ * sort)) list * binding) * mixfix)
blanchet@57206
   151
         * ((binding, binding * typ) Ctr_Sugar.ctr_spec * mixfix) list) * (binding * binding))
blanchet@57206
   152
       * term list) list ->
blanchet@49297
   153
    local_theory -> local_theory
blanchet@55575
   154
  val parse_co_datatype_cmd: BNF_Util.fp_kind -> (mixfix list -> binding list -> binding list ->
blanchet@51867
   155
      binding list list -> binding list -> (string * sort) list -> typ list * typ list list ->
traytel@55803
   156
      BNF_Def.bnf list -> BNF_Comp.absT_info list -> local_theory ->
traytel@55803
   157
      BNF_FP_Util.fp_result * local_theory) ->
blanchet@49308
   158
    (local_theory -> local_theory) parser
blanchet@49112
   159
end;
blanchet@49112
   160
blanchet@49636
   161
structure BNF_FP_Def_Sugar : BNF_FP_DEF_SUGAR =
blanchet@49112
   162
struct
blanchet@49112
   163
blanchet@54006
   164
open Ctr_Sugar
blanchet@55571
   165
open BNF_FP_Rec_Sugar_Util
blanchet@49119
   166
open BNF_Util
blanchet@53222
   167
open BNF_Comp
blanchet@49214
   168
open BNF_Def
blanchet@51850
   169
open BNF_FP_Util
blanchet@49636
   170
open BNF_FP_Def_Sugar_Tactics
blanchet@49119
   171
blanchet@51788
   172
val EqN = "Eq_";
desharna@57489
   173
desharna@58093
   174
val case_transferN = "case_transfer";
desharna@57999
   175
val ctr_transferN = "ctr_transfer";
desharna@58095
   176
val disc_transferN = "disc_transfer";
desharna@58676
   177
val sel_transferN = "sel_transfer";
desharna@57489
   178
val corec_codeN = "corec_code";
desharna@58448
   179
val corec_transferN = "corec_transfer";
blanchet@57983
   180
val map_disc_iffN = "map_disc_iff";
desharna@58734
   181
val map_o_corecN = "map_o_corec";
blanchet@57983
   182
val map_selN = "map_sel";
desharna@58732
   183
val rec_o_mapN = "rec_o_map";
desharna@58446
   184
val rec_transferN = "rec_transfer";
desharna@57893
   185
val set_casesN = "set_cases";
desharna@57891
   186
val set_introsN = "set_intros";
desharna@57700
   187
val set_inductN = "set_induct";
blanchet@57983
   188
val set_selN = "set_sel";
blanchet@51777
   189
desharna@58460
   190
type fp_ctr_sugar =
desharna@58460
   191
  {ctrXs_Tss: typ list list,
desharna@58460
   192
   ctr_defs: thm list,
desharna@58569
   193
   ctr_sugar: Ctr_Sugar.ctr_sugar,
desharna@58570
   194
   ctr_transfers: thm list,
desharna@58571
   195
   case_transfers: thm list,
desharna@58676
   196
   disc_transfers: thm list,
desharna@58676
   197
   sel_transfers: thm list};
desharna@58458
   198
desharna@58458
   199
type fp_bnf_sugar =
desharna@58462
   200
  {map_thms: thm list,
desharna@58560
   201
   map_disc_iffs: thm list,
desharna@58672
   202
   map_selss: thm list list,
desharna@58462
   203
   rel_injects: thm list,
desharna@58562
   204
   rel_distincts: thm list,
desharna@58563
   205
   rel_sels: thm list,
desharna@58564
   206
   rel_intros: thm list,
desharna@58565
   207
   rel_cases: thm list,
desharna@58566
   208
   set_thms: thm list,
desharna@58671
   209
   set_selssss: thm list list list list,
desharna@58673
   210
   set_introssss: thm list list list list,
desharna@58568
   211
   set_cases: thm list};
desharna@58458
   212
desharna@58459
   213
type fp_co_induct_sugar =
desharna@58461
   214
  {co_rec: term,
desharna@58461
   215
   common_co_inducts: thm list,
desharna@58461
   216
   co_inducts: thm list,
desharna@58461
   217
   co_rec_def: thm,
desharna@58459
   218
   co_rec_thms: thm list,
desharna@58459
   219
   co_rec_discs: thm list,
desharna@58572
   220
   co_rec_disc_iffs: thm list,
desharna@58573
   221
   co_rec_selss: thm list list,
desharna@58573
   222
   co_rec_codes: thm list,
desharna@58574
   223
   co_rec_transfers: thm list,
desharna@58734
   224
   co_rec_o_maps: thm list,
desharna@58575
   225
   common_rel_co_inducts: thm list,
desharna@58576
   226
   rel_co_inducts: thm list,
desharna@58577
   227
   common_set_inducts: thm list,
desharna@58577
   228
   set_inducts: thm list};
desharna@58457
   229
blanchet@58180
   230
type fp_sugar =
blanchet@58180
   231
  {T: typ,
blanchet@58180
   232
   BT: typ,
blanchet@58180
   233
   X: typ,
blanchet@58180
   234
   fp: fp_kind,
blanchet@58180
   235
   fp_res_index: int,
blanchet@58180
   236
   fp_res: fp_result,
blanchet@58180
   237
   pre_bnf: bnf,
desharna@58674
   238
   fp_bnf: bnf,
blanchet@58180
   239
   absT_info: absT_info,
blanchet@58180
   240
   fp_nesting_bnfs: bnf list,
blanchet@58180
   241
   live_nesting_bnfs: bnf list,
desharna@58457
   242
   fp_ctr_sugar: fp_ctr_sugar,
desharna@58457
   243
   fp_bnf_sugar: fp_bnf_sugar,
desharna@58457
   244
   fp_co_induct_sugar: fp_co_induct_sugar};
blanchet@58180
   245
blanchet@59276
   246
fun co_induct_of (i :: _) = i;
blanchet@59276
   247
fun strong_co_induct_of [_, s] = s;
blanchet@59276
   248
desharna@58672
   249
fun morph_fp_bnf_sugar phi ({map_thms, map_disc_iffs, map_selss, rel_injects, rel_distincts,
desharna@58673
   250
    rel_sels, rel_intros, rel_cases, set_thms, set_selssss, set_introssss,
desharna@58673
   251
    set_cases} : fp_bnf_sugar) =
desharna@58462
   252
  {map_thms = map (Morphism.thm phi) map_thms,
desharna@58560
   253
   map_disc_iffs = map (Morphism.thm phi) map_disc_iffs,
desharna@58672
   254
   map_selss = map (map (Morphism.thm phi)) map_selss,
desharna@58462
   255
   rel_injects = map (Morphism.thm phi) rel_injects,
desharna@58562
   256
   rel_distincts = map (Morphism.thm phi) rel_distincts,
desharna@58563
   257
   rel_sels = map (Morphism.thm phi) rel_sels,
desharna@58564
   258
   rel_intros = map (Morphism.thm phi) rel_intros,
desharna@58565
   259
   rel_cases = map (Morphism.thm phi) rel_cases,
desharna@58566
   260
   set_thms = map (Morphism.thm phi) set_thms,
desharna@58671
   261
   set_selssss = map (map (map (map (Morphism.thm phi)))) set_selssss,
desharna@58673
   262
   set_introssss = map (map (map (map (Morphism.thm phi)))) set_introssss,
desharna@58568
   263
   set_cases = map (Morphism.thm phi) set_cases};
desharna@58458
   264
desharna@58461
   265
fun morph_fp_co_induct_sugar phi ({co_rec, common_co_inducts, co_inducts, co_rec_def, co_rec_thms,
desharna@58734
   266
    co_rec_discs, co_rec_disc_iffs, co_rec_selss, co_rec_codes, co_rec_transfers, co_rec_o_maps,
desharna@58577
   267
    common_rel_co_inducts, rel_co_inducts, common_set_inducts, set_inducts} : fp_co_induct_sugar) =
desharna@58461
   268
  {co_rec = Morphism.term phi co_rec,
desharna@58461
   269
   common_co_inducts = map (Morphism.thm phi) common_co_inducts,
desharna@58461
   270
   co_inducts = map (Morphism.thm phi) co_inducts,
desharna@58461
   271
   co_rec_def = Morphism.thm phi co_rec_def,
desharna@58459
   272
   co_rec_thms = map (Morphism.thm phi) co_rec_thms,
desharna@58459
   273
   co_rec_discs = map (Morphism.thm phi) co_rec_discs,
desharna@58572
   274
   co_rec_disc_iffs = map (Morphism.thm phi) co_rec_disc_iffs,
desharna@58573
   275
   co_rec_selss = map (map (Morphism.thm phi)) co_rec_selss,
desharna@58573
   276
   co_rec_codes = map (Morphism.thm phi) co_rec_codes,
desharna@58574
   277
   co_rec_transfers = map (Morphism.thm phi) co_rec_transfers,
desharna@58734
   278
   co_rec_o_maps = map (Morphism.thm phi) co_rec_o_maps,
desharna@58575
   279
   common_rel_co_inducts = map (Morphism.thm phi) common_rel_co_inducts,
desharna@58576
   280
   rel_co_inducts = map (Morphism.thm phi) rel_co_inducts,
desharna@58577
   281
   common_set_inducts = map (Morphism.thm phi) common_set_inducts,
desharna@58577
   282
   set_inducts = map (Morphism.thm phi) set_inducts};
desharna@58459
   283
desharna@58571
   284
fun morph_fp_ctr_sugar phi ({ctrXs_Tss, ctr_defs, ctr_sugar, ctr_transfers, case_transfers,
desharna@58676
   285
    disc_transfers, sel_transfers} : fp_ctr_sugar) =
desharna@58460
   286
  {ctrXs_Tss = map (map (Morphism.typ phi)) ctrXs_Tss,
desharna@58460
   287
   ctr_defs = map (Morphism.thm phi) ctr_defs,
desharna@58569
   288
   ctr_sugar = morph_ctr_sugar phi ctr_sugar,
desharna@58570
   289
   ctr_transfers = map (Morphism.thm phi) ctr_transfers,
desharna@58571
   290
   case_transfers = map (Morphism.thm phi) case_transfers,
desharna@58676
   291
   disc_transfers = map (Morphism.thm phi) disc_transfers,
desharna@58676
   292
   sel_transfers = map (Morphism.thm phi) sel_transfers};
desharna@58460
   293
desharna@58674
   294
fun morph_fp_sugar phi ({T, BT, X, fp, fp_res, fp_res_index, pre_bnf, fp_bnf, absT_info,
desharna@58674
   295
    fp_nesting_bnfs, live_nesting_bnfs, fp_ctr_sugar, fp_bnf_sugar,
desharna@58460
   296
    fp_co_induct_sugar} : fp_sugar) =
blanchet@58180
   297
  {T = Morphism.typ phi T,
blanchet@58180
   298
   BT = Morphism.typ phi BT,
blanchet@58180
   299
   X = Morphism.typ phi X,
blanchet@58180
   300
   fp = fp,
blanchet@58180
   301
   fp_res = morph_fp_result phi fp_res,
blanchet@58180
   302
   fp_res_index = fp_res_index,
blanchet@58180
   303
   pre_bnf = morph_bnf phi pre_bnf,
desharna@58674
   304
   fp_bnf = morph_bnf phi fp_bnf,
blanchet@58180
   305
   absT_info = morph_absT_info phi absT_info,
blanchet@58180
   306
   fp_nesting_bnfs = map (morph_bnf phi) fp_nesting_bnfs,
blanchet@58180
   307
   live_nesting_bnfs = map (morph_bnf phi) live_nesting_bnfs,
desharna@58460
   308
   fp_ctr_sugar = morph_fp_ctr_sugar phi fp_ctr_sugar,
desharna@58458
   309
   fp_bnf_sugar = morph_fp_bnf_sugar phi fp_bnf_sugar,
desharna@58459
   310
   fp_co_induct_sugar = morph_fp_co_induct_sugar phi fp_co_induct_sugar};
blanchet@58180
   311
blanchet@58180
   312
val transfer_fp_sugar = morph_fp_sugar o Morphism.transfer_morphism;
blanchet@58180
   313
blanchet@51823
   314
structure Data = Generic_Data
blanchet@51823
   315
(
blanchet@51840
   316
  type T = fp_sugar Symtab.table;
blanchet@51823
   317
  val empty = Symtab.empty;
blanchet@51823
   318
  val extend = I;
blanchet@55394
   319
  fun merge data : T = Symtab.merge (K true) data;
blanchet@51823
   320
);
blanchet@51823
   321
blanchet@58116
   322
fun fp_sugar_of_generic context =
blanchet@58116
   323
  Option.map (transfer_fp_sugar (Context.theory_of context)) o Symtab.lookup (Data.get context)
blanchet@58116
   324
blanchet@58116
   325
fun fp_sugars_of_generic context =
blanchet@58116
   326
  Symtab.fold (cons o transfer_fp_sugar (Context.theory_of context) o snd) (Data.get context) [];
blanchet@53907
   327
blanchet@58116
   328
val fp_sugar_of = fp_sugar_of_generic o Context.Proof;
blanchet@58116
   329
val fp_sugar_of_global = fp_sugar_of_generic o Context.Theory;
blanchet@58116
   330
blanchet@58116
   331
val fp_sugars_of = fp_sugars_of_generic o Context.Proof;
blanchet@58116
   332
val fp_sugars_of_global = fp_sugars_of_generic o Context.Theory;
blanchet@51823
   333
wenzelm@58659
   334
structure FP_Sugar_Plugin = Plugin(type T = fp_sugar list);
blanchet@56347
   335
wenzelm@58659
   336
fun fp_sugars_interpretation name f =
wenzelm@58659
   337
  FP_Sugar_Plugin.interpretation name
wenzelm@58659
   338
    (fn fp_sugars => fn lthy =>
wenzelm@58659
   339
      f (map (transfer_fp_sugar (Proof_Context.theory_of lthy)) fp_sugars) lthy);
blanchet@56376
   340
wenzelm@58659
   341
val interpret_fp_sugars = FP_Sugar_Plugin.data;
blanchet@56347
   342
blanchet@58182
   343
fun register_fp_sugars_raw fp_sugars =
blanchet@56648
   344
  fold (fn fp_sugar as {T = Type (s, _), ...} =>
blanchet@56637
   345
      Local_Theory.declaration {syntax = false, pervasive = true}
blanchet@56637
   346
        (fn phi => Data.map (Symtab.update (s, morph_fp_sugar phi fp_sugar))))
blanchet@58182
   347
    fp_sugars;
blanchet@58182
   348
blanchet@58189
   349
fun register_fp_sugars plugins fp_sugars =
blanchet@58189
   350
  register_fp_sugars_raw fp_sugars #> interpret_fp_sugars plugins fp_sugars;
blanchet@51823
   351
blanchet@58189
   352
fun interpret_bnfs_register_fp_sugars plugins Ts BTs Xs fp pre_bnfs absT_infos fp_nesting_bnfs
desharna@58462
   353
    live_nesting_bnfs fp_res ctrXs_Tsss ctr_defss ctr_sugars co_recs co_rec_defs map_thmss
blanchet@58177
   354
    common_co_inducts co_inductss co_rec_thmss co_rec_discss co_rec_selsss rel_injectss
desharna@58672
   355
    rel_distinctss map_disc_iffss map_selsss rel_selss rel_intross rel_casess set_thmss set_selsssss
desharna@58673
   356
    set_introsssss set_casess ctr_transferss case_transferss disc_transferss co_rec_disc_iffss
desharna@58577
   357
    co_rec_codess co_rec_transferss common_rel_co_inducts rel_co_inductss common_set_inducts
desharna@58734
   358
    set_inductss sel_transferss co_rec_o_mapss noted =
blanchet@56637
   359
  let
blanchet@56637
   360
    val fp_sugars =
blanchet@56637
   361
      map_index (fn (kk, T) =>
blanchet@56648
   362
        {T = T, BT = nth BTs kk, X = nth Xs kk, fp = fp, fp_res = fp_res, fp_res_index = kk,
blanchet@57397
   363
         pre_bnf = nth pre_bnfs kk, absT_info = nth absT_infos kk,
desharna@58674
   364
         fp_bnf = nth (#bnfs fp_res) kk,
blanchet@57397
   365
         fp_nesting_bnfs = fp_nesting_bnfs, live_nesting_bnfs = live_nesting_bnfs,
desharna@58460
   366
         fp_ctr_sugar =
desharna@58460
   367
           {ctrXs_Tss = nth ctrXs_Tsss kk,
desharna@58460
   368
            ctr_defs = nth ctr_defss kk,
desharna@58569
   369
            ctr_sugar = nth ctr_sugars kk,
desharna@58570
   370
            ctr_transfers = nth ctr_transferss kk,
desharna@58571
   371
            case_transfers = nth case_transferss kk,
desharna@58676
   372
            disc_transfers = nth disc_transferss kk,
desharna@58676
   373
            sel_transfers = nth sel_transferss kk},
desharna@58459
   374
         fp_bnf_sugar =
desharna@58462
   375
           {map_thms = nth map_thmss kk,
desharna@58560
   376
            map_disc_iffs = nth map_disc_iffss kk,
desharna@58672
   377
            map_selss = nth map_selsss kk,
desharna@58462
   378
            rel_injects = nth rel_injectss kk,
desharna@58562
   379
            rel_distincts = nth rel_distinctss kk,
desharna@58563
   380
            rel_sels = nth rel_selss kk,
desharna@58564
   381
            rel_intros = nth rel_intross kk,
desharna@58565
   382
            rel_cases = nth rel_casess kk,
desharna@58566
   383
            set_thms = nth set_thmss kk,
desharna@58671
   384
            set_selssss = nth set_selsssss kk,
desharna@58673
   385
            set_introssss = nth set_introsssss kk,
desharna@58568
   386
            set_cases = nth set_casess kk},
desharna@58459
   387
         fp_co_induct_sugar =
desharna@58461
   388
           {co_rec = nth co_recs kk,
desharna@58461
   389
            common_co_inducts = common_co_inducts,
desharna@58461
   390
            co_inducts = nth co_inductss kk,
desharna@58461
   391
            co_rec_def = nth co_rec_defs kk,
desharna@58459
   392
            co_rec_thms = nth co_rec_thmss kk,
desharna@58459
   393
            co_rec_discs = nth co_rec_discss kk,
desharna@58572
   394
            co_rec_disc_iffs = nth co_rec_disc_iffss kk,
desharna@58573
   395
            co_rec_selss = nth co_rec_selsss kk,
desharna@58573
   396
            co_rec_codes = nth co_rec_codess kk,
desharna@58574
   397
            co_rec_transfers = nth co_rec_transferss kk,
desharna@58734
   398
            co_rec_o_maps = nth co_rec_o_mapss kk,
desharna@58575
   399
            common_rel_co_inducts = common_rel_co_inducts,
desharna@58576
   400
            rel_co_inducts = nth rel_co_inductss kk,
desharna@58577
   401
            common_set_inducts = common_set_inducts,
desharna@58577
   402
            set_inducts = nth set_inductss kk}}
blanchet@57633
   403
        |> morph_fp_sugar (substitute_noted_thm noted)) Ts;
blanchet@56637
   404
  in
blanchet@58182
   405
    register_fp_sugars_raw fp_sugars
blanchet@58189
   406
    #> fold (interpret_bnf plugins) (#bnfs fp_res)
blanchet@58189
   407
    #> interpret_fp_sugars plugins fp_sugars
blanchet@56637
   408
  end;
blanchet@51824
   409
blanchet@49622
   410
fun quasi_unambiguous_case_names names =
blanchet@49622
   411
  let
blanchet@49622
   412
    val ps = map (`Long_Name.base_name) names;
blanchet@49622
   413
    val dups = Library.duplicates (op =) (map fst ps);
blanchet@49622
   414
    fun underscore s =
blanchet@49622
   415
      let val ss = space_explode Long_Name.separator s in
blanchet@49622
   416
        space_implode "_" (drop (length ss - 2) ss)
blanchet@49622
   417
      end;
blanchet@49622
   418
  in
blanchet@49622
   419
    map (fn (base, full) => if member (op =) dups base then underscore full else base) ps
blanchet@58285
   420
    |> Name.variant_list []
blanchet@49622
   421
  end;
blanchet@49622
   422
blanchet@58180
   423
fun zipper_map f =
blanchet@58180
   424
  let
blanchet@58180
   425
    fun zed _ [] = []
blanchet@58686
   426
      | zed xs (y :: ys) = f (xs, y, ys) :: zed (xs @ [y]) ys;
blanchet@58180
   427
  in zed [] end;
blanchet@58180
   428
desharna@58912
   429
fun unfla xss = fold_map (fn _ => fn (c :: cs) => (c,cs)) xss;
blanchet@58686
   430
fun unflat xss = fold_map unfla xss;
blanchet@58686
   431
fun unflatt xsss = fold_map unflat xsss;
blanchet@58686
   432
fun unflattt xssss = fold_map unflatt xssss;
desharna@58671
   433
desharna@58675
   434
fun ctr_sugar_kind_of_fp_kind Least_FP = Datatype
blanchet@58686
   435
  | ctr_sugar_kind_of_fp_kind Greatest_FP = Codatatype;
desharna@58675
   436
blanchet@58265
   437
fun uncurry_thm 0 thm = thm
blanchet@58265
   438
  | uncurry_thm 1 thm = thm
blanchet@58265
   439
  | uncurry_thm n thm = rotate_prems ~1 (uncurry_thm (n - 1) (rotate_prems 1 (conjI RS thm)));
blanchet@58265
   440
blanchet@58180
   441
fun choose_binary_fun fs AB =
blanchet@58180
   442
  find_first (fastype_of #> binder_types #> (fn [A, B] => AB = (A, B))) fs;
blanchet@58180
   443
fun build_binary_fun_app fs t u =
blanchet@58180
   444
  Option.map (rapp u o rapp t) (choose_binary_fun fs (fastype_of t, fastype_of u));
blanchet@58180
   445
blanchet@58180
   446
fun build_the_rel rel_table ctxt Rs Ts A B =
blanchet@58180
   447
  build_rel rel_table ctxt Ts (the o choose_binary_fun Rs) (A, B);
blanchet@58180
   448
fun build_rel_app ctxt Rs Ts t u =
blanchet@58180
   449
  build_the_rel [] ctxt Rs Ts (fastype_of t) (fastype_of u) $ t $ u;
blanchet@58180
   450
blanchet@58180
   451
fun mk_parametricity_goal ctxt Rs t u =
blanchet@58180
   452
  let val prem = build_the_rel [] ctxt Rs [] (fastype_of t) (fastype_of u) in
blanchet@58180
   453
    HOLogic.mk_Trueprop (prem $ t $ u)
blanchet@58180
   454
  end;
blanchet@58180
   455
blanchet@58284
   456
val name_of_set = name_of_const "set function" domain_type;
blanchet@58180
   457
blanchet@49591
   458
val mp_conj = @{thm mp_conj};
blanchet@49591
   459
blanchet@55397
   460
val fundefcong_attrs = @{attributes [fundef_cong]};
blanchet@54145
   461
val nitpicksimp_attrs = @{attributes [nitpick_simp]};
blanchet@49300
   462
val simp_attrs = @{attributes [simp]};
blanchet@49300
   463
blanchet@49297
   464
val lists_bmoc = fold (fn xs => fn t => Term.list_comb (t, xs));
blanchet@49202
   465
blanchet@55871
   466
fun flat_corec_predss_getterss qss gss = maps (op @) (qss ~~ gss);
blanchet@51829
   467
blanchet@55871
   468
fun flat_corec_preds_predsss_gettersss [] [qss] [gss] = flat_corec_predss_getterss qss gss
blanchet@55871
   469
  | flat_corec_preds_predsss_gettersss (p :: ps) (qss :: qsss) (gss :: gsss) =
blanchet@55871
   470
    p :: flat_corec_predss_getterss qss gss @ flat_corec_preds_predsss_gettersss ps qsss gsss;
blanchet@51829
   471
blanchet@49585
   472
fun mk_flip (x, Type (_, [T1, Type (_, [T2, T3])])) =
blanchet@49585
   473
  Abs ("x", T1, Abs ("y", T2, Var (x, T2 --> T1 --> T3) $ Bound 0 $ Bound 1));
blanchet@49585
   474
blanchet@49585
   475
fun flip_rels lthy n thm =
blanchet@49585
   476
  let
wenzelm@59582
   477
    val Rs = Term.add_vars (Thm.prop_of thm) [];
blanchet@49585
   478
    val Rs' = rev (drop (length Rs - n) Rs);
wenzelm@59621
   479
    val cRs = map (fn f => (Thm.cterm_of lthy (Var f), Thm.cterm_of lthy (mk_flip f))) Rs';
blanchet@49585
   480
  in
blanchet@49585
   481
    Drule.cterm_instantiate cRs thm
blanchet@49585
   482
  end;
blanchet@49585
   483
blanchet@49536
   484
fun mk_ctor_or_dtor get_T Ts t =
blanchet@49536
   485
  let val Type (_, Ts0) = get_T (fastype_of t) in
blanchet@49536
   486
    Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@49536
   487
  end;
blanchet@49536
   488
blanchet@49536
   489
val mk_ctor = mk_ctor_or_dtor range_type;
blanchet@49536
   490
val mk_dtor = mk_ctor_or_dtor domain_type;
blanchet@49536
   491
blanchet@55867
   492
fun mk_xtor_co_recs thy fp fpTs Cs ts0 =
blanchet@51911
   493
  let
blanchet@51911
   494
    val nn = length fpTs;
blanchet@51911
   495
    val (fpTs0, Cs0) =
blanchet@52207
   496
      map ((fp = Greatest_FP ? swap) o dest_funT o snd o strip_typeN nn o fastype_of) ts0
blanchet@51911
   497
      |> split_list;
blanchet@51911
   498
    val rho = tvar_subst thy (fpTs0 @ Cs0) (fpTs @ Cs);
blanchet@51911
   499
  in
blanchet@52170
   500
    map (Term.subst_TVars rho) ts0
blanchet@51911
   501
  end;
blanchet@51827
   502
blanchet@57665
   503
fun mk_set Ts t =
blanchet@57665
   504
  subst_nonatomic_types (snd (Term.dest_Type (domain_type (fastype_of t))) ~~ Ts) t;
blanchet@57665
   505
blanchet@52347
   506
fun liveness_of_fp_bnf n bnf =
blanchet@52347
   507
  (case T_of_bnf bnf of
blanchet@52347
   508
    Type (_, Ts) => map (not o member (op =) (deads_of_bnf bnf)) Ts
blanchet@52347
   509
  | _ => replicate n false);
blanchet@52347
   510
blanchet@55700
   511
fun cannot_merge_types fp =
blanchet@55700
   512
  error ("Mutually " ^ co_prefix fp ^ "recursive types must have the same type parameters");
blanchet@52347
   513
blanchet@55700
   514
fun merge_type_arg fp T T' = if T = T' then T else cannot_merge_types fp;
blanchet@52347
   515
blanchet@55700
   516
fun merge_type_args fp (As, As') =
blanchet@55700
   517
  if length As = length As' then map2 (merge_type_arg fp) As As' else cannot_merge_types fp;
blanchet@52347
   518
blanchet@57200
   519
fun type_args_named_constrained_of_spec (((((ncAs, _), _), _), _), _) = ncAs;
blanchet@57200
   520
fun type_binding_of_spec (((((_, b), _), _), _), _) = b;
blanchet@57206
   521
fun mixfix_of_spec ((((_, mx), _), _), _) = mx;
blanchet@57206
   522
fun mixfixed_ctr_specs_of_spec (((_, mx_ctr_specs), _), _) = mx_ctr_specs;
blanchet@57206
   523
fun map_binding_of_spec ((_, (b, _)), _) = b;
blanchet@57206
   524
fun rel_binding_of_spec ((_, (_, b)), _) = b;
blanchet@57200
   525
fun sel_default_eqs_of_spec (_, ts) = ts;
blanchet@52347
   526
blanchet@57397
   527
fun add_nesting_bnf_names Us =
blanchet@52347
   528
  let
blanchet@52347
   529
    fun add (Type (s, Ts)) ss =
blanchet@52347
   530
        let val (needs, ss') = fold_map add Ts ss in
blanchet@52347
   531
          if exists I needs then (true, insert (op =) s ss') else (false, ss')
blanchet@52347
   532
        end
blanchet@52347
   533
      | add T ss = (member (op =) Us T, ss);
blanchet@52347
   534
  in snd oo add end;
blanchet@52347
   535
blanchet@57397
   536
fun nesting_bnfs ctxt ctr_Tsss Us =
blanchet@57397
   537
  map_filter (bnf_of ctxt) (fold (fold (fold (add_nesting_bnf_names Us))) ctr_Tsss []);
blanchet@52347
   538
blanchet@54237
   539
fun indexify proj xs f p = f (find_index (curry (op =) (proj p)) xs) p;
blanchet@52347
   540
blanchet@58346
   541
fun massage_simple_notes base =
blanchet@58346
   542
  filter_out (null o #2)
blanchet@58346
   543
  #> map (fn (thmN, thms, f_attrs) =>
blanchet@58346
   544
    ((Binding.qualify true base (Binding.name thmN), []),
blanchet@58346
   545
     map_index (fn (i, thm) => ([thm], f_attrs i)) thms));
blanchet@58346
   546
blanchet@58346
   547
fun massage_multi_notes b_names Ts =
blanchet@58346
   548
  maps (fn (thmN, thmss, attrs) =>
wenzelm@58634
   549
    @{map 3} (fn b_name => fn Type (T_name, _) => fn thms =>
blanchet@58346
   550
        ((Binding.qualify true b_name (Binding.name thmN), attrs T_name), [(thms, [])]))
blanchet@58346
   551
      b_names Ts thmss)
blanchet@58346
   552
  #> filter_out (null o fst o hd o snd);
blanchet@58346
   553
desharna@58676
   554
fun derive_map_set_rel_thms plugins fp n live As Bs abs_inverses ctr_defs' fp_nesting_set_maps
blanchet@58347
   555
    live_nesting_map_id0s live_nesting_set_maps live_nesting_rel_eqs fp_b_name fp_bnf fpT ctor
blanchet@58347
   556
    ctor_dtor dtor_ctor pre_map_def pre_set_defs pre_rel_def fp_map_thm fp_set_thms fp_rel_thm
blanchet@58347
   557
    ctr_Tss abs
desharna@58676
   558
    ({casex, case_thms, discs, selss, sel_defs, ctrs, exhaust, exhaust_discs, disc_thmss, sel_thmss,
desharna@58676
   559
      injects, distincts, distinct_discsss, ...} : ctr_sugar)
blanchet@58346
   560
    lthy =
blanchet@58346
   561
  if live = 0 then
desharna@58676
   562
    (([], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []), lthy)
blanchet@58346
   563
  else
blanchet@58346
   564
    let
blanchet@58347
   565
      val n = length ctr_Tss;
blanchet@58347
   566
      val ks = 1 upto n;
blanchet@58347
   567
      val ms = map length ctr_Tss;
blanchet@58347
   568
desharna@58446
   569
      val B_ify_T = Term.typ_subst_atomic (As ~~ Bs);
blanchet@58346
   570
desharna@58446
   571
      val fpBT = B_ify_T fpT;
blanchet@58346
   572
      val live_AsBs = filter (op <>) (As ~~ Bs);
blanchet@58346
   573
      val fTs = map (op -->) live_AsBs;
blanchet@58346
   574
blanchet@58347
   575
      val (((((((([C, E], xss), yss), fs), Rs), ta), tb), thesis), names_lthy) = lthy
blanchet@58435
   576
        |> fold (fold Variable.declare_typ) [As, Bs]
blanchet@58346
   577
        |> mk_TFrees 2
blanchet@58347
   578
        ||>> mk_Freess "x" ctr_Tss
desharna@58446
   579
        ||>> mk_Freess "y" (map (map B_ify_T) ctr_Tss)
blanchet@58346
   580
        ||>> mk_Frees "f" fTs
blanchet@58346
   581
        ||>> mk_Frees "R" (map (uncurry mk_pred2T) live_AsBs)
blanchet@58346
   582
        ||>> yield_singleton (mk_Frees "a") fpT
blanchet@58346
   583
        ||>> yield_singleton (mk_Frees "b") fpBT
blanchet@58346
   584
        ||>> apfst HOLogic.mk_Trueprop o yield_singleton (mk_Frees "thesis") HOLogic.boolT;
blanchet@58346
   585
blanchet@58346
   586
      val mapx = mk_map live As Bs (map_of_bnf fp_bnf);
blanchet@58346
   587
      val ctrAs = map (mk_ctr As) ctrs;
blanchet@58346
   588
      val ctrBs = map (mk_ctr Bs) ctrs;
blanchet@58346
   589
      val relAsBs = mk_rel live As Bs (rel_of_bnf fp_bnf);
blanchet@58346
   590
      val setAs = map (mk_set As) (sets_of_bnf fp_bnf);
blanchet@58346
   591
      val discAs = map (mk_disc_or_sel As) discs;
blanchet@58346
   592
      val discBs = map (mk_disc_or_sel Bs) discs;
blanchet@58346
   593
      val selAss = map (map (mk_disc_or_sel As)) selss;
desharna@58676
   594
      val selBss = map (map (mk_disc_or_sel Bs)) selss;
blanchet@58346
   595
blanchet@58346
   596
      val ctor_cong =
blanchet@58346
   597
        if fp = Least_FP then
blanchet@58346
   598
          Drule.dummy_thm
blanchet@58346
   599
        else
blanchet@58346
   600
          let val ctor' = mk_ctor Bs ctor in
wenzelm@59621
   601
            cterm_instantiate_pos [NONE, NONE, SOME (Thm.cterm_of lthy ctor')] arg_cong
blanchet@58346
   602
          end;
blanchet@58346
   603
blanchet@58346
   604
      fun mk_cIn ctor k xs =
blanchet@58346
   605
        let val absT = domain_type (fastype_of ctor) in
blanchet@58346
   606
          mk_absumprod absT abs n k xs
blanchet@58346
   607
          |> fp = Greatest_FP ? curry (op $) ctor
wenzelm@59621
   608
          |> Thm.cterm_of lthy
blanchet@58346
   609
        end;
blanchet@58346
   610
blanchet@58346
   611
      val cxIns = map2 (mk_cIn ctor) ks xss;
desharna@58446
   612
      val cyIns = map2 (mk_cIn (Term.map_types B_ify_T ctor)) ks yss;
blanchet@58346
   613
blanchet@58346
   614
      fun mk_map_thm ctr_def' cxIn =
blanchet@58346
   615
        fold_thms lthy [ctr_def']
blanchet@58346
   616
          (unfold_thms lthy (o_apply :: pre_map_def ::
blanchet@58346
   617
               (if fp = Least_FP then [] else [dtor_ctor]) @ sumprod_thms_map @ abs_inverses)
wenzelm@59621
   618
             (cterm_instantiate_pos (map (SOME o Thm.cterm_of lthy) fs @ [SOME cxIn])
blanchet@58346
   619
                (if fp = Least_FP then fp_map_thm
blanchet@58346
   620
                 else fp_map_thm RS ctor_cong RS (ctor_dtor RS sym RS trans))))
blanchet@58346
   621
        |> singleton (Proof_Context.export names_lthy lthy);
blanchet@58346
   622
blanchet@58346
   623
      fun mk_set0_thm fp_set_thm ctr_def' cxIn =
blanchet@58346
   624
        fold_thms lthy [ctr_def']
blanchet@58346
   625
          (unfold_thms lthy (pre_set_defs @ fp_nesting_set_maps @ live_nesting_set_maps @
blanchet@58346
   626
               (if fp = Least_FP then [] else [dtor_ctor]) @ basic_sumprod_thms_set @
blanchet@58346
   627
               @{thms UN_Un sup_assoc[THEN sym]} @ abs_inverses)
blanchet@58346
   628
             (cterm_instantiate_pos [SOME cxIn] fp_set_thm))
blanchet@58346
   629
        |> singleton (Proof_Context.export names_lthy lthy);
blanchet@58346
   630
blanchet@58346
   631
      fun mk_set0_thms fp_set_thm = map2 (mk_set0_thm fp_set_thm) ctr_defs' cxIns;
blanchet@58346
   632
blanchet@58346
   633
      val map_thms = map2 mk_map_thm ctr_defs' cxIns;
blanchet@58346
   634
      val set0_thmss = map mk_set0_thms fp_set_thms;
blanchet@58346
   635
      val set0_thms = flat set0_thmss;
blanchet@58346
   636
      val set_thms = set0_thms
blanchet@58346
   637
        |> map (unfold_thms lthy @{thms insert_is_Un[THEN sym] Un_empty_left Un_insert_left});
blanchet@58346
   638
blanchet@58346
   639
      val rel_infos = (ctr_defs' ~~ cxIns, ctr_defs' ~~ cyIns);
blanchet@58346
   640
blanchet@58346
   641
      fun mk_rel_thm postproc ctr_defs' cxIn cyIn =
blanchet@58346
   642
        fold_thms lthy ctr_defs'
blanchet@58347
   643
          (unfold_thms lthy (pre_rel_def :: abs_inverses @
blanchet@58346
   644
               (if fp = Least_FP then [] else [dtor_ctor]) @ sumprod_thms_rel @
blanchet@58346
   645
               @{thms vimage2p_def sum.inject sum.distinct(1)[THEN eq_False[THEN iffD2]]})
wenzelm@59621
   646
             (cterm_instantiate_pos (map (SOME o Thm.cterm_of lthy) Rs @ [SOME cxIn, SOME cyIn])
blanchet@58346
   647
                fp_rel_thm))
blanchet@58346
   648
        |> postproc
blanchet@58346
   649
        |> singleton (Proof_Context.export names_lthy lthy);
blanchet@58346
   650
blanchet@58346
   651
      fun mk_rel_inject_thm ((ctr_def', cxIn), (_, cyIn)) =
blanchet@58346
   652
        mk_rel_thm (unfold_thms lthy @{thms eq_sym_Unity_conv}) [ctr_def'] cxIn cyIn;
blanchet@58346
   653
blanchet@58346
   654
      fun mk_rel_intro_thm m thm =
blanchet@58346
   655
        uncurry_thm m (thm RS iffD2) handle THM _ => thm;
blanchet@58346
   656
blanchet@58346
   657
      fun mk_half_rel_distinct_thm ((xctr_def', cxIn), (yctr_def', cyIn)) =
blanchet@58346
   658
        mk_rel_thm (fn thm => thm RS @{thm eq_False[THEN iffD1]}) [xctr_def', yctr_def'] cxIn cyIn;
blanchet@58346
   659
blanchet@58346
   660
      val rel_flip = rel_flip_of_bnf fp_bnf;
blanchet@58346
   661
blanchet@58346
   662
      fun mk_other_half_rel_distinct_thm thm =
blanchet@58346
   663
        flip_rels lthy live thm RS (rel_flip RS sym RS @{thm arg_cong[of _ _ Not]} RS iffD2);
blanchet@58346
   664
blanchet@58346
   665
      val rel_inject_thms = map mk_rel_inject_thm (op ~~ rel_infos);
blanchet@58346
   666
      val rel_intro_thms = map2 mk_rel_intro_thm ms rel_inject_thms;
blanchet@58346
   667
blanchet@58346
   668
      val half_rel_distinct_thmss = map (map mk_half_rel_distinct_thm) (mk_half_pairss rel_infos);
blanchet@58346
   669
      val other_half_rel_distinct_thmss =
blanchet@58346
   670
        map (map mk_other_half_rel_distinct_thm) half_rel_distinct_thmss;
blanchet@58346
   671
      val (rel_distinct_thms, _) =
blanchet@58346
   672
        join_halves n half_rel_distinct_thmss other_half_rel_distinct_thmss;
blanchet@58346
   673
desharna@58582
   674
      val rel_code_thms =
blanchet@58346
   675
        map (fn thm => thm RS @{thm eq_False[THEN iffD2]}) rel_distinct_thms @
blanchet@58346
   676
        map2 (fn thm => fn 0 => thm RS @{thm eq_True[THEN iffD2]} | _ => thm) rel_inject_thms ms;
blanchet@58346
   677
blanchet@58346
   678
      val ctr_transfer_thms =
blanchet@58346
   679
        let val goals = map2 (mk_parametricity_goal names_lthy Rs) ctrAs ctrBs in
blanchet@58346
   680
          Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
blanchet@58346
   681
            (fn {context = ctxt, prems = _} =>
blanchet@58346
   682
               mk_ctr_transfer_tac ctxt rel_intro_thms live_nesting_rel_eqs)
blanchet@58346
   683
          |> Conjunction.elim_balanced (length goals)
blanchet@58346
   684
          |> Proof_Context.export names_lthy lthy
blanchet@58346
   685
          |> map Thm.close_derivation
blanchet@58346
   686
        end;
blanchet@58346
   687
blanchet@58346
   688
      val (set_cases_thms, set_cases_attrss) =
blanchet@58346
   689
        let
blanchet@58346
   690
          fun mk_prems assms elem t ctxt =
blanchet@58346
   691
            (case fastype_of t of
blanchet@58346
   692
              Type (type_name, xs) =>
blanchet@58346
   693
              (case bnf_of ctxt type_name of
blanchet@58346
   694
                NONE => ([], ctxt)
blanchet@58346
   695
              | SOME bnf =>
blanchet@58346
   696
                apfst flat (fold_map (fn set => fn ctxt =>
blanchet@58346
   697
                  let
blanchet@58346
   698
                    val T = HOLogic.dest_setT (range_type (fastype_of set));
blanchet@58346
   699
                    val new_var = not (T = fastype_of elem);
blanchet@58346
   700
                    val (x, ctxt') =
blanchet@58346
   701
                      if new_var then yield_singleton (mk_Frees "x") T ctxt else (elem, ctxt);
blanchet@58346
   702
                  in
blanchet@58346
   703
                    mk_prems (mk_Trueprop_mem (x, set $ t) :: assms) elem x ctxt'
blanchet@58346
   704
                    |>> map (new_var ? Logic.all x)
blanchet@58346
   705
                  end) (map (mk_set xs) (sets_of_bnf bnf)) ctxt))
blanchet@58346
   706
            | T =>
blanchet@58346
   707
              rpair ctxt
blanchet@58346
   708
                (if T = fastype_of elem then [fold (curry Logic.mk_implies) assms thesis] else []));
blanchet@58346
   709
        in
blanchet@58346
   710
          split_list (map (fn set =>
blanchet@58346
   711
            let
blanchet@58346
   712
              val A = HOLogic.dest_setT (range_type (fastype_of set));
blanchet@58346
   713
              val (elem, names_lthy) = yield_singleton (mk_Frees "e") A names_lthy;
blanchet@58346
   714
              val premss =
blanchet@58346
   715
                map (fn ctr =>
blanchet@58346
   716
                  let
blanchet@58346
   717
                    val (args, names_lthy) =
blanchet@58346
   718
                      mk_Frees "z" (binder_types (fastype_of ctr)) names_lthy;
blanchet@58346
   719
                  in
blanchet@58346
   720
                    flat (zipper_map (fn (prev_args, arg, next_args) =>
blanchet@58346
   721
                      let
blanchet@58346
   722
                        val (args_with_elem, args_without_elem) =
blanchet@58346
   723
                          if fastype_of arg = A then
blanchet@58346
   724
                            (prev_args @ [elem] @ next_args, prev_args @ next_args)
blanchet@58346
   725
                          else
blanchet@58346
   726
                            `I (prev_args @ [arg] @ next_args);
blanchet@58346
   727
                      in
blanchet@58346
   728
                        mk_prems [mk_Trueprop_eq (ta, Term.list_comb (ctr, args_with_elem))]
blanchet@58346
   729
                          elem arg names_lthy
blanchet@58346
   730
                        |> fst
blanchet@58346
   731
                        |> map (fold_rev Logic.all args_without_elem)
blanchet@58346
   732
                      end) args)
blanchet@58346
   733
                  end) ctrAs;
blanchet@58346
   734
              val goal = Logic.mk_implies (mk_Trueprop_mem (elem, set $ ta), thesis);
blanchet@58346
   735
              val thm =
blanchet@58346
   736
                Goal.prove_sorry lthy [] (flat premss) goal (fn {context = ctxt, prems} =>
wenzelm@59621
   737
                  mk_set_cases_tac ctxt (Thm.cterm_of ctxt ta) prems exhaust set_thms)
blanchet@58346
   738
                |> singleton (Proof_Context.export names_lthy lthy)
blanchet@58346
   739
                |> Thm.close_derivation
blanchet@58346
   740
                |> rotate_prems ~1;
blanchet@58346
   741
blanchet@58346
   742
              val consumes_attr = Attrib.internal (K (Rule_Cases.consumes 1));
blanchet@58346
   743
              val cases_set_attr =
blanchet@58346
   744
                Attrib.internal (K (Induct.cases_pred (name_of_set set)));
desharna@58456
   745
desharna@58456
   746
              val ctr_names = quasi_unambiguous_case_names (flat
desharna@58456
   747
                (map (uncurry mk_names o map_prod length name_of_ctr) (premss ~~ ctrAs)));
desharna@58456
   748
              val case_names_attr = Attrib.internal (K (Rule_Cases.case_names ctr_names));
blanchet@58346
   749
            in
blanchet@58346
   750
              (* TODO: @{attributes [elim?]} *)
desharna@58456
   751
              (thm, [consumes_attr, cases_set_attr, case_names_attr])
blanchet@58346
   752
            end) setAs)
blanchet@58346
   753
        end;
blanchet@58346
   754
desharna@58673
   755
      val (set_intros_thmssss, set_intros_thms) =
blanchet@58346
   756
        let
blanchet@58346
   757
          fun mk_goals A setA ctr_args t ctxt =
blanchet@58346
   758
            (case fastype_of t of
blanchet@58346
   759
              Type (type_name, innerTs) =>
blanchet@58346
   760
              (case bnf_of ctxt type_name of
blanchet@58346
   761
                NONE => ([], ctxt)
blanchet@58346
   762
              | SOME bnf =>
blanchet@58346
   763
                apfst flat (fold_map (fn set => fn ctxt =>
blanchet@58346
   764
                  let
blanchet@58346
   765
                    val T = HOLogic.dest_setT (range_type (fastype_of set));
blanchet@58346
   766
                    val (x, ctxt') = yield_singleton (mk_Frees "x") T ctxt;
blanchet@58346
   767
                    val assm = mk_Trueprop_mem (x, set $ t);
blanchet@58346
   768
                  in
blanchet@58346
   769
                    apfst (map (Logic.mk_implies o pair assm)) (mk_goals A setA ctr_args x ctxt')
blanchet@58346
   770
                  end) (map (mk_set innerTs) (sets_of_bnf bnf)) ctxt))
blanchet@58346
   771
            | T => (if T = A then [mk_Trueprop_mem (t, setA $ ctr_args)] else [], ctxt));
blanchet@58346
   772
desharna@58673
   773
          val (goalssss, names_lthy) =
desharna@58673
   774
            fold_map (fn set =>
blanchet@58346
   775
              let val A = HOLogic.dest_setT (range_type (fastype_of set)) in
desharna@58673
   776
                fold_map (fn ctr => fn ctxt =>
desharna@58673
   777
                  let val (args, ctxt') = mk_Frees "a" (binder_types (fastype_of ctr)) ctxt in
desharna@58673
   778
                    fold_map (mk_goals A set (Term.list_comb (ctr, args))) args ctxt'
desharna@58673
   779
                  end) ctrAs
desharna@58673
   780
              end) setAs lthy;
desharna@58673
   781
          val goals = flat (flat (flat goalssss));
blanchet@58346
   782
        in
desharna@58673
   783
          `(fst o unflattt goalssss)
desharna@58673
   784
            (if null goals then []
desharna@58673
   785
             else
desharna@58673
   786
               Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
desharna@58673
   787
                 (fn {context = ctxt, prems = _} => mk_set_intros_tac ctxt set0_thms)
desharna@58673
   788
               |> Conjunction.elim_balanced (length goals)
desharna@58673
   789
               |> Proof_Context.export names_lthy lthy
desharna@58673
   790
               |> map Thm.close_derivation)
blanchet@58346
   791
        end;
blanchet@58346
   792
blanchet@58346
   793
      val rel_sel_thms =
blanchet@58346
   794
        let
blanchet@58346
   795
          val n = length discAs;
blanchet@58346
   796
          fun mk_conjunct n k discA selAs discB selBs =
blanchet@58346
   797
            (if k = n then [] else [HOLogic.mk_eq (discA $ ta, discB $ tb)]) @
desharna@58674
   798
            (if null selAs then []
blanchet@58346
   799
             else
desharna@58674
   800
               [Library.foldr HOLogic.mk_imp
desharna@58674
   801
                  (if n = 1 then [] else [discA $ ta, discB $ tb],
desharna@58674
   802
                   Library.foldr1 HOLogic.mk_conj (map2 (build_rel_app names_lthy Rs [])
desharna@58674
   803
                     (map (rapp ta) selAs) (map (rapp tb) selBs)))]);
blanchet@58346
   804
blanchet@58346
   805
          val goals =
desharna@58674
   806
            if n = 0 then []
blanchet@58346
   807
            else
blanchet@58346
   808
              [mk_Trueprop_eq (build_rel_app names_lthy Rs [] ta tb,
wenzelm@58634
   809
                 (case flat (@{map 5} (mk_conjunct n) (1 upto n) discAs selAss discBs selBss) of
blanchet@58346
   810
                   [] => @{term True}
blanchet@58346
   811
                 | conjuncts => Library.foldr1 HOLogic.mk_conj conjuncts))];
blanchet@58346
   812
blanchet@58346
   813
          fun prove goal =
blanchet@58346
   814
            Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, prems = _} =>
wenzelm@59621
   815
              mk_rel_sel_tac ctxt (Thm.cterm_of ctxt ta) (Thm.cterm_of ctxt tb) exhaust (flat disc_thmss)
blanchet@58346
   816
                (flat sel_thmss) rel_inject_thms distincts rel_distinct_thms live_nesting_rel_eqs)
blanchet@58346
   817
            |> singleton (Proof_Context.export names_lthy lthy)
blanchet@58346
   818
            |> Thm.close_derivation;
blanchet@58346
   819
        in
blanchet@58346
   820
          map prove goals
blanchet@58346
   821
        end;
blanchet@58346
   822
blanchet@58346
   823
      val (rel_cases_thm, rel_cases_attrs) =
blanchet@58346
   824
        let
blanchet@58346
   825
          val rel_Rs_a_b = list_comb (relAsBs, Rs) $ ta $ tb;
blanchet@58346
   826
          val ctrBs = map (mk_ctr Bs) ctrs;
blanchet@58346
   827
blanchet@58346
   828
          fun mk_assms ctrA ctrB ctxt =
blanchet@58346
   829
            let
blanchet@58346
   830
              val argA_Ts = binder_types (fastype_of ctrA);
blanchet@58346
   831
              val argB_Ts = binder_types (fastype_of ctrB);
blanchet@58346
   832
              val ((argAs, argBs), names_ctxt) =  ctxt
blanchet@58346
   833
                |> mk_Frees "x" argA_Ts
blanchet@58346
   834
                ||>> mk_Frees "y" argB_Ts;
blanchet@58346
   835
              val ctrA_args = list_comb (ctrA, argAs);
blanchet@58346
   836
              val ctrB_args = list_comb (ctrB, argBs);
blanchet@58346
   837
            in
blanchet@58346
   838
              (fold_rev Logic.all (argAs @ argBs) (Logic.list_implies
blanchet@58346
   839
                 (mk_Trueprop_eq (ta, ctrA_args) :: mk_Trueprop_eq (tb, ctrB_args) ::
blanchet@58346
   840
                    map2 (HOLogic.mk_Trueprop oo build_rel_app lthy Rs []) argAs argBs,
blanchet@58346
   841
                  thesis)),
blanchet@58346
   842
               names_ctxt)
blanchet@58346
   843
            end;
blanchet@58346
   844
wenzelm@58634
   845
          val (assms, names_lthy) = @{fold_map 2} mk_assms ctrAs ctrBs names_lthy;
blanchet@58346
   846
          val goal = Logic.list_implies (HOLogic.mk_Trueprop rel_Rs_a_b :: assms, thesis);
blanchet@58346
   847
          val thm =
blanchet@58346
   848
            Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, prems = _} =>
wenzelm@59621
   849
              mk_rel_cases_tac ctxt (Thm.cterm_of ctxt ta) (Thm.cterm_of ctxt tb) exhaust injects
blanchet@58346
   850
                rel_inject_thms distincts rel_distinct_thms live_nesting_rel_eqs)
blanchet@58346
   851
            |> singleton (Proof_Context.export names_lthy lthy)
blanchet@58346
   852
            |> Thm.close_derivation;
blanchet@58346
   853
blanchet@58346
   854
          val ctr_names = quasi_unambiguous_case_names (map name_of_ctr ctrAs);
blanchet@58346
   855
          val case_names_attr = Attrib.internal (K (Rule_Cases.case_names ctr_names));
blanchet@58346
   856
          val consumes_attr = Attrib.internal (K (Rule_Cases.consumes 1));
blanchet@58346
   857
          val cases_pred_attr = Attrib.internal o K o Induct.cases_pred;
blanchet@58346
   858
        in
blanchet@58346
   859
          (thm, [consumes_attr, case_names_attr, cases_pred_attr ""])
blanchet@58346
   860
        end;
blanchet@58346
   861
desharna@58570
   862
      val case_transfer_thm =
blanchet@58346
   863
        let
blanchet@58435
   864
          val (S, names_lthy) = yield_singleton (mk_Frees "S") (mk_pred2T C E) names_lthy;
blanchet@58346
   865
          val caseA = mk_case As C casex;
blanchet@58346
   866
          val caseB = mk_case Bs E casex;
blanchet@58435
   867
          val goal = mk_parametricity_goal names_lthy (S :: Rs) caseA caseB;
blanchet@58346
   868
        in
blanchet@58346
   869
          Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, prems = _} =>
blanchet@58346
   870
            mk_case_transfer_tac ctxt rel_cases_thm case_thms)
blanchet@58346
   871
          |> singleton (Proof_Context.export names_lthy lthy)
blanchet@58346
   872
          |> Thm.close_derivation
blanchet@58346
   873
        end;
blanchet@58346
   874
desharna@58676
   875
      val sel_transfer_thms =
desharna@58676
   876
        if null selAss then []
desharna@58676
   877
        else
desharna@58676
   878
          let
desharna@58676
   879
            val shared_sels = foldl1 (uncurry (inter (op =))) (map (op ~~) (selAss ~~ selBss));
desharna@58676
   880
            val goals = map (uncurry (mk_parametricity_goal names_lthy Rs)) shared_sels;
desharna@58676
   881
          in
desharna@58676
   882
            if null goals then []
desharna@58676
   883
            else
desharna@58676
   884
              Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
desharna@58676
   885
                (fn {context = ctxt, prems = _} =>
desharna@58676
   886
                   mk_sel_transfer_tac ctxt n sel_defs case_transfer_thm)
desharna@58676
   887
              |> Conjunction.elim_balanced (length goals)
desharna@58676
   888
              |> Proof_Context.export names_lthy lthy
desharna@58676
   889
              |> map Thm.close_derivation
desharna@58676
   890
          end;
desharna@58676
   891
blanchet@58346
   892
      val disc_transfer_thms =
blanchet@58346
   893
        let val goals = map2 (mk_parametricity_goal names_lthy Rs) discAs discBs in
blanchet@58346
   894
          if null goals then
blanchet@58346
   895
            []
blanchet@58346
   896
          else
blanchet@58346
   897
            Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
blanchet@58346
   898
              (K (mk_disc_transfer_tac (the_single rel_sel_thms) (the_single exhaust_discs)
blanchet@58346
   899
                 (flat (flat distinct_discsss))))
blanchet@58346
   900
            |> Conjunction.elim_balanced (length goals)
blanchet@58346
   901
            |> Proof_Context.export names_lthy lthy
blanchet@58346
   902
            |> map Thm.close_derivation
blanchet@58346
   903
        end;
blanchet@58346
   904
blanchet@58346
   905
      val map_disc_iff_thms =
blanchet@58346
   906
        let
blanchet@58346
   907
          val discsB = map (mk_disc_or_sel Bs) discs;
blanchet@58346
   908
          val discsA_t = map (fn disc1 => Term.betapply (disc1, ta)) discAs;
blanchet@58346
   909
blanchet@58346
   910
          fun mk_goal (discA_t, discB) =
blanchet@58346
   911
            if head_of discA_t aconv HOLogic.Not orelse is_refl_bool discA_t then
blanchet@58346
   912
              NONE
blanchet@58346
   913
            else
blanchet@58346
   914
              SOME (mk_Trueprop_eq (betapply (discB, (Term.list_comb (mapx, fs) $ ta)), discA_t));
blanchet@58346
   915
blanchet@58346
   916
          val goals = map_filter mk_goal (discsA_t ~~ discsB);
blanchet@58346
   917
        in
blanchet@58346
   918
          if null goals then
blanchet@58346
   919
            []
blanchet@58346
   920
          else
blanchet@58346
   921
            Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
blanchet@58346
   922
              (fn {context = ctxt, prems = _} =>
wenzelm@59621
   923
                 mk_map_disc_iff_tac ctxt (Thm.cterm_of ctxt ta) exhaust (flat disc_thmss) map_thms)
blanchet@58346
   924
            |> Conjunction.elim_balanced (length goals)
blanchet@58346
   925
            |> Proof_Context.export names_lthy lthy
blanchet@58346
   926
            |> map Thm.close_derivation
blanchet@58346
   927
        end;
blanchet@58346
   928
desharna@58672
   929
      val (map_sel_thmss, map_sel_thms) =
blanchet@58346
   930
        let
desharna@58676
   931
          fun mk_goal discA selA selB =
blanchet@58346
   932
            let
blanchet@58346
   933
              val prem = Term.betapply (discA, ta);
blanchet@58346
   934
              val lhs = selB $ (Term.list_comb (mapx, fs) $ ta);
blanchet@58346
   935
              val lhsT = fastype_of lhs;
blanchet@58346
   936
              val map_rhsT =
blanchet@58346
   937
                map_atyps (perhaps (AList.lookup (op =) (map swap live_AsBs))) lhsT;
blanchet@58346
   938
              val map_rhs = build_map lthy []
blanchet@58346
   939
                (the o (AList.lookup (op =) (live_AsBs ~~ fs))) (map_rhsT, lhsT);
blanchet@58346
   940
              val rhs = (case map_rhs of
blanchet@58346
   941
                  Const (@{const_name id}, _) => selA $ ta
blanchet@58346
   942
                | _ => map_rhs $ (selA $ ta));
blanchet@58346
   943
              val concl = mk_Trueprop_eq (lhs, rhs);
blanchet@58346
   944
            in
blanchet@58346
   945
              if is_refl_bool prem then concl
blanchet@58346
   946
              else Logic.mk_implies (HOLogic.mk_Trueprop prem, concl)
blanchet@58346
   947
            end;
blanchet@58346
   948
desharna@58676
   949
          val goalss = @{map 3} (map2 o mk_goal) discAs selAss selBss;
desharna@58672
   950
          val goals = flat goalss;
blanchet@58346
   951
        in
desharna@58672
   952
          `(fst o unflat goalss)
desharna@58672
   953
            (if null goals then []
desharna@58672
   954
             else
desharna@58672
   955
               Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
desharna@58672
   956
                 (fn {context = ctxt, prems = _} =>
wenzelm@59621
   957
                    mk_map_sel_tac ctxt (Thm.cterm_of ctxt ta) exhaust (flat disc_thmss) map_thms
desharna@58672
   958
                      (flat sel_thmss) live_nesting_map_id0s)
desharna@58672
   959
               |> Conjunction.elim_balanced (length goals)
desharna@58672
   960
               |> Proof_Context.export names_lthy lthy
desharna@58672
   961
               |> map Thm.close_derivation)
blanchet@58346
   962
        end;
blanchet@58346
   963
desharna@58671
   964
      val (set_sel_thmssss, set_sel_thms) =
blanchet@58346
   965
        let
desharna@58671
   966
          fun mk_goal setA discA selA ctxt =
blanchet@58346
   967
            let
blanchet@58346
   968
              val prem = Term.betapply (discA, ta);
blanchet@58346
   969
              val sel_rangeT = range_type (fastype_of selA);
blanchet@58346
   970
              val A = HOLogic.dest_setT (range_type (fastype_of setA));
blanchet@58346
   971
blanchet@58346
   972
              fun travese_nested_types t ctxt =
blanchet@58346
   973
                (case fastype_of t of
blanchet@58346
   974
                  Type (type_name, innerTs) =>
blanchet@58346
   975
                  (case bnf_of ctxt type_name of
blanchet@58346
   976
                    NONE => ([], ctxt)
blanchet@58346
   977
                  | SOME bnf =>
blanchet@58346
   978
                    let
blanchet@58346
   979
                      fun seq_assm a set ctxt =
blanchet@58346
   980
                        let
blanchet@58346
   981
                          val T = HOLogic.dest_setT (range_type (fastype_of set));
blanchet@58346
   982
                          val (x, ctxt') = yield_singleton (mk_Frees "x") T ctxt;
blanchet@58346
   983
                          val assm = mk_Trueprop_mem (x, set $ a);
blanchet@58346
   984
                        in
blanchet@58346
   985
                          travese_nested_types x ctxt'
blanchet@58346
   986
                          |>> map (Logic.mk_implies o pair assm)
blanchet@58346
   987
                        end;
blanchet@58346
   988
                    in
blanchet@58346
   989
                      fold_map (seq_assm t o mk_set innerTs) (sets_of_bnf bnf) ctxt
blanchet@58346
   990
                      |>> flat
blanchet@58346
   991
                    end)
blanchet@58346
   992
                | T =>
blanchet@58346
   993
                  if T = A then ([mk_Trueprop_mem (t, setA $ ta)], ctxt) else ([], ctxt));
blanchet@58346
   994
blanchet@58346
   995
              val (concls, ctxt') =
blanchet@58346
   996
                if sel_rangeT = A then ([mk_Trueprop_mem (selA $ ta, setA $ ta)], ctxt)
blanchet@58346
   997
                else travese_nested_types (selA $ ta) ctxt;
blanchet@58346
   998
            in
blanchet@58346
   999
              if exists_subtype_in [A] sel_rangeT then
blanchet@58346
  1000
                if is_refl_bool prem then (concls, ctxt')
blanchet@58346
  1001
                else (map (Logic.mk_implies o pair (HOLogic.mk_Trueprop prem)) concls, ctxt')
blanchet@58346
  1002
              else
blanchet@58346
  1003
                ([], ctxt)
blanchet@58346
  1004
            end;
desharna@58671
  1005
desharna@58671
  1006
          val (goalssss, names_lthy) =
desharna@58671
  1007
            fold_map (fn set => @{fold_map 2} (fold_map o mk_goal set) discAs selAss)
desharna@58671
  1008
              setAs names_lthy;
desharna@58671
  1009
          val goals = flat (flat (flat goalssss));
blanchet@58346
  1010
        in
desharna@58671
  1011
          `(fst o unflattt goalssss)
desharna@58671
  1012
            (if null goals then []
desharna@58671
  1013
             else
desharna@58671
  1014
               Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
desharna@58671
  1015
                 (fn {context = ctxt, prems = _} =>
wenzelm@59621
  1016
                    mk_set_sel_tac ctxt (Thm.cterm_of ctxt ta) exhaust (flat disc_thmss)
desharna@58671
  1017
                      (flat sel_thmss) set0_thms)
desharna@58671
  1018
               |> Conjunction.elim_balanced (length goals)
desharna@58671
  1019
               |> Proof_Context.export names_lthy lthy
desharna@58671
  1020
               |> map Thm.close_derivation)
blanchet@58346
  1021
        end;
blanchet@58346
  1022
blanchet@59283
  1023
      val code_attrs = if plugins code_plugin then [Code.add_default_eqn_attrib] else [];
blanchet@58346
  1024
blanchet@58346
  1025
      val anonymous_notes =
desharna@58582
  1026
        [(rel_code_thms, code_attrs @ nitpicksimp_attrs)]
blanchet@58346
  1027
        |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
blanchet@58346
  1028
blanchet@58346
  1029
      val notes =
desharna@58570
  1030
        [(case_transferN, [case_transfer_thm], K []),
blanchet@58346
  1031
         (ctr_transferN, ctr_transfer_thms, K []),
blanchet@58346
  1032
         (disc_transferN, disc_transfer_thms, K []),
desharna@58676
  1033
         (sel_transferN, sel_transfer_thms, K []),
blanchet@58346
  1034
         (mapN, map_thms, K (code_attrs @ nitpicksimp_attrs @ simp_attrs)),
blanchet@58346
  1035
         (map_disc_iffN, map_disc_iff_thms, K simp_attrs),
blanchet@58346
  1036
         (map_selN, map_sel_thms, K []),
blanchet@58346
  1037
         (rel_casesN, [rel_cases_thm], K rel_cases_attrs),
blanchet@58346
  1038
         (rel_distinctN, rel_distinct_thms, K simp_attrs),
blanchet@58346
  1039
         (rel_injectN, rel_inject_thms, K simp_attrs),
blanchet@58346
  1040
         (rel_introsN, rel_intro_thms, K []),
blanchet@58346
  1041
         (rel_selN, rel_sel_thms, K []),
blanchet@58346
  1042
         (setN, set_thms, K (code_attrs @ nitpicksimp_attrs @ simp_attrs)),
blanchet@58346
  1043
         (set_casesN, set_cases_thms, nth set_cases_attrss),
blanchet@58346
  1044
         (set_introsN, set_intros_thms, K []),
blanchet@58346
  1045
         (set_selN, set_sel_thms, K [])]
blanchet@58346
  1046
        |> massage_simple_notes fp_b_name;
blanchet@58346
  1047
blanchet@58346
  1048
      val (noted, lthy') =
blanchet@58346
  1049
        lthy
blanchet@58346
  1050
        |> Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) map_thms)
blanchet@58346
  1051
        |> fp = Least_FP
desharna@58582
  1052
          ? Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) rel_code_thms)
blanchet@58346
  1053
        |> Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) set0_thms)
blanchet@58346
  1054
        |> Local_Theory.notes (anonymous_notes @ notes);
blanchet@58346
  1055
blanchet@58346
  1056
      val subst = Morphism.thm (substitute_noted_thm noted);
blanchet@58346
  1057
    in
desharna@58561
  1058
      ((map subst map_thms,
desharna@58561
  1059
        map subst map_disc_iff_thms,
desharna@58672
  1060
        map (map subst) map_sel_thmss,
desharna@58561
  1061
        map subst rel_inject_thms,
desharna@58561
  1062
        map subst rel_distinct_thms,
desharna@58562
  1063
        map subst rel_sel_thms,
desharna@58563
  1064
        map subst rel_intro_thms,
desharna@58564
  1065
        [subst rel_cases_thm],
desharna@58566
  1066
        map subst set_thms,
desharna@58671
  1067
        map (map (map (map subst))) set_sel_thmssss,
desharna@58673
  1068
        map (map (map (map subst))) set_intros_thmssss,
desharna@58569
  1069
        map subst set_cases_thms,
desharna@58570
  1070
        map subst ctr_transfer_thms,
desharna@58571
  1071
        [subst case_transfer_thm],
desharna@58676
  1072
        map subst disc_transfer_thms,
desharna@58676
  1073
        map subst sel_transfer_thms), lthy')
blanchet@58346
  1074
    end;
blanchet@58346
  1075
blanchet@58214
  1076
type lfp_sugar_thms = (thm list * thm * Token.src list) * (thm list list * Token.src list);
blanchet@53746
  1077
blanchet@55867
  1078
fun morph_lfp_sugar_thms phi ((inducts, induct, induct_attrs), (recss, rec_attrs)) =
blanchet@54256
  1079
  ((map (Morphism.thm phi) inducts, Morphism.thm phi induct, induct_attrs),
blanchet@58291
  1080
   (map (map (Morphism.thm phi)) recss, rec_attrs)) : lfp_sugar_thms;
blanchet@54256
  1081
blanchet@58115
  1082
val transfer_lfp_sugar_thms = morph_lfp_sugar_thms o Morphism.transfer_morphism;
blanchet@54256
  1083
blanchet@53746
  1084
type gfp_sugar_thms =
wenzelm@58011
  1085
  ((thm list * thm) list * (Token.src list * Token.src list))
desharna@57489
  1086
  * thm list list
desharna@57489
  1087
  * thm list list
wenzelm@58011
  1088
  * (thm list list * Token.src list)
wenzelm@58011
  1089
  * (thm list list list * Token.src list);
blanchet@53746
  1090
blanchet@57260
  1091
fun morph_gfp_sugar_thms phi ((coinducts_pairs, coinduct_attrs_pair),
blanchet@57983
  1092
    corecss, corec_discss, (corec_disc_iffss, corec_disc_iff_attrs),
blanchet@57983
  1093
    (corec_selsss, corec_sel_attrs)) =
blanchet@54256
  1094
  ((map (apfst (map (Morphism.thm phi)) o apsnd (Morphism.thm phi)) coinducts_pairs,
blanchet@57260
  1095
    coinduct_attrs_pair),
desharna@57489
  1096
   map (map (Morphism.thm phi)) corecss,
blanchet@57983
  1097
   map (map (Morphism.thm phi)) corec_discss,
blanchet@57983
  1098
   (map (map (Morphism.thm phi)) corec_disc_iffss, corec_disc_iff_attrs),
blanchet@57983
  1099
   (map (map (map (Morphism.thm phi))) corec_selsss, corec_sel_attrs)) : gfp_sugar_thms;
blanchet@54256
  1100
blanchet@58115
  1101
val transfer_gfp_sugar_thms = morph_gfp_sugar_thms o Morphism.transfer_morphism;
blanchet@54256
  1102
blanchet@58352
  1103
fun unzip_recT (Type (@{type_name prod}, [_, TFree x]))
blanchet@58352
  1104
      (T as Type (@{type_name prod}, Ts as [_, TFree y])) =
blanchet@58352
  1105
    if x = y then [T] else Ts
blanchet@58352
  1106
  | unzip_recT _ (Type (@{type_name prod}, Ts as [_, TFree _])) = Ts
blanchet@58159
  1107
  | unzip_recT _ T = [T];
blanchet@58159
  1108
blanchet@55867
  1109
fun mk_recs_args_types ctr_Tsss Cs absTs repTs ns mss ctor_rec_fun_Ts lthy =
blanchet@51832
  1110
  let
blanchet@52214
  1111
    val Css = map2 replicate ns Cs;
blanchet@55869
  1112
    val x_Tssss =
wenzelm@58634
  1113
      @{map 6} (fn absT => fn repT => fn n => fn ms => fn ctr_Tss => fn ctor_rec_fun_T =>
traytel@55803
  1114
          map2 (map2 unzip_recT)
blanchet@55867
  1115
            ctr_Tss (dest_absumprodT absT repT n ms (domain_type ctor_rec_fun_T)))
blanchet@55867
  1116
        absTs repTs ns mss ctr_Tsss ctor_rec_fun_Ts;
blanchet@51832
  1117
blanchet@55869
  1118
    val x_Tsss' = map (map flat_rec_arg_args) x_Tssss;
blanchet@55869
  1119
    val f_Tss = map2 (map2 (curry (op --->))) x_Tsss' Css;
blanchet@51832
  1120
blanchet@55869
  1121
    val ((fss, xssss), lthy) =
blanchet@52214
  1122
      lthy
blanchet@55869
  1123
      |> mk_Freess "f" f_Tss
blanchet@55869
  1124
      ||>> mk_Freessss "x" x_Tssss;
blanchet@51832
  1125
  in
blanchet@55869
  1126
    ((f_Tss, x_Tssss, fss, xssss), lthy)
blanchet@51832
  1127
  end;
blanchet@51832
  1128
blanchet@58159
  1129
fun unzip_corecT (Type (@{type_name sum}, _)) T = [T]
blanchet@58159
  1130
  | unzip_corecT _ (Type (@{type_name sum}, Ts)) = Ts
blanchet@58159
  1131
  | unzip_corecT _ T = [T];
blanchet@58159
  1132
blanchet@55867
  1133
(*avoid "'a itself" arguments in corecursors*)
blanchet@55966
  1134
fun repair_nullary_single_ctr [[]] = [[HOLogic.unitT]]
blanchet@55772
  1135
  | repair_nullary_single_ctr Tss = Tss;
blanchet@55772
  1136
blanchet@55867
  1137
fun mk_corec_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss fun_Ts =
blanchet@51829
  1138
  let
blanchet@55772
  1139
    val ctr_Tsss' = map repair_nullary_single_ctr ctr_Tsss;
blanchet@55869
  1140
    val g_absTs = map range_type fun_Ts;
wenzelm@58634
  1141
    val g_Tsss = map repair_nullary_single_ctr (@{map 5} dest_absumprodT absTs repTs ns mss g_absTs);
wenzelm@58634
  1142
    val g_Tssss = @{map 3} (fn C => map2 (map2 (map (curry (op -->) C) oo unzip_corecT)))
blanchet@55869
  1143
      Cs ctr_Tsss' g_Tsss;
blanchet@55869
  1144
    val q_Tssss = map (map (map (fn [_] => [] | [_, T] => [mk_pred1T (domain_type T)]))) g_Tssss;
blanchet@52870
  1145
  in
blanchet@55869
  1146
    (q_Tssss, g_Tsss, g_Tssss, g_absTs)
blanchet@52870
  1147
  end;
blanchet@51829
  1148
blanchet@55867
  1149
fun mk_corec_p_pred_types Cs ns = map2 (fn n => replicate (Int.max (0, n - 1)) o mk_pred1T) ns Cs;
blanchet@52898
  1150
blanchet@55867
  1151
fun mk_corec_fun_arg_types ctr_Tsss Cs absTs repTs ns mss dtor_corec =
blanchet@55867
  1152
  (mk_corec_p_pred_types Cs ns,
blanchet@55867
  1153
   mk_corec_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss
blanchet@55867
  1154
     (binder_fun_types (fastype_of dtor_corec)));
blanchet@51829
  1155
blanchet@55867
  1156
fun mk_corecs_args_types ctr_Tsss Cs absTs repTs ns mss dtor_corec_fun_Ts lthy =
blanchet@55867
  1157
  let
blanchet@55867
  1158
    val p_Tss = mk_corec_p_pred_types Cs ns;
blanchet@51829
  1159
blanchet@55869
  1160
    val (q_Tssss, g_Tsss, g_Tssss, corec_types) =
blanchet@55867
  1161
      mk_corec_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss dtor_corec_fun_Ts;
blanchet@51831
  1162
blanchet@55869
  1163
    val (((((Free (x, _), cs), pss), qssss), gssss), lthy) =
blanchet@51829
  1164
      lthy
blanchet@55869
  1165
      |> yield_singleton (mk_Frees "x") dummyT
blanchet@52347
  1166
      ||>> mk_Frees "a" Cs
blanchet@51829
  1167
      ||>> mk_Freess "p" p_Tss
blanchet@55869
  1168
      ||>> mk_Freessss "q" q_Tssss
blanchet@55869
  1169
      ||>> mk_Freessss "g" g_Tssss;
blanchet@51831
  1170
blanchet@51831
  1171
    val cpss = map2 (map o rapp) cs pss;
blanchet@51829
  1172
desharna@57303
  1173
    fun build_sum_inj mk_inj = build_map lthy [] (uncurry mk_inj o dest_sumT o snd);
blanchet@52347
  1174
blanchet@55871
  1175
    fun build_dtor_corec_arg _ [] [cg] = cg
blanchet@55871
  1176
      | build_dtor_corec_arg T [cq] [cg, cg'] =
blanchet@55871
  1177
        mk_If cq (build_sum_inj Inl_const (fastype_of cg, T) $ cg)
blanchet@55871
  1178
          (build_sum_inj Inr_const (fastype_of cg', T) $ cg');
blanchet@52347
  1179
wenzelm@58634
  1180
    val pgss = @{map 3} flat_corec_preds_predsss_gettersss pss qssss gssss;
blanchet@55869
  1181
    val cqssss = map2 (map o map o map o rapp) cs qssss;
blanchet@55869
  1182
    val cgssss = map2 (map o map o map o rapp) cs gssss;
wenzelm@58634
  1183
    val cqgsss = @{map 3} (@{map 3} (@{map 3} build_dtor_corec_arg)) g_Tsss cqssss cgssss;
blanchet@51831
  1184
  in
desharna@58448
  1185
    ((x, cs, cpss, (((pgss, pss, qssss, gssss), cqgsss), corec_types)), lthy)
blanchet@51831
  1186
  end;
blanchet@51829
  1187
blanchet@55867
  1188
fun mk_co_recs_prelims fp ctr_Tsss fpTs Cs absTs repTs ns mss xtor_co_recs0 lthy =
blanchet@51903
  1189
  let
blanchet@52169
  1190
    val thy = Proof_Context.theory_of lthy;
blanchet@52169
  1191
blanchet@55867
  1192
    val (xtor_co_rec_fun_Ts, xtor_co_recs) =
blanchet@55867
  1193
      mk_xtor_co_recs thy fp fpTs Cs xtor_co_recs0 |> `(binder_fun_types o fastype_of o hd);
blanchet@51903
  1194
blanchet@55867
  1195
    val ((recs_args_types, corecs_args_types), lthy') =
blanchet@52207
  1196
      if fp = Least_FP then
blanchet@56641
  1197
        mk_recs_args_types ctr_Tsss Cs absTs repTs ns mss xtor_co_rec_fun_Ts lthy
blanchet@56641
  1198
        |>> (rpair NONE o SOME)
blanchet@51903
  1199
      else
blanchet@55867
  1200
        mk_corecs_args_types ctr_Tsss Cs absTs repTs ns mss xtor_co_rec_fun_Ts lthy
traytel@55803
  1201
        |>> (pair NONE o SOME);
blanchet@51903
  1202
  in
blanchet@55867
  1203
    ((xtor_co_recs, recs_args_types, corecs_args_types), lthy')
blanchet@51903
  1204
  end;
blanchet@51903
  1205
blanchet@55869
  1206
fun mk_preds_getterss_join c cps absT abs cqgss =
traytel@55803
  1207
  let
blanchet@55869
  1208
    val n = length cqgss;
blanchet@55869
  1209
    val ts = map2 (mk_absumprod absT abs n) (1 upto n) cqgss;
traytel@55803
  1210
  in
traytel@55803
  1211
    Term.lambda c (mk_IfN absT cps ts)
blanchet@51900
  1212
  end;
blanchet@51886
  1213
blanchet@58210
  1214
fun define_co_rec_as fp Cs fpT b rhs lthy0 =
blanchet@51897
  1215
  let
blanchet@52170
  1216
    val thy = Proof_Context.theory_of lthy0;
blanchet@52170
  1217
traytel@53569
  1218
    val maybe_conceal_def_binding = Thm.def_binding
blanchet@58208
  1219
      #> not (Config.get lthy0 bnf_note_all) ? Binding.conceal;
traytel@53569
  1220
blanchet@55864
  1221
    val ((cst, (_, def)), (lthy', lthy)) = lthy0
blanchet@55864
  1222
      |> Local_Theory.define ((b, NoSyn), ((maybe_conceal_def_binding b, []), rhs))
blanchet@52327
  1223
      ||> `Local_Theory.restore;
blanchet@52327
  1224
blanchet@52327
  1225
    val phi = Proof_Context.export_morphism lthy lthy';
blanchet@52327
  1226
blanchet@58211
  1227
    val cst' = mk_co_rec thy fp Cs fpT (Morphism.term phi cst);
blanchet@55864
  1228
    val def' = Morphism.thm phi def;
blanchet@52327
  1229
  in
blanchet@55864
  1230
    ((cst', def'), lthy')
blanchet@52327
  1231
  end;
blanchet@52327
  1232
blanchet@56641
  1233
fun define_rec (_, _, fss, xssss) mk_binding fpTs Cs reps ctor_rec =
blanchet@56641
  1234
  let
blanchet@56641
  1235
    val nn = length fpTs;
blanchet@56641
  1236
    val (ctor_rec_absTs, fpT) = strip_typeN nn (fastype_of ctor_rec)
blanchet@56641
  1237
      |>> map domain_type ||> domain_type;
blanchet@56641
  1238
  in
blanchet@58210
  1239
    define_co_rec_as Least_FP Cs fpT (mk_binding recN)
blanchet@56641
  1240
      (fold_rev (fold_rev Term.lambda) fss (Term.list_comb (ctor_rec,
wenzelm@58634
  1241
         @{map 4} (fn ctor_rec_absT => fn rep => fn fs => fn xsss =>
blanchet@56641
  1242
             mk_case_absumprod ctor_rec_absT rep fs (map (map HOLogic.mk_tuple) xsss)
blanchet@56641
  1243
               (map flat_rec_arg_args xsss))
blanchet@56641
  1244
           ctor_rec_absTs reps fss xssss)))
blanchet@56641
  1245
  end;
blanchet@51897
  1246
desharna@58448
  1247
fun define_corec (_, cs, cpss, (((pgss, _, _, _), cqgsss), f_absTs)) mk_binding fpTs Cs abss dtor_corec =
blanchet@51897
  1248
  let
blanchet@51899
  1249
    val nn = length fpTs;
blanchet@55867
  1250
    val fpT = range_type (snd (strip_typeN nn (fastype_of dtor_corec)));
blanchet@51897
  1251
  in
blanchet@58210
  1252
    define_co_rec_as Greatest_FP Cs fpT (mk_binding corecN)
blanchet@55869
  1253
      (fold_rev (fold_rev Term.lambda) pgss (Term.list_comb (dtor_corec,
wenzelm@58634
  1254
         @{map 5} mk_preds_getterss_join cs cpss f_absTs abss cqgsss)))
blanchet@52320
  1255
  end;
blanchet@51897
  1256
desharna@57471
  1257
fun postproc_co_induct lthy nn prop prop_conj =
desharna@57471
  1258
  Drule.zero_var_indexes
desharna@57471
  1259
  #> `(conj_dests nn)
blanchet@58472
  1260
  #>> map (fn thm => Thm.permute_prems 0 ~1 (thm RS prop))
blanchet@58472
  1261
  ##> (fn thm => Thm.permute_prems 0 (~ nn)
desharna@57471
  1262
    (if nn = 1 then thm RS prop
desharna@57932
  1263
     else funpow nn (fn thm => unfold_thms lthy @{thms conj_assoc} (thm RS prop_conj)) thm));
desharna@57471
  1264
desharna@57471
  1265
fun mk_induct_attrs ctrss =
desharna@57471
  1266
  let
desharna@57471
  1267
    val induct_cases = quasi_unambiguous_case_names (maps (map name_of_ctr) ctrss);
desharna@57471
  1268
    val induct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names induct_cases));
desharna@57471
  1269
  in
desharna@57471
  1270
    [induct_case_names_attr]
desharna@57471
  1271
  end;
desharna@57471
  1272
blanchet@57535
  1273
fun derive_rel_induct_thms_for_types lthy fpA_Ts As Bs ctrAss ctrAs_Tsss exhausts ctor_rel_induct
blanchet@57535
  1274
    ctor_defss ctor_injects pre_rel_defs abs_inverses live_nesting_rel_eqs =
desharna@57471
  1275
  let
desharna@58446
  1276
    val B_ify_T = Term.typ_subst_atomic (As ~~ Bs);
desharna@58446
  1277
    val B_ify = Term.subst_atomic_types (As ~~ Bs);
desharna@58446
  1278
desharna@58446
  1279
    val fpB_Ts = map B_ify_T fpA_Ts;
desharna@58446
  1280
    val ctrBs_Tsss = map (map (map B_ify_T)) ctrAs_Tsss;
desharna@58446
  1281
    val ctrBss = map (map B_ify) ctrAss;
desharna@57471
  1282
desharna@57471
  1283
    val ((((Rs, IRs), ctrAsss), ctrBsss), names_lthy) = lthy
desharna@57471
  1284
      |> mk_Frees "R" (map2 mk_pred2T As Bs)
desharna@57471
  1285
      ||>> mk_Frees "IR" (map2 mk_pred2T fpA_Ts fpB_Ts)
desharna@57471
  1286
      ||>> mk_Freesss "a" ctrAs_Tsss
desharna@57471
  1287
      ||>> mk_Freesss "b" ctrBs_Tsss;
desharna@57471
  1288
blanchet@58291
  1289
    val prems =
desharna@57471
  1290
      let
desharna@57471
  1291
        fun mk_prem ctrA ctrB argAs argBs =
desharna@57471
  1292
          fold_rev Logic.all (argAs @ argBs) (fold_rev (curry Logic.mk_implies)
desharna@57565
  1293
            (map2 (HOLogic.mk_Trueprop oo build_rel_app names_lthy (Rs @ IRs) fpA_Ts) argAs argBs)
desharna@57565
  1294
            (HOLogic.mk_Trueprop (build_rel_app names_lthy (Rs @ IRs) fpA_Ts
desharna@57565
  1295
              (Term.list_comb (ctrA, argAs)) (Term.list_comb (ctrB, argBs)))));
desharna@57471
  1296
      in
wenzelm@58634
  1297
        flat (@{map 4} (@{map 4} mk_prem) ctrAss ctrBss ctrAsss ctrBsss)
desharna@57471
  1298
      end;
desharna@57471
  1299
desharna@57525
  1300
    val goal = HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 mk_leq
desharna@58104
  1301
      (map2 (build_the_rel [] lthy (Rs @ IRs) []) fpA_Ts fpB_Ts) IRs));
desharna@57471
  1302
blanchet@57898
  1303
    val rel_induct0_thm =
blanchet@58291
  1304
      Goal.prove_sorry lthy [] prems goal (fn {context = ctxt, prems} =>
wenzelm@59621
  1305
        mk_rel_induct0_tac ctxt ctor_rel_induct prems (map (Thm.cterm_of ctxt) IRs) exhausts ctor_defss
blanchet@57898
  1306
          ctor_injects pre_rel_defs abs_inverses live_nesting_rel_eqs)
desharna@57471
  1307
      |> singleton (Proof_Context.export names_lthy lthy)
desharna@57471
  1308
      |> Thm.close_derivation;
desharna@57471
  1309
  in
desharna@57471
  1310
    (postproc_co_induct lthy (length fpA_Ts) @{thm predicate2D} @{thm predicate2D_conj}
desharna@57471
  1311
       rel_induct0_thm,
desharna@57471
  1312
     mk_induct_attrs ctrAss)
desharna@57471
  1313
  end;
desharna@57471
  1314
blanchet@58335
  1315
fun derive_induct_recs_thms_for_types plugins pre_bnfs rec_args_typess ctor_induct ctor_rec_thms
blanchet@57397
  1316
    live_nesting_bnfs fp_nesting_bnfs fpTs Cs Xs ctrXs_Tsss fp_abs_inverses fp_type_definitions
blanchet@57397
  1317
    abs_inverses ctrss ctr_defss recs rec_defs lthy =
blanchet@51808
  1318
  let
blanchet@51827
  1319
    val ctr_Tsss = map (map (binder_types o fastype_of)) ctrss;
blanchet@51827
  1320
blanchet@51815
  1321
    val nn = length pre_bnfs;
blanchet@51827
  1322
    val ns = map length ctr_Tsss;
blanchet@51827
  1323
    val mss = map (map length) ctr_Tsss;
blanchet@51815
  1324
blanchet@51808
  1325
    val pre_map_defs = map map_def_of_bnf pre_bnfs;
blanchet@51808
  1326
    val pre_set_defss = map set_defs_of_bnf pre_bnfs;
blanchet@57399
  1327
    val live_nesting_map_ident0s = map map_ident0_of_bnf live_nesting_bnfs;
blanchet@57399
  1328
    val fp_nesting_map_ident0s = map map_ident0_of_bnf fp_nesting_bnfs;
blanchet@57397
  1329
    val fp_nesting_set_maps = maps set_map_of_bnf fp_nesting_bnfs;
blanchet@51808
  1330
blanchet@51816
  1331
    val fp_b_names = map base_name_of_typ fpTs;
blanchet@51811
  1332
blanchet@51832
  1333
    val ((((ps, ps'), xsss), us'), names_lthy) =
blanchet@52315
  1334
      lthy
blanchet@51808
  1335
      |> mk_Frees' "P" (map mk_pred1T fpTs)
blanchet@51827
  1336
      ||>> mk_Freesss "x" ctr_Tsss
blanchet@51816
  1337
      ||>> Variable.variant_fixes fp_b_names;
blanchet@51808
  1338
blanchet@51808
  1339
    val us = map2 (curry Free) us' fpTs;
blanchet@51808
  1340
blanchet@57665
  1341
    fun mk_sets bnf =
blanchet@51808
  1342
      let
blanchet@51808
  1343
        val Type (T_name, Us) = T_of_bnf bnf;
blanchet@51808
  1344
        val lives = lives_of_bnf bnf;
blanchet@51808
  1345
        val sets = sets_of_bnf bnf;
blanchet@51808
  1346
        fun mk_set U =
blanchet@54237
  1347
          (case find_index (curry (op =) U) lives of
blanchet@51808
  1348
            ~1 => Term.dummy
blanchet@51808
  1349
          | i => nth sets i);
blanchet@51808
  1350
      in
blanchet@51808
  1351
        (T_name, map mk_set Us)
blanchet@51808
  1352
      end;
blanchet@51808
  1353
blanchet@57665
  1354
    val setss_fp_nesting = map mk_sets fp_nesting_bnfs;
blanchet@51808
  1355
blanchet@51808
  1356
    val (induct_thms, induct_thm) =
blanchet@51808
  1357
      let
blanchet@52310
  1358
        fun mk_raw_prem_prems _ (x as Free (_, Type _)) (X as TFree _) =
blanchet@54237
  1359
            [([], (find_index (curry (op =) X) Xs + 1, x))]
blanchet@52310
  1360
          | mk_raw_prem_prems names_lthy (x as Free (s, Type (T_name, Ts0))) (Type (_, Xs_Ts0)) =
blanchet@57665
  1361
            (case AList.lookup (op =) setss_fp_nesting T_name of
blanchet@52310
  1362
              NONE => []
blanchet@52310
  1363
            | SOME raw_sets0 =>
blanchet@52310
  1364
              let
blanchet@52310
  1365
                val (Xs_Ts, (Ts, raw_sets)) =
blanchet@52310
  1366
                  filter (exists_subtype_in Xs o fst) (Xs_Ts0 ~~ (Ts0 ~~ raw_sets0))
blanchet@52310
  1367
                  |> split_list ||> split_list;
blanchet@52310
  1368
                val sets = map (mk_set Ts0) raw_sets;
blanchet@52310
  1369
                val (ys, names_lthy') = names_lthy |> mk_Frees s Ts;
blanchet@52310
  1370
                val xysets = map (pair x) (ys ~~ sets);
blanchet@52310
  1371
                val ppremss = map2 (mk_raw_prem_prems names_lthy') ys Xs_Ts;
blanchet@52310
  1372
              in
blanchet@52310
  1373
                flat (map2 (map o apfst o cons) xysets ppremss)
blanchet@52310
  1374
              end)
blanchet@52310
  1375
          | mk_raw_prem_prems _ _ _ = [];
blanchet@51808
  1376
blanchet@51808
  1377
        fun close_prem_prem xs t =
blanchet@51808
  1378
          fold_rev Logic.all (map Free (drop (nn + length xs)
blanchet@51808
  1379
            (rev (Term.add_frees t (map dest_Free xs @ ps'))))) t;
blanchet@51808
  1380
blanchet@51808
  1381
        fun mk_prem_prem xs (xysets, (j, x)) =
blanchet@51808
  1382
          close_prem_prem xs (Logic.list_implies (map (fn (x', (y, set)) =>
desharna@57567
  1383
              mk_Trueprop_mem (y, set $ x')) xysets,
blanchet@51808
  1384
            HOLogic.mk_Trueprop (nth ps (j - 1) $ x)));
blanchet@51808
  1385
blanchet@52310
  1386
        fun mk_raw_prem phi ctr ctr_Ts ctrXs_Ts =
blanchet@51808
  1387
          let
blanchet@51808
  1388
            val (xs, names_lthy') = names_lthy |> mk_Frees "x" ctr_Ts;
blanchet@52310
  1389
            val pprems = flat (map2 (mk_raw_prem_prems names_lthy') xs ctrXs_Ts);
blanchet@51808
  1390
          in (xs, pprems, HOLogic.mk_Trueprop (phi $ Term.list_comb (ctr, xs))) end;
blanchet@51808
  1391
blanchet@51808
  1392
        fun mk_prem (xs, raw_pprems, concl) =
blanchet@51808
  1393
          fold_rev Logic.all xs (Logic.list_implies (map (mk_prem_prem xs) raw_pprems, concl));
blanchet@51808
  1394
wenzelm@58634
  1395
        val raw_premss = @{map 4} (@{map 3} o mk_raw_prem) ps ctrss ctr_Tsss ctrXs_Tsss;
blanchet@51808
  1396
blanchet@51808
  1397
        val goal =
blanchet@51808
  1398
          Library.foldr (Logic.list_implies o apfst (map mk_prem)) (raw_premss,
blanchet@54237
  1399
            HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 (curry (op $)) ps us)));
blanchet@51808
  1400
blanchet@51808
  1401
        val kksss = map (map (map (fst o snd) o #2)) raw_premss;
blanchet@51808
  1402
traytel@55803
  1403
        val ctor_induct' = ctor_induct OF (map2 mk_absumprodE fp_type_definitions mss);
blanchet@51808
  1404
blanchet@51808
  1405
        val thm =
blanchet@51808
  1406
          Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
traytel@55803
  1407
            mk_induct_tac ctxt nn ns mss kksss (flat ctr_defss) ctor_induct' fp_abs_inverses
blanchet@57397
  1408
              abs_inverses fp_nesting_set_maps pre_set_defss)
blanchet@57633
  1409
          |> singleton (Proof_Context.export names_lthy lthy);
blanchet@51808
  1410
      in
blanchet@51808
  1411
        `(conj_dests nn) thm
blanchet@51808
  1412
      end;
blanchet@51808
  1413
blanchet@52305
  1414
    val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
blanchet@52305
  1415
blanchet@55867
  1416
    fun mk_rec_thmss (_, x_Tssss, fss, _) recs rec_defs ctor_rec_thms =
blanchet@51808
  1417
      let
blanchet@55867
  1418
        val frecs = map (lists_bmoc fss) recs;
blanchet@51808
  1419
blanchet@55871
  1420
        fun mk_goal frec xctr f xs fxs =
blanchet@51808
  1421
          fold_rev (fold_rev Logic.all) (xs :: fss)
blanchet@55867
  1422
            (mk_Trueprop_eq (frec $ xctr, Term.list_comb (f, fxs)));
blanchet@51808
  1423
blanchet@52302
  1424
        fun maybe_tick (T, U) u f =
blanchet@52302
  1425
          if try (fst o HOLogic.dest_prodT) U = SOME T then
blanchet@52302
  1426
            Term.lambda u (HOLogic.mk_prod (u, f $ u))
blanchet@52302
  1427
          else
blanchet@52302
  1428
            f;
blanchet@51808
  1429
blanchet@55867
  1430
        fun build_rec (x as Free (_, T)) U =
blanchet@52368
  1431
          if T = U then
blanchet@52368
  1432
            x
blanchet@52368
  1433
          else
blanchet@58352
  1434
            let
blanchet@58352
  1435
              val build_simple =
blanchet@58352
  1436
                indexify (perhaps (try (snd o HOLogic.dest_prodT)) o snd) Cs
blanchet@58352
  1437
                  (fn kk => fn TU => maybe_tick TU (nth us kk) (nth frecs kk));
blanchet@58352
  1438
            in
blanchet@58352
  1439
              build_map lthy [] build_simple (T, U) $ x
blanchet@58352
  1440
            end;
blanchet@52301
  1441
blanchet@55867
  1442
        val fxsss = map2 (map2 (flat_rec_arg_args oo map2 (map o build_rec))) xsss x_Tssss;
wenzelm@58634
  1443
        val goalss = @{map 5} (@{map 4} o mk_goal) frecs xctrss fss xsss fxsss;
blanchet@51808
  1444
wenzelm@58634
  1445
        val tacss = @{map 4} (map ooo
blanchet@57399
  1446
              mk_rec_tac pre_map_defs (fp_nesting_map_ident0s @ live_nesting_map_ident0s) rec_defs)
blanchet@55867
  1447
            ctor_rec_thms fp_abs_inverses abs_inverses ctr_defss;
blanchet@51808
  1448
blanchet@51808
  1449
        fun prove goal tac =
blanchet@51808
  1450
          Goal.prove_sorry lthy [] [] goal (tac o #context)
blanchet@51808
  1451
          |> Thm.close_derivation;
blanchet@51808
  1452
      in
blanchet@52305
  1453
        map2 (map2 prove) goalss tacss
blanchet@51808
  1454
      end;
blanchet@51808
  1455
blanchet@56641
  1456
    val rec_thmss = mk_rec_thmss (the rec_args_typess) recs rec_defs ctor_rec_thms;
blanchet@58335
  1457
blanchet@59283
  1458
    val code_attrs = if plugins code_plugin then [Code.add_default_eqn_attrib] else [];
blanchet@51808
  1459
  in
desharna@57471
  1460
    ((induct_thms, induct_thm, mk_induct_attrs ctrss),
blanchet@58335
  1461
     (rec_thmss, code_attrs @ nitpicksimp_attrs @ simp_attrs))
blanchet@51808
  1462
  end;
blanchet@51808
  1463
blanchet@58283
  1464
fun mk_coinduct_attrs fpTs ctrss discss mss =
desharna@57302
  1465
  let
desharna@57302
  1466
    val nn = length fpTs;
desharna@57302
  1467
    val fp_b_names = map base_name_of_typ fpTs;
blanchet@57535
  1468
desharna@57302
  1469
    fun mk_coinduct_concls ms discs ctrs =
desharna@57302
  1470
      let
desharna@57302
  1471
        fun mk_disc_concl disc = [name_of_disc disc];
desharna@57302
  1472
        fun mk_ctr_concl 0 _ = []
blanchet@58284
  1473
          | mk_ctr_concl _ ctr = [name_of_ctr ctr];
desharna@57302
  1474
        val disc_concls = map mk_disc_concl (fst (split_last discs)) @ [[]];
desharna@57302
  1475
        val ctr_concls = map2 mk_ctr_concl ms ctrs;
desharna@57302
  1476
      in
desharna@57302
  1477
        flat (map2 append disc_concls ctr_concls)
desharna@57302
  1478
      end;
blanchet@57535
  1479
desharna@57302
  1480
    val coinduct_cases = quasi_unambiguous_case_names (map (prefix EqN) fp_b_names);
desharna@57302
  1481
    val coinduct_conclss =
wenzelm@58634
  1482
      @{map 3} (quasi_unambiguous_case_names ooo mk_coinduct_concls) mss discss ctrss;
desharna@57302
  1483
desharna@57302
  1484
    val common_coinduct_consumes_attr = Attrib.internal (K (Rule_Cases.consumes nn));
desharna@57302
  1485
    val coinduct_consumes_attr = Attrib.internal (K (Rule_Cases.consumes 1));
desharna@57302
  1486
desharna@57302
  1487
    val coinduct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names coinduct_cases));
desharna@57302
  1488
    val coinduct_case_concl_attrs =
desharna@57302
  1489
      map2 (fn casex => fn concls =>
desharna@57302
  1490
          Attrib.internal (K (Rule_Cases.case_conclusion (casex, concls))))
desharna@57302
  1491
        coinduct_cases coinduct_conclss;
desharna@57302
  1492
desharna@57302
  1493
    val common_coinduct_attrs =
desharna@57302
  1494
      common_coinduct_consumes_attr :: coinduct_case_names_attr :: coinduct_case_concl_attrs;
desharna@57302
  1495
    val coinduct_attrs =
desharna@57302
  1496
      coinduct_consumes_attr :: coinduct_case_names_attr :: coinduct_case_concl_attrs;
desharna@57302
  1497
  in
desharna@57302
  1498
    (coinduct_attrs, common_coinduct_attrs)
desharna@57302
  1499
  end;
desharna@57302
  1500
blanchet@57535
  1501
fun derive_rel_coinduct_thm_for_types lthy fpA_Ts ns As Bs mss (ctr_sugars : ctr_sugar list)
blanchet@57535
  1502
    abs_inverses abs_injects ctor_injects dtor_ctors rel_pre_defs ctor_defss dtor_rel_coinduct
blanchet@57535
  1503
    live_nesting_rel_eqs =
desharna@57301
  1504
  let
desharna@58446
  1505
    val B_ify_T = Term.typ_subst_atomic (As ~~ Bs);
desharna@58446
  1506
    val fpB_Ts = map B_ify_T fpA_Ts;
desharna@57301
  1507
desharna@57301
  1508
    val (Rs, IRs, fpAs, fpBs, names_lthy) =
desharna@57301
  1509
      let
desharna@57301
  1510
        val fp_names = map base_name_of_typ fpA_Ts;
desharna@57301
  1511
        val ((((Rs, IRs), fpAs_names), fpBs_names), names_lthy) = lthy
desharna@57301
  1512
          |> mk_Frees "R" (map2 mk_pred2T As Bs)
desharna@57301
  1513
          ||>> mk_Frees "IR" (map2 mk_pred2T fpA_Ts fpB_Ts)
desharna@57301
  1514
          ||>> Variable.variant_fixes fp_names
desharna@57301
  1515
          ||>> Variable.variant_fixes (map (suffix "'") fp_names);
desharna@57301
  1516
      in
blanchet@58291
  1517
        (Rs, IRs, map2 (curry Free) fpAs_names fpA_Ts, map2 (curry Free) fpBs_names fpB_Ts,
blanchet@58291
  1518
         names_lthy)
desharna@57301
  1519
      end;
desharna@57301
  1520
desharna@57301
  1521
    val ((discA_tss, selA_tsss), (discB_tss, selB_tsss)) =
desharna@57301
  1522
      let
desharna@57301
  1523
        val discss = map #discs ctr_sugars;
desharna@57301
  1524
        val selsss = map #selss ctr_sugars;
blanchet@58291
  1525
desharna@57301
  1526
        fun mk_discss ts Ts = map2 (map o rapp) ts (map (map (mk_disc_or_sel Ts)) discss);
blanchet@58291
  1527
        fun mk_selsss ts Ts =
blanchet@58291
  1528
          map2 (map o map o rapp) ts (map (map (map (mk_disc_or_sel Ts))) selsss);
desharna@57301
  1529
      in
desharna@57302
  1530
        ((mk_discss fpAs As, mk_selsss fpAs As),
desharna@57302
  1531
         (mk_discss fpBs Bs, mk_selsss fpBs Bs))
desharna@57301
  1532
      end;
desharna@57301
  1533
blanchet@58291
  1534
    val prems =
desharna@57301
  1535
      let
desharna@57301
  1536
        fun mk_prem_ctr_concls n k discA_t selA_ts discB_t selB_ts =
desharna@57301
  1537
          (if k = n then [] else [HOLogic.mk_eq (discA_t, discB_t)]) @
desharna@57301
  1538
          (case (selA_ts, selB_ts) of
desharna@57303
  1539
            ([], []) => []
desharna@57301
  1540
          | (_ :: _, _ :: _) =>
desharna@57565
  1541
            [Library.foldr HOLogic.mk_imp
desharna@57565
  1542
              (if n = 1 then [] else [discA_t, discB_t],
desharna@57565
  1543
               Library.foldr1 HOLogic.mk_conj
desharna@57565
  1544
                 (map2 (build_rel_app lthy (Rs @ IRs) fpA_Ts) selA_ts selB_ts))]);
desharna@57301
  1545
desharna@57301
  1546
        fun mk_prem_concl n discA_ts selA_tss discB_ts selB_tss =
wenzelm@58634
  1547
          Library.foldr1 HOLogic.mk_conj (flat (@{map 5} (mk_prem_ctr_concls n)
desharna@57301
  1548
            (1 upto n) discA_ts selA_tss discB_ts selB_tss))
desharna@57301
  1549
          handle List.Empty => @{term True};
desharna@57301
  1550
desharna@57301
  1551
        fun mk_prem IR tA tB n discA_ts selA_tss discB_ts selB_tss =
desharna@57301
  1552
          fold_rev Logic.all [tA, tB] (Logic.mk_implies (HOLogic.mk_Trueprop (IR $ tA $ tB),
desharna@57301
  1553
            HOLogic.mk_Trueprop (mk_prem_concl n discA_ts selA_tss discB_ts selB_tss)));
desharna@57301
  1554
      in
wenzelm@58634
  1555
        @{map 8} mk_prem IRs fpAs fpBs ns discA_tss selA_tsss discB_tss selB_tsss
desharna@57301
  1556
      end;
desharna@57301
  1557
desharna@57525
  1558
    val goal = HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 mk_leq
desharna@58104
  1559
      IRs (map2 (build_the_rel [] lthy (Rs @ IRs) []) fpA_Ts fpB_Ts)));
desharna@57302
  1560
blanchet@57898
  1561
    val rel_coinduct0_thm =
blanchet@58291
  1562
      Goal.prove_sorry lthy [] prems goal (fn {context = ctxt, prems} =>
wenzelm@59621
  1563
        mk_rel_coinduct0_tac ctxt dtor_rel_coinduct (map (Thm.cterm_of ctxt) IRs) prems
blanchet@57898
  1564
          (map #exhaust ctr_sugars) (map (flat o #disc_thmss) ctr_sugars)
blanchet@57898
  1565
          (map (flat o #sel_thmss) ctr_sugars) ctor_defss dtor_ctors ctor_injects abs_injects
blanchet@57898
  1566
          rel_pre_defs abs_inverses live_nesting_rel_eqs)
desharna@57301
  1567
      |> singleton (Proof_Context.export names_lthy lthy)
desharna@57302
  1568
      |> Thm.close_derivation;
desharna@57302
  1569
  in
desharna@57471
  1570
    (postproc_co_induct lthy (length fpA_Ts) @{thm predicate2D} @{thm predicate2D_conj}
desharna@57471
  1571
       rel_coinduct0_thm,
blanchet@58283
  1572
     mk_coinduct_attrs fpA_Ts (map #ctrs ctr_sugars) (map #discs ctr_sugars) mss)
desharna@57301
  1573
  end;
desharna@57301
  1574
desharna@57700
  1575
fun derive_set_induct_thms_for_types lthy nn fpTs ctrss setss dtor_set_inducts exhausts
desharna@57700
  1576
    set_pre_defs ctor_defs dtor_ctors Abs_pre_inverses =
desharna@57700
  1577
  let
desharna@57700
  1578
    fun mk_prems A Ps ctr_args t ctxt =
desharna@57700
  1579
      (case fastype_of t of
desharna@57891
  1580
        Type (type_name, innerTs) =>
desharna@57700
  1581
        (case bnf_of ctxt type_name of
desharna@57700
  1582
          NONE => ([], ctxt)
desharna@57700
  1583
        | SOME bnf =>
desharna@57700
  1584
          let
desharna@57700
  1585
            fun seq_assm a set ctxt =
desharna@57700
  1586
              let
desharna@57700
  1587
                val X = HOLogic.dest_setT (range_type (fastype_of set));
desharna@57700
  1588
                val (x, ctxt') = yield_singleton (mk_Frees "x") X ctxt;
desharna@57700
  1589
                val assm = mk_Trueprop_mem (x, set $ a);
desharna@57700
  1590
              in
desharna@57700
  1591
                (case build_binary_fun_app Ps x a of
desharna@57700
  1592
                  NONE =>
desharna@57700
  1593
                  mk_prems A Ps ctr_args x ctxt'
desharna@57700
  1594
                  |>> map (Logic.all x o Logic.mk_implies o pair assm)
desharna@57700
  1595
                | SOME f =>
desharna@57700
  1596
                  ([Logic.all x
desharna@57700
  1597
                      (Logic.mk_implies (assm,
desharna@57700
  1598
                         Logic.mk_implies (HOLogic.mk_Trueprop f,
desharna@57700
  1599
                           HOLogic.mk_Trueprop (the (build_binary_fun_app Ps x ctr_args)))))],
desharna@57700
  1600
                   ctxt'))
desharna@57700
  1601
              end;
desharna@57700
  1602
          in
desharna@57891
  1603
            fold_map (seq_assm t o mk_set innerTs) (sets_of_bnf bnf) ctxt
desharna@57700
  1604
            |>> flat
desharna@57700
  1605
          end)
desharna@57700
  1606
      | T =>
desharna@57700
  1607
        if T = A then ([HOLogic.mk_Trueprop (the (build_binary_fun_app Ps t ctr_args))], ctxt)
desharna@57700
  1608
        else ([], ctxt));
desharna@57700
  1609
desharna@57700
  1610
    fun mk_prems_for_ctr A Ps ctr ctxt =
desharna@57700
  1611
      let
desharna@57893
  1612
        val (args, ctxt') = mk_Frees "z" (binder_types (fastype_of ctr)) ctxt;
desharna@57700
  1613
      in
desharna@57700
  1614
        fold_map (mk_prems A Ps (list_comb (ctr, args))) args ctxt'
desharna@57700
  1615
        |>> map (fold_rev Logic.all args) o flat
desharna@57700
  1616
        |>> (fn prems => (prems, mk_names (length prems) (name_of_ctr ctr)))
desharna@57700
  1617
      end;
desharna@57700
  1618
desharna@57700
  1619
    fun mk_prems_and_concl_for_type A Ps ((fpT, ctrs), set) ctxt =
desharna@57700
  1620
      let
desharna@57700
  1621
        val ((x, fp), ctxt') = ctxt
desharna@57700
  1622
          |> yield_singleton (mk_Frees "x") A
desharna@57700
  1623
          ||>> yield_singleton (mk_Frees "a") fpT;
desharna@57700
  1624
        val concl = mk_Ball (set $ fp) (Term.absfree (dest_Free x)
desharna@57700
  1625
          (the (build_binary_fun_app Ps x fp)));
desharna@57700
  1626
      in
desharna@57700
  1627
        fold_map (mk_prems_for_ctr A Ps) ctrs ctxt'
desharna@57700
  1628
        |>> split_list
desharna@57700
  1629
        |>> map_prod flat flat
desharna@57700
  1630
        |>> apfst (rpair concl)
desharna@57700
  1631
      end;
desharna@57700
  1632
desharna@57700
  1633
    fun mk_thm ctxt fpTs ctrss sets =
desharna@57700
  1634
      let
desharna@57700
  1635
        val A = HOLogic.dest_setT (range_type (fastype_of (hd sets)));
desharna@57700
  1636
        val (Ps, ctxt') = mk_Frees "P" (map (fn fpT => A --> fpT --> HOLogic.boolT) fpTs) ctxt;
blanchet@58291
  1637
        val (((prems, concl), case_names), ctxt'') =
blanchet@58291
  1638
          fold_map (mk_prems_and_concl_for_type A Ps) (fpTs ~~ ctrss ~~ sets) ctxt'
desharna@57700
  1639
          |>> apfst split_list o split_list
desharna@57700
  1640
          |>> apfst (apfst flat)
desharna@57700
  1641
          |>> apfst (apsnd (Library.foldr1 HOLogic.mk_conj))
desharna@57700
  1642
          |>> apsnd flat;
desharna@57700
  1643
blanchet@57898
  1644
        val thm =
blanchet@58291
  1645
          Goal.prove_sorry lthy [] prems (HOLogic.mk_Trueprop concl)
blanchet@57898
  1646
            (fn {context = ctxt, prems} =>
wenzelm@59621
  1647
               mk_set_induct0_tac ctxt (map (Thm.cterm_of ctxt'') Ps) prems dtor_set_inducts exhausts
blanchet@57898
  1648
                 set_pre_defs ctor_defs dtor_ctors Abs_pre_inverses)
desharna@57700
  1649
          |> singleton (Proof_Context.export ctxt'' ctxt)
desharna@57700
  1650
          |> Thm.close_derivation;
desharna@57700
  1651
desharna@57700
  1652
        val case_names_attr =
desharna@57700
  1653
          Attrib.internal (K (Rule_Cases.case_names (quasi_unambiguous_case_names case_names)));
desharna@57700
  1654
        val induct_set_attrs = map (Attrib.internal o K o Induct.induct_pred o name_of_set) sets;
desharna@57700
  1655
      in
desharna@57700
  1656
        (thm, case_names_attr :: induct_set_attrs)
desharna@57700
  1657
      end
desharna@57700
  1658
    val consumes_attr = Attrib.internal (K (Rule_Cases.consumes 1));
desharna@57700
  1659
  in
blanchet@58472
  1660
    map (mk_thm lthy fpTs ctrss
blanchet@58472
  1661
        #> nn = 1 ? map_prod (fn thm => rotate_prems ~1 (thm RS bspec)) (cons consumes_attr))
blanchet@58472
  1662
      (transpose setss)
desharna@57700
  1663
  end;
desharna@57700
  1664
desharna@58448
  1665
fun derive_coinduct_corecs_thms_for_types pre_bnfs (x, cs, cpss, (((pgss, _, _, _), cqgsss), _))
blanchet@57397
  1666
    dtor_coinduct dtor_injects dtor_ctors dtor_corec_thms live_nesting_bnfs fpTs Cs Xs ctrXs_Tsss
blanchet@57397
  1667
    kss mss ns fp_abs_inverses abs_inverses mk_vimage2p ctr_defss (ctr_sugars : ctr_sugar list)
blanchet@55864
  1668
    corecs corec_defs export_args lthy =
blanchet@51810
  1669
  let
blanchet@55867
  1670
    fun mk_ctor_dtor_corec_thm dtor_inject dtor_ctor corec =
blanchet@55867
  1671
      iffD1 OF [dtor_inject, trans OF [corec, dtor_ctor RS sym]];
traytel@53203
  1672
wenzelm@58634
  1673
    val ctor_dtor_corec_thms =
wenzelm@58634
  1674
      @{map 3} mk_ctor_dtor_corec_thm dtor_injects dtor_ctors dtor_corec_thms;
traytel@53203
  1675
blanchet@51815
  1676
    val nn = length pre_bnfs;
blanchet@51815
  1677
blanchet@51810
  1678
    val pre_map_defs = map map_def_of_bnf pre_bnfs;
blanchet@51810
  1679
    val pre_rel_defs = map rel_def_of_bnf pre_bnfs;
blanchet@57399
  1680
    val live_nesting_map_ident0s = map map_ident0_of_bnf live_nesting_bnfs;
blanchet@57397
  1681
    val live_nesting_rel_eqs = map rel_eq_of_bnf live_nesting_bnfs;
blanchet@51810
  1682
blanchet@51816
  1683
    val fp_b_names = map base_name_of_typ fpTs;
blanchet@51811
  1684
blanchet@53210
  1685
    val ctrss = map #ctrs ctr_sugars;
blanchet@53210
  1686
    val discss = map #discs ctr_sugars;
blanchet@53210
  1687
    val selsss = map #selss ctr_sugars;
blanchet@51840
  1688
    val exhausts = map #exhaust ctr_sugars;
blanchet@51840
  1689
    val disc_thmsss = map #disc_thmss ctr_sugars;
blanchet@51840
  1690
    val discIss = map #discIs ctr_sugars;
blanchet@51840
  1691
    val sel_thmsss = map #sel_thmss ctr_sugars;
blanchet@51810
  1692
blanchet@51810
  1693
    val (((rs, us'), vs'), names_lthy) =
blanchet@52341
  1694
      lthy
blanchet@51810
  1695
      |> mk_Frees "R" (map (fn T => mk_pred2T T T) fpTs)
blanchet@51816
  1696
      ||>> Variable.variant_fixes fp_b_names
blanchet@51816
  1697
      ||>> Variable.variant_fixes (map (suffix "'") fp_b_names);
blanchet@51810
  1698
blanchet@51810
  1699
    val us = map2 (curry Free) us' fpTs;
blanchet@51810
  1700
    val udiscss = map2 (map o rapp) us discss;
blanchet@51810
  1701
    val uselsss = map2 (map o map o rapp) us selsss;
blanchet@51810
  1702
blanchet@51810
  1703
    val vs = map2 (curry Free) vs' fpTs;
blanchet@51810
  1704
    val vdiscss = map2 (map o rapp) vs discss;
blanchet@51810
  1705
    val vselsss = map2 (map o map o rapp) vs selsss;
blanchet@51810
  1706
blanchet@52345
  1707
    val coinduct_thms_pairs =
blanchet@51810
  1708
      let
wenzelm@58634
  1709
        val uvrs = @{map 3} (fn r => fn u => fn v => r $ u $ v) rs us vs;
blanchet@51810
  1710
        val uv_eqs = map2 (curry HOLogic.mk_eq) us vs;
blanchet@51810
  1711
        val strong_rs =
wenzelm@58634
  1712
          @{map 4} (fn u => fn v => fn uvr => fn uv_eq =>
blanchet@51810
  1713
            fold_rev Term.lambda [u, v] (HOLogic.mk_disj (uvr, uv_eq))) us vs uvrs uv_eqs;
blanchet@51810
  1714
blanchet@54237
  1715
        fun build_the_rel rs' T Xs_T =
desharna@58104
  1716
          build_rel [] lthy [] (fn (_, X) => nth rs' (find_index (curry (op =) X) Xs)) (T, Xs_T)
blanchet@54237
  1717
          |> Term.subst_atomic_types (Xs ~~ fpTs);
blanchet@51810
  1718
blanchet@54237
  1719
        fun build_rel_app rs' usel vsel Xs_T =
blanchet@54237
  1720
          fold rapp [usel, vsel] (build_the_rel rs' (fastype_of usel) Xs_T);
blanchet@51810
  1721
blanchet@54237
  1722
        fun mk_prem_ctr_concls rs' n k udisc usels vdisc vsels ctrXs_Ts =
blanchet@51810
  1723
          (if k = n then [] else [HOLogic.mk_eq (udisc, vdisc)]) @
blanchet@51810
  1724
          (if null usels then
blanchet@51810
  1725
             []
blanchet@51810
  1726
           else
blanchet@51810
  1727
             [Library.foldr HOLogic.mk_imp (if n = 1 then [] else [udisc, vdisc],
wenzelm@58634
  1728
                Library.foldr1 HOLogic.mk_conj (@{map 3} (build_rel_app rs') usels vsels ctrXs_Ts))]);
blanchet@51810
  1729
blanchet@54237
  1730
        fun mk_prem_concl rs' n udiscs uselss vdiscs vselss ctrXs_Tss =
wenzelm@58634
  1731
          Library.foldr1 HOLogic.mk_conj (flat (@{map 6} (mk_prem_ctr_concls rs' n)
blanchet@54237
  1732
            (1 upto n) udiscs uselss vdiscs vselss ctrXs_Tss))
blanchet@51810
  1733
          handle List.Empty => @{term True};
blanchet@51810
  1734
blanchet@54237
  1735
        fun mk_prem rs' uvr u v n udiscs uselss vdiscs vselss ctrXs_Tss =
blanchet@51810
  1736
          fold_rev Logic.all [u, v] (Logic.mk_implies (HOLogic.mk_Trueprop uvr,
blanchet@54237
  1737
            HOLogic.mk_Trueprop (mk_prem_concl rs' n udiscs uselss vdiscs vselss ctrXs_Tss)));
blanchet@51810
  1738
blanchet@51810
  1739
        val concl =
blanchet@51810
  1740
          HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
wenzelm@58634
  1741
            (@{map 3} (fn uvr => fn u => fn v => HOLogic.mk_imp (uvr, HOLogic.mk_eq (u, v)))
blanchet@51810
  1742
               uvrs us vs));
blanchet@51810
  1743
blanchet@51810
  1744
        fun mk_goal rs' =
wenzelm@58634
  1745
          Logic.list_implies (@{map 9} (mk_prem rs') uvrs us vs ns udiscss uselsss vdiscss vselsss
blanchet@54237
  1746
            ctrXs_Tsss, concl);
blanchet@51810
  1747
blanchet@52345
  1748
        val goals = map mk_goal [rs, strong_rs];
blanchet@51810
  1749
blanchet@51810
  1750
        fun prove dtor_coinduct' goal =
blanchet@51810
  1751
          Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@57397
  1752
            mk_coinduct_tac ctxt live_nesting_rel_eqs nn ns dtor_coinduct' pre_rel_defs
blanchet@57397
  1753
              fp_abs_inverses abs_inverses dtor_ctors exhausts ctr_defss disc_thmsss sel_thmsss)
blanchet@51810
  1754
          |> singleton (Proof_Context.export names_lthy lthy)
blanchet@51810
  1755
          |> Thm.close_derivation;
blanchet@51810
  1756
traytel@53106
  1757
        val rel_eqs = map rel_eq_of_bnf pre_bnfs;
traytel@53106
  1758
        val rel_monos = map rel_mono_of_bnf pre_bnfs;
traytel@53106
  1759
        val dtor_coinducts =
blanchet@57983
  1760
          [dtor_coinduct, mk_coinduct_strong_thm dtor_coinduct rel_eqs rel_monos mk_vimage2p lthy]
blanchet@51810
  1761
      in
desharna@57471
  1762
        map2 (postproc_co_induct lthy nn mp mp_conj oo prove) dtor_coinducts goals
blanchet@51810
  1763
      end;
blanchet@51810
  1764
blanchet@51810
  1765
    fun mk_maybe_not pos = not pos ? HOLogic.mk_not;
blanchet@51810
  1766
blanchet@55869
  1767
    val gcorecs = map (lists_bmoc pgss) corecs;
blanchet@51810
  1768
blanchet@55856
  1769
    val corec_thmss =
blanchet@51810
  1770
      let
blanchet@55869
  1771
        fun mk_goal c cps gcorec n k ctr m cfs' =
blanchet@55869
  1772
          fold_rev (fold_rev Logic.all) ([c] :: pgss)
blanchet@51810
  1773
            (Logic.list_implies (seq_conds (HOLogic.mk_Trueprop oo mk_maybe_not) n k cps,
blanchet@55869
  1774
               mk_Trueprop_eq (gcorec $ c, Term.list_comb (ctr, take m cfs'))));
blanchet@51810
  1775
blanchet@55869
  1776
        val mk_U = typ_subst_nonatomic (map2 (fn C => fn fpT => (mk_sumT (fpT, C), fpT)) Cs fpTs);
blanchet@52347
  1777
blanchet@55869
  1778
        fun tack (c, u) f =
blanchet@55869
  1779
          let val x' = Free (x, mk_sumT (fastype_of u, fastype_of c)) in
blanchet@55869
  1780
            Term.lambda x' (mk_case_sum (Term.lambda u u, Term.lambda c (f $ c)) $ x')
blanchet@52347
  1781
          end;
blanchet@51810
  1782
blanchet@55869
  1783
        fun build_corec cqg =
blanchet@55869
  1784
          let val T = fastype_of cqg in
blanchet@52347
  1785
            if exists_subtype_in Cs T then
blanchet@58352
  1786
              let
blanchet@58352
  1787
                val U = mk_U T;
blanchet@58352
  1788
                val build_simple =
blanchet@58352
  1789
                  indexify fst (map2 (curry mk_sumT) fpTs Cs)
blanchet@58352
  1790
                    (fn kk => fn _ => tack (nth cs kk, nth us kk) (nth gcorecs kk));
blanchet@58352
  1791
              in
blanchet@58352
  1792
                build_map lthy [] build_simple (T, U) $ cqg
blanchet@52368
  1793
              end
blanchet@52347
  1794
            else
blanchet@55869
  1795
              cqg
blanchet@52347
  1796
          end;
blanchet@51810
  1797
blanchet@55869
  1798
        val cqgsss' = map (map (map build_corec)) cqgsss;
wenzelm@58634
  1799
        val goalss = @{map 8} (@{map 4} oooo mk_goal) cs cpss gcorecs ns kss ctrss mss cqgsss';
blanchet@51810
  1800
blanchet@55856
  1801
        val tacss =
wenzelm@58634
  1802
          @{map 4} (map ooo mk_corec_tac corec_defs live_nesting_map_ident0s)
blanchet@55867
  1803
            ctor_dtor_corec_thms pre_map_defs abs_inverses ctr_defss;
blanchet@51810
  1804
blanchet@51810
  1805
        fun prove goal tac =
blanchet@51815
  1806
          Goal.prove_sorry lthy [] [] goal (tac o #context)
blanchet@51815
  1807
          |> Thm.close_derivation;
blanchet@51810
  1808
      in
blanchet@55856
  1809
        map2 (map2 prove) goalss tacss
blanchet@55856
  1810
        |> map (map (unfold_thms lthy @{thms case_sum_if}))
blanchet@51810
  1811
      end;
blanchet@51810
  1812
blanchet@57983
  1813
    val corec_disc_iff_thmss =
blanchet@51810
  1814
      let
blanchet@55869
  1815
        fun mk_goal c cps gcorec n k disc =
blanchet@55869
  1816
          mk_Trueprop_eq (disc $ (gcorec $ c),
blanchet@51810
  1817
            if n = 1 then @{const True}
blanchet@51810
  1818
            else Library.foldr1 HOLogic.mk_conj (seq_conds mk_maybe_not n k cps));
blanchet@51810
  1819
wenzelm@58634
  1820
        val goalss = @{map 6} (map2 oooo mk_goal) cs cpss gcorecs ns kss discss;
blanchet@51810
  1821
wenzelm@59621
  1822
        fun mk_case_split' cp = Drule.instantiate' [] [SOME (Thm.cterm_of lthy cp)] @{thm case_split};
blanchet@51810
  1823
blanchet@51810
  1824
        val case_splitss' = map (map mk_case_split') cpss;
blanchet@51810
  1825
wenzelm@58634
  1826
        val tacss = @{map 3} (map oo mk_corec_disc_iff_tac) case_splitss' corec_thmss disc_thmsss;
blanchet@51810
  1827
blanchet@51810
  1828
        fun prove goal tac =
blanchet@51810
  1829
          Goal.prove_sorry lthy [] [] goal (tac o #context)
blanchet@52357
  1830
          |> singleton export_args
blanchet@51829
  1831
          |> singleton (Proof_Context.export names_lthy lthy)
blanchet@51810
  1832
          |> Thm.close_derivation;
blanchet@51810
  1833
blanchet@51810
  1834
        fun proves [_] [_] = []
blanchet@51810
  1835
          | proves goals tacs = map2 prove goals tacs;
blanchet@51810
  1836
      in
blanchet@55856
  1837
        map2 proves goalss tacss
blanchet@51810
  1838
      end;
blanchet@51810
  1839
blanchet@57983
  1840
    fun mk_corec_disc_thms corecs discIs = map (op RS) (corecs ~~ discIs);
blanchet@51810
  1841
blanchet@57983
  1842
    val corec_disc_thmss = map2 mk_corec_disc_thms corec_thmss discIss;
blanchet@51810
  1843
blanchet@57983
  1844
    fun mk_corec_sel_thm corec_thm sel sel_thm =
blanchet@51810
  1845
      let
blanchet@51810
  1846
        val (domT, ranT) = dest_funT (fastype_of sel);
blanchet@51810
  1847
        val arg_cong' =
wenzelm@59621
  1848
          Drule.instantiate' (map (SOME o Thm.ctyp_of lthy) [domT, ranT])
wenzelm@59621
  1849
            [NONE, NONE, SOME (Thm.cterm_of lthy sel)] arg_cong
blanchet@51810
  1850
          |> Thm.varifyT_global;
blanchet@51810
  1851
        val sel_thm' = sel_thm RSN (2, trans);
blanchet@51810
  1852
      in
blanchet@55867
  1853
        corec_thm RS arg_cong' RS sel_thm'
blanchet@51810
  1854
      end;
blanchet@51810
  1855
blanchet@57983
  1856
    fun mk_corec_sel_thms corec_thmss =
wenzelm@58634
  1857
      @{map 3} (@{map 3} (map2 o mk_corec_sel_thm)) corec_thmss selsss sel_thmsss;
blanchet@51810
  1858
blanchet@57983
  1859
    val corec_sel_thmsss = mk_corec_sel_thms corec_thmss;
blanchet@51810
  1860
  in
blanchet@57535
  1861
    ((coinduct_thms_pairs,
blanchet@58283
  1862
      mk_coinduct_attrs fpTs (map #ctrs ctr_sugars) (map #discs ctr_sugars) mss),
desharna@57489
  1863
     corec_thmss,
blanchet@57983
  1864
     corec_disc_thmss,
blanchet@57983
  1865
     (corec_disc_iff_thmss, simp_attrs),
blanchet@57983
  1866
     (corec_sel_thmsss, simp_attrs))
blanchet@51810
  1867
  end;
blanchet@51810
  1868
wenzelm@58659
  1869
fun define_co_datatypes prepare_plugins prepare_constraint prepare_typ prepare_term fp construct_fp
wenzelm@58659
  1870
    ((raw_plugins, discs_sels0), specs) no_defs_lthy =
blanchet@49112
  1871
  let
blanchet@49298
  1872
    (* TODO: sanity checks on arguments *)
blanchet@49298
  1873
wenzelm@58659
  1874
    val plugins = prepare_plugins no_defs_lthy raw_plugins;
blanchet@57094
  1875
    val discs_sels = discs_sels0 orelse fp = Greatest_FP;
blanchet@49278
  1876
blanchet@49367
  1877
    val nn = length specs;
blanchet@55469
  1878
    val fp_bs = map type_binding_of_spec specs;
blanchet@49498
  1879
    val fp_b_names = map Binding.name_of fp_bs;
blanchet@49498
  1880
    val fp_common_name = mk_common_name fp_b_names;
blanchet@55469
  1881
    val map_bs = map map_binding_of_spec specs;
blanchet@55469
  1882
    val rel_bs = map rel_binding_of_spec specs;
blanchet@49298
  1883
blanchet@51758
  1884
    fun prepare_type_arg (_, (ty, c)) =
blanchet@58434
  1885
      let val TFree (s, _) = prepare_typ no_defs_lthy ty in
blanchet@58434
  1886
        TFree (s, prepare_constraint no_defs_lthy c)
blanchet@49298
  1887
      end;
blanchet@49298
  1888
blanchet@55469
  1889
    val Ass0 = map (map prepare_type_arg o type_args_named_constrained_of_spec) specs;
blanchet@58234
  1890
    val unsorted_Ass0 = map (map (resort_tfree_or_tvar @{sort type})) Ass0;
blanchet@55700
  1891
    val unsorted_As = Library.foldr1 (merge_type_args fp) unsorted_Ass0;
blanchet@53266
  1892
    val num_As = length unsorted_As;
blanchet@55699
  1893
blanchet@55699
  1894
    val set_boss = map (map fst o type_args_named_constrained_of_spec) specs;
blanchet@55699
  1895
    val set_bss = map (map (the_default Binding.empty)) set_boss;
blanchet@49119
  1896
desharna@58446
  1897
    val ((((Bs0, Cs), Es), Xs), names_no_defs_lthy) =
blanchet@58434
  1898
      no_defs_lthy
blanchet@58234
  1899
      |> fold (Variable.declare_typ o resort_tfree_or_tvar dummyS) unsorted_As
blanchet@53266
  1900
      |> mk_TFrees num_As
blanchet@49585
  1901
      ||>> mk_TFrees nn
desharna@58446
  1902
      ||>> mk_TFrees nn
blanchet@51858
  1903
      ||>> variant_tfrees fp_b_names;
blanchet@49119
  1904
blanchet@55469
  1905
    fun add_fake_type spec =
blanchet@55469
  1906
      Typedecl.basic_typedecl (type_binding_of_spec spec, num_As, mixfix_of_spec spec);
blanchet@51768
  1907
blanchet@58434
  1908
    val (fake_T_names, fake_lthy) = fold_map add_fake_type specs no_defs_lthy;
blanchet@49119
  1909
blanchet@53262
  1910
    val qsoty = quote o Syntax.string_of_typ fake_lthy;
blanchet@53262
  1911
blanchet@54253
  1912
    val _ = (case Library.duplicates (op =) unsorted_As of [] => ()
blanchet@53262
  1913
      | A :: _ => error ("Duplicate type parameter " ^ qsoty A ^ " in " ^ co_prefix fp ^
blanchet@53262
  1914
          "datatype specification"));
blanchet@53262
  1915
blanchet@53262
  1916
    val bad_args =
blanchet@58434
  1917
      map (Logic.type_map (singleton (Variable.polymorphic no_defs_lthy))) unsorted_As
blanchet@53262
  1918
      |> filter_out Term.is_TVar;
blanchet@53262
  1919
    val _ = null bad_args orelse
blanchet@53262
  1920
      error ("Locally fixed type argument " ^ qsoty (hd bad_args) ^ " in " ^ co_prefix fp ^
blanchet@53262
  1921
        "datatype specification");
blanchet@53262
  1922
blanchet@55469
  1923
    val mixfixes = map mixfix_of_spec specs;
blanchet@49119
  1924
blanchet@54253
  1925
    val _ = (case Library.duplicates Binding.eq_name fp_bs of [] => ()
blanchet@49119
  1926
      | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
blanchet@49119
  1927
blanchet@55469
  1928
    val mx_ctr_specss = map mixfixed_ctr_specs_of_spec specs;
blanchet@55469
  1929
    val ctr_specss = map (map fst) mx_ctr_specss;
blanchet@55469
  1930
    val ctr_mixfixess = map (map snd) mx_ctr_specss;
blanchet@49119
  1931
blanchet@55469
  1932
    val disc_bindingss = map (map disc_of_ctr_spec) ctr_specss;
blanchet@49336
  1933
    val ctr_bindingss =
blanchet@55469
  1934
      map2 (fn fp_b_name => map (Binding.qualify false fp_b_name o ctr_of_ctr_spec)) fp_b_names
blanchet@55469
  1935
        ctr_specss;
blanchet@55469
  1936
    val ctr_argsss = map (map args_of_ctr_spec) ctr_specss;
blanchet@49119
  1937
blanchet@49336
  1938
    val sel_bindingsss = map (map (map fst)) ctr_argsss;
blanchet@49298
  1939
    val fake_ctr_Tsss0 = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
blanchet@57200
  1940
    val raw_sel_default_eqss = map sel_default_eqs_of_spec specs;
blanchet@49286
  1941
blanchet@49308
  1942
    val (As :: _) :: fake_ctr_Tsss =
blanchet@49298
  1943
      burrow (burrow (Syntax.check_typs fake_lthy)) (Ass0 :: fake_ctr_Tsss0);
blanchet@53262
  1944
    val As' = map dest_TFree As;
blanchet@49298
  1945
blanchet@49183
  1946
    val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
blanchet@53262
  1947
    val _ = (case subtract (op =) As' rhs_As' of [] => ()
blanchet@53262
  1948
      | extras => error ("Extra type variables on right-hand side: " ^
blanchet@53262
  1949
          commas (map (qsoty o TFree) extras)));
blanchet@49165
  1950
blanchet@53268
  1951
    val fake_Ts = map (fn s => Type (s, As)) fake_T_names;
blanchet@53268
  1952
blanchet@53262
  1953
    fun eq_fpT_check (T as Type (s, Ts)) (T' as Type (s', Ts')) =
blanchet@53262
  1954
        s = s' andalso (Ts = Ts' orelse
blanchet@53262
  1955
          error ("Wrong type arguments in " ^ co_prefix fp ^ "recursive type " ^ qsoty T ^
blanchet@53262
  1956
            " (expected " ^ qsoty T' ^ ")"))
blanchet@49591
  1957
      | eq_fpT_check _ _ = false;
blanchet@49146
  1958
blanchet@53222
  1959
    fun freeze_fp (T as Type (s, Ts)) =
blanchet@49591
  1960
        (case find_index (eq_fpT_check T) fake_Ts of
blanchet@53222
  1961
          ~1 => Type (s, map freeze_fp Ts)
blanchet@49591
  1962
        | kk => nth Xs kk)
blanchet@49204
  1963
      | freeze_fp T = T;
blanchet@49121
  1964
blanchet@53222
  1965
    val unfreeze_fp = Term.typ_subst_atomic (Xs ~~ fake_Ts);
blanchet@53222
  1966
blanchet@52310
  1967
    val ctrXs_Tsss = map (map (map freeze_fp)) fake_ctr_Tsss;
blanchet@55966
  1968
    val ctrXs_repTs = map mk_sumprodT_balanced ctrXs_Tsss;
blanchet@49119
  1969
desharna@58731
  1970
    val _ =
desharna@58731
  1971
      let
desharna@58731
  1972
        fun mk_edges Xs ctrXs_Tsss =
desharna@58731
  1973
          let
desharna@58731
  1974
            fun add_edges i =
desharna@58731
  1975
              fold (fn T => fold_index (fn (j, X) =>
desharna@58731
  1976
                exists_subtype (curry (op =) X) T ? cons (i, j)) Xs);
desharna@58731
  1977
          in
desharna@58731
  1978
            fold_index (uncurry (fold o add_edges)) ctrXs_Tsss []
desharna@58731
  1979
          end;
desharna@58731
  1980
desharna@58731
  1981
        fun mk_graph nn edges =
desharna@58731
  1982
          Int_Graph.empty
desharna@58731
  1983
          |> fold (fn kk => Int_Graph.new_node (kk, ())) (0 upto nn - 1)
desharna@58731
  1984
          |> fold Int_Graph.add_edge edges;
desharna@58731
  1985
desharna@58731
  1986
        val str_of_scc = curry (op ^) (co_prefix fp ^ "datatype ") o
desharna@58731
  1987
          space_implode " and " o map (suffix " = \<dots>" o Long_Name.base_name);
desharna@58731
  1988
desharna@58731
  1989
        fun warn [_] = ()
desharna@58731
  1990
          | warn sccs =
desharna@58731
  1991
            warning ("Defined types not fully mutually " ^ co_prefix fp ^ "recursive\n\
desharna@58731
  1992
              \Alternative specification:\n" ^
desharna@58731
  1993
              cat_lines (map (prefix "  " o str_of_scc o map (nth fp_b_names)) sccs));
desharna@58731
  1994
desharna@58731
  1995
        val edges = mk_edges Xs ctrXs_Tsss;
desharna@58731
  1996
        val G = mk_graph nn edges;
desharna@58731
  1997
        val sccs = rev (map (sort int_ord) (Int_Graph.strong_conn G));
desharna@58731
  1998
      in warn sccs end;
desharna@58731
  1999
blanchet@58507
  2000
    val fp_eqs = map dest_TFree Xs ~~ map (Term.typ_subst_atomic (As ~~ unsorted_As)) ctrXs_repTs;
blanchet@49121
  2001
blanchet@55701
  2002
    val killed_As =
blanchet@55701
  2003
      map_filter (fn (A, set_bos) => if exists is_none set_bos then SOME A else NONE)
blanchet@55701
  2004
        (unsorted_As ~~ transpose set_boss);
blanchet@55701
  2005
traytel@55803
  2006
    val ((pre_bnfs, absT_infos), (fp_res as {bnfs = fp_bnfs as any_fp_bnf :: _, ctors = ctors0,
blanchet@55868
  2007
             dtors = dtors0, xtor_co_recs = xtor_co_recs0, xtor_co_induct, dtor_ctors,
desharna@58585
  2008
             ctor_dtors, ctor_injects, dtor_injects, xtor_maps, xtor_setss, xtor_rels,
desharna@58580
  2009
             xtor_co_rec_thms, xtor_rel_co_induct, dtor_set_inducts,
desharna@58732
  2010
             xtor_co_rec_transfers, xtor_co_rec_o_maps, ...},
traytel@53203
  2011
           lthy)) =
blanchet@55701
  2012
      fp_bnf (construct_fp mixfixes map_bs rel_bs set_bss) fp_bs (map dest_TFree unsorted_As)
blanchet@58434
  2013
        (map dest_TFree killed_As) fp_eqs no_defs_lthy
blanchet@53222
  2014
      handle BAD_DEAD (X, X_backdrop) =>
blanchet@53222
  2015
        (case X_backdrop of
blanchet@53222
  2016
          Type (bad_tc, _) =>
blanchet@53222
  2017
          let
blanchet@53222
  2018
            val fake_T = qsoty (unfreeze_fp X);
blanchet@53222
  2019
            val fake_T_backdrop = qsoty (unfreeze_fp X_backdrop);
blanchet@53222
  2020
            fun register_hint () =
wenzelm@58928
  2021
              "\nUse the " ^ quote (#1 @{command_spec "bnf"}) ^ " command to register " ^
blanchet@53222
  2022
              quote bad_tc ^ " as a bounded natural functor to allow nested (co)recursion through \
blanchet@53222
  2023
              \it";
blanchet@53222
  2024
          in
blanchet@53222
  2025
            if is_some (bnf_of no_defs_lthy bad_tc) orelse
blanchet@53222
  2026
               is_some (fp_sugar_of no_defs_lthy bad_tc) then
blanchet@53256
  2027
              error ("Inadmissible " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
blanchet@53256
  2028
                " in type expression " ^ fake_T_backdrop)
blanchet@58112
  2029
            else if is_some (Old_Datatype_Data.get_info (Proof_Context.theory_of no_defs_lthy)
blanchet@53222
  2030
                bad_tc) then
blanchet@53222
  2031
              error ("Unsupported " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
blanchet@53222
  2032
                " via the old-style datatype " ^ quote bad_tc ^ " in type expression " ^
blanchet@53222
  2033
                fake_T_backdrop ^ register_hint ())
blanchet@53222
  2034
            else
blanchet@53222
  2035
              error ("Unsupported " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
blanchet@53222
  2036
                " via type constructor " ^ quote bad_tc ^ " in type expression " ^ fake_T_backdrop ^
blanchet@53222
  2037
                register_hint ())
blanchet@53222
  2038
          end);
blanchet@49585
  2039
traytel@55803
  2040
    val abss = map #abs absT_infos;
traytel@55803
  2041
    val reps = map #rep absT_infos;
traytel@55803
  2042
    val absTs = map #absT absT_infos;
traytel@55803
  2043
    val repTs = map #repT absT_infos;
traytel@55803
  2044
    val abs_injects = map #abs_inject absT_infos;
traytel@55803
  2045
    val abs_inverses = map #abs_inverse absT_infos;
traytel@55803
  2046
    val type_definitions = map #type_definition absT_infos;
traytel@55803
  2047
traytel@53143
  2048
    val time = time lthy;
blanchet@49585
  2049
    val timer = time (Timer.startRealTimer ());
blanchet@49121
  2050
blanchet@57397
  2051
    val fp_nesting_bnfs = nesting_bnfs lthy ctrXs_Tsss Xs;
blanchet@57397
  2052
    val live_nesting_bnfs = nesting_bnfs lthy ctrXs_Tsss As;
blanchet@49226
  2053
blanchet@49585
  2054
    val pre_map_defs = map map_def_of_bnf pre_bnfs;
blanchet@49585
  2055
    val pre_set_defss = map set_defs_of_bnf pre_bnfs;
blanchet@49585
  2056
    val pre_rel_defs = map rel_def_of_bnf pre_bnfs;
blanchet@57397
  2057
    val fp_nesting_set_maps = maps set_map_of_bnf fp_nesting_bnfs;
blanchet@58347
  2058
    val live_nesting_map_id0s = map map_id0_of_bnf live_nesting_bnfs;
desharna@58732
  2059
    val live_nesting_map_ident0s = map map_ident0_of_bnf live_nesting_bnfs;
blanchet@57397
  2060
    val live_nesting_set_maps = maps set_map_of_bnf live_nesting_bnfs;
desharna@58328
  2061
    val live_nesting_rel_eqs = map rel_eq_of_bnf live_nesting_bnfs;
blanchet@49585
  2062
blanchet@49585
  2063
    val live = live_of_bnf any_fp_bnf;
blanchet@52961
  2064
    val _ =
blanchet@52961
  2065
      if live = 0 andalso exists (not o Binding.is_empty) (map_bs @ rel_bs) then
blanchet@53266
  2066
        warning "Map function and relator names ignored"
blanchet@52961
  2067
      else
blanchet@52961
  2068
        ();
blanchet@49585
  2069
blanchet@49585
  2070
    val Bs =
wenzelm@58634
  2071
      @{map 3} (fn alive => fn A as TFree (_, S) => fn B =>
blanchet@58234
  2072
          if alive then resort_tfree_or_tvar S B else A)
blanchet@53266
  2073
        (liveness_of_fp_bnf num_As any_fp_bnf) As Bs0;
blanchet@49585
  2074
desharna@58446
  2075
    val B_ify_T = Term.typ_subst_atomic (As ~~ Bs);
desharna@58732
  2076
    val live_AsBs = filter (op <>) (As ~~ Bs);
blanchet@49167
  2077
blanchet@49501
  2078
    val ctors = map (mk_ctor As) ctors0;
blanchet@49501
  2079
    val dtors = map (mk_dtor As) dtors0;
blanchet@49124
  2080
blanchet@49501
  2081
    val fpTs = map (domain_type o fastype_of) dtors;
desharna@58446
  2082
    val fpBTs = map B_ify_T fpTs;
blanchet@49362
  2083
blanchet@59283
  2084
    val code_attrs = if plugins code_plugin then [Code.add_default_eqn_attrib] else [];
blanchet@58337
  2085
blanchet@52310
  2086
    val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Xs ~~ fpTs)))) ctrXs_Tsss;
blanchet@49203
  2087
    val ns = map length ctr_Tsss;
blanchet@49212
  2088
    val kss = map (fn n => 1 upto n) ns;
blanchet@49203
  2089
    val mss = map (map length) ctr_Tsss;
blanchet@49203
  2090
blanchet@55867
  2091
    val ((xtor_co_recs, recs_args_types, corecs_args_types), lthy') =
blanchet@55868
  2092
      mk_co_recs_prelims fp ctr_Tsss fpTs Cs absTs repTs ns mss xtor_co_recs0 lthy;
blanchet@49210
  2093
desharna@58675
  2094
    fun define_ctrs_dtrs_for_type fp (((((((((((((((((((((((((((fp_bnf, fp_b), fpT), ctor), dtor),
blanchet@55867
  2095
              xtor_co_rec), ctor_dtor), dtor_ctor), ctor_inject), pre_map_def), pre_set_defs),
traytel@55803
  2096
            pre_rel_def), fp_map_thm), fp_set_thms), fp_rel_thm), n), ks), ms), abs),
traytel@55803
  2097
          abs_inject), abs_inverse), type_definition), ctr_bindings), ctr_mixfixes), ctr_Tss),
blanchet@57200
  2098
        disc_bindings), sel_bindingss), raw_sel_default_eqs) no_defs_lthy =
blanchet@49176
  2099
      let
blanchet@49498
  2100
        val fp_b_name = Binding.name_of fp_b;
blanchet@49498
  2101
traytel@55803
  2102
        val ctr_absT = domain_type (fastype_of ctor);
blanchet@49119
  2103
blanchet@58347
  2104
        val (((w, xss), u'), _) = no_defs_lthy
traytel@55803
  2105
          |> yield_singleton (mk_Frees "w") ctr_absT
blanchet@49370
  2106
          ||>> mk_Freess "x" ctr_Tss
blanchet@49498
  2107
          ||>> yield_singleton Variable.variant_fixes fp_b_name;
blanchet@49370
  2108
blanchet@49498
  2109
        val u = Free (u', fpT);
blanchet@49121
  2110
blanchet@49129
  2111
        val ctr_rhss =
traytel@55803
  2112
          map2 (fn k => fn xs => fold_rev Term.lambda xs (ctor $ mk_absumprod ctr_absT abs n k xs))
traytel@55803
  2113
            ks xss;
blanchet@49121
  2114
traytel@53569
  2115
        val maybe_conceal_def_binding = Thm.def_binding
blanchet@58208
  2116
          #> not (Config.get no_defs_lthy bnf_note_all) ? Binding.conceal;
traytel@53569
  2117
blanchet@52968
  2118
        val ((raw_ctrs, raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
wenzelm@58634
  2119
          |> apfst split_list o @{fold_map 3} (fn b => fn mx => fn rhs =>
traytel@53569
  2120
              Local_Theory.define ((b, mx), ((maybe_conceal_def_binding b, []), rhs)) #>> apsnd snd)
blanchet@52968
  2121
            ctr_bindings ctr_mixfixes ctr_rhss
blanchet@49121
  2122
          ||> `Local_Theory.restore;
blanchet@49121
  2123
blanchet@49121
  2124
        val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49121
  2125
blanchet@49121
  2126
        val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
blanchet@49585
  2127
        val ctr_defs' =
blanchet@49585
  2128
          map2 (fn m => fn def => mk_unabs_def m (def RS meta_eq_to_obj_eq)) ms ctr_defs;
blanchet@49130
  2129
blanchet@49203
  2130
        val ctrs0 = map (Morphism.term phi) raw_ctrs;
blanchet@49203
  2131
        val ctrs = map (mk_ctr As) ctrs0;
blanchet@49121
  2132
blanchet@51897
  2133
        fun wrap_ctrs lthy =
blanchet@49123
  2134
          let
traytel@50170
  2135
            fun exhaust_tac {context = ctxt, prems = _} =
blanchet@49135
  2136
              let
blanchet@49585
  2137
                val ctor_iff_dtor_thm =
blanchet@49585
  2138
                  let
blanchet@49585
  2139
                    val goal =
blanchet@49585
  2140
                      fold_rev Logic.all [w, u]
blanchet@49585
  2141
                        (mk_Trueprop_eq (HOLogic.mk_eq (u, ctor $ w), HOLogic.mk_eq (dtor $ u, w)));
blanchet@49585
  2142
                  in
wenzelm@51551
  2143
                    Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
wenzelm@59621
  2144
                      mk_ctor_iff_dtor_tac ctxt (map (SOME o Thm.ctyp_of lthy) [ctr_absT, fpT])
wenzelm@59621
  2145
                        (Thm.cterm_of lthy ctor) (Thm.cterm_of lthy dtor) ctor_dtor dtor_ctor)
blanchet@55409
  2146
                    |> Morphism.thm phi
blanchet@49585
  2147
                    |> Thm.close_derivation
blanchet@49585
  2148
                  end;
blanchet@49585
  2149
blanchet@49585
  2150
                val sumEN_thm' =
traytel@55803
  2151
                  unfold_thms lthy @{thms unit_all_eq1} (mk_absumprodE type_definition ms)
blanchet@49585
  2152
                  |> Morphism.thm phi;
blanchet@49135
  2153
              in
blanchet@49585
  2154
                mk_exhaust_tac ctxt n ctr_defs ctor_iff_dtor_thm sumEN_thm'
blanchet@49135
  2155
              end;
blanchet@49135
  2156
blanchet@49585
  2157
            val inject_tacss =
traytel@55803
  2158
              map2 (fn ctr_def => fn 0 => [] | _ => [fn {context = ctxt, ...} =>
traytel@55803
  2159
                mk_inject_tac ctxt ctr_def ctor_inject abs_inject]) ctr_defs ms;
blanchet@49585
  2160
blanchet@49585
  2161
            val half_distinct_tacss =
blanchet@49585
  2162
              map (map (fn (def, def') => fn {context = ctxt, ...} =>
traytel@55803
  2163
                  mk_half_distinct_tac ctxt ctor_inject abs_inject [def, def']))
traytel@55803
  2164
                (mk_half_pairss (`I ctr_defs));
blanchet@49585
  2165
blanchet@52968
  2166
            val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss;
blanchet@49585
  2167
blanchet@57830
  2168
            val sel_Tss = map (map (curry (op -->) fpT)) ctr_Tss;
blanchet@57830
  2169
            val sel_bTs =
blanchet@57830
  2170
              flat sel_bindingss ~~ flat sel_Tss
blanchet@57830
  2171
              |> filter_out (Binding.is_empty o fst)
wenzelm@59058
  2172
              |> distinct (Binding.eq_name o apply2 fst);
blanchet@57830
  2173
            val sel_default_lthy = fake_local_theory_for_sel_defaults sel_bTs lthy;
blanchet@57830
  2174
blanchet@57830
  2175
            val sel_default_eqs = map (prepare_term sel_default_lthy) raw_sel_default_eqs;
blanchet@55469
  2176
blanchet@57200
  2177
            fun ctr_spec_of disc_b ctr0 sel_bs = ((disc_b, ctr0), sel_bs);
wenzelm@58634
  2178
            val ctr_specs = @{map 3} ctr_spec_of disc_bindings ctrs0 sel_bindingss;
blanchet@58267
  2179
blanchet@58267
  2180
            val (ctr_sugar as {case_cong, ...}, lthy') =
desharna@58675
  2181
              free_constructors (ctr_sugar_kind_of_fp_kind fp) tacss
desharna@58675
  2182
                ((((plugins, discs_sels), standard_binding), ctr_specs), sel_default_eqs) lthy
blanchet@58267
  2183
blanchet@58267
  2184
            val anonymous_notes =
blanchet@58267
  2185
              [([case_cong], fundefcong_attrs)]
blanchet@58267
  2186
              |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
blanchet@49123
  2187
          in
blanchet@58267
  2188
            (ctr_sugar, lthy' |> Local_Theory.notes anonymous_notes |> snd)
blanchet@49123
  2189
          end;
blanchet@49121
  2190
blanchet@55410
  2191
        fun mk_binding pre = Binding.qualify false fp_b_name (Binding.prefix_name (pre ^ "_") fp_b);
blanchet@49287
  2192
blanchet@58346
  2193
        fun massage_res (((ctr_sugar, maps_sets_rels), co_rec_res), lthy) =
blanchet@55867
  2194
          (((maps_sets_rels, (ctrs, xss, ctr_defs, ctr_sugar)), co_rec_res), lthy);
blanchet@49119
  2195
      in
blanchet@51897
  2196
        (wrap_ctrs
blanchet@58346
  2197
         #> (fn (ctr_sugar, lthy) =>
desharna@58676
  2198
           derive_map_set_rel_thms plugins fp n live As Bs abs_inverses ctr_defs'
desharna@58676
  2199
             fp_nesting_set_maps live_nesting_map_id0s live_nesting_set_maps live_nesting_rel_eqs
desharna@58676
  2200
             fp_b_name fp_bnf fpT ctor ctor_dtor dtor_ctor pre_map_def pre_set_defs pre_rel_def
desharna@58676
  2201
             fp_map_thm fp_set_thms fp_rel_thm ctr_Tss abs ctr_sugar lthy
blanchet@58346
  2202
           |>> pair ctr_sugar)
blanchet@52313
  2203
         ##>>
blanchet@56641
  2204
           (if fp = Least_FP then define_rec (the recs_args_types) mk_binding fpTs Cs reps
blanchet@58352
  2205
            else define_corec (the corecs_args_types) mk_binding fpTs Cs abss) xtor_co_rec
blanchet@51835
  2206
         #> massage_res, lthy')
blanchet@49119
  2207
      end;
blanchet@49167
  2208
blanchet@58345
  2209
    fun wrap_ctrs_derive_map_set_rel_thms_define_co_rec_for_types (wrap_one_etc, lthy) =
blanchet@58345
  2210
      fold_map I wrap_one_etc lthy
desharna@58676
  2211
      |>> apsnd split_list o apfst (apsnd @{split_list 4} o apfst @{split_list 16} o split_list)
blanchet@52342
  2212
        o split_list;
blanchet@49226
  2213
desharna@58462
  2214
    fun mk_simp_thms ({injects, distincts, case_thms, ...} : ctr_sugar) co_recs map_thms rel_injects
desharna@58565
  2215
        rel_distincts set_thmss =
desharna@58565
  2216
      injects @ distincts @ case_thms @ co_recs @ map_thms @ rel_injects @ rel_distincts @
desharna@58565
  2217
      set_thmss;
blanchet@49479
  2218
desharna@58448
  2219
    fun mk_co_rec_transfer_goals lthy co_recs =
desharna@58446
  2220
      let
desharna@58732
  2221
        val B_ify = Term.subst_atomic_types (live_AsBs @ (Cs ~~ Es));
desharna@58446
  2222
desharna@58446
  2223
        val ((Rs, Ss), names_lthy) = lthy
desharna@58732
  2224
          |> mk_Frees "R" (map (uncurry mk_pred2T) live_AsBs)
desharna@58446
  2225
          ||>> mk_Frees "S" (map2 mk_pred2T Cs Es);
desharna@58446
  2226
desharna@58448
  2227
        val co_recBs = map B_ify co_recs;
desharna@58446
  2228
      in
desharna@58448
  2229
        (Rs, Ss, map2 (mk_parametricity_goal lthy (Rs @ Ss)) co_recs co_recBs, names_lthy)
desharna@58448
  2230
      end;
desharna@58448
  2231
desharna@58966
  2232
    fun derive_rec_transfer_thms lthy recs rec_defs (SOME (_, _, _, xsssss)) =
desharna@58448
  2233
      let val (Rs, Ss, goals, names_lthy) = mk_co_rec_transfer_goals lthy recs in
desharna@58446
  2234
        Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
desharna@58446
  2235
          (fn {context = ctxt, prems = _} =>
wenzelm@59621
  2236
             mk_rec_transfer_tac ctxt nn ns (map (Thm.cterm_of ctxt) Ss) (map (Thm.cterm_of ctxt) Rs) xsssss
desharna@58966
  2237
               rec_defs xtor_co_rec_transfers pre_rel_defs live_nesting_rel_eqs)
desharna@58446
  2238
        |> Conjunction.elim_balanced nn
desharna@58446
  2239
        |> Proof_Context.export names_lthy lthy
desharna@58446
  2240
        |> map Thm.close_derivation
desharna@58446
  2241
      end;
desharna@58446
  2242
desharna@58732
  2243
    fun derive_rec_o_map_thmss lthy recs rec_defs =
desharna@58732
  2244
      if live = 0 then replicate nn []
desharna@58732
  2245
      else
desharna@58732
  2246
        let
desharna@58732
  2247
          fun variant_names n pre = fst (Variable.variant_fixes (replicate n pre) lthy);
desharna@58732
  2248
desharna@58732
  2249
          val maps0 = map map_of_bnf fp_bnfs;
desharna@58732
  2250
          val ABs = As ~~ Bs
desharna@58732
  2251
          val liveness = map (op <>) ABs;
desharna@58732
  2252
          val f_names = variant_names num_As "f";
desharna@58732
  2253
          val fs = map2 (curry Free) f_names (map (op -->) ABs);
desharna@58732
  2254
          val live_gs = AList.find (op =) (fs ~~ liveness) true;
desharna@58732
  2255
desharna@58732
  2256
          val gmaps = map (fn map0 => Term.list_comb (mk_map live As Bs map0, live_gs)) maps0;
desharna@58732
  2257
desharna@58732
  2258
          val rec_Ts as rec_T1 :: _ = map fastype_of recs;
desharna@58732
  2259
          val rec_arg_Ts = binder_fun_types rec_T1;
desharna@58732
  2260
desharna@58732
  2261
          val B_ify_T = Term.typ_subst_atomic (As ~~ Bs);
desharna@58732
  2262
desharna@58732
  2263
          val num_rec_args = length rec_arg_Ts;
desharna@58732
  2264
          val g_Ts = map B_ify_T rec_arg_Ts;
desharna@58732
  2265
          val g_names = variant_names num_rec_args "g";
desharna@58732
  2266
          val gs = map2 (curry Free) g_names g_Ts;
desharna@58732
  2267
          val grecs = map (fn recx => Term.list_comb (Term.map_types B_ify_T recx, gs)) recs;
desharna@58732
  2268
desharna@58732
  2269
          val rec_o_map_lhss = map2 (curry HOLogic.mk_comp) grecs gmaps;
desharna@58732
  2270
desharna@58732
  2271
          val ABfs = ABs ~~ fs;
desharna@58732
  2272
desharna@58732
  2273
          fun mk_rec_arg_arg (x as Free (_, T)) =
desharna@58732
  2274
            let val U = B_ify_T T in
desharna@58732
  2275
              if T = U then x else build_map lthy [] (the o AList.lookup (op =) ABfs) (T, U) $ x
desharna@58732
  2276
            end;
desharna@58732
  2277
desharna@58732
  2278
          fun mk_rec_o_map_arg rec_arg_T h =
desharna@58732
  2279
            let
desharna@58732
  2280
              val x_Ts = binder_types rec_arg_T;
desharna@58732
  2281
              val m = length x_Ts;
desharna@58732
  2282
              val x_names = variant_names m "x";
desharna@58732
  2283
              val xs = map2 (curry Free) x_names x_Ts;
desharna@58732
  2284
              val xs' = map mk_rec_arg_arg xs;
desharna@58732
  2285
            in
desharna@58732
  2286
              fold_rev Term.lambda xs (Term.list_comb (h, xs'))
desharna@58732
  2287
            end;
desharna@58732
  2288
desharna@58732
  2289
          fun mk_rec_o_map_rhs recx =
desharna@58732
  2290
            let val args = map2 mk_rec_o_map_arg rec_arg_Ts gs in
desharna@58732
  2291
              Term.list_comb (recx, args)
desharna@58732
  2292
            end;
desharna@58732
  2293
desharna@58732
  2294
          val rec_o_map_rhss = map mk_rec_o_map_rhs recs;
desharna@58732
  2295
desharna@58732
  2296
          val rec_o_map_goals =
desharna@58732
  2297
            map2 (fold_rev (fold_rev Logic.all) [fs, gs] o HOLogic.mk_Trueprop oo
desharna@58732
  2298
              curry HOLogic.mk_eq) rec_o_map_lhss rec_o_map_rhss;
desharna@58732
  2299
          val rec_o_map_thms =
desharna@58732
  2300
            @{map 3} (fn goal => fn rec_def => fn ctor_rec_o_map =>
desharna@58732
  2301
                Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
desharna@58734
  2302
                  mk_co_rec_o_map_tac ctxt rec_def pre_map_defs live_nesting_map_ident0s
desharna@58734
  2303
                    abs_inverses ctor_rec_o_map)
desharna@58732
  2304
                |> Thm.close_derivation)
desharna@58732
  2305
              rec_o_map_goals rec_defs xtor_co_rec_o_maps;
desharna@58732
  2306
        in
desharna@58732
  2307
          map single rec_o_map_thms
desharna@58732
  2308
        end;
desharna@58732
  2309
blanchet@55867
  2310
    fun derive_note_induct_recs_thms_for_types
desharna@58672
  2311
        ((((map_thmss, map_disc_iffss, map_selsss, rel_injectss, rel_distinctss, rel_selss,
desharna@58673
  2312
            rel_intross, rel_casess, set_thmss, set_selsssss, set_introsssss,
desharna@58676
  2313
            set_casess, ctr_transferss, case_transferss, disc_transferss, sel_transferss),
desharna@58560
  2314
           (ctrss, _, ctr_defss, ctr_sugars)),
blanchet@55864
  2315
          (recs, rec_defs)), lthy) =
blanchet@49202
  2316
      let
blanchet@55869
  2317
        val ((induct_thms, induct_thm, induct_attrs), (rec_thmss, rec_attrs)) =
blanchet@58335
  2318
          derive_induct_recs_thms_for_types plugins pre_bnfs recs_args_types xtor_co_induct
blanchet@58335
  2319
            xtor_co_rec_thms live_nesting_bnfs fp_nesting_bnfs fpTs Cs Xs ctrXs_Tsss abs_inverses
blanchet@58335
  2320
            type_definitions abs_inverses ctrss ctr_defss recs rec_defs lthy;
blanchet@49201
  2321
desharna@58446
  2322
        val rec_transfer_thmss =
desharna@58967
  2323
          map single (derive_rec_transfer_thms lthy recs rec_defs recs_args_types);
desharna@58446
  2324
blanchet@51830
  2325
        val induct_type_attr = Attrib.internal o K o Induct.induct_type;
desharna@57471
  2326
        val induct_pred_attr = Attrib.internal o K o Induct.induct_pred;
desharna@57471
  2327
desharna@57471
  2328
        val ((rel_induct_thmss, common_rel_induct_thms),
desharna@57471
  2329
             (rel_induct_attrs, common_rel_induct_attrs)) =
desharna@57471
  2330
          if live = 0 then
desharna@57471
  2331
            ((replicate nn [], []), ([], []))
desharna@57471
  2332
          else
desharna@57471
  2333
            let
desharna@57471
  2334
              val ((rel_induct_thms, common_rel_induct_thm), rel_induct_attrs) =
blanchet@57535
  2335
                derive_rel_induct_thms_for_types lthy fpTs As Bs ctrss ctr_Tsss
desharna@58579
  2336
                  (map #exhaust ctr_sugars) xtor_rel_co_induct ctr_defss ctor_injects
desharna@58328
  2337
                  pre_rel_defs abs_inverses live_nesting_rel_eqs;
desharna@57471
  2338
            in
desharna@57471
  2339
              ((map single rel_induct_thms, single common_rel_induct_thm),
desharna@57471
  2340
               (rel_induct_attrs, rel_induct_attrs))
desharna@57471
  2341
            end;
blanchet@51810
  2342
desharna@58732
  2343
        val rec_o_map_thmss = derive_rec_o_map_thmss lthy recs rec_defs;
desharna@58732
  2344
blanchet@51835
  2345
        val simp_thmss =
wenzelm@58634
  2346
          @{map 6} mk_simp_thms ctr_sugars rec_thmss map_thmss rel_injectss rel_distinctss set_thmss;
blanchet@49438
  2347
blanchet@49337
  2348
        val common_notes =
desharna@57471
  2349
          (if nn > 1 then
desharna@57700
  2350
             [(inductN, [induct_thm], K induct_attrs),
desharna@57700
  2351
              (rel_inductN, common_rel_induct_thms, K common_rel_induct_attrs)]
blanchet@57633
  2352
           else
blanchet@57633
  2353
             [])
blanchet@51780
  2354
          |> massage_simple_notes fp_common_name;
blanchet@49337
  2355
blanchet@49226
  2356
        val notes =
blanchet@55856
  2357
          [(inductN, map single induct_thms, fn T_name => induct_attrs @ [induct_type_attr T_name]),
blanchet@55869
  2358
           (recN, rec_thmss, K rec_attrs),
desharna@58732
  2359
           (rec_o_mapN, rec_o_map_thmss, K []),
desharna@58446
  2360
           (rec_transferN, rec_transfer_thmss, K []),
desharna@57471
  2361
           (rel_inductN, rel_induct_thmss, K (rel_induct_attrs @ [induct_pred_attr ""])),
blanchet@49585
  2362
           (simpsN, simp_thmss, K [])]
blanchet@58346
  2363
          |> massage_multi_notes fp_b_names fpTs;
blanchet@49202
  2364
      in
blanchet@51824
  2365
        lthy
blanchet@56641
  2366
        |> Spec_Rules.add Spec_Rules.Equational (recs, flat rec_thmss)
blanchet@57631
  2367
        |> Local_Theory.notes (common_notes @ notes)
blanchet@57633
  2368
        (* for "datatype_realizer.ML": *)
blanchet@57633
  2369
        |>> name_noted_thms
blanchet@57633
  2370
          (fst (dest_Type (hd fpTs)) ^ (implode (map (prefix "_") (tl fp_b_names)))) inductN
blanchet@58189
  2371
        |-> interpret_bnfs_register_fp_sugars plugins fpTs fpBTs Xs Least_FP pre_bnfs absT_infos
blanchet@58177
  2372
          fp_nesting_bnfs live_nesting_bnfs fp_res ctrXs_Tsss ctr_defss ctr_sugars recs rec_defs
desharna@58565
  2373
          map_thmss [induct_thm] (map single induct_thms) rec_thmss (replicate nn [])
desharna@58672
  2374
          (replicate nn []) rel_injectss rel_distinctss map_disc_iffss map_selsss rel_selss
desharna@58673
  2375
          rel_intross rel_casess set_thmss set_selsssss set_introsssss set_casess ctr_transferss
desharna@58573
  2376
          case_transferss disc_transferss (replicate nn []) (replicate nn []) rec_transfer_thmss
desharna@58676
  2377
          common_rel_induct_thms rel_induct_thmss [] (replicate nn []) sel_transferss
desharna@58732
  2378
          rec_o_map_thmss
blanchet@49202
  2379
      end;
blanchet@49202
  2380
desharna@58448
  2381
    fun derive_corec_transfer_thms lthy corecs corec_defs =
desharna@58448
  2382
      let
desharna@58448
  2383
        val (Rs, Ss, goals, names_lthy) = mk_co_rec_transfer_goals lthy corecs;
desharna@58448
  2384
        val (_, _, _, (((pgss, pss, qssss, gssss), _), _)) = the corecs_args_types;
desharna@58448
  2385
      in
desharna@58448
  2386
        Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
desharna@58448
  2387
          (fn {context = ctxt, prems = _} =>
wenzelm@59621
  2388
             mk_corec_transfer_tac ctxt (map (Thm.cterm_of ctxt) Ss) (map (Thm.cterm_of ctxt) Rs)
desharna@58581
  2389
               type_definitions corec_defs xtor_co_rec_transfers pre_rel_defs
desharna@58448
  2390
               live_nesting_rel_eqs (flat pgss) pss qssss gssss)
desharna@58448
  2391
        |> Conjunction.elim_balanced (length goals)
desharna@58448
  2392
        |> Proof_Context.export names_lthy lthy
desharna@58448
  2393
        |> map Thm.close_derivation
desharna@58448
  2394
      end;
desharna@58448
  2395
desharna@58734
  2396
    fun derive_map_o_corec_thmss lthy0 lthy2 corecs corec_defs =
desharna@58734
  2397
      if live = 0 then replicate nn []
desharna@58734
  2398
      else
desharna@58734
  2399
        let
desharna@58734
  2400
          fun variant_names n pre = fst (Variable.variant_fixes (replicate n pre) lthy0);
desharna@58734
  2401
          val maps0 = map map_of_bnf fp_bnfs;
desharna@58734
  2402
          val ABs = As ~~ Bs
desharna@58734
  2403
          val liveness = map (op <>) ABs;
desharna@58734
  2404
          val f_names = variant_names num_As "f";
desharna@58734
  2405
          val fs = map2 (curry Free) f_names (map (op -->) ABs);
desharna@58734
  2406
          val live_fs = AList.find (op =) (fs ~~ liveness) true;
desharna@58734
  2407
desharna@58734
  2408
          val fmaps = map (fn map0 => Term.list_comb (mk_map live As Bs map0, live_fs)) maps0;
desharna@58734
  2409
desharna@58734
  2410
          val corec_Ts as corec_T1 :: _ = map fastype_of corecs;
desharna@58734
  2411
          val corec_arg_Ts = binder_fun_types corec_T1;
desharna@58734
  2412
desharna@58734
  2413
          val B_ify = Term.subst_atomic_types (As ~~ Bs);
desharna@58734
  2414
          val B_ify_T = Term.typ_subst_atomic (As ~~ Bs);
desharna@58734
  2415
desharna@58734
  2416
          val num_rec_args = length corec_arg_Ts;
desharna@58734
  2417
          val g_names = variant_names num_rec_args "g";
desharna@58734
  2418
          val gs = map2 (curry Free) g_names corec_arg_Ts;
desharna@58734
  2419
          val gcorecs = map (fn corecx => Term.list_comb (corecx, gs)) corecs;
desharna@58734
  2420
desharna@58734
  2421
          val map_o_corec_lhss = map2 (curry HOLogic.mk_comp) fmaps gcorecs;
desharna@58734
  2422
desharna@58734
  2423
          val ABgs = ABs ~~ fs;
desharna@58734
  2424
desharna@58734
  2425
          fun mk_map_o_corec_arg corec_argB_T g =
desharna@58734
  2426
            let
desharna@58734
  2427
              val T = range_type (fastype_of g);
desharna@58734
  2428
              val U = range_type corec_argB_T;
desharna@58734
  2429
            in
desharna@58734
  2430
              if T = U then g
desharna@58734
  2431
              else HOLogic.mk_comp (build_map lthy2 [] (the o AList.lookup (op =) ABgs) (T, U), g)
desharna@58734
  2432
            end;
desharna@58734
  2433
desharna@58734
  2434
          fun mk_map_o_corec_rhs corecx =
desharna@58734
  2435
            let val args = map2 (mk_map_o_corec_arg o B_ify_T) corec_arg_Ts gs in
desharna@58734
  2436
              Term.list_comb (B_ify corecx, args)
desharna@58734
  2437
            end;
desharna@58734
  2438
desharna@58734
  2439
          val map_o_corec_rhss = map mk_map_o_corec_rhs corecs;
desharna@58734
  2440
desharna@58734
  2441
          val map_o_corec_goals =
desharna@58734
  2442
            map2 (fold_rev (fold_rev Logic.all) [fs, gs] o HOLogic.mk_Trueprop oo
desharna@58734
  2443
              curry HOLogic.mk_eq) map_o_corec_lhss map_o_corec_rhss;
desharna@58734
  2444
desharna@58734
  2445
          val map_o_corec_thms =
desharna@58734
  2446
            @{map 3} (fn goal => fn corec_def => fn dtor_map_o_corec =>
desharna@58734
  2447
                Goal.prove_sorry lthy2 [] [] goal (fn {context = ctxt, ...} =>
desharna@58734
  2448
                  mk_co_rec_o_map_tac ctxt corec_def pre_map_defs live_nesting_map_ident0s
desharna@58734
  2449
                    abs_inverses dtor_map_o_corec)
desharna@58734
  2450
                |> Thm.close_derivation)
desharna@58734
  2451
              map_o_corec_goals corec_defs xtor_co_rec_o_maps;
desharna@58734
  2452
        in
desharna@58734
  2453
          map single map_o_corec_thms
desharna@58734
  2454
        end;
desharna@58734
  2455
blanchet@55867
  2456
    fun derive_note_coinduct_corecs_thms_for_types
desharna@58672
  2457
        ((((map_thmss, map_disc_iffss, map_selsss, rel_injectss, rel_distinctss, rel_selss,
desharna@58673
  2458
            rel_intross, rel_casess, set_thmss, set_selsssss, set_introsssss, set_casess,
desharna@58676
  2459
            ctr_transferss, case_transferss, disc_transferss, sel_transferss),
desharna@58560
  2460
           (_, _, ctr_defss, ctr_sugars)),
blanchet@55867
  2461
          (corecs, corec_defs)), lthy) =
blanchet@49212
  2462
      let
blanchet@57983
  2463
        val (([(coinduct_thms, coinduct_thm), (coinduct_strong_thms, coinduct_strong_thm)],
blanchet@57260
  2464
              (coinduct_attrs, common_coinduct_attrs)),
blanchet@57983
  2465
             corec_thmss, corec_disc_thmss,