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