src/HOL/Codatatype/Tools/bnf_fp_sugar.ML
author blanchet
Sat, 08 Sep 2012 21:04:26 +0200
changeset 50225 656fb50d33f0
parent 50224 3c0deda51b32
child 50226 239a4fa29ddf
permissions -rw-r--r--
define coiterators
blanchet@50127
     1
(*  Title:      HOL/Codatatype/Tools/bnf_fp_sugar.ML
blanchet@50127
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@50127
     3
    Copyright   2012
blanchet@50127
     4
blanchet@50127
     5
Sugar for constructing LFPs and GFPs.
blanchet@50127
     6
*)
blanchet@50127
     7
blanchet@50127
     8
signature BNF_FP_SUGAR =
blanchet@50127
     9
sig
blanchet@50220
    10
  (* TODO: programmatic interface *)
blanchet@50127
    11
end;
blanchet@50127
    12
blanchet@50127
    13
structure BNF_FP_Sugar : BNF_FP_SUGAR =
blanchet@50127
    14
struct
blanchet@50127
    15
blanchet@50134
    16
open BNF_Util
blanchet@50134
    17
open BNF_Wrap
blanchet@50134
    18
open BNF_FP_Util
blanchet@50134
    19
open BNF_LFP
blanchet@50134
    20
open BNF_GFP
blanchet@50138
    21
open BNF_FP_Sugar_Tactics
blanchet@50134
    22
blanchet@50144
    23
val caseN = "case";
blanchet@50217
    24
val itersN = "iters";
blanchet@50217
    25
val recsN = "recs";
blanchet@50144
    26
blanchet@50220
    27
