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