src/HOL/Tools/Datatype/datatype_codegen.ML
author haftmann
Mon Sep 28 14:54:15 2009 +0200 (2009-09-28)
changeset 32730 3958b45b29e4
parent 31784 bd3486c57ba3
child 32896 99cd75a18b78
permissions -rw-r--r--
tuned
haftmann@24589
     1
(*  Title:      HOL/Tools/datatype_codegen.ML
wenzelm@29265
     2
    Author:     Stefan Berghofer and Florian Haftmann, TU Muenchen
berghofe@12445
     3
haftmann@25534
     4
Code generator facilities for inductive datatypes.
berghofe@12445
     5
*)
berghofe@12445
     6
berghofe@12445
     7
signature DATATYPE_CODEGEN =
berghofe@12445
     8
sig
haftmann@31737
     9
  val find_shortest_path: Datatype.descr -> int -> (string * int) option
haftmann@31134
    10
  val mk_eq_eqns: theory -> string -> (thm * bool) list
haftmann@30076
    11
  val mk_case_cert: theory -> string -> thm
wenzelm@18708
    12
  val setup: theory -> theory
berghofe@12445
    13
end;
berghofe@12445
    14
berghofe@12445
    15
structure DatatypeCodegen : DATATYPE_CODEGEN =
berghofe@12445
    16
struct
berghofe@12445
    17
haftmann@31625
    18
(** find shortest path to constructor with no recursive arguments **)
berghofe@14104
    19
haftmann@31737
    20
fun find_nonempty (descr: Datatype.descr) is i =
berghofe@14104
    21
  let
haftmann@31246
    22
    val (_, _, constrs) = the (AList.lookup (op =) descr i);
haftmann@31246
    23
    fun arg_nonempty (_, DatatypeAux.DtRec i) = if member (op =) is i
haftmann@31246
    24
          then NONE
skalberg@15570
    25
          else Option.map (curry op + 1 o snd) (find_nonempty descr (i::is) i)
skalberg@15531
    26
      | arg_nonempty _ = SOME 0;
skalberg@15570
    27
    fun max xs = Library.foldl
skalberg@15531
    28
      (fn (NONE, _) => NONE
skalberg@15531
    29
        | (SOME i, SOME j) => SOME (Int.max (i, j))
skalberg@15531
    30
        | (_, NONE) => NONE) (SOME 0, xs);
berghofe@14104
    31
    val xs = sort (int_ord o pairself snd)
