src/HOL/Tools/datatype_codegen.ML
author haftmann
Thu Aug 17 09:24:47 2006 +0200 (2006-08-17)
changeset 20389 8b6ecb22ef35
parent 20382 39964c8dcd54
child 20426 9ffea7a8b31c
permissions -rw-r--r--
cleanup
berghofe@12446
     1
(*  Title:      HOL/datatype_codegen.ML
berghofe@12445
     2
    ID:         $Id$
haftmann@20105
     3
    Author:     Stefan Berghofer & Florian Haftmann, TU Muenchen
berghofe@12445
     4
berghofe@12445
     5
Code generator for inductive datatypes.
berghofe@12445
     6
*)
berghofe@12445
     7
berghofe@12445
     8
signature DATATYPE_CODEGEN =
berghofe@12445
     9
sig
haftmann@19346
    10
  val get_datatype_spec_thms: theory -> string
haftmann@19346
    11
    -> (((string * sort) list * (string * typ list) list) * tactic) option
haftmann@20389
    12
  val datatype_tac: theory -> string -> tactic
haftmann@20105
    13
  val dest_case_expr: theory -> term
haftmann@20177
    14
    -> ((string * typ) list * ((term * typ) * (term * term) list)) option
haftmann@19886
    15
  val add_datatype_case_const: string -> theory -> theory
haftmann@19886
    16
  val add_datatype_case_defs: string -> theory -> theory
haftmann@20177
    17
  val datatypes_dependency: theory -> string list list
haftmann@20382
    18
  val add_hook_bootstrap: DatatypeHooks.hook -> theory -> theory
haftmann@20177
    19
  val get_datatype_mut_specs: theory -> string list
haftmann@20177
    20
    -> ((string * sort) list * (string * (string * typ list) list) list)
haftmann@20177
    21
  val get_datatype_arities: theory -> string list -> sort
haftmann@20190
    22
    -> (string * (((string * sort list) * sort) * term list)) list option
haftmann@20182
    23
  val prove_arities: (thm list -> tactic) -> string list -> sort
haftmann@20389
    24
    -> (theory -> ((string * sort list) * sort) list -> (string * term list) list
haftmann@20177
    25
    -> ((bstring * attribute list) * term) list) -> theory -> theory
wenzelm@18708
    26
  val setup: theory -> theory
berghofe@12445
    27
end;
berghofe@12445
    28
berghofe@12445
    29
structure DatatypeCodegen : DATATYPE_CODEGEN =
berghofe@12445
    30
struct
berghofe@12445
    31
berghofe@12445
    32
open Codegen;
berghofe@12445
    33
berghofe@12445
    34
fun mk_tuple [p] = p
berghofe@12445
    35
  | mk_tuple ps = Pretty.block (Pretty.str "(" ::
skalberg@15570
    36
      List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
berghofe@12445
    37
        [Pretty.str ")"]);
berghofe@12445
    38
berghofe@12445
    39
(**** datatype definition ****)
berghofe@12445
    40
berghofe@14104
    41
(* find shortest path to constructor with no recursive arguments *)
berghofe@14104
    42
berghofe@14104
    43
fun find_nonempty (descr: DatatypeAux.descr) is i =
berghofe@14104
    44
  let
haftmann@17521
    45
    val (_, _, constrs) = valOf (AList.lookup (op =) descr i);
skalberg@15531
    46
    fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then NONE
skalberg@15570
    47
          else Option.map (curry op + 1 o snd) (find_nonempty descr (i::is) i)
skalberg@15531
    48
      | arg_nonempty _ = SOME 0;
skalberg@15570
    49
    fun max xs = Library.foldl
skalberg@15531
    50
      (fn (NONE, _) => NONE
skalberg@15531
    51
        | (SOME i, SOME j) => SOME (Int.max (i, j))
skalberg@15531
    52
        | (_, NONE) => NONE) (SOME 0, xs);
berghofe@14104
    53
    val xs = sort (int_ord o pairself snd)
