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