haftmann@31246
    32
      (map_filter (fn (s, dts) => Option.map (pair s)
berghofe@14104
    33
        (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
skalberg@15531
    34
  in case xs of [] => NONE | x :: _ => SOME x end;
berghofe@14104
    35
haftmann@31246
    36
fun find_shortest_path descr i = find_nonempty descr [i] i;
haftmann@31246
    37
haftmann@31625
    38
haftmann@31625
    39
(** SML code generator **)
haftmann@31625
    40
haftmann@31625
    41
open Codegen;
haftmann@31625
    42
haftmann@31625
    43
(* datatype definition *)
haftmann@31625
    44
haftmann@31737
    45
fun add_dt_defs thy defs dep module (descr: Datatype.descr) sorts gr =
berghofe@12445
    46
  let
skalberg@15570
    47
    val descr' = List.filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
skalberg@15570
    48
    val rtnames = map (#1 o snd) (List.filter (fn (_, (_, _, cs)) =>
berghofe@14104
    49
      exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
berghofe@12445
    50
berghofe@17144
    51
    val (_, (tname, _, _)) :: _ = descr';
berghofe@17144
    52
    val node_id = tname ^ " (type)";
haftmann@27398
    53
    val module' = if_library (thyname_of_type thy tname) module;
berghofe@12445
    54
haftmann@28537
    55
    fun mk_dtdef prfx [] gr = ([], gr)
haftmann@28537
    56
      | mk_dtdef prfx ((_, (tname, dts, cs))::xs) gr =
berghofe@12445
    57
          let
berghofe@12445
    58
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@12445
    59
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
haftmann@28537
    60
            val ((_, type_id), gr') = mk_type_id module' tname gr;
haftmann@28537
    61
            val (ps, gr'') = gr' |>
haftmann@28537
    62
              fold_map (fn (cname, cargs) =>
haftmann@28537
    63
                fold_map (invoke_tycodegen thy defs node_id module' false)
haftmann@28537
    64
                  cargs ##>>
haftmann@28537
    65
                mk_const_id module' cname) cs';
haftmann@28537
    66
            val (rest, gr''') = mk_dtdef "and " xs gr''
berghofe@12445
    67
          in
haftmann@28537
    68
            (Pretty.block (str prfx ::
berghofe@12445
    69
               (if null tvs then [] else
berghofe@26975
    70
                  [mk_tuple (map str tvs), str " "]) @
berghofe@26975
    71
               [str (type_id ^ " ="), Pretty.brk 1] @
berghofe@26975
    72
               List.concat (separate [Pretty.brk 1, str "| "]
berghofe@17144
    73
                 (map (fn (ps', (_, cname)) => [Pretty.block
berghofe@26975
    74
                   (str cname ::
berghofe@12445
    75
                    (if null ps' then [] else
berghofe@26975
    76
                     List.concat ([str " of", Pretty.brk 1] ::
berghofe@26975
    77
                       separate [str " *", Pretty.brk 1]
haftmann@28537
    78
                         (map single ps'))))]) ps))) :: rest, gr''')
berghofe@13754
    79
          end;
berghofe@13754
    80
berghofe@25889
    81
    fun mk_constr_term cname Ts T ps =
berghofe@26975
    82
      List.concat (separate [str " $", Pretty.brk 1]
berghofe@26975
    83
        ([str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
berghofe@26975
    84
          mk_type false (Ts ---> T), str ")"] :: ps));
berghofe@25889
    85
berghofe@17144
    86
    fun mk_term_of_def gr prfx [] = []
berghofe@17144
    87
      | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
    88
          let
berghofe@13754
    89
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@13754
    90
            val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@13754
    91
            val T = Type (tname, dts');
berghofe@17144
    92
            val rest = mk_term_of_def gr "and " xs;
haftmann@31458
    93
            val (eqs, _) = fold_map (fn (cname, Ts) => fn prfx =>
berghofe@13754
    94
              let val args = map (fn i =>
berghofe@26975
    95
                str ("x" ^ string_of_int i)) (1 upto length Ts)
haftmann@31458
    96
              in (Pretty.blk (4,
berghofe@26975
    97
                [str prfx, mk_term_of gr module' false T, Pretty.brk 1,
haftmann@28537
    98
                 if null Ts then str (snd (get_const_id gr cname))
berghofe@16645
    99
                 else parens (Pretty.block
haftmann@28537
   100
                   [str (snd (get_const_id gr cname)),
berghofe@13754
   101
                    Pretty.brk 1, mk_tuple args]),
berghofe@26975
   102
                 str " =", Pretty.brk 1] @
berghofe@25889
   103
                 mk_constr_term cname Ts T
haftmann@31458
   104
                   (map2 (fn x => fn U => [Pretty.block [mk_term_of gr module' false U,
haftmann@31458
   105
                      Pretty.brk 1, x]]) args Ts)), "  | ")
haftmann@31458
   106
              end) cs' prfx
berghofe@14104
   107
          in eqs @ rest end;
berghofe@14104
   108
berghofe@17144
   109
    fun mk_gen_of_def gr prfx [] = []
berghofe@17144
   110
      | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   111
          let
berghofe@14104
   112
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@25889
   113
            val Us = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@25889
   114
            val T = Type (tname, Us);
berghofe@14104
   115
            val (cs1, cs2) =
skalberg@15570
   116
              List.partition (exists DatatypeAux.is_rec_type o snd) cs;
haftmann@31246
   117
            val SOME (cname, _) = find_shortest_path descr i;
berghofe@14104
   118
berghofe@14104
   119
            fun mk_delay p = Pretty.block
berghofe@26975
   120
              [str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   121
berghofe@26975
   122
            fun mk_force p = Pretty.block [p, Pretty.brk 1, str "()"];
berghofe@25889
   123
berghofe@15397
   124
            fun mk_constr s b (cname, dts) =
berghofe@14104
   125
              let
berghofe@17144
   126
                val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
berghofe@15397
   127
                    (DatatypeAux.typ_of_dtyp descr sorts dt))
berghofe@26975
   128
                  [str (if b andalso DatatypeAux.is_rec_type dt then "0"
berghofe@15397
   129
                     else "j")]) dts;
berghofe@25889
   130
                val Ts = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@26975
   131
                val xs = map str
berghofe@25889
   132
                  (DatatypeProp.indexify_names (replicate (length dts) "x"));
berghofe@26975
   133
                val ts = map str
berghofe@25889
   134
                  (DatatypeProp.indexify_names (replicate (length dts) "t"));
haftmann@28537
   135
                val (_, id) = get_const_id gr cname
berghofe@25889
   136
              in
berghofe@25889
   137
                mk_let
berghofe@25889
   138
                  (map2 (fn p => fn q => mk_tuple [p, q]) xs ts ~~ gs)
berghofe@25889
   139
                  (mk_tuple
berghofe@25889
   140
                    [case xs of
berghofe@25889
   141
                       _ :: _ :: _ => Pretty.block
berghofe@26975
   142
                         [str id, Pretty.brk 1, mk_tuple xs]
berghofe@26975
   143
                     | _ => mk_app false (str id) xs,
berghofe@25889
   144
                     mk_delay (Pretty.block (mk_constr_term cname Ts T
berghofe@25889
   145
                       (map (single o mk_force) ts)))])
berghofe@14104
   146
              end;
berghofe@14104
   147
berghofe@15397
   148
            fun mk_choice [c] = mk_constr "(i-1)" false c
berghofe@26975
   149
              | mk_choice cs = Pretty.block [str "one_of",
berghofe@26975
   150
                  Pretty.brk 1, Pretty.blk (1, str "[" ::
berghofe@26975
   151
                  List.concat (separate [str ",", Pretty.fbrk]
berghofe@15397
   152
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
berghofe@26975
   153
                  [str "]"]), Pretty.brk 1, str "()"];
berghofe@14104
   154
berghofe@25889
   155
            val gs = maps (fn s =>
berghofe@25889
   156
              let val s' = strip_tname s
berghofe@26975
   157
              in [str (s' ^ "G"), str (s' ^ "T")] end) tvs;
haftmann@28537
   158
            val gen_name = "gen_" ^ snd (get_type_id gr tname)
berghofe@14104
   159
berghofe@14104
   160
          in
berghofe@14104
   161
            Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@26975
   162
                (str (prfx ^ gen_name ^
berghofe@14104
   163
                   (if null cs1 then "" else "'")) :: gs @
berghofe@26975
   164
                 (if null cs1 then [] else [str "i"]) @
berghofe@26975
   165
                 [str "j"]) @
berghofe@26975
   166
              [str " =", Pretty.brk 1] @
berghofe@14104
   167
              (if not (null cs1) andalso not (null cs2)
berghofe@26975
   168
               then [str "frequency", Pretty.brk 1,
berghofe@26975
   169
                 Pretty.blk (1, [str "[",
berghofe@26975
   170
                   mk_tuple [str "i", mk_delay (mk_choice cs1)],
berghofe@26975
   171
                   str ",", Pretty.fbrk,
berghofe@26975
   172
                   mk_tuple [str "1", mk_delay (mk_choice cs2)],
berghofe@26975
   173
                   str "]"]), Pretty.brk 1, str "()"]
berghofe@14104
   174
               else if null cs2 then
berghofe@26975
   175
                 [Pretty.block [str "(case", Pretty.brk 1,
berghofe@26975
   176
                   str "i", Pretty.brk 1, str "of",
berghofe@26975
   177
                   Pretty.brk 1, str "0 =>", Pretty.brk 1,
haftmann@17521
   178
                   mk_constr "0" true (cname, valOf (AList.lookup (op =) cs cname)),
berghofe@26975
   179
                   Pretty.brk 1, str "| _ =>", Pretty.brk 1,
berghofe@26975
   180
                   mk_choice cs1, str ")"]]
berghofe@14104
   181
               else [mk_choice cs2])) ::
berghofe@14104
   182
            (if null cs1 then []
berghofe@14104
   183
             else [Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@26975
   184
                 (str ("and " ^ gen_name) :: gs @ [str "i"]) @
berghofe@26975
   185
               [str " =", Pretty.brk 1] @
berghofe@26975
   186
               separate (Pretty.brk 1) (str (gen_name ^ "'") :: gs @
berghofe@26975
   187
                 [str "i", str "i"]))]) @
berghofe@17144
   188
            mk_gen_of_def gr "and " xs
berghofe@14104
   189
          end
berghofe@13754
   190
berghofe@12445
   191
  in
haftmann@28537
   192
    (module', (add_edge_acyclic (node_id, dep) gr
berghofe@12445
   193
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   194
         let
berghofe@17144
   195
           val gr1 = add_edge (node_id, dep)
berghofe@17144
   196
             (new_node (node_id, (NONE, "", "")) gr);
haftmann@28537
   197
           val (dtdef, gr2) = mk_dtdef "datatype " descr' gr1 ;
berghofe@12445
   198
         in
berghofe@17144
   199
           map_node node_id (K (NONE, module',
berghofe@26975
   200
             string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
berghofe@26975
   201
               [str ";"])) ^ "\n\n" ^
berghofe@13754
   202
             (if "term_of" mem !mode then
berghofe@26975
   203
                string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@26975
   204
                  (mk_term_of_def gr2 "fun " descr') @ [str ";"])) ^ "\n\n"
berghofe@14104
   205
              else "") ^
berghofe@14104
   206
             (if "test" mem !mode then
berghofe@26975
   207
                string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@26975
   208
                  (mk_gen_of_def gr2 "fun " descr') @ [str ";"])) ^ "\n\n"
berghofe@13754
   209
              else ""))) gr2
haftmann@28537
   210
         end)
berghofe@12445
   211
  end;
berghofe@12445
   212
berghofe@12445
   213
haftmann@31625
   214
(* case expressions *)
berghofe@12445
   215
haftmann@28537
   216
fun pretty_case thy defs dep module brack constrs (c as Const (_, T)) ts gr =
berghofe@12445
   217
  let val i = length constrs
berghofe@12445
   218
  in if length ts <= i then
haftmann@28537
   219
       invoke_codegen thy defs dep module brack (eta_expand c ts (i+1)) gr
berghofe@12445
   220
    else
berghofe@12445
   221
      let
skalberg@15570
   222
        val ts1 = Library.take (i, ts);
skalberg@15570
   223
        val t :: ts2 = Library.drop (i, ts);
wenzelm@30190
   224
        val names = List.foldr OldTerm.add_term_names
wenzelm@30190
   225
          (map (fst o fst o dest_Var) (List.foldr OldTerm.add_term_vars [] ts1)) ts1;
skalberg@15570
   226
        val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
berghofe@12445
   227
haftmann@28537
   228
        fun pcase [] [] [] gr = ([], gr)
haftmann@28537
   229
          | pcase ((cname, cargs)::cs) (t::ts) (U::Us) gr =
berghofe@12445
   230
              let
berghofe@12445
   231
                val j = length cargs;
wenzelm@20071
   232
                val xs = Name.variant_list names (replicate j "x");
skalberg@15570
   233
                val Us' = Library.take (j, fst (strip_type U));
berghofe@12445
   234
                val frees = map Free (xs ~~ Us');
haftmann@28537
   235
                val (cp, gr0) = invoke_codegen thy defs dep module false
haftmann@28537
   236
                  (list_comb (Const (cname, Us' ---> dT), frees)) gr;
berghofe@12445
   237
                val t' = Envir.beta_norm (list_comb (t, frees));
haftmann@28537
   238
                val (p, gr1) = invoke_codegen thy defs dep module false t' gr0;
haftmann@28537
   239
                val (ps, gr2) = pcase cs ts Us gr1;
berghofe@12445
   240
              in
berghofe@26975
   241
                ([Pretty.block [cp, str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   242
              end;
berghofe@12445
   243
haftmann@28537
   244
        val (ps1, gr1) = pcase constrs ts1 Ts gr ;
berghofe@26975
   245
        val ps = List.concat (separate [Pretty.brk 1, str "| "] ps1);
haftmann@28537
   246
        val (p, gr2) = invoke_codegen thy defs dep module false t gr1;
haftmann@28537
   247
        val (ps2, gr3) = fold_map (invoke_codegen thy defs dep module true) ts2 gr2;
haftmann@28537
   248
      in ((if not (null ts2) andalso brack then parens else I)
berghofe@12445
   249
        (Pretty.block (separate (Pretty.brk 1)
berghofe@26975
   250
          (Pretty.block ([str "(case ", p, str " of",
haftmann@28537
   251
             Pretty.brk 1] @ ps @ [str ")"]) :: ps2))), gr3)
berghofe@12445
   252
      end
berghofe@12445
   253
  end;
berghofe@12445
   254
berghofe@12445
   255
haftmann@31625
   256
(* constructors *)
berghofe@12445
   257
haftmann@28537
   258
fun pretty_constr thy defs dep module brack args (c as Const (s, T)) ts gr =
berghofe@12445
   259
  let val i = length args
berghofe@12445
   260
  in if i > 1 andalso length ts < i then
haftmann@28537
   261
      invoke_codegen thy defs dep module brack (eta_expand c ts i) gr
berghofe@12445
   262
     else
berghofe@12445
   263
       let
haftmann@28537
   264
         val id = mk_qual_id module (get_const_id gr s);
haftmann@28537
   265
         val (ps, gr') = fold_map
haftmann@28537
   266
           (invoke_codegen thy defs dep module (i = 1)) ts gr;
berghofe@12445
   267
       in (case args of
haftmann@28537
   268
          _ :: _ :: _ => (if brack then parens else I)
haftmann@28537
   269
            (Pretty.block [str id, Pretty.brk 1, mk_tuple ps])
haftmann@28537
   270
        | _ => (mk_app brack (str id) ps), gr')
berghofe@12445
   271
       end
berghofe@12445
   272
  end;
berghofe@12445
   273
berghofe@12445
   274
haftmann@31625
   275
(* code generators for terms and types *)
berghofe@12445
   276
haftmann@28537
   277
fun datatype_codegen thy defs dep module brack t gr = (case strip_comb t of
berghofe@12445
   278
   (c as Const (s, T), ts) =>
haftmann@31784
   279
     (case Datatype.info_of_case thy s of
berghofe@22778
   280
        SOME {index, descr, ...} =>
haftmann@22921
   281
          if is_some (get_assoc_code thy (s, T)) then NONE else
haftmann@28537
   282
          SOME (pretty_case thy defs dep module brack
haftmann@28537
   283
            (#3 (the (AList.lookup op = descr index))) c ts gr )
haftmann@31784
   284
      | NONE => case (Datatype.info_of_constr thy s, strip_type T) of
berghofe@28639
   285
        (SOME {index, descr, ...}, (_, U as Type (tyname, _))) =>
haftmann@22921
   286
          if is_some (get_assoc_code thy (s, T)) then NONE else
berghofe@28639
   287
          let
berghofe@28639
   288
            val SOME (tyname', _, constrs) = AList.lookup op = descr index;
berghofe@28639
   289
            val SOME args = AList.lookup op = constrs s
berghofe@22778
   290
          in
berghofe@28639
   291
            if tyname <> tyname' then NONE
berghofe@28639
   292
            else SOME (pretty_constr thy defs
haftmann@28537
   293
              dep module brack args c ts (snd (invoke_tycodegen thy defs dep module false U gr)))
berghofe@22778
   294
          end
berghofe@22778
   295
      | _ => NONE)
berghofe@22778
   296
 | _ => NONE);
berghofe@12445
   297
haftmann@28537
   298
fun datatype_tycodegen thy defs dep module brack (Type (s, Ts)) gr =
haftmann@31784
   299
      (case Datatype.get_info thy s of
skalberg@15531
   300
         NONE => NONE
berghofe@25889
   301
       | SOME {descr, sorts, ...} =>
haftmann@22921
   302
           if is_some (get_assoc_type thy s) then NONE else
berghofe@16645
   303
           let
haftmann@28537
   304
             val (ps, gr') = fold_map
haftmann@28537
   305
               (invoke_tycodegen thy defs dep module false) Ts gr;
haftmann@28537
   306
             val (module', gr'') = add_dt_defs thy defs dep module descr sorts gr' ;
haftmann@28537
   307
             val (tyid, gr''') = mk_type_id module' s gr''
haftmann@28537
   308
           in SOME (Pretty.block ((if null Ts then [] else
berghofe@26975
   309
               [mk_tuple ps, str " "]) @
haftmann@28537
   310
               [str (mk_qual_id module tyid)]), gr''')
berghofe@12445
   311
           end)
berghofe@16645
   312
  | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
berghofe@12445
   313
haftmann@18247
   314
haftmann@25534
   315
(** generic code generator **)
haftmann@20105
   316
haftmann@31625
   317
(* liberal addition of code data for datatypes *)
haftmann@31625
   318
haftmann@31625
   319
fun mk_constr_consts thy vs dtco cos =
haftmann@31625
   320
  let
haftmann@31625
   321
    val cs = map (fn (c, tys) => (c, tys ---> Type (dtco, map TFree vs))) cos;
haftmann@31625
   322
    val cs' = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) cs;
haftmann@31625
   323
  in if is_some (try (Code.constrset_of_consts thy) cs')
haftmann@31625
   324
    then SOME cs
haftmann@31625
   325
    else NONE
haftmann@31625
   326
  end;
haftmann@31625
   327
haftmann@31625
   328
haftmann@25534
   329
(* case certificates *)
haftmann@19346
   330
haftmann@30076
   331
fun mk_case_cert thy tyco =
haftmann@23811
   332
  let
haftmann@23811
   333
    val raw_thms =
haftmann@31784
   334
      (#case_rewrites o Datatype.the_info thy) tyco;
haftmann@23811
   335
    val thms as hd_thm :: _ = raw_thms
haftmann@23811
   336
      |> Conjunction.intr_balanced
wenzelm@24976
   337
      |> Thm.unvarify
haftmann@23811
   338
      |> Conjunction.elim_balanced (length raw_thms)
haftmann@23811
   339
      |> map Simpdata.mk_meta_eq
haftmann@23811
   340
      |> map Drule.zero_var_indexes
haftmann@23811
   341
    val params = fold_aterms (fn (Free (v, _)) => insert (op =) v
haftmann@23811
   342
      | _ => I) (Thm.prop_of hd_thm) [];
haftmann@23811
   343
    val rhs = hd_thm
haftmann@23811
   344
      |> Thm.prop_of
haftmann@23811
   345
      |> Logic.dest_equals
haftmann@23811
   346
      |> fst
haftmann@23811
   347
      |> Term.strip_comb
haftmann@23811
   348
      |> apsnd (fst o split_last)
haftmann@23811
   349
      |> list_comb;
haftmann@23811
   350
    val lhs = Free (Name.variant params "case", Term.fastype_of rhs);
haftmann@23811
   351
    val asm = (Thm.cterm_of thy o Logic.mk_equals) (lhs, rhs);
haftmann@23811
   352
  in
haftmann@23811
   353
    thms
haftmann@23811
   354
    |> Conjunction.intr_balanced
haftmann@23811
   355
    |> MetaSimplifier.rewrite_rule [(Thm.symmetric o Thm.assume) asm]
haftmann@23811
   356
    |> Thm.implies_intr asm
haftmann@23811
   357
    |> Thm.generalize ([], params) 0
haftmann@25597
   358
    |> AxClass.unoverload thy
haftmann@23811
   359
    |> Thm.varifyT
haftmann@23811
   360
  end;
haftmann@23811
   361
haftmann@25534
   362
haftmann@25534
   363
(* equality *)
haftmann@25534
   364
haftmann@31134
   365
fun mk_eq_eqns thy dtco =
haftmann@25534
   366
  let
haftmann@31784
   367
    val (vs, cos) = Datatype.the_spec thy dtco;
haftmann@31784
   368
    val { descr, index, inject = inject_thms, ... } = Datatype.the_info thy dtco;
haftmann@31134
   369
    val ty = Type (dtco, map TFree vs);
haftmann@31134
   370
    fun mk_eq (t1, t2) = Const (@{const_name eq_class.eq}, ty --> ty --> HOLogic.boolT)
haftmann@31134
   371
      $ t1 $ t2;
haftmann@31134
   372
    fun true_eq t12 = HOLogic.mk_eq (mk_eq t12, HOLogic.true_const);
haftmann@31134
   373
    fun false_eq t12 = HOLogic.mk_eq (mk_eq t12, HOLogic.false_const);
haftmann@31134
   374
    val triv_injects = map_filter
haftmann@31134
   375
     (fn (c, []) => SOME (HOLogic.mk_Trueprop (true_eq (Const (c, ty), Const (c, ty))))
haftmann@31134
   376
       | _ => NONE) cos;
haftmann@31134
   377
    fun prep_inject (trueprop $ (equiv $ (_ $ t1 $ t2) $ rhs)) =
haftmann@31134
   378
      trueprop $ (equiv $ mk_eq (t1, t2) $ rhs);
haftmann@31134
   379
    val injects = map prep_inject (nth (DatatypeProp.make_injs [descr] vs) index);
haftmann@31134
   380
    fun prep_distinct (trueprop $ (not $ (_ $ t1 $ t2))) =
haftmann@31134
   381
      [trueprop $ false_eq (t1, t2), trueprop $ false_eq (t2, t1)];
haftmann@31134
   382
    val distincts = maps prep_distinct (snd (nth (DatatypeProp.make_distincts [descr] vs) index));
haftmann@31134
   383
    val refl = HOLogic.mk_Trueprop (true_eq (Free ("x", ty), Free ("x", ty)));
haftmann@31134
   384
    val simpset = Simplifier.context (ProofContext.init thy) (HOL_basic_ss
haftmann@31134
   385
      addsimps (map Simpdata.mk_eq (@{thm eq} :: @{thm eq_True} :: inject_thms))
haftmann@31723
   386
      addsimprocs [Datatype.distinct_simproc]);
haftmann@31625
   387
    fun prove prop = SkipProof.prove_global thy [] [] prop (K (ALLGOALS (simp_tac simpset)))
haftmann@31151
   388
      |> Simpdata.mk_eq;
haftmann@31134
   389
  in map (rpair true o prove) (triv_injects @ injects @ distincts) @ [(prove refl, false)] end;
haftmann@20426
   390
haftmann@31134
   391
fun add_equality vs dtcos thy =
haftmann@20597
   392
  let
haftmann@28350
   393
    fun add_def dtco lthy =
haftmann@26513
   394
      let
haftmann@31134
   395
        val ty = Type (dtco, map TFree vs);
haftmann@26513
   396
        fun mk_side const_name = Const (const_name, ty --> ty --> HOLogic.boolT)
haftmann@26513
   397
          $ Free ("x", ty) $ Free ("y", ty);
haftmann@26513
   398
        val def = HOLogic.mk_Trueprop (HOLogic.mk_eq
haftmann@26732
   399
          (mk_side @{const_name eq_class.eq}, mk_side @{const_name "op ="}));
haftmann@26513
   400
        val def' = Syntax.check_term lthy def;
haftmann@26513
   401
        val ((_, (_, thm)), lthy') = Specification.definition
haftmann@28965
   402
          (NONE, (Attrib.empty_binding, def')) lthy;
haftmann@26513
   403
        val ctxt_thy = ProofContext.init (ProofContext.theory_of lthy);
haftmann@26513
   404
        val thm' = singleton (ProofContext.export lthy' ctxt_thy) thm;
haftmann@26513
   405
      in (thm', lthy') end;
haftmann@26513
   406
    fun tac thms = Class.intro_classes_tac []
haftmann@26513
   407
      THEN ALLGOALS (ProofContext.fact_tac thms);
haftmann@25534
   408
    fun add_eq_thms dtco thy =
haftmann@20597
   409
      let
haftmann@31134
   410
        val const = AxClass.param_of_inst thy (@{const_name eq_class.eq}, dtco);
wenzelm@24137
   411
        val thy_ref = Theory.check_thy thy;
haftmann@31134
   412
        fun mk_thms () = rev ((mk_eq_eqns (Theory.deref thy_ref) dtco));
haftmann@20597
   413
      in
haftmann@30076
   414
        Code.add_eqnl (const, Lazy.lazy mk_thms) thy
haftmann@20597
   415
      end;
haftmann@20597
   416
  in
haftmann@25534
   417
    thy
haftmann@31134
   418
    |> TheoryTarget.instantiation (dtcos, vs, [HOLogic.class_eq])
haftmann@26513
   419
    |> fold_map add_def dtcos
haftmann@31134
   420
    |-> (fn def_thms => Class.prove_instantiation_exit_result (map o Morphism.thm)
haftmann@31134
   421
         (fn _ => fn def_thms => tac def_thms) def_thms)
haftmann@31134
   422
    |-> (fn def_thms => fold Code.del_eqn def_thms)
haftmann@31134
   423
    |> fold add_eq_thms dtcos
haftmann@31134
   424
  end;
haftmann@31134
   425
haftmann@31134
   426
haftmann@31625
   427
(* register a datatype etc. *)
haftmann@20597
   428
haftmann@31668
   429
fun add_all_code config dtcos thy =
haftmann@31134
   430
  let
haftmann@31784
   431
    val (vs :: _, coss) = (split_list o map (Datatype.the_spec thy)) dtcos;
haftmann@31134
   432
    val any_css = map2 (mk_constr_consts thy vs) dtcos coss;
haftmann@31134
   433
    val css = if exists is_none any_css then []
haftmann@31134
   434
      else map_filter I any_css;
haftmann@31784
   435
    val case_rewrites = maps (#case_rewrites o Datatype.the_info thy) dtcos;
haftmann@31134
   436
    val certs = map (mk_case_cert thy) dtcos;
haftmann@31134
   437
  in
haftmann@31134
   438
    if null css then thy
haftmann@31134
   439
    else thy
haftmann@31668
   440
      |> tap (fn _ => DatatypeAux.message config "Registering datatype for code generator ...")
haftmann@31134
   441
      |> fold Code.add_datatype css
haftmann@31134
   442
      |> fold_rev Code.add_default_eqn case_rewrites
haftmann@31134
   443
      |> fold Code.add_case certs
haftmann@31134
   444
      |> add_equality vs dtcos
haftmann@31134
   445
   end;
haftmann@31134
   446
haftmann@31134
   447
haftmann@20426
   448
(** theory setup **)
haftmann@20426
   449
haftmann@19008
   450
val setup = 
haftmann@20597
   451
  add_codegen "datatype" datatype_codegen
haftmann@24626
   452
  #> add_tycodegen "datatype" datatype_tycodegen
haftmann@31723
   453
  #> Datatype.interpretation add_all_code
haftmann@20597
   454
berghofe@12445
   455
end;