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