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