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