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