skalberg@15570
    54
      (List.mapPartial (fn (s, dts) => Option.map (pair s)
berghofe@14104
    55
        (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
skalberg@15531
    56
  in case xs of [] => NONE | x :: _ => SOME x end;
berghofe@14104
    57
berghofe@17144
    58
fun add_dt_defs thy defs dep module gr (descr: DatatypeAux.descr) =
berghofe@12445
    59
  let
berghofe@12445
    60
    val sg = sign_of thy;
berghofe@12445
    61
    val tab = DatatypePackage.get_datatypes thy;
berghofe@12445
    62
skalberg@15570
    63
    val descr' = List.filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
skalberg@15570
    64
    val rtnames = map (#1 o snd) (List.filter (fn (_, (_, _, cs)) =>
berghofe@14104
    65
      exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
berghofe@12445
    66
berghofe@17144
    67
    val (_, (tname, _, _)) :: _ = descr';
berghofe@17144
    68
    val node_id = tname ^ " (type)";
berghofe@17144
    69
    val module' = if_library (thyname_of_type tname thy) module;
berghofe@12445
    70
berghofe@12445
    71
    fun mk_dtdef gr prfx [] = (gr, [])
berghofe@12445
    72
      | mk_dtdef gr prfx ((_, (tname, dts, cs))::xs) =
berghofe@12445
    73
          let
berghofe@12445
    74
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@12445
    75
            val sorts = map (rpair []) tvs;
berghofe@12445
    76
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@17144
    77
            val (gr', (_, type_id)) = mk_type_id module' tname gr;
berghofe@17144
    78
            val (gr'', ps) =
berghofe@17144
    79
              foldl_map (fn (gr, (cname, cargs)) =>
berghofe@17144
    80
                foldl_map (invoke_tycodegen thy defs node_id module' false)
berghofe@17144
    81
                  (gr, cargs) |>>>
berghofe@17144
    82
                mk_const_id module' cname) (gr', cs');
berghofe@17144
    83
            val (gr''', rest) = mk_dtdef gr'' "and " xs
berghofe@12445
    84
          in
berghofe@17144
    85
            (gr''',
berghofe@12445
    86
             Pretty.block (Pretty.str prfx ::
berghofe@12445
    87
               (if null tvs then [] else
berghofe@12445
    88
                  [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
berghofe@17144
    89
               [Pretty.str (type_id ^ " ="), Pretty.brk 1] @
skalberg@15570
    90
               List.concat (separate [Pretty.brk 1, Pretty.str "| "]
berghofe@17144
    91
                 (map (fn (ps', (_, cname)) => [Pretty.block
berghofe@17144
    92
                   (Pretty.str cname ::
berghofe@12445
    93
                    (if null ps' then [] else
skalberg@15570
    94
                     List.concat ([Pretty.str " of", Pretty.brk 1] ::
berghofe@12445
    95
                       separate [Pretty.str " *", Pretty.brk 1]
berghofe@12445
    96
                         (map single ps'))))]) ps))) :: rest)
berghofe@13754
    97
          end;
berghofe@13754
    98
berghofe@17144
    99
    fun mk_term_of_def gr prfx [] = []
berghofe@17144
   100
      | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
   101
          let
berghofe@13754
   102
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@13754
   103
            val sorts = map (rpair []) tvs;
berghofe@13754
   104
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@13754
   105
            val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@13754
   106
            val T = Type (tname, dts');
berghofe@17144
   107
            val rest = mk_term_of_def gr "and " xs;
berghofe@13754
   108
            val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
berghofe@13754
   109
              let val args = map (fn i =>
berghofe@13754
   110
                Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
berghofe@13754
   111
              in ("  | ", Pretty.blk (4,
berghofe@17144
   112
                [Pretty.str prfx, mk_term_of gr module' false T, Pretty.brk 1,
berghofe@17144
   113
                 if null Ts then Pretty.str (snd (get_const_id cname gr))
berghofe@16645
   114
                 else parens (Pretty.block
berghofe@17144
   115
                   [Pretty.str (snd (get_const_id cname gr)),
berghofe@13754
   116
                    Pretty.brk 1, mk_tuple args]),
berghofe@13754
   117
                 Pretty.str " =", Pretty.brk 1] @
skalberg@15570
   118
                 List.concat (separate [Pretty.str " $", Pretty.brk 1]
berghofe@13754
   119
                   ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
berghofe@13754
   120
                     mk_type false (Ts ---> T), Pretty.str ")"] ::
berghofe@17144
   121
                    map (fn (x, U) => [Pretty.block [mk_term_of gr module' false U,
berghofe@13754
   122
                      Pretty.brk 1, x]]) (args ~~ Ts)))))
berghofe@13754
   123
              end) (prfx, cs')
berghofe@14104
   124
          in eqs @ rest end;
berghofe@14104
   125
berghofe@17144
   126
    fun mk_gen_of_def gr prfx [] = []
berghofe@17144
   127
      | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   128
          let
berghofe@14104
   129
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@14104
   130
            val sorts = map (rpair []) tvs;
berghofe@14104
   131
            val (cs1, cs2) =
skalberg@15570
   132
              List.partition (exists DatatypeAux.is_rec_type o snd) cs;
skalberg@15531
   133
            val SOME (cname, _) = find_nonempty descr [i] i;
berghofe@14104
   134
berghofe@14104
   135
            fun mk_delay p = Pretty.block
berghofe@14104
   136
              [Pretty.str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   137
berghofe@15397
   138
            fun mk_constr s b (cname, dts) =
berghofe@14104
   139
              let
berghofe@17144
   140
                val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
berghofe@15397
   141
                    (DatatypeAux.typ_of_dtyp descr sorts dt))
berghofe@15397
   142
                  [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
berghofe@15397
   143
                     else "j")]) dts;
berghofe@17144
   144
                val (_, id) = get_const_id cname gr
berghofe@14104
   145
              in case gs of
berghofe@14104
   146
                  _ :: _ :: _ => Pretty.block
berghofe@14104
   147
                    [Pretty.str id, Pretty.brk 1, mk_tuple gs]
berghofe@14104
   148
                | _ => mk_app false (Pretty.str id) (map parens gs)
berghofe@14104
   149
              end;
berghofe@14104
   150
berghofe@15397
   151
            fun mk_choice [c] = mk_constr "(i-1)" false c
berghofe@14104
   152
              | mk_choice cs = Pretty.block [Pretty.str "one_of",
berghofe@14104
   153
                  Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
skalberg@15570
   154
                  List.concat (separate [Pretty.str ",", Pretty.fbrk]
berghofe@15397
   155
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
berghofe@14104
   156
                  [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
berghofe@14104
   157
berghofe@14104
   158
            val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
berghofe@17144
   159
            val gen_name = "gen_" ^ snd (get_type_id tname gr)
berghofe@14104
   160
berghofe@14104
   161
          in
berghofe@14104
   162
            Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   163
                (Pretty.str (prfx ^ gen_name ^
berghofe@14104
   164
                   (if null cs1 then "" else "'")) :: gs @
berghofe@14104
   165
                 (if null cs1 then [] else [Pretty.str "i"]) @
berghofe@14104
   166
                 [Pretty.str "j"]) @
berghofe@14104
   167
              [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   168
              (if not (null cs1) andalso not (null cs2)
berghofe@14104
   169
               then [Pretty.str "frequency", Pretty.brk 1,
berghofe@14104
   170
                 Pretty.blk (1, [Pretty.str "[",
berghofe@14104
   171
                   mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
berghofe@14104
   172
                   Pretty.str ",", Pretty.fbrk,
berghofe@14104
   173
                   mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
berghofe@14104
   174
                   Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
berghofe@14104
   175
               else if null cs2 then
berghofe@14104
   176
                 [Pretty.block [Pretty.str "(case", Pretty.brk 1,
berghofe@14104
   177
                   Pretty.str "i", Pretty.brk 1, Pretty.str "of",
berghofe@14104
   178
                   Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
haftmann@17521
   179
                   mk_constr "0" true (cname, valOf (AList.lookup (op =) cs cname)),
berghofe@14104
   180
                   Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
berghofe@14104
   181
                   mk_choice cs1, Pretty.str ")"]]
berghofe@14104
   182
               else [mk_choice cs2])) ::
berghofe@14104
   183
            (if null cs1 then []
berghofe@14104
   184
             else [Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   185
                 (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
berghofe@14104
   186
               [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   187
               separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
berghofe@14104
   188
                 [Pretty.str "i", Pretty.str "i"]))]) @
berghofe@17144
   189
            mk_gen_of_def gr "and " xs
berghofe@14104
   190
          end
berghofe@13754
   191
berghofe@12445
   192
  in
berghofe@17144
   193
    (add_edge_acyclic (node_id, dep) gr
berghofe@12445
   194
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   195
         let
berghofe@17144
   196
           val gr1 = add_edge (node_id, dep)
berghofe@17144
   197
             (new_node (node_id, (NONE, "", "")) gr);
berghofe@12445
   198
           val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
berghofe@12445
   199
         in
berghofe@17144
   200
           map_node node_id (K (NONE, module',
berghofe@12445
   201
             Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
berghofe@13754
   202
               [Pretty.str ";"])) ^ "\n\n" ^
berghofe@13754
   203
             (if "term_of" mem !mode then
berghofe@13754
   204
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@17144
   205
                  (mk_term_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@14104
   206
              else "") ^
berghofe@14104
   207
             (if "test" mem !mode then
berghofe@14104
   208
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@17144
   209
                  (mk_gen_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@13754
   210
              else ""))) gr2
berghofe@17144
   211
         end
berghofe@12445
   212
  end;
berghofe@12445
   213
berghofe@12445
   214
berghofe@12445
   215
(**** case expressions ****)
berghofe@12445
   216
berghofe@17144
   217
fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
berghofe@12445
   218
  let val i = length constrs
berghofe@12445
   219
  in if length ts <= i then
berghofe@17144
   220
       invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
berghofe@12445
   221
    else
berghofe@12445
   222
      let
skalberg@15570
   223
        val ts1 = Library.take (i, ts);
skalberg@15570
   224
        val t :: ts2 = Library.drop (i, ts);
skalberg@15574
   225
        val names = foldr add_term_names
skalberg@15574
   226
          (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
skalberg@15570
   227
        val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
berghofe@12445
   228
berghofe@12445
   229
        fun pcase gr [] [] [] = ([], gr)
berghofe@12445
   230
          | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
berghofe@12445
   231
              let
berghofe@12445
   232
                val j = length cargs;
wenzelm@20071
   233
                val xs = Name.variant_list names (replicate j "x");
skalberg@15570
   234
                val Us' = Library.take (j, fst (strip_type U));
berghofe@12445
   235
                val frees = map Free (xs ~~ Us');
berghofe@17144
   236
                val (gr0, cp) = invoke_codegen thy defs dep module false
berghofe@12445
   237
                  (gr, list_comb (Const (cname, Us' ---> dT), frees));
berghofe@12445
   238
                val t' = Envir.beta_norm (list_comb (t, frees));
berghofe@17144
   239
                val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
berghofe@12445
   240
                val (ps, gr2) = pcase gr1 cs ts Us;
berghofe@12445
   241
              in
berghofe@12445
   242
                ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   243
              end;
berghofe@12445
   244
berghofe@12445
   245
        val (ps1, gr1) = pcase gr constrs ts1 Ts;
skalberg@15570
   246
        val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
berghofe@17144
   247
        val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
berghofe@17144
   248
        val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
berghofe@12445
   249
      in (gr3, (if not (null ts2) andalso brack then parens else I)
berghofe@12445
   250
        (Pretty.block (separate (Pretty.brk 1)
berghofe@12445
   251
          (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
berghofe@12445
   252
             Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
berghofe@12445
   253
      end
berghofe@12445
   254
  end;
berghofe@12445
   255
berghofe@12445
   256
berghofe@12445
   257
(**** constructors ****)
berghofe@12445
   258
berghofe@17144
   259
fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
berghofe@12445
   260
  let val i = length args
berghofe@12445
   261
  in if i > 1 andalso length ts < i then
berghofe@17144
   262
      invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
berghofe@12445
   263
     else
berghofe@12445
   264
       let
berghofe@17144
   265
         val id = mk_qual_id module (get_const_id s gr);
berghofe@16645
   266
         val (gr', ps) = foldl_map
berghofe@17144
   267
           (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
berghofe@12445
   268
       in (case args of
berghofe@12445
   269
          _ :: _ :: _ => (gr', (if brack then parens else I)
berghofe@12445
   270
            (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
berghofe@12445
   271
        | _ => (gr', mk_app brack (Pretty.str id) ps))
berghofe@12445
   272
       end
berghofe@12445
   273
  end;
berghofe@12445
   274
berghofe@12445
   275
berghofe@12445
   276
(**** code generators for terms and types ****)
berghofe@12445
   277
berghofe@17144
   278
fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
berghofe@12445
   279
   (c as Const (s, T), ts) =>
haftmann@18247
   280
       (case Library.find_first (fn (_, {index, descr, case_name, ...}) =>
berghofe@12445
   281
         s = case_name orelse
haftmann@17521
   282
           AList.defined (op =) ((#3 o the o AList.lookup (op =) descr) index) s)
berghofe@12445
   283
             (Symtab.dest (DatatypePackage.get_datatypes thy)) of
skalberg@15531
   284
          NONE => NONE
skalberg@15531
   285
        | SOME (tname, {index, descr, ...}) =>
haftmann@18247
   286
           if is_some (get_assoc_code thy s T) then NONE else
haftmann@17521
   287
           let val SOME (_, _, constrs) = AList.lookup (op =) descr index
haftmann@17521
   288
           in (case (AList.lookup (op =) constrs s, strip_type T) of
berghofe@17144
   289
               (NONE, _) => SOME (pretty_case thy defs gr dep module brack
haftmann@18247
   290
                 ((#3 o the o AList.lookup (op =) descr) index) c ts)
berghofe@16645
   291
             | (SOME args, (_, Type _)) => SOME (pretty_constr thy defs
berghofe@17144
   292
                 (fst (invoke_tycodegen thy defs dep module false
berghofe@16645
   293
                    (gr, snd (strip_type T))))
berghofe@17144
   294
                 dep module brack args c ts)
skalberg@15531
   295
             | _ => NONE)
berghofe@12445
   296
           end)
skalberg@15531
   297
 |  _ => NONE);
berghofe@12445
   298
berghofe@17144
   299
fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
wenzelm@17412
   300
      (case Symtab.lookup (DatatypePackage.get_datatypes thy) s of
skalberg@15531
   301
         NONE => NONE
skalberg@15531
   302
       | SOME {descr, ...} =>
skalberg@15570
   303
           if isSome (get_assoc_type thy s) then NONE else
berghofe@16645
   304
           let
berghofe@16645
   305
             val (gr', ps) = foldl_map
berghofe@17144
   306
               (invoke_tycodegen thy defs dep module false) (gr, Ts);
berghofe@17144
   307
             val gr'' = add_dt_defs thy defs dep module gr' descr
berghofe@16645
   308
           in SOME (gr'',
berghofe@12445
   309
             Pretty.block ((if null Ts then [] else
berghofe@12445
   310
               [mk_tuple ps, Pretty.str " "]) @
berghofe@17144
   311
               [Pretty.str (mk_qual_id module (get_type_id s gr''))]))
berghofe@12445
   312
           end)
berghofe@16645
   313
  | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
berghofe@12445
   314
haftmann@18247
   315
haftmann@19346
   316
(** code 2nd generation **)
haftmann@19346
   317
haftmann@20177
   318
fun datatypes_dependency thy =
haftmann@20177
   319
  let
haftmann@20177
   320
    val dtnames = DatatypePackage.get_datatypes thy;
haftmann@20177
   321
    fun add_node (dtname, _) =
haftmann@20177
   322
      let
haftmann@20177
   323
        fun add_tycos (Type (tyco, tys)) = insert (op =) tyco #> fold add_tycos tys
haftmann@20177
   324
          | add_tycos _ = I;
haftmann@20177
   325
        val deps = (filter (Symtab.defined dtnames) o maps (fn ty =>
haftmann@20177
   326
          add_tycos ty [])
haftmann@20177
   327
            o maps snd o snd o the o DatatypePackage.get_datatype_spec thy) dtname
haftmann@20177
   328
      in
haftmann@20177
   329
        Graph.default_node (dtname, ())
haftmann@20177
   330
        #> fold (fn dtname' =>
haftmann@20177
   331
             Graph.default_node (dtname', ())
haftmann@20177
   332
             #> Graph.add_edge (dtname', dtname)
haftmann@20177
   333
           ) deps
haftmann@20177
   334
      end
haftmann@20177
   335
  in
haftmann@20177
   336
    Graph.empty
haftmann@20177
   337
    |> Symtab.fold add_node dtnames
haftmann@20177
   338
    |> Graph.strong_conn
haftmann@20177
   339
  end;
haftmann@20177
   340
haftmann@20382
   341
fun add_hook_bootstrap hook thy =
haftmann@20382
   342
  thy
haftmann@20382
   343
  |> fold hook (datatypes_dependency thy)
haftmann@20382
   344
  |> DatatypeHooks.add hook;
haftmann@20382
   345
haftmann@20177
   346
fun get_datatype_mut_specs thy (tycos as tyco :: _) =
haftmann@20177
   347
  let
haftmann@20177
   348
    val tycos' = (map (#1 o snd) o #descr o DatatypePackage.the_datatype thy) tyco;
haftmann@20177
   349
    val _ = if gen_subset (op =) (tycos, tycos') then () else
haftmann@20177
   350
      error ("datatype constructors are not mutually recursive: " ^ (commas o map quote) tycos);
haftmann@20177
   351
    val (vs::_, css) = split_list (map (the o DatatypePackage.get_datatype_spec thy) tycos);
haftmann@20177
   352
  in (vs, tycos ~~ css) end;
haftmann@20177
   353
haftmann@20177
   354
fun get_datatype_arities thy tycos sort =
haftmann@20177
   355
  let
haftmann@20177
   356
    val algebra = Sign.classes_of thy;
haftmann@20177
   357
    val (vs_proto, css_proto) = get_datatype_mut_specs thy tycos;
haftmann@20177
   358
    val vs = map (fn (v, vsort) => (v, Sorts.inter_sort algebra (vsort, sort))) vs_proto;
haftmann@20177
   359
    fun inst_type tyco (c, tys) =
haftmann@20177
   360
      let
haftmann@20177
   361
        val tys' = (map o map_atyps)
haftmann@20177
   362
          (fn TFree (v, _) => TFree (v, the (AList.lookup (op =) vs v))) tys
haftmann@20177
   363
      in (c, tys') end;
haftmann@20177
   364
    val css = map (fn (tyco, cs) => (tyco, (map (inst_type tyco) cs))) css_proto;
haftmann@20177
   365
    fun mk_arity tyco =
haftmann@20177
   366
      ((tyco, map snd vs), sort);
haftmann@20177
   367
    fun typ_of_sort ty =
haftmann@20177
   368
      let
haftmann@20177
   369
        val arities = map (fn (tyco, _) => ((tyco, map snd vs), sort)) css;
haftmann@20177
   370
      in ClassPackage.assume_arities_of_sort thy arities (ty, sort) end;
haftmann@20177
   371
    fun mk_cons tyco (c, tys) =
haftmann@20177
   372
      let
haftmann@20192
   373
        val ts = Name.names Name.context "a" tys;
haftmann@20177
   374
        val ty = tys ---> Type (tyco, map TFree vs);
haftmann@20177
   375
      in list_comb (Const (c, ty), map Free ts) end;
haftmann@20177
   376
  in if forall (fn (_, cs) => forall (fn (_, tys) => forall typ_of_sort tys) cs) css
haftmann@20177
   377
    then SOME (
haftmann@20177
   378
      map (fn (tyco, cs) => (tyco, (mk_arity tyco, map (mk_cons tyco) cs))) css
haftmann@20177
   379
    ) else NONE
haftmann@20177
   380
  end;
haftmann@20177
   381
haftmann@20182
   382
fun prove_arities tac tycos sort f thy =
haftmann@20177
   383
  case get_datatype_arities thy tycos sort
haftmann@20177
   384
   of NONE => thy
haftmann@20177
   385
    | SOME insts => let
haftmann@20177
   386
        fun proven ((tyco, asorts), sort) =
haftmann@20177
   387
          Sorts.of_sort (Sign.classes_of thy)
haftmann@20192
   388
            (Type (tyco, map TFree (Name.names Name.context "'a" asorts)), sort);
haftmann@20177
   389
        val (arities, css) = (split_list o map_filter
haftmann@20177
   390
          (fn (tyco, (arity, cs)) => if proven arity
haftmann@20182
   391
            then NONE else SOME (arity, (tyco, cs)))) insts;
haftmann@20177
   392
      in
haftmann@20177
   393
        thy
haftmann@20182
   394
        |> K ((not o null) arities) ? ClassPackage.prove_instance_arity tac
haftmann@20389
   395
             arities ("", []) (f thy arities css)
haftmann@20177
   396
      end;
haftmann@20177
   397
haftmann@20105
   398
fun dtyp_of_case_const thy c =
haftmann@20105
   399
  get_first (fn (dtco, { case_name, ... }) => if case_name = c then SOME dtco else NONE)
haftmann@20105
   400
    ((Symtab.dest o DatatypePackage.get_datatypes) thy);
haftmann@20105
   401
haftmann@20105
   402
fun dest_case_app cs ts tys =
haftmann@20105
   403
  let
haftmann@20192
   404
    val abs = Name.names Name.context "a" (Library.drop (length ts, tys));
haftmann@20105
   405
    val (ts', t) = split_last (ts @ map Free abs);
haftmann@20105
   406
    val (tys', sty) = split_last tys;
haftmann@20105
   407
    fun freenames_of t = fold_aterms
haftmann@20105
   408
      (fn Free (v, _) => insert (op =) v | _ => I) t [];
haftmann@20105
   409
    fun dest_case ((c, tys_decl), ty) t =
haftmann@20105
   410
      let
haftmann@20105
   411
        val (vs, t') = Term.strip_abs_eta (length tys_decl) t;
haftmann@20105
   412
        val c' = list_comb (Const (c, map snd vs ---> sty), map Free vs);
haftmann@20105
   413
      in (c', t') end;
haftmann@20105
   414
  in (abs, ((t, sty), map2 dest_case (cs ~~ tys') ts')) end;
haftmann@20105
   415
haftmann@20105
   416
fun dest_case_expr thy t =
haftmann@20105
   417
  case strip_comb t
haftmann@20105
   418
   of (Const (c, ty), ts) =>
haftmann@20105
   419
        (case dtyp_of_case_const thy c
haftmann@20105
   420
         of SOME dtco =>
haftmann@20105
   421
              let val (vs, cs) = (the o DatatypePackage.get_datatype_spec thy) dtco;
haftmann@20105
   422
              in SOME (dest_case_app cs ts (Library.take (length cs + 1, (fst o strip_type) ty))) end
haftmann@20105
   423
          | _ => NONE)
haftmann@20105
   424
    | _ => NONE;
haftmann@20105
   425
haftmann@19346
   426
fun datatype_tac thy dtco =
haftmann@19346
   427
  let
haftmann@19346
   428
    val ctxt = Context.init_proof thy;
haftmann@19346
   429
    val inject = (#inject o DatatypePackage.the_datatype thy) dtco;
haftmann@19346
   430
    val simpset = Simplifier.context ctxt
haftmann@19346
   431
      (MetaSimplifier.empty_ss addsimprocs [distinct_simproc]);
haftmann@19346
   432
  in
haftmann@19458
   433
    (TRY o ALLGOALS o match_tac) [HOL.eq_reflection]
haftmann@19346
   434
    THEN (
haftmann@19458
   435
      (ALLGOALS o match_tac) (eqTrueI :: inject)
haftmann@19346
   436
      ORELSE (ALLGOALS o simp_tac) simpset
haftmann@19346
   437
    )
haftmann@19458
   438
    THEN (ALLGOALS o match_tac) [HOL.refl, Drule.reflexive_thm]
haftmann@19346
   439
  end;
haftmann@19346
   440
haftmann@19346
   441
fun get_datatype_spec_thms thy dtco =
haftmann@19346
   442
  case DatatypePackage.get_datatype_spec thy dtco
haftmann@19346
   443
   of SOME vs_cos =>
haftmann@19346
   444
        SOME (vs_cos, datatype_tac thy dtco)
haftmann@19346
   445
    | NONE => NONE;
haftmann@19346
   446
haftmann@19599
   447
fun add_datatype_case_const dtco thy =
haftmann@19599
   448
  let
haftmann@20105
   449
    val {case_name, index, descr, ...} = DatatypePackage.the_datatype thy dtco;
haftmann@19599
   450
  in
haftmann@20105
   451
    CodegenPackage.add_appconst_i (case_name, CodegenPackage.appgen_case dest_case_expr) thy
haftmann@19599
   452
  end;
haftmann@19346
   453
haftmann@19818
   454
fun add_datatype_case_defs dtco thy =
haftmann@19818
   455
  let
haftmann@19818
   456
    val {case_rewrites, ...} = DatatypePackage.the_datatype thy dtco
haftmann@19818
   457
  in
haftmann@19818
   458
    fold CodegenTheorems.add_fun case_rewrites thy
haftmann@19818
   459
  end;
haftmann@19818
   460
haftmann@19008
   461
val setup = 
wenzelm@18708
   462
  add_codegen "datatype" datatype_codegen #>
wenzelm@18708
   463
  add_tycodegen "datatype" datatype_tycodegen #>
haftmann@19346
   464
  CodegenTheorems.add_datatype_extr
haftmann@19346
   465
    get_datatype_spec_thms #>
haftmann@20177
   466
  DatatypeHooks.add (fold add_datatype_case_const) #>
haftmann@20177
   467
  DatatypeHooks.add (fold add_datatype_case_defs)
berghofe@12445
   468
berghofe@12445
   469
end;