src/HOL/Tools/BNF/bnf_fp_def_sugar.ML
author blanchet
Mon Mar 03 12:48:20 2014 +0100 (2014-03-03)
changeset 55864 516ab2906e7e
parent 55863 fa3a1ec69a1b
child 55865 3be27c07e36d
permissions -rw-r--r--
rationalized internals
blanchet@55061
     1
(*  Title:      HOL/Tools/BNF/bnf_fp_def_sugar.ML
blanchet@49112
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@52349
     3
    Copyright   2012, 2013
blanchet@49112
     4
blanchet@49389
     5
Sugared datatype and codatatype constructions.
blanchet@49112
     6
*)
blanchet@49112
     7
blanchet@49636
     8
signature BNF_FP_DEF_SUGAR =
blanchet@49112
     9
sig
blanchet@51840
    10
  type fp_sugar =
blanchet@51859
    11
    {T: typ,
blanchet@55772
    12
     X: typ,
blanchet@55575
    13
     fp: BNF_Util.fp_kind,
blanchet@55539
    14
     fp_res_index: int,
blanchet@55539
    15
     fp_res: BNF_FP_Util.fp_result,
blanchet@55539
    16
     pre_bnf: BNF_Def.bnf,
traytel@55803
    17
     absT_info: BNF_Comp.absT_info,
blanchet@52356
    18
     nested_bnfs: BNF_Def.bnf list,
traytel@53267
    19
     nesting_bnfs: BNF_Def.bnf list,
blanchet@55772
    20
     ctrXs_Tss: typ list list,
blanchet@55539
    21
     ctr_defs: thm list,
blanchet@55539
    22
     ctr_sugar: Ctr_Sugar.ctr_sugar,
blanchet@55863
    23
     co_rec: term,
blanchet@55539
    24
     maps: thm list,
blanchet@55539
    25
     common_co_inducts: thm list,
blanchet@52343
    26
     co_inducts: thm list,
blanchet@55863
    27
     co_rec_thms: thm list,
blanchet@55863
    28
     disc_co_recs: thm list,
blanchet@55863
    29
     sel_co_recss: thm list list};
blanchet@51823
    30
blanchet@51896
    31
  val morph_fp_sugar: morphism -> fp_sugar -> fp_sugar
blanchet@54256
    32
  val transfer_fp_sugar: Proof.context -> fp_sugar -> fp_sugar
blanchet@51896
    33
  val fp_sugar_of: Proof.context -> string -> fp_sugar option
blanchet@53907
    34
  val fp_sugars_of: Proof.context -> fp_sugar list
blanchet@51852
    35
traytel@53106
    36
  val co_induct_of: 'a list -> 'a
traytel@53106
    37
  val strong_co_induct_of: 'a list -> 'a
traytel@53106
    38
blanchet@52868
    39
  val flat_corec_preds_predsss_gettersss: 'a list -> 'a list list list -> 'a list list list ->
blanchet@52868
    40
    'a list
blanchet@51907
    41
  val nesty_bnfs: Proof.context -> typ list list list -> typ list -> BNF_Def.bnf list
blanchet@53746
    42
blanchet@53746
    43
  type lfp_sugar_thms =
blanchet@55856
    44
    (thm list * thm * Args.src list) * (thm list list * Args.src list)
blanchet@53746
    45
blanchet@54256
    46
  val morph_lfp_sugar_thms: morphism -> lfp_sugar_thms -> lfp_sugar_thms
blanchet@54256
    47
  val transfer_lfp_sugar_thms: Proof.context -> lfp_sugar_thms -> lfp_sugar_thms
blanchet@54256
    48
blanchet@53746
    49
  type gfp_sugar_thms =
blanchet@53746
    50
    ((thm list * thm) list * Args.src list)
blanchet@55856
    51
    * (thm list list * Args.src list)
blanchet@55856
    52
    * (thm list list * Args.src list)
blanchet@55856
    53
    * (thm list list * Args.src list)
blanchet@55856
    54
    * (thm list list list * Args.src list)
blanchet@53746
    55
blanchet@54256
    56
  val morph_gfp_sugar_thms: morphism -> gfp_sugar_thms -> gfp_sugar_thms
blanchet@54256
    57
  val transfer_gfp_sugar_thms: Proof.context -> gfp_sugar_thms -> gfp_sugar_thms
blanchet@54256
    58
blanchet@55575
    59
  val mk_co_iters_prelims: BNF_Util.fp_kind -> typ list list list -> typ list -> typ list ->
blanchet@55862
    60
     typ list -> typ list -> int list -> int list list -> term list list -> Proof.context ->
blanchet@55862
    61
     (term list list * (typ list list * typ list list list list * term list list
blanchet@55862
    62
        * term list list list list) option
blanchet@55862
    63
      * (string * term list * term list list
blanchet@55862
    64
        * ((term list list * term list list list) * typ list)) option)
blanchet@55862
    65
     * Proof.context
blanchet@55772
    66
  val repair_nullary_single_ctr: typ list list -> typ list list
blanchet@55772
    67
  val mk_coiter_p_pred_types: typ list -> int list -> typ list list
traytel@55803
    68
  val mk_coiter_fun_arg_types: typ list list list -> typ list -> typ list -> typ list -> int list ->
traytel@55803
    69
    int list list -> term ->
traytel@55803
    70
    typ list list
traytel@55803
    71
    * (typ list list list list * typ list list list * typ list list list list * typ list)
blanchet@55862
    72
  val define_iter:
blanchet@55862
    73
    (typ list list * typ list list list list * term list list * term list list list list) option ->
blanchet@55862
    74
    (string -> binding) -> typ list -> typ list -> term list -> term -> Proof.context ->
blanchet@55864
    75
    (term * thm) * Proof.context
blanchet@55862
    76
  val define_coiter: 'a * term list * term list list
blanchet@55862
    77
      * ((term list list * term list list list) * typ list) -> (string -> binding) -> 'b list ->
blanchet@55864
    78
    typ list -> term list -> term -> Proof.context -> (term * thm) * local_theory
blanchet@52346
    79
  val derive_induct_iters_thms_for_types: BNF_Def.bnf list ->
blanchet@55862
    80
     ('a * typ list list list list * term list list * 'b) option -> thm -> thm list list ->
blanchet@55862
    81
     BNF_Def.bnf list -> BNF_Def.bnf list -> typ list -> typ list -> typ list ->
blanchet@55862
    82
     typ list list list -> thm list -> thm list -> thm list -> term list list -> thm list list ->
blanchet@55864
    83
     term list -> thm list -> Proof.context -> lfp_sugar_thms
blanchet@52346
    84
  val derive_coinduct_coiters_thms_for_types: BNF_Def.bnf list ->
blanchet@55862
    85
    string * term list * term list list * ((term list list * term list list list) * typ list) ->
traytel@53203
    86
    thm -> thm list -> thm list -> thm list list -> BNF_Def.bnf list -> typ list -> typ list ->
traytel@55803
    87
    typ list -> typ list list list -> int list list -> int list list -> int list -> thm list ->
blanchet@55864
    88
    thm list -> (thm -> thm) -> thm list list -> Ctr_Sugar.ctr_sugar list -> term list ->
blanchet@55864
    89
    thm list -> (thm list -> thm list) -> local_theory -> gfp_sugar_thms
blanchet@55469
    90
blanchet@55469
    91
  type co_datatype_spec =
blanchet@55699
    92
    ((((binding option * (typ * sort)) list * binding) * (binding * binding)) * mixfix)
blanchet@55469
    93
    * ((binding, binding * typ, term) Ctr_Sugar.ctr_spec * mixfix) list
blanchet@55469
    94
blanchet@55575
    95
  val co_datatypes: BNF_Util.fp_kind -> (mixfix list -> binding list -> binding list ->
blanchet@52207
    96
      binding list list -> binding list -> (string * sort) list -> typ list * typ list list ->
traytel@55803
    97
      BNF_Def.bnf list -> BNF_Comp.absT_info list -> local_theory ->
traytel@55803
    98
      BNF_FP_Util.fp_result * local_theory) ->
blanchet@55469
    99
    (bool * bool) * co_datatype_spec list ->
blanchet@49297
   100
    local_theory -> local_theory
blanchet@55575
   101
  val parse_co_datatype_cmd: BNF_Util.fp_kind -> (mixfix list -> binding list -> binding list ->
blanchet@51867
   102
      binding list list -> binding list -> (string * sort) list -> typ list * typ list list ->
traytel@55803
   103
      BNF_Def.bnf list -> BNF_Comp.absT_info list -> local_theory ->
traytel@55803
   104
      BNF_FP_Util.fp_result * local_theory) ->
blanchet@49308
   105
    (local_theory -> local_theory) parser
blanchet@49112
   106
end;
blanchet@49112
   107
blanchet@49636
   108
structure BNF_FP_Def_Sugar : BNF_FP_DEF_SUGAR =
blanchet@49112
   109
struct
blanchet@49112
   110
blanchet@54006
   111
open Ctr_Sugar
blanchet@55571
   112
open BNF_FP_Rec_Sugar_Util
blanchet@49119
   113
open BNF_Util
blanchet@53222
   114
open BNF_Comp
blanchet@49214
   115
open BNF_Def
blanchet@51850
   116
open BNF_FP_Util
blanchet@49636
   117
open BNF_FP_Def_Sugar_Tactics
blanchet@49119
   118
blanchet@51788
   119
val EqN = "Eq_";
blanchet@51777
   120
blanchet@51840
   121
type fp_sugar =
blanchet@51859
   122
  {T: typ,
blanchet@55772
   123
   X: typ,
blanchet@52207
   124
   fp: fp_kind,
blanchet@55539
   125
   fp_res_index: int,
blanchet@55539
   126
   fp_res: fp_result,
blanchet@55539
   127
   pre_bnf: bnf,
traytel@55803
   128
   absT_info: absT_info,
blanchet@52356
   129
   nested_bnfs: bnf list,
traytel@53267
   130
   nesting_bnfs: bnf list,
blanchet@55772
   131
   ctrXs_Tss: typ list list,
blanchet@55539
   132
   ctr_defs: thm list,
blanchet@55539
   133
   ctr_sugar: Ctr_Sugar.ctr_sugar,
blanchet@55863
   134
   co_rec: term,
blanchet@55539
   135
   maps: thm list,
blanchet@55539
   136
   common_co_inducts: thm list,
blanchet@52343
   137
   co_inducts: thm list,
blanchet@55863
   138
   co_rec_thms: thm list,
blanchet@55863
   139
   disc_co_recs: thm list,
blanchet@55863
   140
   sel_co_recss: thm list list};
blanchet@52295
   141
traytel@55803
   142
fun morph_fp_sugar phi ({T, X, fp, fp_res, fp_res_index, pre_bnf, absT_info, nested_bnfs,
blanchet@55863
   143
    nesting_bnfs, ctrXs_Tss, ctr_defs, ctr_sugar, co_rec, maps, common_co_inducts, co_inducts,
blanchet@55863
   144
    co_rec_thms, disc_co_recs, sel_co_recss} : fp_sugar) =
blanchet@55539
   145
  {T = Morphism.typ phi T,
blanchet@55772
   146
   X = Morphism.typ phi X,
blanchet@55539
   147
   fp = fp,
traytel@53267
   148
   fp_res = morph_fp_result phi fp_res,
blanchet@55539
   149
   fp_res_index = fp_res_index,
blanchet@55539
   150
   pre_bnf = morph_bnf phi pre_bnf,
traytel@55803
   151
   absT_info = morph_absT_info phi absT_info,
blanchet@55539
   152
   nested_bnfs = map (morph_bnf phi) nested_bnfs,
blanchet@55539
   153
   nesting_bnfs = map (morph_bnf phi) nesting_bnfs,
blanchet@55772
   154
   ctrXs_Tss = map (map (Morphism.typ phi)) ctrXs_Tss,
blanchet@55539
   155
   ctr_defs = map (Morphism.thm phi) ctr_defs,
blanchet@55539
   156
   ctr_sugar = morph_ctr_sugar phi ctr_sugar,
blanchet@55863
   157
   co_rec = Morphism.term phi co_rec,
blanchet@55539
   158
   maps = map (Morphism.thm phi) maps,
blanchet@55539
   159
   common_co_inducts = map (Morphism.thm phi) common_co_inducts,
blanchet@52343
   160
   co_inducts = map (Morphism.thm phi) co_inducts,
blanchet@55863
   161
   co_rec_thms = map (Morphism.thm phi) co_rec_thms,
blanchet@55863
   162
   disc_co_recs = map (Morphism.thm phi) disc_co_recs,
blanchet@55863
   163
   sel_co_recss = map (map (Morphism.thm phi)) sel_co_recss};
blanchet@51823
   164
blanchet@53907
   165
val transfer_fp_sugar =
wenzelm@54740
   166
  morph_fp_sugar o Morphism.transfer_morphism o Proof_Context.theory_of;
blanchet@53907
   167
blanchet@51823
   168
structure Data = Generic_Data
blanchet@51823
   169
(
blanchet@51840
   170
  type T = fp_sugar Symtab.table;
blanchet@51823
   171
  val empty = Symtab.empty;
blanchet@51823
   172
  val extend = I;
blanchet@55394
   173
  fun merge data : T = Symtab.merge (K true) data;
blanchet@51823
   174
);
blanchet@51823
   175
traytel@53126
   176
fun fp_sugar_of ctxt =
traytel@53126
   177
  Symtab.lookup (Data.get (Context.Proof ctxt))
blanchet@53907
   178
  #> Option.map (transfer_fp_sugar ctxt);
blanchet@53907
   179
blanchet@53907
   180
fun fp_sugars_of ctxt =
blanchet@53907
   181
  Symtab.fold (cons o transfer_fp_sugar ctxt o snd) (Data.get (Context.Proof ctxt)) [];
blanchet@51823
   182
traytel@53106
   183
fun co_induct_of (i :: _) = i;
traytel@53106
   184
fun strong_co_induct_of [_, s] = s;
traytel@53106
   185
blanchet@53259
   186
(* TODO: register "sum" and "prod" as datatypes to enable N2M reduction for them *)
blanchet@53259
   187