fun split_list7 xs = (map #1 xs, map #2 xs, map #3 xs, map #4 xs, map #5 xs, map #6 xs, map #7 xs);
blanchet@50220
    28
blanchet@50214
    29
fun retype_free (Free (s, _)) T = Free (s, T);
blanchet@50214
    30
blanchet@50217
    31
fun flat_list_comb (f, xss) = fold (fn xs => fn t => Term.list_comb (t, xs)) xss f
blanchet@50217
    32
blanchet@50215
    33
fun mk_tupled_fun x f xs = HOLogic.tupled_lambda x (Term.list_comb (f, xs));
blanchet@50215
    34
fun mk_uncurried_fun f xs = mk_tupled_fun (HOLogic.mk_tuple xs) f xs;
blanchet@50217
    35
fun mk_uncurried2_fun f xss =
blanchet@50215
    36
  mk_tupled_fun (HOLogic.mk_tuple (map HOLogic.mk_tuple xss)) f (flat xss);
blanchet@50215
    37
blanchet@50139
    38
fun cannot_merge_types () = error "Mutually recursive types must have the same type parameters";
blanchet@50134
    39
blanchet@50134
    40
fun merge_type_arg_constrained ctxt (T, c) (T', c') =
blanchet@50134
    41
  if T = T' then
blanchet@50134
    42
    (case (c, c') of
blanchet@50134
    43
      (_, NONE) => (T, c)
blanchet@50134
    44
    | (NONE, _) => (T, c')
blanchet@50134
    45
    | _ =>
blanchet@50134
    46
      if c = c' then
blanchet@50134
    47
        (T, c)
blanchet@50134
    48
      else
blanchet@50134
    49
        error ("Inconsistent sort constraints for type variable " ^
blanchet@50134
    50
          quote (Syntax.string_of_typ ctxt T)))
blanchet@50134
    51
  else
blanchet@50134
    52
    cannot_merge_types ();
blanchet@50134
    53
blanchet@50134
    54
fun merge_type_args_constrained ctxt (cAs, cAs') =
blanchet@50134
    55
  if length cAs = length cAs' then map2 (merge_type_arg_constrained ctxt) cAs cAs'
blanchet@50134
    56
  else cannot_merge_types ();
blanchet@50134
    57
blanchet@50136
    58
fun type_args_constrained_of (((cAs, _), _), _) = cAs;
blanchet@50136
    59
val type_args_of = map fst o type_args_constrained_of;
blanchet@50144
    60
fun type_binder_of (((_, b), _), _) = b;
blanchet@50196
    61
fun mixfix_of ((_, mx), _) = mx;
blanchet@50136
    62
fun ctr_specs_of (_, ctr_specs) = ctr_specs;
blanchet@50134
    63
blanchet@50136
    64
fun disc_of (((disc, _), _), _) = disc;
blanchet@50136
    65
fun ctr_of (((_, ctr), _), _) = ctr;
blanchet@50136
    66
fun args_of ((_, args), _) = args;
blanchet@50196
    67
fun ctr_mixfix_of (_, mx) = mx;
blanchet@50134
    68
blanchet@50223
    69
fun prepare_datatype prepare_typ lfp specs fake_lthy no_defs_lthy =
blanchet@50127
    70
  let
blanchet@50136
    71
    val constrained_As =
blanchet@50136
    72
      map (map (apfst (prepare_typ fake_lthy)) o type_args_constrained_of) specs
blanchet@50219
    73
      |> Library.foldr1 (merge_type_args_constrained no_defs_lthy);
blanchet@50136
    74
    val As = map fst constrained_As;
blanchet@50149
    75
    val As' = map dest_TFree As;
blanchet@50134
    76
blanchet@50136
    77
    val _ = (case duplicates (op =) As of [] => ()
blanchet@50219
    78
      | A :: _ => error ("Duplicate type parameter " ^
blanchet@50219
    79
          quote (Syntax.string_of_typ no_defs_lthy A)));
blanchet@50134
    80
blanchet@50134
    81
    (* TODO: use sort constraints on type args *)
blanchet@50134
    82
blanchet@50134
    83
    val N = length specs;
blanchet@50134
    84
blanchet@50197
    85
    fun mk_fake_T b =
blanchet@50136
    86
      Type (fst (Term.dest_Type (Proof_Context.read_type_name fake_lthy true (Binding.name_of b))),
blanchet@50136
    87
        As);
blanchet@50136
    88
blanchet@50144
    89
    val bs = map type_binder_of specs;
blanchet@50219
    90
    val fakeTs = map mk_fake_T bs;
blanchet@50136
    91
blanchet@50196
    92
    val mixfixes = map mixfix_of specs;
blanchet@50134
    93
blanchet@50134
    94
    val _ = (case duplicates Binding.eq_name bs of [] => ()
blanchet@50134
    95
      | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
blanchet@50134
    96
blanchet@50136
    97
    val ctr_specss = map ctr_specs_of specs;
blanchet@50134
    98
blanchet@50144
    99
    val disc_binderss = map (map disc_of) ctr_specss;
blanchet@50144
   100
    val ctr_binderss = map (map ctr_of) ctr_specss;
blanchet@50136
   101
    val ctr_argsss = map (map args_of) ctr_specss;
blanchet@50196
   102
    val ctr_mixfixess = map (map ctr_mixfix_of) ctr_specss;
blanchet@50134
   103
blanchet@50144
   104
    val sel_bindersss = map (map (map fst)) ctr_argsss;
blanchet@50198
   105
    val fake_ctr_Tsss = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
blanchet@50134
   106
blanchet@50198
   107
    val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
blanchet@50182
   108
    val _ = (case subtract (op =) As' rhs_As' of
blanchet@50180
   109
        [] => ()
blanchet@50180
   110
      | A' :: _ => error ("Extra type variables on rhs: " ^
blanchet@50219
   111
          quote (Syntax.string_of_typ no_defs_lthy (TFree A'))));
blanchet@50180
   112
blanchet@50191
   113
    val ((Cs, Xs), _) =
blanchet@50219
   114
      no_defs_lthy
blanchet@50136
   115
      |> fold (fold (fn s => Variable.declare_typ (TFree (s, dummyS))) o type_args_of) specs
blanchet@50136
   116
      |> mk_TFrees N
blanchet@50191
   117
      ||>> mk_TFrees N;
blanchet@50134
   118
blanchet@50219
   119
    fun eq_fpT (T as Type (s, Us)) (Type (s', Us')) =
blanchet@50161
   120
        s = s' andalso (Us = Us' orelse error ("Illegal occurrence of recursive type " ^
blanchet@50161
   121
          quote (Syntax.string_of_typ fake_lthy T)))
blanchet@50219
   122
      | eq_fpT _ _ = false;
blanchet@50161
   123
blanchet@50219
   124
    fun freeze_fp (T as Type (s, Us)) =
blanchet@50219
   125
        (case find_index (eq_fpT T) fakeTs of ~1 => Type (s, map freeze_fp Us) | j => nth Xs j)
blanchet@50219
   126
      | freeze_fp T = T;
blanchet@50134
   127
blanchet@50219
   128
    val ctr_TsssXs = map (map (map freeze_fp)) fake_ctr_Tsss;
blanchet@50191
   129
    val sum_prod_TsXs = map (mk_sumTN o map HOLogic.mk_tupleT) ctr_TsssXs;
blanchet@50134
   130
blanchet@50191
   131
    val eqs = map dest_TFree Xs ~~ sum_prod_TsXs;
blanchet@50136
   132
blanchet@50222
   133
    val (pre_map_defs, ((unfs0, flds0, fp_iters0, fp_recs0, unf_flds, fld_unfs, fld_injects,
blanchet@50222
   134
        fp_iter_thms, fp_rec_thms), lthy)) =
blanchet@50223
   135
      fp_bnf (if lfp then bnf_lfp else bnf_gfp) bs mixfixes As' eqs no_defs_lthy;
blanchet@50136
   136
blanchet@50182
   137
    val timer = time (Timer.startRealTimer ());
blanchet@50182
   138
blanchet@50191
   139
    fun mk_unf_or_fld get_T Ts t =
blanchet@50191
   140
      let val Type (_, Ts0) = get_T (fastype_of t) in
blanchet@50139
   141
        Term.subst_atomic_types (Ts0 ~~ Ts) t
blanchet@50136
   142
      end;
blanchet@50136
   143
blanchet@50141
   144
    val mk_unf = mk_unf_or_fld domain_type;
blanchet@50141
   145
    val mk_fld = mk_unf_or_fld range_type;
blanchet@50139
   146
blanchet@50218
   147
    val unfs = map (mk_unf As) unfs0;
blanchet@50218
   148
    val flds = map (mk_fld As) flds0;
blanchet@50136
   149
blanchet@50216
   150
    val fpTs = map (domain_type o fastype_of) unfs;
blanchet@50219
   151
    val is_fpT = member (op =) fpTs;
blanchet@50219
   152
blanchet@50216
   153
    val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Xs ~~ fpTs)))) ctr_TsssXs;
blanchet@50218
   154
    val ns = map length ctr_Tsss;
blanchet@50218
   155
    val mss = map (map length) ctr_Tsss;
blanchet@50218
   156
    val Css = map2 replicate ns Cs;
blanchet@50218
   157
blanchet@50225
   158
    fun mk_iter_like Ts Us c =
blanchet@50134
   159
      let
blanchet@50216
   160
        val (binders, body) = strip_type (fastype_of c);
blanchet@50225
   161
        val (f_Us, prebody) = split_last binders;
blanchet@50225
   162
        val Type (_, Ts0) = if lfp then prebody else body;
blanchet@50225
   163
        val Us0 = distinct (op =) (map (if lfp then body_type else domain_type) f_Us);
blanchet@50191
   164
      in
blanchet@50216
   165
        Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) c
blanchet@50191
   166
      end;
blanchet@50191
   167
blanchet@50225
   168
    val fp_iters as fp_iter1 :: _ = map (mk_iter_like As Cs) fp_iters0;
blanchet@50225
   169
    val fp_recs as fp_rec1 :: _ = map (mk_iter_like As Cs) fp_recs0;
blanchet@50225
   170
blanchet@50225
   171
    val fp_iter_f_Ts = fst (split_last (binder_types (fastype_of fp_iter1)));
blanchet@50225
   172
    val fp_rec_f_Ts = fst (split_last (binder_types (fastype_of fp_rec1)));
blanchet@50219
   173
blanchet@50219
   174
    fun dest_rec_pair (T as Type (@{type_name prod}, Us as [_, U])) =
blanchet@50219
   175
        if member (op =) Cs U then Us else [T]
blanchet@50219
   176
      | dest_rec_pair T = [T];
blanchet@50219
   177
blanchet@50225
   178
    val (((gss, g_Tss, ysss, y_Tsss), (hss, h_Tss, zssss, z_Tssss)),
blanchet@50225
   179
         (cs, (qss, q_Tss, gsss, g_Tsss), ())) =
blanchet@50223
   180
      if lfp then
blanchet@50223
   181
        let
blanchet@50223
   182
          val y_Tsss =
blanchet@50225
   183
            map3 (fn n => fn ms => map2 dest_tupleT ms o dest_sumTN n o domain_type)
blanchet@50225
   184
              ns mss fp_iter_f_Ts;
blanchet@50223
   185
          val g_Tss = map2 (map2 (curry (op --->))) y_Tsss Css;
blanchet@50219
   186
blanchet@50223
   187
          val ((gss, ysss), _) =
blanchet@50223
   188
            lthy
blanchet@50223
   189
            |> mk_Freess "f" g_Tss
blanchet@50223
   190
            ||>> mk_Freesss "x" y_Tsss;
blanchet@50219
   191
blanchet@50223
   192
          val z_Tssss =
blanchet@50225
   193
            map3 (fn n => fn ms => map2 (map dest_rec_pair oo dest_tupleT) ms o dest_sumTN n
blanchet@50225
   194
              o domain_type) ns mss fp_rec_f_Ts;
blanchet@50223
   195
          val h_Tss = map2 (map2 (fold_rev (curry (op --->)))) z_Tssss Css;
blanchet@50223
   196
blanchet@50223
   197
          val hss = map2 (map2 retype_free) gss h_Tss;
blanchet@50223
   198
          val (zssss, _) =
blanchet@50223
   199
            lthy
blanchet@50223
   200
            |> mk_Freessss "x" z_Tssss;
blanchet@50225
   201
        in
blanchet@50225
   202
          (((gss, g_Tss, ysss, y_Tsss), (hss, h_Tss, zssss, z_Tssss)),
blanchet@50225
   203
           ([], ([], [], [], []), ()))
blanchet@50225
   204
        end
blanchet@50223
   205
      else
blanchet@50225
   206
        let
blanchet@50225
   207
          val q_Tss =
blanchet@50225
   208
            map2 (fn C => fn n => replicate (Int.max (0, n - 1)) (C --> HOLogic.boolT)) Cs ns;
blanchet@50225
   209
          val g_Tsss =
blanchet@50225
   210
            map4 (fn C => fn n => fn ms => map2 (map (curry (op -->) C) oo dest_tupleT) ms o
blanchet@50225
   211
              dest_sumTN n o range_type) Cs ns mss fp_iter_f_Ts;
blanchet@50191
   212
blanchet@50225
   213
          val (((c, qss), gsss), _) =
blanchet@50225
   214
            lthy
blanchet@50225
   215
            |> yield_singleton (mk_Frees "c") dummyT
blanchet@50225
   216
            ||>> mk_Freess "p" q_Tss
blanchet@50225
   217
            ||>> mk_Freesss "g" g_Tsss;
blanchet@50225
   218
blanchet@50225
   219
          val cs = map (retype_free c) Cs;
blanchet@50225
   220
        in
blanchet@50225
   221
          ((([], [], [], []), ([], [], [], [])),
blanchet@50225
   222
           (cs, (qss, q_Tss, gsss, g_Tsss), ()))
blanchet@50225
   223
        end;
blanchet@50225
   224
blanchet@50225
   225
    fun pour_some_sugar_on_type ((((((((((((((b, fpT), C), fld), unf), fp_iter), fp_rec), fld_unf),
blanchet@50225
   226
          unf_fld), fld_inject), ctr_binders), ctr_mixfixes), ctr_Tss), disc_binders),
blanchet@50225
   227
          sel_binderss) no_defs_lthy =
blanchet@50191
   228
      let
blanchet@50191
   229
        val n = length ctr_Tss;
blanchet@50136
   230
        val ks = 1 upto n;
blanchet@50136
   231
        val ms = map length ctr_Tss;
blanchet@50136
   232
blanchet@50216
   233
        val unfT = domain_type (fastype_of fld);
blanchet@50225
   234
        val ctr_prod_Ts = map HOLogic.mk_tupleT ctr_Tss;
blanchet@50149
   235
        val case_Ts = map (fn Ts => Ts ---> C) ctr_Tss;
blanchet@50139
   236
blanchet@50191
   237
        val ((((u, v), fs), xss), _) =
blanchet@50219
   238
          no_defs_lthy
blanchet@50216
   239
          |> yield_singleton (mk_Frees "u") unfT
blanchet@50216
   240
          ||>> yield_singleton (mk_Frees "v") fpT
blanchet@50191
   241
          ||>> mk_Frees "f" case_Ts
blanchet@50139
   242
          ||>> mk_Freess "x" ctr_Tss;
blanchet@50136
   243
blanchet@50144
   244
        val ctr_rhss =
blanchet@50136
   245
          map2 (fn k => fn xs =>
blanchet@50225
   246
            fold_rev Term.lambda xs (fld $ mk_InN ctr_prod_Ts (HOLogic.mk_tuple xs) k)) ks xss;
blanchet@50136
   247
blanchet@50145
   248
        val case_binder = Binding.suffix_name ("_" ^ caseN) b;
blanchet@50144
   249
blanchet@50149
   250
        val case_rhs =
blanchet@50191
   251
          fold_rev Term.lambda (fs @ [v]) (mk_sum_caseN (map2 mk_uncurried_fun fs xss) $ (unf $ v));
blanchet@50144
   252
blanchet@50216
   253
        val ((raw_case :: raw_ctrs, raw_case_def :: raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
blanchet@50184
   254
          |> apfst split_list o fold_map3 (fn b => fn mx => fn rhs =>
blanchet@50184
   255
               Local_Theory.define ((b, mx), ((Thm.def_binding b, []), rhs)) #>> apsnd snd)
blanchet@50216
   256
             (case_binder :: ctr_binders) (NoSyn :: ctr_mixfixes) (case_rhs :: ctr_rhss)
blanchet@50136
   257
          ||> `Local_Theory.restore;
blanchet@50136
   258
blanchet@50136
   259
        (*transforms defined frees into consts (and more)*)
blanchet@50136
   260
        val phi = Proof_Context.export_morphism lthy lthy';
blanchet@50136
   261
blanchet@50136
   262
        val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
blanchet@50145
   263
        val case_def = Morphism.thm phi raw_case_def;
blanchet@50145
   264
blanchet@50218
   265
        val ctrs0 = map (Morphism.term phi) raw_ctrs;
blanchet@50218
   266
        val casex0 = Morphism.term phi raw_case;
blanchet@50218
   267
blanchet@50218
   268
        val ctrs = map (mk_ctr As) ctrs0;
blanchet@50136
   269
blanchet@50150
   270
        fun exhaust_tac {context = ctxt, ...} =
blanchet@50138
   271
          let
blanchet@50150
   272
            val fld_iff_unf_thm =
blanchet@50150
   273
              let
blanchet@50150
   274
                val goal =
blanchet@50150
   275
                  fold_rev Logic.all [u, v]
blanchet@50150
   276
                    (mk_Trueprop_eq (HOLogic.mk_eq (v, fld $ u), HOLogic.mk_eq (unf $ v, u)));
blanchet@50150
   277
              in
blanchet@50150
   278
                Skip_Proof.prove lthy [] [] goal (fn {context = ctxt, ...} =>
blanchet@50216
   279
                  mk_fld_iff_unf_tac ctxt (map (SOME o certifyT lthy) [unfT, fpT])
blanchet@50191
   280
                    (certify lthy fld) (certify lthy unf) fld_unf unf_fld)
blanchet@50150
   281
                |> Thm.close_derivation
blanchet@50150
   282
                |> Morphism.thm phi
blanchet@50150
   283
              end;
blanchet@50150
   284
blanchet@50150
   285
            val sumEN_thm' =
blanchet@50150
   286
              Local_Defs.unfold lthy @{thms all_unit_eq}
blanchet@50225
   287
                (Drule.instantiate' (map (SOME o certifyT lthy) ctr_prod_Ts) [] (mk_sumEN n))
blanchet@50150
   288
              |> Morphism.thm phi;
blanchet@50138
   289
          in
blanchet@50176
   290
            mk_exhaust_tac ctxt n ctr_defs fld_iff_unf_thm sumEN_thm'
blanchet@50138
   291
          end;
blanchet@50136
   292
blanchet@50141
   293
        val inject_tacss =
blanchet@50220
   294
          map2 (fn 0 => K [] | _ => fn ctr_def => [fn {context = ctxt, ...} =>
blanchet@50220
   295
              mk_inject_tac ctxt ctr_def fld_inject]) ms ctr_defs;
blanchet@50141
   296
blanchet@50142
   297
        val half_distinct_tacss =
blanchet@50142
   298
          map (map (fn (def, def') => fn {context = ctxt, ...} =>
blanchet@50142
   299
            mk_half_distinct_tac ctxt fld_inject [def, def'])) (mk_half_pairss ctr_defs);
blanchet@50142
   300
blanchet@50145
   301
        val case_tacs =
blanchet@50145
   302
          map3 (fn k => fn m => fn ctr_def => fn {context = ctxt, ...} =>
blanchet@50145
   303
            mk_case_tac ctxt n k m case_def ctr_def unf_fld) ks ms ctr_defs;
blanchet@50136
   304
blanchet@50136
   305
        val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss @ [case_tacs];
blanchet@50149
   306
blanchet@50225
   307
        fun some_lfp_sugar no_defs_lthy =
blanchet@50149
   308
          let
blanchet@50223
   309
            val fpT_to_C = fpT --> C;
blanchet@50223
   310
            val iter_T = fold_rev (curry (op --->)) g_Tss fpT_to_C;
blanchet@50223
   311
            val rec_T = fold_rev (curry (op --->)) h_Tss fpT_to_C;
blanchet@50214
   312
blanchet@50214
   313
            val iter_binder = Binding.suffix_name ("_" ^ iterN) b;
blanchet@50214
   314
            val rec_binder = Binding.suffix_name ("_" ^ recN) b;
blanchet@50214
   315
blanchet@50214
   316
            val iter_free = Free (Binding.name_of iter_binder, iter_T);
blanchet@50214
   317
            val rec_free = Free (Binding.name_of rec_binder, rec_T);
blanchet@50214
   318
blanchet@50214
   319
            val iter_spec =
blanchet@50217
   320
              mk_Trueprop_eq (flat_list_comb (iter_free, gss),
blanchet@50214
   321
                Term.list_comb (fp_iter, map2 (mk_sum_caseN oo map2 mk_uncurried_fun) gss ysss));
blanchet@50214
   322
            val rec_spec =
blanchet@50217
   323
              mk_Trueprop_eq (flat_list_comb (rec_free, hss),
blanchet@50217
   324
                Term.list_comb (fp_rec, map2 (mk_sum_caseN oo map2 mk_uncurried2_fun) hss zssss));
blanchet@50214
   325
blanchet@50214
   326
            val (([raw_iter, raw_rec], [raw_iter_def, raw_rec_def]), (lthy', lthy)) = no_defs_lthy
blanchet@50216
   327
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@50214
   328
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@50216
   329
                #>> apsnd snd) [iter_binder, rec_binder] [iter_spec, rec_spec]
blanchet@50214
   330
              ||> `Local_Theory.restore;
blanchet@50216
   331
blanchet@50216
   332
            (*transforms defined frees into consts (and more)*)
blanchet@50216
   333
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@50216
   334
blanchet@50216
   335
            val iter_def = Morphism.thm phi raw_iter_def;
blanchet@50216
   336
            val rec_def = Morphism.thm phi raw_rec_def;
blanchet@50216
   337
blanchet@50218
   338
            val iter0 = Morphism.term phi raw_iter;
blanchet@50218
   339
            val rec0 = Morphism.term phi raw_rec;
blanchet@50218
   340
blanchet@50225
   341
            val iter = mk_iter_like As Cs iter0;
blanchet@50225
   342
            val recx = mk_iter_like As Cs rec0;
blanchet@50149
   343
          in
blanchet@50220
   344
            ((ctrs, iter, recx, xss, ctr_defs, iter_def, rec_def), lthy)
blanchet@50149
   345
          end;
blanchet@50149
   346
blanchet@50225
   347
        fun some_gfp_sugar no_defs_lthy =
blanchet@50225
   348
          let
blanchet@50225
   349
            (* qss, q_Tss, gsss, g_Tsss *)
blanchet@50225
   350
            fun zip_preds_and_getters p_Ts f_Tss = p_Ts @ flat f_Tss;
blanchet@50225
   351
blanchet@50225
   352
            val qg_Tss = map2 zip_preds_and_getters q_Tss g_Tsss;
blanchet@50225
   353
blanchet@50225
   354
            val B_to_fpT = C --> fpT;
blanchet@50225
   355
            val coiter_T = fold_rev (curry (op --->)) qg_Tss B_to_fpT;
blanchet@50225
   356
(*
blanchet@50225
   357
            val corec_T = fold_rev (curry (op --->)) h_Tss fpT_to_C;
blanchet@50225
   358
*)
blanchet@50225
   359
blanchet@50225
   360
            val qgss = map2 zip_preds_and_getters qss gsss;
blanchet@50225
   361
            val cqss = map2 (fn c => map (fn q => q $ c)) cs qss;
blanchet@50225
   362
            val cgsss = map2 (fn c => map (map (fn g => g $ c))) cs gsss;
blanchet@50225
   363
blanchet@50225
   364
            val coiter_binder = Binding.suffix_name ("_" ^ coiterN) b;
blanchet@50225
   365
            val corec_binder = Binding.suffix_name ("_" ^ corecN) b;
blanchet@50225
   366
blanchet@50225
   367
            val coiter_free = Free (Binding.name_of coiter_binder, coiter_T);
blanchet@50225
   368
(*
blanchet@50225
   369
            val corec_free = Free (Binding.name_of corec_binder, corec_T);
blanchet@50225
   370
*)
blanchet@50225
   371
blanchet@50225
   372
            val coiter_sum_prod_Ts = map range_type fp_iter_f_Ts;
blanchet@50225
   373
            val coiter_prod_Tss = map2 dest_sumTN ns coiter_sum_prod_Ts;
blanchet@50225
   374
blanchet@50225
   375
            fun mk_join c n cqs sum_prod_T prod_Ts cgss =
blanchet@50225
   376
              Term.lambda c (mk_IfN sum_prod_T cqs
blanchet@50225
   377
                (map2 (mk_InN prod_Ts) (map HOLogic.mk_tuple cgss) (1 upto n)));
blanchet@50225
   378
blanchet@50225
   379
            val coiter_spec =
blanchet@50225
   380
              mk_Trueprop_eq (flat_list_comb (coiter_free, qgss),
blanchet@50225
   381
                Term.list_comb (fp_iter,
blanchet@50225
   382
                  map6 mk_join cs ns cqss coiter_sum_prod_Ts coiter_prod_Tss cgsss));
blanchet@50225
   383
(*
blanchet@50225
   384
            val corec_spec =
blanchet@50225
   385
              mk_Trueprop_eq (flat_list_comb (corec_free, hss),
blanchet@50225
   386
                Term.list_comb (fp_rec, map2 (mk_sum_caseN oo map2 mk_uncurried2_fun) hss zssss));
blanchet@50225
   387
*)
blanchet@50225
   388
blanchet@50225
   389
            val (([raw_coiter (*, raw_corec*)], [raw_coiter_def (*, raw_corec_def*)]), (lthy', lthy)) = no_defs_lthy
blanchet@50225
   390
              |> apfst split_list o fold_map2 (fn b => fn spec =>
blanchet@50225
   391
                Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
blanchet@50225
   392
                #>> apsnd snd) [coiter_binder (*, corec_binder*)] [coiter_spec (*, corec_spec*)]
blanchet@50225
   393
              ||> `Local_Theory.restore;
blanchet@50225
   394
blanchet@50225
   395
            (*transforms defined frees into consts (and more)*)
blanchet@50225
   396
            val phi = Proof_Context.export_morphism lthy lthy';
blanchet@50225
   397
blanchet@50225
   398
            val coiter_def = Morphism.thm phi raw_coiter_def;
blanchet@50225
   399
(*
blanchet@50225
   400
            val corec_def = Morphism.thm phi raw_corec_def;
blanchet@50225
   401
*)
blanchet@50225
   402
blanchet@50225
   403
            val coiter0 = Morphism.term phi raw_coiter;
blanchet@50225
   404
(*
blanchet@50225
   405
            val corec0 = Morphism.term phi raw_corec;
blanchet@50225
   406
*)
blanchet@50225
   407
blanchet@50225
   408
            val coiter = mk_iter_like As Cs coiter0;
blanchet@50225
   409
(*
blanchet@50225
   410
            val corec = mk_iter_like As Cs corec0;
blanchet@50225
   411
*)
blanchet@50225
   412
blanchet@50225
   413
            (*###*)
blanchet@50225
   414
            val corec = @{term True};
blanchet@50225
   415
            val corec_def = TrueI;
blanchet@50225
   416
          in
blanchet@50225
   417
            ((ctrs, coiter, corec, xss, ctr_defs, coiter_def, corec_def), lthy)
blanchet@50225
   418
          end;
blanchet@50134
   419
      in
blanchet@50218
   420
        wrap_datatype tacss ((ctrs0, casex0), (disc_binders, sel_binderss)) lthy'
blanchet@50225
   421
        |> (if lfp then some_lfp_sugar else some_gfp_sugar)
blanchet@50134
   422
      end;
blanchet@50182
   423
blanchet@50220
   424
    fun pour_more_sugar_on_datatypes ((ctrss, iters, recs, xsss, ctr_defss, iter_defs, rec_defs),
blanchet@50220
   425
        lthy) =
blanchet@50217
   426
      let
blanchet@50217
   427
        val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
blanchet@50219
   428
        val giters = map (fn iter => flat_list_comb (iter, gss)) iters;
blanchet@50219
   429
        val hrecs = map (fn recx => flat_list_comb (recx, hss)) recs;
blanchet@50216
   430
blanchet@50217
   431
        val (iter_thmss, rec_thmss) =
blanchet@50222
   432
          let
blanchet@50219
   433
            fun mk_goal_iter_or_rec fss fc xctr f xs xs' =
blanchet@50222
   434
              fold_rev (fold_rev Logic.all) (xs :: fss)
blanchet@50222
   435
                (mk_Trueprop_eq (fc $ xctr, Term.list_comb (f, xs')));
blanchet@50216
   436
blanchet@50219
   437
            fun fix_iter_free (x as Free (_, T)) =
blanchet@50219
   438
              (case find_index (eq_fpT T) fpTs of ~1 => x | j => nth giters j $ x);
blanchet@50219
   439
            fun fix_rec_free (x as Free (_, T)) =
blanchet@50219
   440
              (case find_index (eq_fpT T) fpTs of ~1 => [x] | j => [x, nth hrecs j $ x]);
blanchet@50219
   441
blanchet@50219
   442
            val iter_xsss = map (map (map fix_iter_free)) xsss;
blanchet@50219
   443
            val rec_xsss = map (map (maps fix_rec_free)) xsss;
blanchet@50219
   444
blanchet@50219
   445
            val goal_iterss =
blanchet@50219
   446
              map5 (map4 o mk_goal_iter_or_rec gss) giters xctrss gss xsss iter_xsss;
blanchet@50219
   447
            val goal_recss =
blanchet@50219
   448
              map5 (map4 o mk_goal_iter_or_rec hss) hrecs xctrss hss xsss rec_xsss;
blanchet@50219
   449
blanchet@50218
   450
            val iter_tacss =
blanchet@50222
   451
              map2 (map o mk_iter_or_rec_tac pre_map_defs iter_defs) fp_iter_thms ctr_defss;
blanchet@50218
   452
            val rec_tacss =
blanchet@50222
   453
              map2 (map o mk_iter_or_rec_tac pre_map_defs rec_defs) fp_rec_thms ctr_defss;
blanchet@50217
   454
          in
blanchet@50220
   455
            (map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@50220
   456
               goal_iterss iter_tacss,
blanchet@50220
   457
             map2 (map2 (fn goal => fn tac => Skip_Proof.prove lthy [] [] goal (tac o #context)))
blanchet@50220
   458
               goal_recss rec_tacss)
blanchet@50217
   459
          end;
blanchet@50216
   460
blanchet@50217
   461
        val notes =
blanchet@50217
   462
          [(itersN, iter_thmss),
blanchet@50217
   463
           (recsN, rec_thmss)]
blanchet@50217
   464
          |> maps (fn (thmN, thmss) =>
blanchet@50217
   465
            map2 (fn b => fn thms =>
blanchet@50217
   466
                ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), []), [(thms, [])]))
blanchet@50217
   467
              bs thmss);
blanchet@50217
   468
      in
blanchet@50217
   469
        lthy |> Local_Theory.notes notes |> snd
blanchet@50217
   470
      end;
blanchet@50217
   471
blanchet@50219
   472
    val lthy' = lthy
blanchet@50225
   473
      |> fold_map pour_some_sugar_on_type (bs ~~ fpTs ~~ Cs ~~ flds ~~ unfs ~~ fp_iters ~~
blanchet@50225
   474
        fp_recs ~~ fld_unfs ~~ unf_flds ~~ fld_injects ~~ ctr_binderss ~~ ctr_mixfixess ~~
blanchet@50225
   475
        ctr_Tsss ~~ disc_binderss ~~ sel_bindersss)
blanchet@50220
   476
      |>> split_list7
blanchet@50223
   477
      |> (if lfp then pour_more_sugar_on_datatypes else snd);
blanchet@50182
   478
blanchet@50182
   479
    val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
blanchet@50223
   480
      (if lfp then "" else "co") ^ "datatype"));
blanchet@50127
   481
  in
blanchet@50219
   482
    (timer; lthy')
blanchet@50127
   483
  end;
blanchet@50127
   484
blanchet@50214
   485
fun datatype_cmd info specs lthy =
blanchet@50136
   486
  let
blanchet@50224
   487
    (* TODO: cleaner handling of fake contexts, without "background_theory" *)
blanchet@50199
   488
    (*the "perhaps o try" below helps gracefully handles the case where the new type is defined in a
blanchet@50199
   489
      locale and shadows an existing global type*)
blanchet@50194
   490
    val fake_thy = Theory.copy
blanchet@50199
   491
      #> fold (fn spec => perhaps (try (Sign.add_type lthy
blanchet@50199
   492
        (type_binder_of spec, length (type_args_constrained_of spec), mixfix_of spec)))) specs;
blanchet@50194
   493
    val fake_lthy = Proof_Context.background_theory fake_thy lthy;
blanchet@50136
   494
  in
blanchet@50214
   495
    prepare_datatype Syntax.read_typ info specs fake_lthy lthy
blanchet@50136
   496
  end;
blanchet@50134
   497
blanchet@50144
   498
val parse_opt_binding_colon = Scan.optional (Parse.binding --| Parse.$$$ ":") no_binder
blanchet@50134
   499
blanchet@50127
   500
val parse_ctr_arg =
blanchet@50134
   501
  Parse.$$$ "(" |-- parse_opt_binding_colon -- Parse.typ --| Parse.$$$ ")" ||
blanchet@50144
   502
  (Parse.typ >> pair no_binder);
blanchet@50127
   503
blanchet@50127
   504
val parse_single_spec =
blanchet@50127
   505
  Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
blanchet@50134
   506
  (@{keyword "="} |-- Parse.enum1 "|" (parse_opt_binding_colon -- Parse.binding --
blanchet@50134
   507
    Scan.repeat parse_ctr_arg -- Parse.opt_mixfix));
blanchet@50127
   508
blanchet@50127
   509
val _ =
blanchet@50127
   510
  Outer_Syntax.local_theory @{command_spec "data"} "define BNF-based inductive datatypes"
blanchet@50223
   511
    (Parse.and_list1 parse_single_spec >> datatype_cmd true);
blanchet@50127
   512
blanchet@50127
   513
val _ =
blanchet@50127
   514
  Outer_Syntax.local_theory @{command_spec "codata"} "define BNF-based coinductive datatypes"
blanchet@50223
   515
    (Parse.and_list1 parse_single_spec >> datatype_cmd false);
blanchet@50127
   516
blanchet@50127
   517
end;