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