blanchet@51840
   188
fun register_fp_sugar key fp_sugar =
blanchet@54285
   189
  Local_Theory.declaration {syntax = false, pervasive = true}
blanchet@55444
   190
    (fn phi => Data.map (Symtab.update (key, morph_fp_sugar phi fp_sugar)));
blanchet@51823
   191
traytel@55803
   192
fun register_fp_sugars Xs fp pre_bnfs absT_infos nested_bnfs nesting_bnfs (fp_res as {Ts, ...})
blanchet@55863
   193
    ctrXs_Tsss ctr_defss ctr_sugars co_recs mapss common_co_inducts co_inductss co_rec_thmss
blanchet@55863
   194
    disc_co_recss sel_co_recsss lthy =
blanchet@51844
   195
  (0, lthy)
blanchet@51859
   196
  |> fold (fn T as Type (s, _) => fn (kk, lthy) => (kk + 1,
blanchet@55772
   197
    register_fp_sugar s {T = T, X = nth Xs kk, fp = fp, fp_res = fp_res, fp_res_index = kk,
traytel@55803
   198
        pre_bnf = nth pre_bnfs kk, absT_info = nth absT_infos kk, nested_bnfs = nested_bnfs,
traytel@55803
   199
        nesting_bnfs = nesting_bnfs, ctrXs_Tss = nth ctrXs_Tsss kk, ctr_defs = nth ctr_defss kk,
blanchet@55863
   200
        ctr_sugar = nth ctr_sugars kk, co_rec = nth co_recs kk, maps = nth mapss kk,
traytel@55803
   201
        common_co_inducts = common_co_inducts, co_inducts = nth co_inductss kk,
blanchet@55863
   202
        co_rec_thms = nth co_rec_thmss kk, disc_co_recs = nth disc_co_recss kk,
blanchet@55863
   203
        sel_co_recss = nth sel_co_recsss kk}
blanchet@52337
   204
      lthy)) Ts
blanchet@51824
   205
  |> snd;
blanchet@51824
   206
blanchet@55342
   207
(* This function could produce (fairly harmless) clashes in contrived examples (e.g., "x.A",
blanchet@55342
   208
   "x.x_A", "y.A"). *)
blanchet@49622
   209
fun quasi_unambiguous_case_names names =
blanchet@49622
   210
  let
blanchet@49622
   211
    val ps = map (`Long_Name.base_name) names;
blanchet@49622
   212
    val dups = Library.duplicates (op =) (map fst ps);
blanchet@49622
   213
    fun underscore s =
blanchet@49622
   214
      let val ss = space_explode Long_Name.separator s in
blanchet@49622
   215
        space_implode "_" (drop (length ss - 2) ss)
blanchet@49622
   216
      end;
blanchet@49622
   217
  in
blanchet@49622
   218
    map (fn (base, full) => if member (op =) dups base then underscore full else base) ps
blanchet@49622
   219
  end;
blanchet@49622
   220
blanchet@52355
   221
val id_def = @{thm id_def};
blanchet@49591
   222
val mp_conj = @{thm mp_conj};
blanchet@49591
   223
blanchet@55397
   224
val fundefcong_attrs = @{attributes [fundef_cong]};
blanchet@54145
   225
val nitpicksimp_attrs = @{attributes [nitpick_simp]};
blanchet@54145
   226
val code_nitpicksimp_attrs = Code.add_default_eqn_attrib :: nitpicksimp_attrs;
blanchet@49300
   227
val simp_attrs = @{attributes [simp]};
blanchet@49300
   228
blanchet@49297
   229
val lists_bmoc = fold (fn xs => fn t => Term.list_comb (t, xs));
blanchet@49202
   230
blanchet@52868
   231
fun flat_corec_predss_getterss qss fss = maps (op @) (qss ~~ fss);
blanchet@51829
   232
blanchet@52868
   233
fun flat_corec_preds_predsss_gettersss [] [qss] [fss] = flat_corec_predss_getterss qss fss
blanchet@52868
   234
  | flat_corec_preds_predsss_gettersss (p :: ps) (qss :: qsss) (fss :: fsss) =
blanchet@52868
   235
    p :: flat_corec_predss_getterss qss fss @ flat_corec_preds_predsss_gettersss ps qsss fsss;
blanchet@51829
   236
blanchet@49585
   237
fun mk_flip (x, Type (_, [T1, Type (_, [T2, T3])])) =
blanchet@49585
   238
  Abs ("x", T1, Abs ("y", T2, Var (x, T2 --> T1 --> T3) $ Bound 0 $ Bound 1));
blanchet@49585
   239
blanchet@49585
   240
fun flip_rels lthy n thm =
blanchet@49585
   241
  let
blanchet@49585
   242
    val Rs = Term.add_vars (prop_of thm) [];
blanchet@49585
   243
    val Rs' = rev (drop (length Rs - n) Rs);
blanchet@49585
   244
    val cRs = map (fn f => (certify lthy (Var f), certify lthy (mk_flip f))) Rs';
blanchet@49585
   245
  in
blanchet@49585
   246
    Drule.cterm_instantiate cRs thm
blanchet@49585
   247
  end;
blanchet@49585
   248
blanchet@49536
   249
fun mk_ctor_or_dtor get_T Ts t =
blanchet@49536
   250
  let val Type (_, Ts0) = get_T (fastype_of t) in
blanchet@49536
   251
    Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@49536
   252
  end;
blanchet@49536
   253
blanchet@49536
   254
val mk_ctor = mk_ctor_or_dtor range_type;
blanchet@49536
   255
val mk_dtor = mk_ctor_or_dtor domain_type;
blanchet@49536
   256
blanchet@52207
   257
fun mk_co_iters thy fp fpTs Cs ts0 =
blanchet@51911
   258
  let
blanchet@51911
   259
    val nn = length fpTs;
blanchet@51911
   260
    val (fpTs0, Cs0) =
blanchet@52207
   261
      map ((fp = Greatest_FP ? swap) o dest_funT o snd o strip_typeN nn o fastype_of) ts0
blanchet@51911
   262
      |> split_list;
blanchet@51911
   263
    val rho = tvar_subst thy (fpTs0 @ Cs0) (fpTs @ Cs);
blanchet@51911
   264
  in
blanchet@52170
   265
    map (Term.subst_TVars rho) ts0
blanchet@51911
   266
  end;
blanchet@51827
   267
blanchet@55575
   268
fun unzip_recT (Type (@{type_name prod}, _)) T = [T]
blanchet@55575
   269
  | unzip_recT _ (Type (@{type_name prod}, Ts)) = Ts
blanchet@55575
   270
  | unzip_recT _ T = [T];
blanchet@55575
   271
blanchet@53591
   272
fun unzip_corecT (Type (@{type_name sum}, _)) T = [T]
blanchet@53901
   273
  | unzip_corecT _ (Type (@{type_name sum}, Ts)) = Ts
blanchet@52871
   274
  | unzip_corecT _ T = [T];
blanchet@52871
   275
blanchet@52347
   276
fun liveness_of_fp_bnf n bnf =
blanchet@52347
   277
  (case T_of_bnf bnf of
blanchet@52347
   278
    Type (_, Ts) => map (not o member (op =) (deads_of_bnf bnf)) Ts
blanchet@52347
   279
  | _ => replicate n false);
blanchet@52347
   280
blanchet@55700
   281
fun cannot_merge_types fp =
blanchet@55700
   282
  error ("Mutually " ^ co_prefix fp ^ "recursive types must have the same type parameters");
blanchet@52347
   283
blanchet@55700
   284
fun merge_type_arg fp T T' = if T = T' then T else cannot_merge_types fp;
blanchet@52347
   285
blanchet@55700
   286
fun merge_type_args fp (As, As') =
blanchet@55700
   287
  if length As = length As' then map2 (merge_type_arg fp) As As' else cannot_merge_types fp;
blanchet@52347
   288
blanchet@52347
   289
fun reassoc_conjs thm =
blanchet@52347
   290
  reassoc_conjs (thm RS @{thm conj_assoc[THEN iffD1]})
blanchet@52347
   291
  handle THM _ => thm;
blanchet@52347
   292
blanchet@55469
   293
type co_datatype_spec =
blanchet@55699
   294
  ((((binding option * (typ * sort)) list * binding) * (binding * binding)) * mixfix)
blanchet@55469
   295
  * ((binding, binding * typ, term) ctr_spec * mixfix) list;
blanchet@52347
   296
blanchet@55469
   297
fun type_args_named_constrained_of_spec ((((ncAs, _), _), _), _) = ncAs;
blanchet@55469
   298
fun type_binding_of_spec ((((_, b), _), _), _) = b;
blanchet@55469
   299
fun map_binding_of_spec (((_, (b, _)), _), _) = b;
blanchet@55469
   300
fun rel_binding_of_spec (((_, (_, b)), _), _) = b;
blanchet@55469
   301
fun mixfix_of_spec ((_, mx), _) = mx;
blanchet@55469
   302
fun mixfixed_ctr_specs_of_spec (_, mx_ctr_specs) = mx_ctr_specs;
blanchet@52347
   303
blanchet@52347
   304
fun add_nesty_bnf_names Us =
blanchet@52347
   305
  let
blanchet@52347
   306
    fun add (Type (s, Ts)) ss =
blanchet@52347
   307
        let val (needs, ss') = fold_map add Ts ss in
blanchet@52347
   308
          if exists I needs then (true, insert (op =) s ss') else (false, ss')
blanchet@52347
   309
        end
blanchet@52347
   310
      | add T ss = (member (op =) Us T, ss);
blanchet@52347
   311
  in snd oo add end;
blanchet@52347
   312
blanchet@52347
   313
fun nesty_bnfs ctxt ctr_Tsss Us =
blanchet@52347
   314
  map_filter (bnf_of ctxt) (fold (fold (fold (add_nesty_bnf_names Us))) ctr_Tsss []);
blanchet@52347
   315
blanchet@54237
   316
fun indexify proj xs f p = f (find_index (curry (op =) (proj p)) xs) p;
blanchet@52347
   317
blanchet@53746
   318
type lfp_sugar_thms =
blanchet@55856
   319
  (thm list * thm * Args.src list) * (thm list list * Args.src list);
blanchet@53746
   320
blanchet@55856
   321
fun morph_lfp_sugar_thms phi ((inducts, induct, induct_attrs), (recss, iter_attrs)) =
blanchet@54256
   322
  ((map (Morphism.thm phi) inducts, Morphism.thm phi induct, induct_attrs),
blanchet@55856
   323
   (map (map (Morphism.thm phi)) recss, iter_attrs))
blanchet@55095
   324
  : lfp_sugar_thms;
blanchet@54256
   325
blanchet@54256
   326
val transfer_lfp_sugar_thms =
wenzelm@54740
   327
  morph_lfp_sugar_thms o Morphism.transfer_morphism o Proof_Context.theory_of;
blanchet@54256
   328
blanchet@53746
   329
type gfp_sugar_thms =
blanchet@53746
   330
  ((thm list * thm) list * Args.src list)
blanchet@55856
   331
  * (thm list list * Args.src list)
blanchet@55856
   332
  * (thm list list * Args.src list)
blanchet@55856
   333
  * (thm list list * Args.src list)
blanchet@55856
   334
  * (thm list list list * Args.src list);
blanchet@53746
   335
blanchet@54256
   336
fun morph_gfp_sugar_thms phi ((coinducts_pairs, coinduct_attrs),
blanchet@55856
   337
    (corecss, coiter_attrs), (disc_corecss, disc_iter_attrs),
blanchet@55856
   338
    (disc_corec_iffss, disc_iter_iff_attrs), (sel_corecsss, sel_iter_attrs)) =
blanchet@54256
   339
  ((map (apfst (map (Morphism.thm phi)) o apsnd (Morphism.thm phi)) coinducts_pairs,
blanchet@54256
   340
    coinduct_attrs),
blanchet@55856
   341
   (map (map (Morphism.thm phi)) corecss, coiter_attrs),
blanchet@55856
   342
   (map (map (Morphism.thm phi)) disc_corecss, disc_iter_attrs),
blanchet@55856
   343
   (map (map (Morphism.thm phi)) disc_corec_iffss, disc_iter_iff_attrs),
blanchet@55856
   344
   (map (map (map (Morphism.thm phi))) sel_corecsss, sel_iter_attrs)) : gfp_sugar_thms;
blanchet@54256
   345
blanchet@54256
   346
val transfer_gfp_sugar_thms =
wenzelm@54740
   347
  morph_gfp_sugar_thms o Morphism.transfer_morphism o Proof_Context.theory_of;
blanchet@54256
   348
traytel@55803
   349
fun mk_iters_args_types ctr_Tsss Cs absTs repTs ns mss ctor_iter_fun_Tss lthy =
blanchet@51832
   350
  let
blanchet@52214
   351
    val Css = map2 replicate ns Cs;
traytel@55803
   352
    val y_Tsss = map5 (fn absT => fn repT => fn n => fn ms =>
traytel@55803
   353
        dest_absumprodT absT repT n ms o domain_type)
traytel@55803
   354
      absTs repTs ns mss (map un_fold_of ctor_iter_fun_Tss);
blanchet@52214
   355
    val g_Tss = map2 (fn C => map (fn y_Ts => y_Ts ---> C)) Cs y_Tsss;
blanchet@51832
   356
blanchet@51832
   357
    val ((gss, ysss), lthy) =
blanchet@51832
   358
      lthy
blanchet@51832
   359
      |> mk_Freess "f" g_Tss
blanchet@51832
   360
      ||>> mk_Freesss "x" y_Tsss;
blanchet@52301
   361
blanchet@52214
   362
    val z_Tssss =
traytel@55803
   363
      map6 (fn absT => fn repT => fn n => fn ms => fn ctr_Tss => fn ctor_iter_fun_Ts =>
traytel@55803
   364
          map2 (map2 unzip_recT)
traytel@55803
   365
            ctr_Tss (dest_absumprodT absT repT n ms (domain_type (co_rec_of ctor_iter_fun_Ts))))
traytel@55803
   366
        absTs repTs ns mss ctr_Tsss ctor_iter_fun_Tss;
blanchet@51832
   367
blanchet@52868
   368
    val z_Tsss' = map (map flat_rec_arg_args) z_Tssss;
blanchet@54237
   369
    val h_Tss = map2 (map2 (curry (op --->))) z_Tsss' Css;
blanchet@51832
   370
blanchet@51832
   371
    val hss = map2 (map2 retype_free) h_Tss gss;
blanchet@52214
   372
    val zssss_hd = map2 (map2 (map2 (retype_free o hd))) z_Tssss ysss;
blanchet@52214
   373
    val (zssss_tl, lthy) =
blanchet@52214
   374
      lthy
blanchet@52214
   375
      |> mk_Freessss "y" (map (map (map tl)) z_Tssss);
blanchet@52214
   376
    val zssss = map2 (map2 (map2 cons)) zssss_hd zssss_tl;
blanchet@51832
   377
  in
blanchet@55862
   378
    ((h_Tss, z_Tssss, hss, zssss), lthy)
blanchet@51832
   379
  end;
blanchet@51832
   380
blanchet@55772
   381
(*avoid "'a itself" arguments in coiterators*)
blanchet@55772
   382
fun repair_nullary_single_ctr [[]] = [[@{typ unit}]]
blanchet@55772
   383
  | repair_nullary_single_ctr Tss = Tss;
blanchet@55772
   384
traytel@55803
   385
fun mk_coiter_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss fun_Ts =
blanchet@51829
   386
  let
blanchet@55772
   387
    val ctr_Tsss' = map repair_nullary_single_ctr ctr_Tsss;
traytel@55803
   388
    val f_absTs = map range_type fun_Ts;
traytel@55803
   389
    val f_Tsss = map repair_nullary_single_ctr (map5 dest_absumprodT absTs repTs ns mss f_absTs);
blanchet@54237
   390
    val f_Tssss = map3 (fn C => map2 (map2 (map (curry (op -->) C) oo unzip_corecT)))
blanchet@53591
   391
      Cs ctr_Tsss' f_Tsss;
blanchet@52871
   392
    val q_Tssss = map (map (map (fn [_] => [] | [_, T] => [mk_pred1T (domain_type T)]))) f_Tssss;
blanchet@52870
   393
  in
traytel@55803
   394
    (q_Tssss, f_Tsss, f_Tssss, f_absTs)
blanchet@52870
   395
  end;
blanchet@51829
   396
blanchet@52898
   397
fun mk_coiter_p_pred_types Cs ns = map2 (fn n => replicate (Int.max (0, n - 1)) o mk_pred1T) ns Cs;
blanchet@52898
   398
traytel@55803
   399
fun mk_coiter_fun_arg_types ctr_Tsss Cs absTs repTs ns mss dtor_coiter =
traytel@55803
   400
  (mk_coiter_p_pred_types Cs ns,
traytel@55803
   401
   mk_coiter_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss
traytel@55803
   402
     (binder_fun_types (fastype_of dtor_coiter)));
traytel@55803
   403
traytel@55803
   404
fun mk_coiters_args_types ctr_Tsss Cs absTs repTs ns mss dtor_coiter_fun_Tss lthy =
blanchet@52870
   405
  let
blanchet@52898
   406
    val p_Tss = mk_coiter_p_pred_types Cs ns;
blanchet@51829
   407
blanchet@52871
   408
    fun mk_types get_Ts =
blanchet@51829
   409
      let
blanchet@52335
   410
        val fun_Ts = map get_Ts dtor_coiter_fun_Tss;
traytel@55803
   411
        val (q_Tssss, f_Tsss, f_Tssss, f_repTs) =
traytel@55803
   412
          mk_coiter_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss fun_Ts;
blanchet@52870
   413
      in
traytel@55803
   414
        (q_Tssss, f_Tsss, f_Tssss, f_repTs)
blanchet@52870
   415
      end;
blanchet@51829
   416
blanchet@52871
   417
    val (s_Tssss, h_Tsss, h_Tssss, corec_types) = mk_types co_rec_of;
blanchet@51831
   418
blanchet@55858
   419
    val (((((Free (z, _), cs), pss), sssss), hssss), lthy) =
blanchet@51829
   420
      lthy
blanchet@52347
   421
      |> yield_singleton (mk_Frees "z") dummyT
blanchet@52347
   422
      ||>> mk_Frees "a" Cs
blanchet@51829
   423
      ||>> mk_Freess "p" p_Tss
blanchet@55856
   424
      ||>> mk_Freessss "q" s_Tssss
blanchet@55858
   425
      ||>> mk_Freessss "g" h_Tssss;
blanchet@51831
   426
blanchet@51831
   427
    val cpss = map2 (map o rapp) cs pss;
blanchet@51829
   428
blanchet@52347
   429
    fun build_sum_inj mk_inj = build_map lthy (uncurry mk_inj o dest_sumT o snd);
blanchet@52347
   430
blanchet@52347
   431
    fun build_dtor_coiter_arg _ [] [cf] = cf
blanchet@52347
   432
      | build_dtor_coiter_arg T [cq] [cf, cf'] =
blanchet@52347
   433
        mk_If cq (build_sum_inj Inl_const (fastype_of cf, T) $ cf)
blanchet@52347
   434
          (build_sum_inj Inr_const (fastype_of cf', T) $ cf');
blanchet@52347
   435
blanchet@52349
   436
    fun mk_args qssss fssss f_Tsss =
blanchet@51831
   437
      let
blanchet@52868
   438
        val pfss = map3 flat_corec_preds_predsss_gettersss pss qssss fssss;
blanchet@51831
   439
        val cqssss = map2 (map o map o map o rapp) cs qssss;
blanchet@51831
   440
        val cfssss = map2 (map o map o map o rapp) cs fssss;
blanchet@52347
   441
        val cqfsss = map3 (map3 (map3 build_dtor_coiter_arg)) f_Tsss cqssss cfssss;
blanchet@52347
   442
      in (pfss, cqfsss) end;
blanchet@51831
   443
blanchet@52349
   444
    val corec_args = mk_args sssss hssss h_Tsss;
blanchet@51831
   445
  in
blanchet@55862
   446
    ((z, cs, cpss, (corec_args, corec_types)), lthy)
blanchet@51831
   447
  end;
blanchet@51829
   448
traytel@55803
   449
fun mk_co_iters_prelims fp ctr_Tsss fpTs Cs absTs repTs ns mss xtor_co_iterss0 lthy =
blanchet@51903
   450
  let
blanchet@52169
   451
    val thy = Proof_Context.theory_of lthy;
blanchet@55862
   452
    val nn = length fpTs;
blanchet@52169
   453
blanchet@52335
   454
    val (xtor_co_iter_fun_Tss, xtor_co_iterss) =
blanchet@55570
   455
      map (mk_co_iters thy fp fpTs Cs #> `(binder_fun_types o fastype_of o hd))
