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