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