blanchet@55570
   456
        (transpose xtor_co_iterss0)
blanchet@52335
   457
      |> apsnd transpose o apfst transpose o split_list;
blanchet@51903
   458
blanchet@52329
   459
    val ((iters_args_types, coiters_args_types), lthy') =
blanchet@52207
   460
      if fp = Least_FP then
blanchet@55862
   461
        if nn = 1 andalso forall (forall (forall (not o exists_subtype_in fpTs))) ctr_Tsss then
blanchet@55862
   462
          ((NONE, NONE), lthy)
blanchet@55862
   463
        else
blanchet@55862
   464
          mk_iters_args_types ctr_Tsss Cs absTs repTs ns mss xtor_co_iter_fun_Tss lthy
blanchet@55862
   465
          |>> (rpair NONE o SOME)
blanchet@51903
   466
      else
traytel@55803
   467
        mk_coiters_args_types ctr_Tsss Cs absTs repTs ns mss xtor_co_iter_fun_Tss lthy
traytel@55803
   468
        |>> (pair NONE o SOME);
blanchet@51903
   469
  in
blanchet@52335
   470
    ((xtor_co_iterss, iters_args_types, coiters_args_types), lthy')
blanchet@51903
   471
  end;
blanchet@51903
   472
traytel@55803
   473
fun mk_preds_getterss_join c cps absT abs cqfss =
traytel@55803
   474
  let
traytel@55803
   475
    val n = length cqfss;
traytel@55803
   476
    val ts = map2 (mk_absumprod absT abs n) (1 upto n) cqfss;
traytel@55803
   477
  in
traytel@55803
   478
    Term.lambda c (mk_IfN absT cps ts)
blanchet@51900
   479
  end;
blanchet@51886
   480
blanchet@55864
   481
fun define_co_iter fp fpT Cs b rhs lthy0 =
blanchet@51897
   482
  let
blanchet@52170
   483
    val thy = Proof_Context.theory_of lthy0;
blanchet@52170
   484
traytel@53569
   485
    val maybe_conceal_def_binding = Thm.def_binding
traytel@53569
   486
      #> Config.get lthy0 bnf_note_all = false ? Binding.conceal;
traytel@53569
   487
blanchet@55864
   488
    val ((cst, (_, def)), (lthy', lthy)) = lthy0
blanchet@55864
   489
      |> Local_Theory.define ((b, NoSyn), ((maybe_conceal_def_binding b, []), rhs))
blanchet@52327
   490
      ||> `Local_Theory.restore;
blanchet@52327
   491
blanchet@52327
   492
    val phi = Proof_Context.export_morphism lthy lthy';
blanchet@52327
   493
blanchet@55864
   494
    val cst' = mk_co_iter thy fp fpT Cs (Morphism.term phi cst);
blanchet@55864
   495
    val def' = Morphism.thm phi def;
blanchet@52327
   496
  in
blanchet@55864
   497
    ((cst', def'), lthy')
blanchet@52327
   498
  end;
blanchet@52327
   499
blanchet@55864
   500
fun define_iter NONE _ _ _ _ _ = pair (Term.dummy, refl)
blanchet@55864
   501
  | define_iter (SOME (_, _, fss, xssss)) mk_binding fpTs Cs reps ctor_iter =
blanchet@55862
   502
    let
blanchet@55862
   503
      val nn = length fpTs;
blanchet@55862
   504
      val (ctor_iter_absTs, fpT) = strip_typeN nn (fastype_of ctor_iter)
blanchet@55862
   505
        |>> map domain_type ||> domain_type;
blanchet@55864
   506
    in
blanchet@55864
   507
      define_co_iter Least_FP fpT Cs (mk_binding recN)
blanchet@55864
   508
        (fold_rev (fold_rev Term.lambda) fss (Term.list_comb (ctor_iter,
traytel@55803
   509
           map4 (fn ctor_iter_absT => fn rep => fn fs => fn xsss =>
traytel@55803
   510
               mk_case_absumprod ctor_iter_absT rep fs
traytel@55803
   511
                 (map (HOLogic.mk_tuple o map HOLogic.mk_tuple) xsss) (map flat_rec_arg_args xsss))
blanchet@55864
   512
             ctor_iter_absTs reps fss xssss)))
blanchet@55862
   513
    end;
blanchet@51897
   514
blanchet@55864
   515
fun define_coiter (_, cs, cpss, ((pfss, cqfsss), f_absTs)) mk_binding fpTs Cs abss dtor_coiter =
blanchet@51897
   516
  let
blanchet@51899
   517
    val nn = length fpTs;
blanchet@55862
   518
    val fpT = range_type (snd (strip_typeN nn (fastype_of dtor_coiter)));
blanchet@51897
   519
  in
blanchet@55864
   520
    define_co_iter Greatest_FP fpT Cs (mk_binding corecN)
blanchet@55864
   521
      (fold_rev (fold_rev Term.lambda) pfss (Term.list_comb (dtor_coiter,
blanchet@55864
   522
         map5 mk_preds_getterss_join cs cpss f_absTs abss cqfsss)))
blanchet@52320
   523
  end;
blanchet@51897
   524
blanchet@55862
   525
fun derive_induct_iters_thms_for_types pre_bnfs rec_args_typess ctor_induct ctor_iter_thmss
blanchet@55856
   526
    nesting_bnfs nested_bnfs fpTs Cs Xs ctrXs_Tsss fp_abs_inverses fp_type_definitions abs_inverses
blanchet@55864
   527
    ctrss ctr_defss recs rec_defs lthy =
blanchet@51808
   528
  let
blanchet@51827
   529
    val ctr_Tsss = map (map (binder_types o fastype_of)) ctrss;
blanchet@51827
   530
blanchet@51815
   531
    val nn = length pre_bnfs;
blanchet@51827
   532
    val ns = map length ctr_Tsss;
blanchet@51827
   533
    val mss = map (map length) ctr_Tsss;
blanchet@51815
   534
blanchet@51808
   535
    val pre_map_defs = map map_def_of_bnf pre_bnfs;
blanchet@51808
   536
    val pre_set_defss = map set_defs_of_bnf pre_bnfs;
blanchet@53329
   537
    val nesting_map_idents = map (unfold_thms lthy [id_def] o map_id0_of_bnf) nesting_bnfs;
blanchet@53329
   538
    val nested_map_idents = map (unfold_thms lthy [id_def] o map_id0_of_bnf) nested_bnfs;
blanchet@53290
   539
    val nested_set_maps = maps set_map_of_bnf nested_bnfs;
blanchet@51808
   540
blanchet@51816
   541
    val fp_b_names = map base_name_of_typ fpTs;
blanchet@51811
   542
blanchet@51832
   543
    val ((((ps, ps'), xsss), us'), names_lthy) =
blanchet@52315
   544
      lthy
blanchet@51808
   545
      |> mk_Frees' "P" (map mk_pred1T fpTs)
blanchet@51827
   546
      ||>> mk_Freesss "x" ctr_Tsss
blanchet@51816
   547
      ||>> Variable.variant_fixes fp_b_names;
blanchet@51808
   548
blanchet@51808
   549
    val us = map2 (curry Free) us' fpTs;
blanchet@51808
   550
blanchet@51808
   551
    fun mk_sets_nested bnf =
blanchet@51808
   552
      let
blanchet@51808
   553
        val Type (T_name, Us) = T_of_bnf bnf;
blanchet@51808
   554
        val lives = lives_of_bnf bnf;
blanchet@51808
   555
        val sets = sets_of_bnf bnf;
blanchet@51808
   556
        fun mk_set U =
blanchet@54237
   557
          (case find_index (curry (op =) U) lives of
blanchet@51808
   558
            ~1 => Term.dummy
blanchet@51808
   559
          | i => nth sets i);
blanchet@51808
   560
      in
blanchet@51808
   561
        (T_name, map mk_set Us)
blanchet@51808
   562
      end;
blanchet@51808
   563
blanchet@51808
   564
    val setss_nested = map mk_sets_nested nested_bnfs;
blanchet@51808
   565
blanchet@51808
   566
    val (induct_thms, induct_thm) =
blanchet@51808
   567
      let
blanchet@51808
   568
        fun mk_set Ts t =
blanchet@51808
   569
          let val Type (_, Ts0) = domain_type (fastype_of t) in
blanchet@51808
   570
            Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@51808
   571
          end;
blanchet@51808
   572
blanchet@52310
   573
        fun mk_raw_prem_prems _ (x as Free (_, Type _)) (X as TFree _) =
blanchet@54237
   574
            [([], (find_index (curry (op =) X) Xs + 1, x))]
blanchet@52310
   575
          | mk_raw_prem_prems names_lthy (x as Free (s, Type (T_name, Ts0))) (Type (_, Xs_Ts0)) =
blanchet@52310
   576
            (case AList.lookup (op =) setss_nested T_name of
blanchet@52310
   577
              NONE => []
blanchet@52310
   578
            | SOME raw_sets0 =>
blanchet@52310
   579
              let
blanchet@52310
   580
                val (Xs_Ts, (Ts, raw_sets)) =
blanchet@52310
   581
                  filter (exists_subtype_in Xs o fst) (Xs_Ts0 ~~ (Ts0 ~~ raw_sets0))
blanchet@52310
   582
                  |> split_list ||> split_list;
blanchet@52310
   583
                val sets = map (mk_set Ts0) raw_sets;
blanchet@52310
   584
                val (ys, names_lthy') = names_lthy |> mk_Frees s Ts;
blanchet@52310
   585
                val xysets = map (pair x) (ys ~~ sets);
blanchet@52310
   586
                val ppremss = map2 (mk_raw_prem_prems names_lthy') ys Xs_Ts;
blanchet@52310
   587
              in
blanchet@52310
   588
                flat (map2 (map o apfst o cons) xysets ppremss)
blanchet@52310
   589
              end)
blanchet@52310
   590
          | mk_raw_prem_prems _ _ _ = [];
blanchet@51808
   591
blanchet@51808
   592
        fun close_prem_prem xs t =
blanchet@51808
   593
          fold_rev Logic.all (map Free (drop (nn + length xs)
blanchet@51808
   594
            (rev (Term.add_frees t (map dest_Free xs @ ps'))))) t;
blanchet@51808
   595
blanchet@51808
   596
        fun mk_prem_prem xs (xysets, (j, x)) =
blanchet@51808
   597
          close_prem_prem xs (Logic.list_implies (map (fn (x', (y, set)) =>
blanchet@51808
   598
              HOLogic.mk_Trueprop (HOLogic.mk_mem (y, set $ x'))) xysets,
blanchet@51808
   599
            HOLogic.mk_Trueprop (nth ps (j - 1) $ x)));
blanchet@51808
   600
blanchet@52310
   601
        fun mk_raw_prem phi ctr ctr_Ts ctrXs_Ts =
blanchet@51808
   602
          let
blanchet@51808
   603
            val (xs, names_lthy') = names_lthy |> mk_Frees "x" ctr_Ts;
blanchet@52310
   604
            val pprems = flat (map2 (mk_raw_prem_prems names_lthy') xs ctrXs_Ts);
blanchet@51808
   605
          in (xs, pprems, HOLogic.mk_Trueprop (phi $ Term.list_comb (ctr, xs))) end;
blanchet@51808
   606
blanchet@51808
   607
        fun mk_prem (xs, raw_pprems, concl) =
blanchet@51808
   608
          fold_rev Logic.all xs (Logic.list_implies (map (mk_prem_prem xs) raw_pprems, concl));
blanchet@51808
   609
blanchet@52310
   610
        val raw_premss = map4 (map3 o mk_raw_prem) ps ctrss ctr_Tsss ctrXs_Tsss;
blanchet@51808
   611
blanchet@51808
   612
        val goal =
blanchet@51808
   613
          Library.foldr (Logic.list_implies o apfst (map mk_prem)) (raw_premss,
blanchet@54237
   614
            HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 (curry (op $)) ps us)));
blanchet@51808
   615
blanchet@51808
   616
        val kksss = map (map (map (fst o snd) o #2)) raw_premss;
blanchet@51808
   617
traytel@55803
   618
        val ctor_induct' = ctor_induct OF (map2 mk_absumprodE fp_type_definitions mss);
blanchet@51808
   619
blanchet@51808
   620
        val thm =
blanchet@51808
   621
          Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
traytel@55803
   622
            mk_induct_tac ctxt nn ns mss kksss (flat ctr_defss) ctor_induct' fp_abs_inverses
traytel@55803
   623
              abs_inverses nested_set_maps pre_set_defss)
blanchet@51808
   624
          |> singleton (Proof_Context.export names_lthy lthy)
blanchet@55409
   625
          (* for "datatype_realizer.ML": *)
blanchet@55409
   626
          |> Thm.name_derivation (fst (dest_Type (hd fpTs)) ^ Long_Name.separator ^
blanchet@55409
   627
            (if nn > 1 then space_implode "_" (tl fp_b_names) ^ Long_Name.separator else "") ^
blanchet@55409
   628
            inductN);
blanchet@51808
   629
      in
blanchet@51808
   630
        `(conj_dests nn) thm
blanchet@51808
   631
      end;
blanchet@51808
   632
blanchet@51808
   633
    val induct_cases = quasi_unambiguous_case_names (maps (map name_of_ctr) ctrss);
blanchet@52305
   634
    val induct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names induct_cases));
blanchet@51808
   635
blanchet@52305
   636
    val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
blanchet@52305
   637
blanchet@52306
   638
    fun mk_iter_thmss (_, x_Tssss, fss, _) iters iter_defs ctor_iter_thms =
blanchet@51808
   639
      let
blanchet@52305
   640
        val fiters = map (lists_bmoc fss) iters;
blanchet@51808
   641
blanchet@51843
   642
        fun mk_goal fss fiter xctr f xs fxs =
blanchet@51808
   643
          fold_rev (fold_rev Logic.all) (xs :: fss)
blanchet@51843
   644
            (mk_Trueprop_eq (fiter $ xctr, Term.list_comb (f, fxs)));
blanchet@51808
   645
blanchet@52302
   646
        fun maybe_tick (T, U) u f =
blanchet@52302
   647
          if try (fst o HOLogic.dest_prodT) U = SOME T then
blanchet@52302
   648
            Term.lambda u (HOLogic.mk_prod (u, f $ u))
blanchet@52302
   649
          else
blanchet@52302
   650
            f;
blanchet@51808
   651
blanchet@52368
   652
        fun build_iter (x as Free (_, T)) U =
blanchet@52368
   653
          if T = U then
blanchet@52368
   654
            x
blanchet@52368
   655
          else
blanchet@52303
   656
            build_map lthy (indexify (perhaps (try (snd o HOLogic.dest_prodT)) o snd) Cs
blanchet@52368
   657
              (fn kk => fn TU => maybe_tick TU (nth us kk) (nth fiters kk))) (T, U) $ x;
blanchet@52301
   658
blanchet@52868
   659
        val fxsss = map2 (map2 (flat_rec_arg_args oo map2 (map o build_iter))) xsss x_Tssss;
blanchet@51808
   660
blanchet@52306
   661
        val goalss = map5 (map4 o mk_goal fss) fiters xctrss fss xsss fxsss;
blanchet@51808
   662
blanchet@52305
   663
        val tacss =
traytel@55803
   664
          map4 (map ooo mk_iter_tac pre_map_defs (nested_map_idents @ nesting_map_idents) iter_defs)
traytel@55803
   665
            ctor_iter_thms fp_abs_inverses abs_inverses ctr_defss;
blanchet@51808
   666
blanchet@51808
   667
        fun prove goal tac =
blanchet@51808
   668
          Goal.prove_sorry lthy [] [] goal (tac o #context)
blanchet@51808
   669
          |> Thm.close_derivation;
blanchet@51808
   670
      in
blanchet@52305
   671
        map2 (map2 prove) goalss tacss
blanchet@51808
   672
      end;
blanchet@51808
   673
blanchet@55862
   674
    val rec_thmss =
blanchet@55862
   675
      (case rec_args_typess of
blanchet@55862
   676
        SOME types =>
blanchet@55864
   677
        mk_iter_thmss types recs rec_defs (map co_rec_of ctor_iter_thmss)
blanchet@55862
   678
      | NONE => replicate nn []);
blanchet@51808
   679
  in
blanchet@52345
   680
    ((induct_thms, induct_thm, [induct_case_names_attr]),
blanchet@55856
   681
     (rec_thmss, code_nitpicksimp_attrs @ simp_attrs))
blanchet@51808
   682
  end;
blanchet@51808
   683
blanchet@52347
   684
fun derive_coinduct_coiters_thms_for_types pre_bnfs (z, cs, cpss,
blanchet@55862
   685
      coiters_args_types as ((phss, cshsss), _))
blanchet@54235
   686
    dtor_coinduct dtor_injects dtor_ctors dtor_coiter_thmss nesting_bnfs fpTs Cs Xs ctrXs_Tsss kss
traytel@55803
   687
    mss ns fp_abs_inverses abs_inverses mk_vimage2p ctr_defss (ctr_sugars : ctr_sugar list)
blanchet@55864
   688
    corecs corec_defs export_args lthy =
blanchet@51810
   689
  let
traytel@53203
   690
    fun mk_ctor_dtor_coiter_thm dtor_inject dtor_ctor coiter =
traytel@53203
   691
      iffD1 OF [dtor_inject, trans OF [coiter, dtor_ctor RS sym]];
traytel@53203
   692
traytel@53203
   693
    val ctor_dtor_coiter_thmss =
traytel@53203
   694
      map3 (map oo mk_ctor_dtor_coiter_thm) dtor_injects dtor_ctors dtor_coiter_thmss;
traytel@53203
   695
blanchet@51815
   696
    val nn = length pre_bnfs;
blanchet@51815
   697
blanchet@51810
   698
    val pre_map_defs = map map_def_of_bnf pre_bnfs;
blanchet@51810
   699
    val pre_rel_defs = map rel_def_of_bnf pre_bnfs;
blanchet@53329
   700
    val nesting_map_idents = map (unfold_thms lthy [id_def] o map_id0_of_bnf) nesting_bnfs;
blanchet@51830
   701
    val nesting_rel_eqs = map rel_eq_of_bnf nesting_bnfs;
blanchet@51810
   702
blanchet@51816
   703
    val fp_b_names = map base_name_of_typ fpTs;
blanchet@51811
   704
blanchet@53210
   705
    val ctrss = map #ctrs ctr_sugars;
blanchet@53210
   706
    val discss = map #discs ctr_sugars;
blanchet@53210
   707
    val selsss = map #selss ctr_sugars;
blanchet@51840
   708
    val exhausts = map #exhaust ctr_sugars;
blanchet@51840
   709
    val disc_thmsss = map #disc_thmss ctr_sugars;
blanchet@51840
   710
    val discIss = map #discIs ctr_sugars;
blanchet@51840
   711
    val sel_thmsss = map #sel_thmss ctr_sugars;
blanchet@51810
   712
blanchet@51810
   713
    val (((rs, us'), vs'), names_lthy) =
blanchet@52341
   714
      lthy
blanchet@51810
   715
      |> mk_Frees "R" (map (fn T => mk_pred2T T T) fpTs)
blanchet@51816
   716
      ||>> Variable.variant_fixes fp_b_names
blanchet@51816
   717
      ||>> Variable.variant_fixes (map (suffix "'") fp_b_names);
blanchet@51810
   718
blanchet@51810
   719
    val us = map2 (curry Free) us' fpTs;
blanchet@51810
   720
    val udiscss = map2 (map o rapp) us discss;
blanchet@51810
   721
    val uselsss = map2 (map o map o rapp) us selsss;
blanchet@51810
   722
blanchet@51810
   723
    val vs = map2 (curry Free) vs' fpTs;
blanchet@51810
   724
    val vdiscss = map2 (map o rapp) vs discss;
blanchet@51810
   725
    val vselsss = map2 (map o map o rapp) vs selsss;
blanchet@51810
   726
blanchet@52345
   727
    val coinduct_thms_pairs =
blanchet@51810
   728
      let
blanchet@51810
   729
        val uvrs = map3 (fn r => fn u => fn v => r $ u $ v) rs us vs;
blanchet@51810
   730
        val uv_eqs = map2 (curry HOLogic.mk_eq) us vs;
blanchet@51810
   731
        val strong_rs =
blanchet@51810
   732
          map4 (fn u => fn v => fn uvr => fn uv_eq =>
blanchet@51810
   733
            fold_rev Term.lambda [u, v] (HOLogic.mk_disj (uvr, uv_eq))) us vs uvrs uv_eqs;
blanchet@51810
   734
blanchet@54237
   735
        fun build_the_rel rs' T Xs_T =
blanchet@54237
   736
          build_rel lthy (fn (_, X) => nth rs' (find_index (curry (op =) X) Xs)) (T, Xs_T)
blanchet@54237
   737
          |> Term.subst_atomic_types (Xs ~~ fpTs);
blanchet@51810
   738
blanchet@54237
   739
        fun build_rel_app rs' usel vsel Xs_T =
blanchet@54237
   740
          fold rapp [usel, vsel] (build_the_rel rs' (fastype_of usel) Xs_T);
blanchet@51810
   741
blanchet@54237
   742
        fun mk_prem_ctr_concls rs' n k udisc usels vdisc vsels ctrXs_Ts =
blanchet@51810
   743
          (if k = n then [] else [HOLogic.mk_eq (udisc, vdisc)]) @
blanchet@51810
   744
          (if null usels then
blanchet@51810
   745
             []
blanchet@51810
   746
           else
blanchet@51810
   747
             [Library.foldr HOLogic.mk_imp (if n = 1 then [] else [udisc, vdisc],
blanchet@54237
   748
                Library.foldr1 HOLogic.mk_conj (map3 (build_rel_app rs') usels vsels ctrXs_Ts))]);
blanchet@51810
   749
blanchet@54237
   750
        fun mk_prem_concl rs' n udiscs uselss vdiscs vselss ctrXs_Tss =
blanchet@54237
   751
          Library.foldr1 HOLogic.mk_conj (flat (map6 (mk_prem_ctr_concls rs' n)
blanchet@54237
   752
            (1 upto n) udiscs uselss vdiscs vselss ctrXs_Tss))
blanchet@51810
   753
          handle List.Empty => @{term True};
blanchet@51810
   754
blanchet@54237
   755
        fun mk_prem rs' uvr u v n udiscs uselss vdiscs vselss ctrXs_Tss =
blanchet@51810
   756
          fold_rev Logic.all [u, v] (Logic.mk_implies (HOLogic.mk_Trueprop uvr,
blanchet@54237
   757
            HOLogic.mk_Trueprop (mk_prem_concl rs' n udiscs uselss vdiscs vselss ctrXs_Tss)));
blanchet@51810
   758
blanchet@51810
   759
        val concl =
blanchet@51810
   760
          HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
blanchet@51810
   761
            (map3 (fn uvr => fn u => fn v => HOLogic.mk_imp (uvr, HOLogic.mk_eq (u, v)))
blanchet@51810
   762
               uvrs us vs));
blanchet@51810
   763
blanchet@51810
   764
        fun mk_goal rs' =
blanchet@54237
   765
          Logic.list_implies (map9 (mk_prem rs') uvrs us vs ns udiscss uselsss vdiscss vselsss
blanchet@54237
   766
            ctrXs_Tsss, concl);
blanchet@51810
   767
blanchet@52345
   768
        val goals = map mk_goal [rs, strong_rs];
blanchet@51810
   769
blanchet@51810
   770
        fun prove dtor_coinduct' goal =
blanchet@51810
   771
          Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
traytel@55803
   772
            mk_coinduct_tac ctxt nesting_rel_eqs nn ns dtor_coinduct' pre_rel_defs fp_abs_inverses
traytel@55803
   773
              abs_inverses dtor_ctors exhausts ctr_defss disc_thmsss sel_thmsss)
blanchet@51810
   774
          |> singleton (Proof_Context.export names_lthy lthy)
blanchet@51810
   775
          |> Thm.close_derivation;
blanchet@51810
   776
blanchet@51810
   777
        fun postproc nn thm =
blanchet@51810
   778
          Thm.permute_prems 0 nn
blanchet@51828
   779
            (if nn = 1 then thm RS mp else funpow nn (fn thm => reassoc_conjs (thm RS mp_conj)) thm)
blanchet@51810
   780
          |> Drule.zero_var_indexes
blanchet@51810
   781
          |> `(conj_dests nn);
traytel@53106
   782
traytel@53106
   783
        val rel_eqs = map rel_eq_of_bnf pre_bnfs;
traytel@53106
   784
        val rel_monos = map rel_mono_of_bnf pre_bnfs;
traytel@53106
   785
        val dtor_coinducts =
traytel@55803
   786
          [dtor_coinduct, mk_strong_coinduct_thm dtor_coinduct rel_eqs rel_monos mk_vimage2p lthy]
blanchet@51810
   787
      in
blanchet@52345
   788
        map2 (postproc nn oo prove) dtor_coinducts goals
blanchet@51810
   789
      end;
blanchet@51810
   790
blanchet@51810
   791
    fun mk_coinduct_concls ms discs ctrs =
blanchet@51810
   792
      let
blanchet@51810
   793
        fun mk_disc_concl disc = [name_of_disc disc];
blanchet@51810
   794
        fun mk_ctr_concl 0 _ = []
blanchet@51810
   795
          | mk_ctr_concl _ ctor = [name_of_ctr ctor];
blanchet@51810
   796
        val disc_concls = map mk_disc_concl (fst (split_last discs)) @ [[]];
blanchet@51810
   797
        val ctr_concls = map2 mk_ctr_concl ms ctrs;
blanchet@51810
   798
      in
blanchet@51810
   799
        flat (map2 append disc_concls ctr_concls)
blanchet@51810
   800
      end;
blanchet@51810
   801
blanchet@51816
   802
    val coinduct_cases = quasi_unambiguous_case_names (map (prefix EqN) fp_b_names);
blanchet@51810
   803
    val coinduct_conclss =
blanchet@51810
   804
      map3 (quasi_unambiguous_case_names ooo mk_coinduct_concls) mss discss ctrss;
blanchet@51810
   805
blanchet@51810
   806
    fun mk_maybe_not pos = not pos ? HOLogic.mk_not;
blanchet@51810
   807
blanchet@55856
   808
    val fcoiterss' as [hcorecs] =
blanchet@55864
   809
      map2 (fn (pfss, _) => map (lists_bmoc pfss)) [fst coiters_args_types] [corecs];
blanchet@51810
   810
blanchet@55856
   811
    val corec_thmss =
blanchet@51810
   812
      let
blanchet@51843
   813
        fun mk_goal pfss c cps fcoiter n k ctr m cfs' =
blanchet@51810
   814
          fold_rev (fold_rev Logic.all) ([c] :: pfss)
blanchet@51810
   815
            (Logic.list_implies (seq_conds (HOLogic.mk_Trueprop oo mk_maybe_not) n k cps,
blanchet@51843
   816
               mk_Trueprop_eq (fcoiter $ c, Term.list_comb (ctr, take m cfs'))));
blanchet@51810
   817
blanchet@52347
   818
        fun mk_U maybe_mk_sumT =
blanchet@52347
   819
          typ_subst_nonatomic (map2 (fn C => fn fpT => (maybe_mk_sumT fpT C, fpT)) Cs fpTs);
blanchet@52347
   820
blanchet@52347
   821
        fun tack z_name (c, u) f =
blanchet@52347
   822
          let val z = Free (z_name, mk_sumT (fastype_of u, fastype_of c)) in
blanchet@55414
   823
            Term.lambda z (mk_case_sum (Term.lambda u u, Term.lambda c (f $ c)) $ z)
blanchet@52347
   824
          end;
blanchet@51810
   825
blanchet@52368
   826
        fun build_coiter fcoiters maybe_mk_sumT maybe_tack cqf =
blanchet@52347
   827
          let val T = fastype_of cqf in
blanchet@52347
   828
            if exists_subtype_in Cs T then
blanchet@52368
   829
              let val U = mk_U maybe_mk_sumT T in
blanchet@55483
   830
                build_map lthy (indexify fst (map2 maybe_mk_sumT fpTs Cs) (fn kk => fn _ =>
blanchet@52368
   831
                  maybe_tack (nth cs kk, nth us kk) (nth fcoiters kk))) (T, U) $ cqf
blanchet@52368
   832
              end
blanchet@52347
   833
            else
blanchet@52347
   834
              cqf
blanchet@52347
   835
          end;
blanchet@51810
   836
blanchet@52368
   837
        val cshsss' = map (map (map (build_coiter (co_rec_of fcoiterss') (curry mk_sumT) (tack z))))
blanchet@52351
   838
          cshsss;
blanchet@51810
   839
blanchet@55856
   840
        val goalss = map8 (map4 oooo mk_goal phss) cs cpss hcorecs ns kss ctrss mss cshsss';
blanchet@51810
   841
blanchet@55856
   842
        val tacss =
traytel@55803
   843
          map4 (map ooo mk_coiter_tac corec_defs nesting_map_idents)
traytel@55803
   844
            (map co_rec_of ctor_dtor_coiter_thmss) pre_map_defs abs_inverses ctr_defss;
blanchet@51810
   845
blanchet@51810
   846
        fun prove goal tac =
blanchet@51815
   847
          Goal.prove_sorry lthy [] [] goal (tac o #context)
blanchet@51815
   848
          |> Thm.close_derivation;
blanchet@51810
   849
      in
blanchet@55856
   850
        map2 (map2 prove) goalss tacss
blanchet@55856
   851
        |> map (map (unfold_thms lthy @{thms case_sum_if}))
blanchet@51810
   852
      end;
blanchet@51810
   853
blanchet@55856
   854
    val disc_corec_iff_thmss =
blanchet@51810
   855
      let
blanchet@51843
   856
        fun mk_goal c cps fcoiter n k disc =
blanchet@51843
   857
          mk_Trueprop_eq (disc $ (fcoiter $ c),
blanchet@51810
   858
            if n = 1 then @{const True}
blanchet@51810
   859
            else Library.foldr1 HOLogic.mk_conj (seq_conds mk_maybe_not n k cps));
blanchet@51810
   860
blanchet@55856
   861
        val goalss = map6 (map2 oooo mk_goal) cs cpss hcorecs ns kss discss;
blanchet@51810
   862
blanchet@51828
   863
        fun mk_case_split' cp = Drule.instantiate' [] [SOME (certify lthy cp)] @{thm case_split};
blanchet@51810
   864
blanchet@51810
   865
        val case_splitss' = map (map mk_case_split') cpss;
blanchet@51810
   866
blanchet@55856
   867
        val tacss = map3 (map oo mk_disc_coiter_iff_tac) case_splitss' corec_thmss disc_thmsss;
blanchet@51810
   868
blanchet@51810
   869
        fun prove goal tac =
blanchet@51810
   870
          Goal.prove_sorry lthy [] [] goal (tac o #context)
blanchet@52357
   871
          |> singleton export_args
blanchet@51829
   872
          |> singleton (Proof_Context.export names_lthy lthy)
blanchet@51810
   873
          |> Thm.close_derivation;
blanchet@51810
   874
blanchet@51810
   875
        fun proves [_] [_] = []
blanchet@51810
   876
          | proves goals tacs = map2 prove goals tacs;
blanchet@51810
   877
      in
blanchet@55856
   878
        map2 proves goalss tacss
blanchet@51810
   879
      end;
blanchet@51810
   880
blanchet@53741
   881
    fun mk_disc_coiter_thms coiters discIs = map (op RS) (coiters ~~ discIs);
blanchet@51810
   882
blanchet@51843
   883
    val disc_corec_thmss = map2 mk_disc_coiter_thms corec_thmss discIss;
blanchet@51810
   884
blanchet@51843
   885
    fun mk_sel_coiter_thm coiter_thm sel sel_thm =
blanchet@51810
   886
      let
blanchet@51810
   887
        val (domT, ranT) = dest_funT (fastype_of sel);
blanchet@51810
   888
        val arg_cong' =
blanchet@51810
   889
          Drule.instantiate' (map (SOME o certifyT lthy) [domT, ranT])
blanchet@51810
   890
            [NONE, NONE, SOME (certify lthy sel)] arg_cong
blanchet@51810
   891
          |> Thm.varifyT_global;
blanchet@51810
   892
        val sel_thm' = sel_thm RSN (2, trans);
blanchet@51810
   893
      in
blanchet@51843
   894
        coiter_thm RS arg_cong' RS sel_thm'
blanchet@51810
   895
      end;
blanchet@51810
   896
blanchet@52321
   897
    fun mk_sel_coiter_thms coiter_thmss =
blanchet@53475
   898
      map3 (map3 (map2 o mk_sel_coiter_thm)) coiter_thmss selsss sel_thmsss;
blanchet@51810
   899
blanchet@53475
   900
    val sel_corec_thmsss = mk_sel_coiter_thms corec_thmss;
blanchet@51810
   901
blanchet@51810
   902
    val coinduct_consumes_attr = Attrib.internal (K (Rule_Cases.consumes nn));
blanchet@51810
   903
    val coinduct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names coinduct_cases));
blanchet@51810
   904
    val coinduct_case_concl_attrs =
blanchet@51810
   905
      map2 (fn casex => fn concls =>
blanchet@51810
   906
          Attrib.internal (K (Rule_Cases.case_conclusion (casex, concls))))
blanchet@51810
   907
        coinduct_cases coinduct_conclss;
blanchet@51810
   908
    val coinduct_case_attrs =
blanchet@51810
   909
      coinduct_consumes_attr :: coinduct_case_names_attr :: coinduct_case_concl_attrs;
blanchet@51810
   910
  in
blanchet@52345
   911
    ((coinduct_thms_pairs, coinduct_case_attrs),
blanchet@55856
   912
     (corec_thmss, code_nitpicksimp_attrs),
blanchet@55856
   913
     (disc_corec_thmss, []),
blanchet@55856
   914
     (disc_corec_iff_thmss, simp_attrs),
blanchet@55856
   915
     (sel_corec_thmsss, simp_attrs))
blanchet@51810
   916
  end;
blanchet@51810
   917
blanchet@52207
   918
fun define_co_datatypes prepare_constraint prepare_typ prepare_term fp construct_fp
blanchet@55410
   919
    (wrap_opts as (no_discs_sels, _), specs) no_defs_lthy0 =
blanchet@49112
   920
  let
blanchet@49298
   921
    (* TODO: sanity checks on arguments *)
blanchet@49298
   922
blanchet@52969
   923
    val _ = if fp = Greatest_FP andalso no_discs_sels then
blanchet@52969
   924
        error "Cannot define codatatypes without discriminators and selectors"
blanchet@52207
   925
      else
blanchet@52207
   926
        ();
blanchet@49278
   927
blanchet@49367
   928
    val nn = length specs;
blanchet@55469
   929
    val fp_bs = map type_binding_of_spec specs;
blanchet@49498
   930
    val fp_b_names = map Binding.name_of fp_bs;
blanchet@49498
   931
    val fp_common_name = mk_common_name fp_b_names;
blanchet@55469
   932
    val map_bs = map map_binding_of_spec specs;
blanchet@55469
   933
    val rel_bs = map rel_binding_of_spec specs;
blanchet@49298
   934
blanchet@51758
   935
    fun prepare_type_arg (_, (ty, c)) =
blanchet@49298
   936
      let val TFree (s, _) = prepare_typ no_defs_lthy0 ty in
blanchet@49298
   937
        TFree (s, prepare_constraint no_defs_lthy0 c)
blanchet@49298
   938
      end;
blanchet@49298
   939
blanchet@55469
   940
    val Ass0 = map (map prepare_type_arg o type_args_named_constrained_of_spec) specs;
blanchet@49298
   941
    val unsorted_Ass0 = map (map (resort_tfree HOLogic.typeS)) Ass0;
blanchet@55700
   942
    val unsorted_As = Library.foldr1 (merge_type_args fp) unsorted_Ass0;
blanchet@53266
   943
    val num_As = length unsorted_As;
blanchet@55699
   944
blanchet@55699
   945
    val set_boss = map (map fst o type_args_named_constrained_of_spec) specs;
blanchet@55699
   946
    val set_bss = map (map (the_default Binding.empty)) set_boss;
blanchet@49119
   947
blanchet@49585
   948
    val (((Bs0, Cs), Xs), no_defs_lthy) =
blanchet@49298
   949
      no_defs_lthy0
blanchet@49298
   950
      |> fold (Variable.declare_typ o resort_tfree dummyS) unsorted_As
blanchet@53266
   951
      |> mk_TFrees num_As
blanchet@49585
   952
      ||>> mk_TFrees nn
blanchet@51858
   953
      ||>> variant_tfrees fp_b_names;
blanchet@49119
   954
blanchet@55469
   955
    fun add_fake_type spec =
blanchet@55469
   956
      Typedecl.basic_typedecl (type_binding_of_spec spec, num_As, mixfix_of_spec spec);
blanchet@51768
   957
blanchet@53268
   958
    val (fake_T_names, fake_lthy) = fold_map add_fake_type specs no_defs_lthy0;
blanchet@49119
   959
blanchet@53262
   960
    val qsoty = quote o Syntax.string_of_typ fake_lthy;
blanchet@53262
   961
blanchet@54253
   962
    val _ = (case Library.duplicates (op =) unsorted_As of [] => ()
blanchet@53262
   963
      | A :: _ => error ("Duplicate type parameter " ^ qsoty A ^ " in " ^ co_prefix fp ^
blanchet@53262
   964
          "datatype specification"));
blanchet@53262
   965
blanchet@53262
   966
    val bad_args =
blanchet@53262
   967
      map (Logic.type_map (singleton (Variable.polymorphic no_defs_lthy0))) unsorted_As
blanchet@53262
   968
      |> filter_out Term.is_TVar;
blanchet@53262
   969
    val _ = null bad_args orelse
blanchet@53262
   970
      error ("Locally fixed type argument " ^ qsoty (hd bad_args) ^ " in " ^ co_prefix fp ^
blanchet@53262
   971
        "datatype specification");
blanchet@53262
   972
blanchet@55469
   973
    val mixfixes = map mixfix_of_spec specs;
blanchet@49119
   974
blanchet@54253
   975
    val _ = (case Library.duplicates Binding.eq_name fp_bs of [] => ()
blanchet@49119
   976
      | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
blanchet@49119
   977
blanchet@55469
   978
    val mx_ctr_specss = map mixfixed_ctr_specs_of_spec specs;
blanchet@55469
   979
    val ctr_specss = map (map fst) mx_ctr_specss;
blanchet@55469
   980
    val ctr_mixfixess = map (map snd) mx_ctr_specss;
blanchet@49119
   981
blanchet@55469
   982
    val disc_bindingss = map (map disc_of_ctr_spec) ctr_specss;
blanchet@49336
   983
    val ctr_bindingss =
blanchet@55469
   984
      map2 (fn fp_b_name => map (Binding.qualify false fp_b_name o ctr_of_ctr_spec)) fp_b_names
blanchet@55469
   985
        ctr_specss;
blanchet@55469
   986
    val ctr_argsss = map (map args_of_ctr_spec) ctr_specss;
blanchet@49119
   987
blanchet@49336
   988
    val sel_bindingsss = map (map (map fst)) ctr_argsss;
blanchet@49298
   989
    val fake_ctr_Tsss0 = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
blanchet@55469
   990
    val raw_sel_defaultsss = map (map sel_defaults_of_ctr_spec) ctr_specss;
blanchet@49286
   991
blanchet@49308
   992
    val (As :: _) :: fake_ctr_Tsss =
blanchet@49298
   993
      burrow (burrow (Syntax.check_typs fake_lthy)) (Ass0 :: fake_ctr_Tsss0);
blanchet@53262
   994
    val As' = map dest_TFree As;
blanchet@49298
   995
blanchet@49183
   996
    val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
blanchet@53262
   997
    val _ = (case subtract (op =) As' rhs_As' of [] => ()
blanchet@53262
   998
      | extras => error ("Extra type variables on right-hand side: " ^
blanchet@53262
   999
          commas (map (qsoty o TFree) extras)));
blanchet@49165
  1000
blanchet@53268
  1001
    val fake_Ts = map (fn s => Type (s, As)) fake_T_names;
blanchet@53268
  1002
blanchet@53262
  1003
    fun eq_fpT_check (T as Type (s, Ts)) (T' as Type (s', Ts')) =
blanchet@53262
  1004
        s = s' andalso (Ts = Ts' orelse
blanchet@53262
  1005
          error ("Wrong type arguments in " ^ co_prefix fp ^ "recursive type " ^ qsoty T ^
blanchet@53262
  1006
            " (expected " ^ qsoty T' ^ ")"))
blanchet@49591
  1007
      | eq_fpT_check _ _ = false;
blanchet@49146
  1008
blanchet@53222
  1009
    fun freeze_fp (T as Type (s, Ts)) =
blanchet@49591
  1010
        (case find_index (eq_fpT_check T) fake_Ts of
blanchet@53222
  1011
          ~1 => Type (s, map freeze_fp Ts)
blanchet@49591
  1012
        | kk => nth Xs kk)
blanchet@49204
  1013
      | freeze_fp T = T;
blanchet@49121
  1014
blanchet@53222
  1015
    val unfreeze_fp = Term.typ_subst_atomic (Xs ~~ fake_Ts);
blanchet@53222
  1016
blanchet@52310
  1017
    val ctrXs_Tsss = map (map (map freeze_fp)) fake_ctr_Tsss;
traytel@55803
  1018
    val ctrXs_repTs = map (mk_sumTN_balanced o map HOLogic.mk_tupleT) ctrXs_Tsss;
blanchet@49119
  1019
blanchet@49298
  1020
    val fp_eqs =
traytel@55803
  1021
      map dest_TFree Xs ~~ map (Term.typ_subst_atomic (As ~~ unsorted_As)) ctrXs_repTs;
blanchet@49121
  1022
blanchet@53262
  1023
    val rhsXs_As' = fold (fold (fold Term.add_tfreesT)) ctrXs_Tsss [];
blanchet@53262
  1024
    val _ = (case subtract (op =) rhsXs_As' As' of [] => ()
blanchet@53266
  1025
      | extras => List.app (fn extra => warning ("Unused type variable on right-hand side of " ^
blanchet@53266
  1026
          co_prefix fp ^ "datatype definition: " ^ qsoty (TFree extra))) extras);
blanchet@53262
  1027
blanchet@55701
  1028
    val killed_As =
blanchet@55701
  1029
      map_filter (fn (A, set_bos) => if exists is_none set_bos then SOME A else NONE)
blanchet@55701
  1030
        (unsorted_As ~~ transpose set_boss);
blanchet@55701
  1031
traytel@55803
  1032
    val ((pre_bnfs, absT_infos), (fp_res as {bnfs = fp_bnfs as any_fp_bnf :: _, ctors = ctors0,
traytel@55803
  1033
             dtors = dtors0, xtor_co_iterss = xtor_co_iterss0, xtor_co_induct, dtor_ctors,
traytel@55803
  1034
             ctor_dtors, ctor_injects, dtor_injects, xtor_map_thms, xtor_set_thmss, xtor_rel_thms,
traytel@55803
  1035
             xtor_co_iter_thmss, ...},
traytel@53203
  1036
           lthy)) =
blanchet@55701
  1037
      fp_bnf (construct_fp mixfixes map_bs rel_bs set_bss) fp_bs (map dest_TFree unsorted_As)
blanchet@55701
  1038
        (map dest_TFree killed_As) fp_eqs no_defs_lthy0
blanchet@53222
  1039
      handle BAD_DEAD (X, X_backdrop) =>
blanchet@53222
  1040
        (case X_backdrop of
blanchet@53222
  1041
          Type (bad_tc, _) =>
blanchet@53222
  1042
          let
blanchet@53222
  1043
            val fake_T = qsoty (unfreeze_fp X);
blanchet@53222
  1044
            val fake_T_backdrop = qsoty (unfreeze_fp X_backdrop);
blanchet@53222
  1045
            fun register_hint () =
blanchet@53222
  1046
              "\nUse the " ^ quote (fst (fst @{command_spec "bnf"})) ^ " command to register " ^
blanchet@53222
  1047
              quote bad_tc ^ " as a bounded natural functor to allow nested (co)recursion through \
blanchet@53222
  1048
              \it";
blanchet@53222
  1049
          in
blanchet@53222
  1050
            if is_some (bnf_of no_defs_lthy bad_tc) orelse
blanchet@53222
  1051
               is_some (fp_sugar_of no_defs_lthy bad_tc) then
blanchet@53256
  1052
              error ("Inadmissible " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
blanchet@53256
  1053
                " in type expression " ^ fake_T_backdrop)
blanchet@53222
  1054
            else if is_some (Datatype_Data.get_info (Proof_Context.theory_of no_defs_lthy)
blanchet@53222
  1055
                bad_tc) then
blanchet@53222
  1056
              error ("Unsupported " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
blanchet@53222
  1057
                " via the old-style datatype " ^ quote bad_tc ^ " in type expression " ^
blanchet@53222
  1058
                fake_T_backdrop ^ register_hint ())
blanchet@53222
  1059
            else
blanchet@53222
  1060
              error ("Unsupported " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
blanchet@53222
  1061
                " via type constructor " ^ quote bad_tc ^ " in type expression " ^ fake_T_backdrop ^
blanchet@53222
  1062
                register_hint ())
blanchet@53222
  1063
          end);
blanchet@49585
  1064
traytel@55803
  1065
    val abss = map #abs absT_infos;
traytel@55803
  1066
    val reps = map #rep absT_infos;
traytel@55803
  1067
    val absTs = map #absT absT_infos;
traytel@55803
  1068
    val repTs = map #repT absT_infos;
traytel@55803
  1069
    val abs_injects = map #abs_inject absT_infos;
traytel@55803
  1070
    val abs_inverses = map #abs_inverse absT_infos;
traytel@55803
  1071
    val type_definitions = map #type_definition absT_infos;
traytel@55803
  1072
traytel@53143
  1073
    val time = time lthy;
blanchet@49585
  1074
    val timer = time (Timer.startRealTimer ());
blanchet@49121
  1075
blanchet@52310
  1076
    val nesting_bnfs = nesty_bnfs lthy ctrXs_Tsss As;
blanchet@52310
  1077
    val nested_bnfs = nesty_bnfs lthy ctrXs_Tsss Xs;
blanchet@49226
  1078
blanchet@49585
  1079
    val pre_map_defs = map map_def_of_bnf pre_bnfs;
blanchet@49585
  1080
    val pre_set_defss = map set_defs_of_bnf pre_bnfs;
blanchet@49585
  1081
    val pre_rel_defs = map rel_def_of_bnf pre_bnfs;
blanchet@53290
  1082
    val nesting_set_maps = maps set_map_of_bnf nesting_bnfs;
blanchet@53290
  1083
    val nested_set_maps = maps set_map_of_bnf nested_bnfs;
blanchet@49585
  1084
blanchet@49585
  1085
    val live = live_of_bnf any_fp_bnf;
blanchet@52961
  1086
    val _ =
blanchet@52961
  1087
      if live = 0 andalso exists (not o Binding.is_empty) (map_bs @ rel_bs) then
blanchet@53266
  1088
        warning "Map function and relator names ignored"
blanchet@52961
  1089
      else
blanchet@52961
  1090
        ();
blanchet@49585
  1091
blanchet@49585
  1092
    val Bs =
blanchet@49585
  1093
      map3 (fn alive => fn A as TFree (_, S) => fn B => if alive then resort_tfree S B else A)
blanchet@53266
  1094
        (liveness_of_fp_bnf num_As any_fp_bnf) As Bs0;
blanchet@49585
  1095
blanchet@49585
  1096
    val B_ify = Term.typ_subst_atomic (As ~~ Bs);
blanchet@49167
  1097
blanchet@49501
  1098
    val ctors = map (mk_ctor As) ctors0;
blanchet@49501
  1099
    val dtors = map (mk_dtor As) dtors0;
blanchet@49124
  1100
blanchet@49501
  1101
    val fpTs = map (domain_type o fastype_of) dtors;
blanchet@49362
  1102
blanchet@51780
  1103
    fun massage_simple_notes base =
blanchet@51780
  1104
      filter_out (null o #2)
blanchet@51780
  1105
      #> map (fn (thmN, thms, attrs) =>
blanchet@55410
  1106
        ((Binding.qualify true base (Binding.name thmN), attrs), [(thms, [])]));
blanchet@51780
  1107
blanchet@51780
  1108
    val massage_multi_notes =
blanchet@51780
  1109
      maps (fn (thmN, thmss, attrs) =>
blanchet@53792
  1110
        map3 (fn fp_b_name => fn Type (T_name, _) => fn thms =>
blanchet@55410
  1111
            ((Binding.qualify true fp_b_name (Binding.name thmN), attrs T_name), [(thms, [])]))
blanchet@53792
  1112
          fp_b_names fpTs thmss)
blanchet@53792
  1113
      #> filter_out (null o fst o hd o snd);
blanchet@51780
  1114
blanchet@52310
  1115
    val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Xs ~~ fpTs)))) ctrXs_Tsss;
blanchet@49203
  1116
    val ns = map length ctr_Tsss;
blanchet@49212
  1117
    val kss = map (fn n => 1 upto n) ns;
blanchet@49203
  1118
    val mss = map (map length) ctr_Tsss;
blanchet@49203
  1119
blanchet@52367
  1120
    val ((xtor_co_iterss, iters_args_types, coiters_args_types), lthy') =
traytel@55803
  1121
      mk_co_iters_prelims fp ctr_Tsss fpTs Cs absTs repTs ns mss xtor_co_iterss0 lthy;
blanchet@49210
  1122
traytel@55803
  1123
    fun define_ctrs_dtrs_for_type (((((((((((((((((((((((((((fp_bnf, fp_b), fpT), ctor), dtor),
traytel@55803
  1124
              xtor_co_iters), ctor_dtor), dtor_ctor), ctor_inject), pre_map_def), pre_set_defs),
traytel@55803
  1125
            pre_rel_def), fp_map_thm), fp_set_thms), fp_rel_thm), n), ks), ms), abs),
traytel@55803
  1126
          abs_inject), abs_inverse), type_definition), ctr_bindings), ctr_mixfixes), ctr_Tss),
traytel@55803
  1127
        disc_bindings), sel_bindingss), raw_sel_defaultss) no_defs_lthy =
blanchet@49176
  1128
      let
blanchet@49498
  1129
        val fp_b_name = Binding.name_of fp_b;
blanchet@49498
  1130
traytel@55803
  1131
        val ctr_absT = domain_type (fastype_of ctor);
blanchet@49119
  1132
blanchet@52968
  1133
        val ((((w, xss), yss), u'), names_lthy) =
blanchet@49204
  1134
          no_defs_lthy
traytel@55803
  1135
          |> yield_singleton (mk_Frees "w") ctr_absT
blanchet@49370
  1136
          ||>> mk_Freess "x" ctr_Tss
blanchet@49585
  1137
          ||>> mk_Freess "y" (map (map B_ify) ctr_Tss)
blanchet@49498
  1138
          ||>> yield_singleton Variable.variant_fixes fp_b_name;
blanchet@49370
  1139
blanchet@49498
  1140
        val u = Free (u', fpT);
blanchet@49121
  1141
blanchet@49129
  1142
        val ctr_rhss =
traytel@55803
  1143
          map2 (fn k => fn xs => fold_rev Term.lambda xs (ctor $ mk_absumprod ctr_absT abs n k xs))
traytel@55803
  1144
            ks xss;
blanchet@49121
  1145
traytel@53569
  1146
        val maybe_conceal_def_binding = Thm.def_binding
traytel@53569
  1147
          #> Config.get no_defs_lthy bnf_note_all = false ? Binding.conceal;
traytel@53569
  1148
blanchet@52968
  1149
        val ((raw_ctrs, raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
blanchet@49169
  1150
          |> apfst split_list o fold_map3 (fn b => fn mx => fn rhs =>
traytel@53569
  1151
              Local_Theory.define ((b, mx), ((maybe_conceal_def_binding b, []), rhs)) #>> apsnd snd)
blanchet@52968
  1152
            ctr_bindings ctr_mixfixes ctr_rhss
blanchet@49121
  1153
          ||> `Local_Theory.restore;
blanchet@49121
  1154
blanchet@49121
  1155
        val phi = Proof_Context.export_morphism lthy lthy';
blanchet@49121
  1156
blanchet@49121
  1157
        val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
blanchet@49585
  1158
        val ctr_defs' =
blanchet@49585
  1159
          map2 (fn m => fn def => mk_unabs_def m (def RS meta_eq_to_obj_eq)) ms ctr_defs;
blanchet@49130
  1160
blanchet@49203
  1161
        val ctrs0 = map (Morphism.term phi) raw_ctrs;
blanchet@49203
  1162
        val ctrs = map (mk_ctr As) ctrs0;
blanchet@49121
  1163
blanchet@51897
  1164
        fun wrap_ctrs lthy =
blanchet@49123
  1165
          let
traytel@50170
  1166
            fun exhaust_tac {context = ctxt, prems = _} =
blanchet@49135
  1167
              let
blanchet@49585
  1168
                val ctor_iff_dtor_thm =
blanchet@49585
  1169
                  let
blanchet@49585
  1170
                    val goal =
blanchet@49585
  1171
                      fold_rev Logic.all [w, u]
blanchet@49585
  1172
                        (mk_Trueprop_eq (HOLogic.mk_eq (u, ctor $ w), HOLogic.mk_eq (dtor $ u, w)));
blanchet@49585
  1173
                  in
wenzelm@51551
  1174
                    Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
traytel@55803
  1175
                      mk_ctor_iff_dtor_tac ctxt (map (SOME o certifyT lthy) [ctr_absT, fpT])
blanchet@49585
  1176
                        (certify lthy ctor) (certify lthy dtor) ctor_dtor dtor_ctor)
blanchet@55409
  1177
                    |> Morphism.thm phi
blanchet@49585
  1178
                    |> Thm.close_derivation
blanchet@49585
  1179
                  end;
blanchet@49585
  1180
blanchet@49585
  1181
                val sumEN_thm' =
traytel@55803
  1182
                  unfold_thms lthy @{thms unit_all_eq1} (mk_absumprodE type_definition ms)
blanchet@49585
  1183
                  |> Morphism.thm phi;
blanchet@49135
  1184
              in
blanchet@49585
  1185
                mk_exhaust_tac ctxt n ctr_defs ctor_iff_dtor_thm sumEN_thm'
blanchet@49135
  1186
              end;
blanchet@49135
  1187
blanchet@49585
  1188
            val inject_tacss =
traytel@55803
  1189
              map2 (fn ctr_def => fn 0 => [] | _ => [fn {context = ctxt, ...} =>
traytel@55803
  1190
                mk_inject_tac ctxt ctr_def ctor_inject abs_inject]) ctr_defs ms;
blanchet@49585
  1191
blanchet@49585
  1192
            val half_distinct_tacss =
blanchet@49585
  1193
              map (map (fn (def, def') => fn {context = ctxt, ...} =>
traytel@55803
  1194
                  mk_half_distinct_tac ctxt ctor_inject abs_inject [def, def']))
traytel@55803
  1195
                (mk_half_pairss (`I ctr_defs));
blanchet@49585
  1196
blanchet@52968
  1197
            val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss;
blanchet@49585
  1198
blanchet@49585
  1199
            val sel_defaultss = map (map (apsnd (prepare_term lthy))) raw_sel_defaultss
blanchet@55469
  1200
blanchet@55469
  1201
            fun ctr_spec_of disc_b ctr0 sel_bs sel_defs = (((disc_b, ctr0), sel_bs), sel_defs);
blanchet@55469
  1202
            val ctr_specs = map4 ctr_spec_of disc_bindings ctrs0 sel_bindingss sel_defaultss;
blanchet@49123
  1203
          in
blanchet@55469
  1204
            free_constructors tacss ((wrap_opts, standard_binding), ctr_specs) lthy
blanchet@49123
  1205
          end;
blanchet@49121
  1206
blanchet@55397
  1207
        fun derive_maps_sets_rels (ctr_sugar as {case_cong, ...} : ctr_sugar, lthy) =
blanchet@51835
  1208
          if live = 0 then
blanchet@51840
  1209
            ((([], [], [], []), ctr_sugar), lthy)
blanchet@51835
  1210
          else
blanchet@51835
  1211
            let
blanchet@51835
  1212
              val rel_flip = rel_flip_of_bnf fp_bnf;
blanchet@51835
  1213
              val nones = replicate live NONE;
blanchet@49585
  1214
blanchet@51835
  1215
              val ctor_cong =
blanchet@52207
  1216
                if fp = Least_FP then
blanchet@51835
  1217
                  Drule.dummy_thm
blanchet@51835
  1218
                else
blanchet@51835
  1219
                  let val ctor' = mk_ctor Bs ctor in
blanchet@51835
  1220
                    cterm_instantiate_pos [NONE, NONE, SOME (certify lthy ctor')] arg_cong
blanchet@51835
  1221
                  end;
blanchet@49585
  1222
traytel@55803
  1223
              fun mk_cIn ctor k xs =
traytel@55803
  1224
                let val absT = domain_type (fastype_of ctor) in
traytel@55803
  1225
                  mk_absumprod absT abs n k xs
traytel@55803
  1226
                  |> fp = Greatest_FP ? curry (op $) ctor
traytel@55803
  1227
                  |> certify lthy
traytel@55803
  1228
                end;
blanchet@49585
  1229
traytel@55803
  1230
              val cxIns = map2 (mk_cIn ctor) ks xss;
traytel@55803
  1231
              val cyIns = map2 (mk_cIn (map_types B_ify ctor)) ks yss;
blanchet@49585
  1232
blanchet@51835
  1233
              fun mk_map_thm ctr_def' cxIn =
blanchet@51835
  1234
                fold_thms lthy [ctr_def']
traytel@55803
  1235
                  (unfold_thms lthy (o_apply :: pre_map_def ::
traytel@55803
  1236
                       (if fp = Least_FP then [] else [ctor_dtor, dtor_ctor]) @ sum_prod_thms_map @
traytel@55803
  1237
                       abs_inverses)
blanchet@51835
  1238
                     (cterm_instantiate_pos (nones @ [SOME cxIn])
blanchet@52207
  1239
                        (if fp = Least_FP then fp_map_thm else fp_map_thm RS ctor_cong)))
blanchet@51835
  1240
                |> singleton (Proof_Context.export names_lthy no_defs_lthy);
blanchet@49585
  1241
blanchet@51835
  1242
              fun mk_set_thm fp_set_thm ctr_def' cxIn =
blanchet@51835
  1243
                fold_thms lthy [ctr_def']
blanchet@53290
  1244
                  (unfold_thms lthy (pre_set_defs @ nested_set_maps @ nesting_set_maps @
traytel@55803
  1245
                       (if fp = Least_FP then [] else [dtor_ctor]) @ sum_prod_thms_set @
traytel@55803
  1246
                       abs_inverses)
blanchet@51835
  1247
                     (cterm_instantiate_pos [SOME cxIn] fp_set_thm))
blanchet@51835
  1248
                |> singleton (Proof_Context.export names_lthy no_defs_lthy);
blanchet@49585
  1249
blanchet@51835
  1250
              fun mk_set_thms fp_set_thm = map2 (mk_set_thm fp_set_thm) ctr_defs' cxIns;
blanchet@49127
  1251
blanchet@51835
  1252
              val map_thms = map2 mk_map_thm ctr_defs' cxIns;
blanchet@51835
  1253
              val set_thmss = map mk_set_thms fp_set_thms;
blanchet@55463
  1254
              val set_thms = flat set_thmss;
blanchet@51835
  1255
blanchet@51835
  1256
              val rel_infos = (ctr_defs' ~~ cxIns, ctr_defs' ~~ cyIns);
blanchet@49585
  1257
blanchet@51835
  1258
              fun mk_rel_thm postproc ctr_defs' cxIn cyIn =
blanchet@51835
  1259
                fold_thms lthy ctr_defs'
traytel@55803
  1260
                  (unfold_thms lthy (pre_rel_def :: abs_inverse ::
traytel@55803
  1261
                       (if fp = Least_FP then [] else [dtor_ctor]) @ sum_prod_thms_rel @
traytel@55803
  1262
                       @{thms vimage2p_def Inl_Inr_False})
blanchet@53266
  1263
                     (cterm_instantiate_pos (nones @ [SOME cxIn, SOME cyIn]) fp_rel_thm))
blanchet@51835
  1264
                |> postproc
blanchet@51835
  1265
                |> singleton (Proof_Context.export names_lthy no_defs_lthy);
blanchet@49585
  1266
blanchet@51835
  1267
              fun mk_rel_inject_thm ((ctr_def', cxIn), (_, cyIn)) =
blanchet@51835
  1268
                mk_rel_thm (unfold_thms lthy @{thms eq_sym_Unity_conv}) [ctr_def'] cxIn cyIn;
blanchet@49585
  1269
blanchet@51835
  1270
              val rel_inject_thms = map mk_rel_inject_thm (op ~~ rel_infos);
blanchet@49585
  1271
blanchet@51835
  1272
              fun mk_half_rel_distinct_thm ((xctr_def', cxIn), (yctr_def', cyIn)) =
blanchet@51835
  1273
                mk_rel_thm (fn thm => thm RS @{thm eq_False[THEN iffD1]}) [xctr_def', yctr_def']
blanchet@51835
  1274
                  cxIn cyIn;
blanchet@49121
  1275
blanchet@51835
  1276
              fun mk_other_half_rel_distinct_thm thm =
blanchet@51835
  1277
                flip_rels lthy live thm
blanchet@51835
  1278
                RS (rel_flip RS sym RS @{thm arg_cong[of _ _ Not]} RS iffD2);
blanchet@49585
  1279
blanchet@51835
  1280
              val half_rel_distinct_thmss =
blanchet@51835
  1281
                map (map mk_half_rel_distinct_thm) (mk_half_pairss rel_infos);
blanchet@51835
  1282
              val other_half_rel_distinct_thmss =
blanchet@51835
  1283
                map (map mk_other_half_rel_distinct_thm) half_rel_distinct_thmss;
blanchet@51835
  1284
              val (rel_distinct_thms, _) =
blanchet@51835
  1285
                join_halves n half_rel_distinct_thmss other_half_rel_distinct_thmss;
blanchet@49134
  1286
blanchet@55463
  1287
              val rel_eq_thms =
blanchet@55463
  1288
                map (fn th => th RS @{thm eq_False[THEN iffD2]}) rel_distinct_thms @
blanchet@55463
  1289
                map2 (fn th => fn 0 => th RS @{thm eq_True[THEN iffD2]} | _ => th)
blanchet@55463
  1290
                  rel_inject_thms ms;
blanchet@55463
  1291
blanchet@54145
  1292
              val anonymous_notes =
blanchet@55397
  1293
                [([case_cong], fundefcong_attrs),
blanchet@55463
  1294
                 (rel_eq_thms, code_nitpicksimp_attrs)]
blanchet@54145
  1295
                |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
blanchet@54145
  1296
blanchet@51835
  1297
              val notes =
blanchet@54145
  1298
                [(mapN, map_thms, code_nitpicksimp_attrs @ simp_attrs),
blanchet@54145
  1299
                 (rel_distinctN, rel_distinct_thms, simp_attrs),
blanchet@54145
  1300
                 (rel_injectN, rel_inject_thms, simp_attrs),
blanchet@55463
  1301
                 (setN, set_thms, code_nitpicksimp_attrs @ simp_attrs)]
blanchet@51835
  1302
                |> massage_simple_notes fp_b_name;
blanchet@51835
  1303
            in
blanchet@51840
  1304
              (((map_thms, rel_inject_thms, rel_distinct_thms, set_thmss), ctr_sugar),
blanchet@55463
  1305
               lthy
blanchet@55535
  1306
               |> Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) map_thms)
blanchet@55535
  1307
               |> Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) rel_eq_thms)
blanchet@55535
  1308
               |> Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) set_thms)
blanchet@55463
  1309
               |> Local_Theory.notes (anonymous_notes @ notes)
blanchet@55463
  1310
               |> snd)
blanchet@51835
  1311
            end;
blanchet@49585
  1312
blanchet@55410
  1313
        fun mk_binding pre = Binding.qualify false fp_b_name (Binding.prefix_name (pre ^ "_") fp_b);
blanchet@49287
  1314
blanchet@51883
  1315
        fun massage_res (((maps_sets_rels, ctr_sugar), co_iter_res), lthy) =
blanchet@51883
  1316
          (((maps_sets_rels, (ctrs, xss, ctr_defs, ctr_sugar)), co_iter_res), lthy);
blanchet@49119
  1317
      in
blanchet@51897
  1318
        (wrap_ctrs
blanchet@51835
  1319
         #> derive_maps_sets_rels
blanchet@52313
  1320
         ##>>
blanchet@55862
  1321
           (if fp = Least_FP then define_iter iters_args_types mk_binding fpTs Cs reps
blanchet@55862
  1322
           else define_coiter (the coiters_args_types) mk_binding fpTs Cs abss)
blanchet@55862
  1323
             (co_rec_of xtor_co_iters)
blanchet@51835
  1324
         #> massage_res, lthy')
blanchet@49119
  1325
      end;
blanchet@49167
  1326
blanchet@51835
  1327
    fun wrap_types_etc (wrap_types_etcs, lthy) =
blanchet@51835
  1328
      fold_map I wrap_types_etcs lthy
blanchet@52342
  1329
      |>> apsnd split_list o apfst (apsnd split_list4 o apfst split_list4 o split_list)
blanchet@52342
  1330
        o split_list;
blanchet@49226
  1331
blanchet@55856
  1332
    fun mk_simp_thms ({injects, distincts, case_thms, ...} : ctr_sugar) co_recs mapsx rel_injects
blanchet@55856
  1333
        rel_distincts setss =
blanchet@55856
  1334
      injects @ distincts @ case_thms @ co_recs @ mapsx @ rel_injects @ rel_distincts @ flat setss;
blanchet@49479
  1335
blanchet@53807
  1336
    fun derive_note_induct_iters_thms_for_types
blanchet@53476
  1337
        ((((mapss, rel_injects, rel_distincts, setss), (ctrss, _, ctr_defss, ctr_sugars)),
blanchet@55864
  1338
          (recs, rec_defs)), lthy) =
blanchet@49202
  1339
      let
blanchet@55856
  1340
        val ((induct_thms, induct_thm, induct_attrs), (rec_thmss, iter_attrs)) =
blanchet@55862
  1341
          derive_induct_iters_thms_for_types pre_bnfs iters_args_types xtor_co_induct
traytel@55803
  1342
            xtor_co_iter_thmss nesting_bnfs nested_bnfs fpTs Cs Xs ctrXs_Tsss abs_inverses
blanchet@55864
  1343
            type_definitions abs_inverses ctrss ctr_defss recs rec_defs lthy;
blanchet@49201
  1344
blanchet@51830
  1345
        val induct_type_attr = Attrib.internal o K o Induct.induct_type;
blanchet@51810
  1346
blanchet@55864
  1347
        val (recs', rec_thmss') =
blanchet@55864
  1348
          if is_some iters_args_types then (recs, rec_thmss)
blanchet@55864
  1349
          else (map #casex ctr_sugars, map #case_thms ctr_sugars);
blanchet@55862
  1350
blanchet@51835
  1351
        val simp_thmss =
blanchet@55856
  1352
          map6 mk_simp_thms ctr_sugars rec_thmss mapss rel_injects rel_distincts setss;
blanchet@49438
  1353
blanchet@49337
  1354
        val common_notes =
blanchet@51808
  1355
          (if nn > 1 then [(inductN, [induct_thm], induct_attrs)] else [])
blanchet@51780
  1356
          |> massage_simple_notes fp_common_name;
blanchet@49337
  1357
blanchet@49226
  1358
        val notes =
blanchet@55856
  1359
          [(inductN, map single induct_thms, fn T_name => induct_attrs @ [induct_type_attr T_name]),
blanchet@53808
  1360
           (recN, rec_thmss, K iter_attrs),
blanchet@49585
  1361
           (simpsN, simp_thmss, K [])]
blanchet@51780
  1362
          |> massage_multi_notes;
blanchet@49202
  1363
      in
blanchet@51824
  1364
        lthy
blanchet@55862
  1365
        |> (if is_some iters_args_types then
blanchet@55864
  1366
              Spec_Rules.add Spec_Rules.Equational (recs, flat rec_thmss)
blanchet@55862
  1367
            else
blanchet@55862
  1368
              I)
blanchet@51824
  1369
        |> Local_Theory.notes (common_notes @ notes) |> snd
traytel@55803
  1370
        |> register_fp_sugars Xs Least_FP pre_bnfs absT_infos nested_bnfs nesting_bnfs fp_res
blanchet@55864
  1371
          ctrXs_Tsss ctr_defss ctr_sugars recs' mapss [induct_thm] (map single induct_thms)
blanchet@55863
  1372
          rec_thmss' (replicate nn []) (replicate nn [])
blanchet@49202
  1373
      end;
blanchet@49202
  1374
blanchet@53807
  1375
    fun derive_note_coinduct_coiters_thms_for_types
blanchet@53476
  1376
        ((((mapss, rel_injects, rel_distincts, setss), (_, _, ctr_defss, ctr_sugars)),
blanchet@55864
  1377
          (coiters, corec_defs)), lthy) =
blanchet@49212
  1378
      let
blanchet@52345
  1379
        val (([(coinduct_thms, coinduct_thm), (strong_coinduct_thms, strong_coinduct_thm)],
blanchet@51810
  1380
              coinduct_attrs),
blanchet@55856
  1381
             (corec_thmss, coiter_attrs),
blanchet@55856
  1382
             (disc_corec_thmss, disc_coiter_attrs),
blanchet@55856
  1383
             (disc_corec_iff_thmss, disc_coiter_iff_attrs),
blanchet@55856
  1384
             (sel_corec_thmsss, sel_coiter_attrs)) =
traytel@53106
  1385
          derive_coinduct_coiters_thms_for_types pre_bnfs (the coiters_args_types) xtor_co_induct
blanchet@54235
  1386
            dtor_injects dtor_ctors xtor_co_iter_thmss nesting_bnfs fpTs Cs Xs ctrXs_Tsss kss mss ns
blanchet@55864
  1387
            abs_inverses abs_inverses I ctr_defss ctr_sugars coiters corec_defs
traytel@55803
  1388
            (Proof_Context.export lthy' no_defs_lthy) lthy;
blanchet@49212
  1389
blanchet@53475
  1390
        val sel_corec_thmss = map flat sel_corec_thmsss;
blanchet@53475
  1391
blanchet@51830
  1392
        val coinduct_type_attr = Attrib.internal o K o Induct.coinduct_type;
blanchet@49479
  1393
blanchet@54030
  1394
        val flat_coiter_thms = append oo append;
blanchet@49479
  1395
blanchet@49479
  1396
        val simp_thmss =
blanchet@55856
  1397
          map6 mk_simp_thms ctr_sugars
blanchet@54030
  1398
            (map3 flat_coiter_thms disc_corec_thmss disc_corec_iff_thmss sel_corec_thmss)
blanchet@53476
  1399
            mapss rel_injects rel_distincts setss;
blanchet@49479
  1400
blanchet@49342
  1401
        val common_notes =
blanchet@49591
  1402
          (if nn > 1 then
blanchet@51810
  1403
             [(coinductN, [coinduct_thm], coinduct_attrs),
blanchet@51810
  1404
              (strong_coinductN, [strong_coinduct_thm], coinduct_attrs)]
blanchet@49591
  1405
           else
blanchet@49591
  1406
             [])
blanchet@51780
  1407
          |> massage_simple_notes fp_common_name;
blanchet@49342
  1408
blanchet@49212
  1409
        val notes =
blanchet@51780
  1410
          [(coinductN, map single coinduct_thms,
blanchet@51810
  1411
            fn T_name => coinduct_attrs @ [coinduct_type_attr T_name]),
blanchet@51843
  1412
           (corecN, corec_thmss, K coiter_attrs),
blanchet@51843
  1413
           (disc_corecN, disc_corec_thmss, K disc_coiter_attrs),
blanchet@51843
  1414
           (disc_corec_iffN, disc_corec_iff_thmss, K disc_coiter_iff_attrs),
blanchet@51843
  1415
           (sel_corecN, sel_corec_thmss, K sel_coiter_attrs),
blanchet@51780
  1416
           (simpsN, simp_thmss, K []),
blanchet@55856
  1417
           (strong_coinductN, map single strong_coinduct_thms, K coinduct_attrs)]
blanchet@51780
  1418
          |> massage_multi_notes;
blanchet@49212
  1419
      in
blanchet@51824
  1420
        lthy
blanchet@55864
  1421
        (* TODO: code theorems *)
blanchet@55864
  1422
        |> fold (curry (Spec_Rules.add Spec_Rules.Equational) coiters)
blanchet@55864
  1423
          [flat sel_corec_thmss, flat corec_thmss]
blanchet@54030
  1424
        |> Local_Theory.notes (common_notes @ notes) |> snd
traytel@55803
  1425
        |> register_fp_sugars Xs Greatest_FP pre_bnfs absT_infos nested_bnfs nesting_bnfs fp_res
blanchet@55864
  1426
          ctrXs_Tsss ctr_defss ctr_sugars coiters mapss [coinduct_thm, strong_coinduct_thm]
blanchet@55864
  1427
          (transpose [coinduct_thms, strong_coinduct_thms]) corec_thmss disc_corec_thmss
blanchet@55864
  1428
          sel_corec_thmsss
blanchet@49212
  1429
      end;
blanchet@49212
  1430
blanchet@52367
  1431
    val lthy'' = lthy'
blanchet@52968
  1432
      |> fold_map define_ctrs_dtrs_for_type (fp_bnfs ~~ fp_bs ~~ fpTs ~~ ctors ~~ dtors ~~
blanchet@52330
  1433
        xtor_co_iterss ~~ ctor_dtors ~~ dtor_ctors ~~ ctor_injects ~~ pre_map_defs ~~
blanchet@52314
  1434
        pre_set_defss ~~ pre_rel_defs ~~ xtor_map_thms ~~ xtor_set_thmss ~~ xtor_rel_thms ~~ ns ~~
traytel@55803
  1435
        kss ~~ mss ~~ abss ~~ abs_injects ~~ abs_inverses ~~ type_definitions ~~
traytel@55803
  1436
        ctr_bindingss ~~ ctr_mixfixess ~~ ctr_Tsss ~~ disc_bindingss ~~ sel_bindingsss ~~
traytel@55803
  1437
        raw_sel_defaultsss)
blanchet@51835
  1438
      |> wrap_types_etc
blanchet@53807
  1439
      |> fp_case fp derive_note_induct_iters_thms_for_types
blanchet@53807
  1440
           derive_note_coinduct_coiters_thms_for_types;
blanchet@49167
  1441
blanchet@49167
  1442
    val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
blanchet@52899
  1443
      co_prefix fp ^ "datatype"));
blanchet@49112
  1444
  in
blanchet@52367
  1445
    timer; lthy''
blanchet@49112
  1446
  end;
blanchet@49112
  1447
wenzelm@53974
  1448
fun co_datatypes x = define_co_datatypes (K I) (K I) (K I) x;
blanchet@49297
  1449
wenzelm@53974
  1450
fun co_datatype_cmd x =
wenzelm@53974
  1451
  define_co_datatypes Typedecl.read_constraint Syntax.parse_typ Syntax.parse_term x;
blanchet@49119
  1452
blanchet@55469
  1453
val parse_ctr_arg =
blanchet@55469
  1454
  @{keyword "("} |-- parse_binding_colon -- Parse.typ --| @{keyword ")"} ||
blanchet@55469
  1455
  (Parse.typ >> pair Binding.empty);
blanchet@55469
  1456
blanchet@55469
  1457
val parse_ctr_specs =
blanchet@55469
  1458
  Parse.enum1 "|" (parse_ctr_spec parse_binding parse_ctr_arg -- Parse.opt_mixfix);
blanchet@51767
  1459
blanchet@51767
  1460
val parse_spec =
blanchet@51790
  1461
  parse_type_args_named_constrained -- parse_binding -- parse_map_rel_bindings --
blanchet@55469
  1462
  Parse.opt_mixfix -- (@{keyword "="} |-- parse_ctr_specs);
blanchet@51767
  1463
blanchet@55469
  1464
val parse_co_datatype = parse_ctr_options -- Parse.and_list1 parse_spec;
blanchet@49278
  1465
blanchet@52207
  1466
fun parse_co_datatype_cmd fp construct_fp = parse_co_datatype >> co_datatype_cmd fp construct_fp;
blanchet@49112
  1467
blanchet@49112
  1468
end;