src/HOL/Tools/datatype_codegen.ML
author berghofe
Fri Jul 01 14:13:40 2005 +0200 (2005-07-01 ago)
changeset 16645 a152d6b21c31
parent 15574 b1d1b5bfc464
child 17144 6642e0f96f44
permissions -rw-r--r--
Adapted to modular code generation.
berghofe@12446
     1
(*  Title:      HOL/datatype_codegen.ML
berghofe@12445
     2
    ID:         $Id$
berghofe@12445
     3
    Author:     Stefan Berghofer, 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
berghofe@12445
    10
  val setup: (theory -> theory) list
berghofe@12445
    11
end;
berghofe@12445
    12
berghofe@12445
    13
structure DatatypeCodegen : DATATYPE_CODEGEN =
berghofe@12445
    14
struct
berghofe@12445
    15
berghofe@12445
    16
open Codegen;
berghofe@12445
    17
berghofe@12445
    18
fun mk_tuple [p] = p
berghofe@12445
    19
  | mk_tuple ps = Pretty.block (Pretty.str "(" ::
skalberg@15570
    20
      List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
berghofe@12445
    21
        [Pretty.str ")"]);
berghofe@12445
    22
berghofe@12445
    23
(**** datatype definition ****)
berghofe@12445
    24
berghofe@14104
    25
(* find shortest path to constructor with no recursive arguments *)
berghofe@14104
    26
berghofe@14104
    27
fun find_nonempty (descr: DatatypeAux.descr) is i =
berghofe@14104
    28
  let
skalberg@15570
    29
    val (_, _, constrs) = valOf (assoc (descr, i));
skalberg@15531
    30
    fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then NONE
skalberg@15570
    31
          else Option.map (curry op + 1 o snd) (find_nonempty descr (i::is) i)
skalberg@15531
    32
      | arg_nonempty _ = SOME 0;
skalberg@15570
    33
    fun max xs = Library.foldl
skalberg@15531
    34
      (fn (NONE, _) => NONE
skalberg@15531
    35
        | (SOME i, SOME j) => SOME (Int.max (i, j))
skalberg@15531
    36
        | (_, NONE) => NONE) (SOME 0, xs);
berghofe@14104
    37
    val xs = sort (int_ord o pairself snd)
skalberg@15570
    38
      (List.mapPartial (fn (s, dts) => Option.map (pair s)
berghofe@14104
    39
        (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
skalberg@15531
    40
  in case xs of [] => NONE | x :: _ => SOME x end;
berghofe@14104
    41
berghofe@16645
    42
fun add_dt_defs thy defs dep gr (descr: DatatypeAux.descr) =
berghofe@12445
    43
  let
berghofe@12445
    44
    val sg = sign_of thy;
berghofe@12445
    45
    val tab = DatatypePackage.get_datatypes thy;
berghofe@12445
    46
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@16645
    51
    val (_, (tname, _, (dname, _) :: _)) :: _ = descr';
berghofe@16645
    52
    val thyname = thyname_of_type tname thy;
berghofe@12445
    53
berghofe@12445
    54
    fun mk_dtdef gr prfx [] = (gr, [])
berghofe@12445
    55
      | mk_dtdef gr prfx ((_, (tname, dts, cs))::xs) =
berghofe@12445
    56
          let
berghofe@12445
    57
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@12445
    58
            val sorts = map (rpair []) tvs;
berghofe@12445
    59
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@12445
    60
            val (gr', ps) = foldl_map (fn (gr, (cname, cargs)) =>
berghofe@12445
    61
              apsnd (pair cname) (foldl_map
berghofe@16645
    62
                (invoke_tycodegen thy defs dname thyname false) (gr, cargs))) (gr, cs');
berghofe@12445
    63
            val (gr'', rest) = mk_dtdef gr' "and " xs
berghofe@12445
    64
          in
berghofe@12445
    65
            (gr'',
berghofe@12445
    66
             Pretty.block (Pretty.str prfx ::
berghofe@12445
    67
               (if null tvs then [] else
berghofe@12445
    68
                  [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
berghofe@16645
    69
               [Pretty.str (mk_type_id sg thyname thyname tname ^ " ="), Pretty.brk 1] @
skalberg@15570
    70
               List.concat (separate [Pretty.brk 1, Pretty.str "| "]
berghofe@12445
    71
                 (map (fn (cname, ps') => [Pretty.block
berghofe@16645
    72
                   (Pretty.str (mk_const_id sg thyname thyname cname) ::
berghofe@12445
    73
                    (if null ps' then [] else
skalberg@15570
    74
                     List.concat ([Pretty.str " of", Pretty.brk 1] ::
berghofe@12445
    75
                       separate [Pretty.str " *", Pretty.brk 1]
berghofe@12445
    76
                         (map single ps'))))]) ps))) :: rest)
berghofe@13754
    77
          end;
berghofe@13754
    78
berghofe@13754
    79
    fun mk_term_of_def prfx [] = []
berghofe@13754
    80
      | mk_term_of_def prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
    81
          let
berghofe@13754
    82
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@13754
    83
            val sorts = map (rpair []) tvs;
berghofe@13754
    84
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@13754
    85
            val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@13754
    86
            val T = Type (tname, dts');
berghofe@13754
    87
            val rest = mk_term_of_def "and " xs;
berghofe@13754
    88
            val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
berghofe@13754
    89
              let val args = map (fn i =>
berghofe@13754
    90
                Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
berghofe@13754
    91
              in ("  | ", Pretty.blk (4,
berghofe@16645
    92
                [Pretty.str prfx, mk_term_of thy thyname false T, Pretty.brk 1,
berghofe@16645
    93
                 if null Ts then Pretty.str (mk_const_id sg thyname thyname cname)
berghofe@16645
    94
                 else parens (Pretty.block
berghofe@16645
    95
                   [Pretty.str (mk_const_id sg thyname thyname cname),
berghofe@13754
    96
                    Pretty.brk 1, mk_tuple args]),
berghofe@13754
    97
                 Pretty.str " =", Pretty.brk 1] @
skalberg@15570
    98
                 List.concat (separate [Pretty.str " $", Pretty.brk 1]
berghofe@13754
    99
                   ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
berghofe@13754
   100
                     mk_type false (Ts ---> T), Pretty.str ")"] ::
berghofe@16645
   101
                    map (fn (x, U) => [Pretty.block [mk_term_of thy thyname false U,
berghofe@13754
   102
                      Pretty.brk 1, x]]) (args ~~ Ts)))))
berghofe@13754
   103
              end) (prfx, cs')
berghofe@14104
   104
          in eqs @ rest end;
berghofe@14104
   105
berghofe@14104
   106
    fun mk_gen_of_def prfx [] = []
berghofe@14104
   107
      | mk_gen_of_def prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   108
          let
berghofe@14104
   109
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@14104
   110
            val sorts = map (rpair []) tvs;
berghofe@14104
   111
            val (cs1, cs2) =
skalberg@15570
   112
              List.partition (exists DatatypeAux.is_rec_type o snd) cs;
skalberg@15531
   113
            val SOME (cname, _) = find_nonempty descr [i] i;
berghofe@14104
   114
berghofe@14104
   115
            fun mk_delay p = Pretty.block
berghofe@14104
   116
              [Pretty.str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   117
berghofe@15397
   118
            fun mk_constr s b (cname, dts) =
berghofe@14104
   119
              let
berghofe@16645
   120
                val gs = map (fn dt => mk_app false (mk_gen thy thyname false rtnames s
berghofe@15397
   121
                    (DatatypeAux.typ_of_dtyp descr sorts dt))
berghofe@15397
   122
                  [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
berghofe@15397
   123
                     else "j")]) dts;
berghofe@16645
   124
                val id = mk_const_id sg thyname thyname cname
berghofe@14104
   125
              in case gs of
berghofe@14104
   126
                  _ :: _ :: _ => Pretty.block
berghofe@14104
   127
                    [Pretty.str id, Pretty.brk 1, mk_tuple gs]
berghofe@14104
   128
                | _ => mk_app false (Pretty.str id) (map parens gs)
berghofe@14104
   129
              end;
berghofe@14104
   130
berghofe@15397
   131
            fun mk_choice [c] = mk_constr "(i-1)" false c
berghofe@14104
   132
              | mk_choice cs = Pretty.block [Pretty.str "one_of",
berghofe@14104
   133
                  Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
skalberg@15570
   134
                  List.concat (separate [Pretty.str ",", Pretty.fbrk]
berghofe@15397
   135
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
berghofe@14104
   136
                  [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
berghofe@14104
   137
berghofe@14104
   138
            val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
berghofe@16645
   139
            val gen_name = "gen_" ^ mk_type_id sg thyname thyname tname
berghofe@14104
   140
berghofe@14104
   141
          in
berghofe@14104
   142
            Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   143
                (Pretty.str (prfx ^ gen_name ^
berghofe@14104
   144
                   (if null cs1 then "" else "'")) :: gs @
berghofe@14104
   145
                 (if null cs1 then [] else [Pretty.str "i"]) @
berghofe@14104
   146
                 [Pretty.str "j"]) @
berghofe@14104
   147
              [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   148
              (if not (null cs1) andalso not (null cs2)
berghofe@14104
   149
               then [Pretty.str "frequency", Pretty.brk 1,
berghofe@14104
   150
                 Pretty.blk (1, [Pretty.str "[",
berghofe@14104
   151
                   mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
berghofe@14104
   152
                   Pretty.str ",", Pretty.fbrk,
berghofe@14104
   153
                   mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
berghofe@14104
   154
                   Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
berghofe@14104
   155
               else if null cs2 then
berghofe@14104
   156
                 [Pretty.block [Pretty.str "(case", Pretty.brk 1,
berghofe@14104
   157
                   Pretty.str "i", Pretty.brk 1, Pretty.str "of",
berghofe@14104
   158
                   Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
skalberg@15570
   159
                   mk_constr "0" true (cname, valOf (assoc (cs, cname))),
berghofe@14104
   160
                   Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
berghofe@14104
   161
                   mk_choice cs1, Pretty.str ")"]]
berghofe@14104
   162
               else [mk_choice cs2])) ::
berghofe@14104
   163
            (if null cs1 then []
berghofe@14104
   164
             else [Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   165
                 (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
berghofe@14104
   166
               [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   167
               separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
berghofe@14104
   168
                 [Pretty.str "i", Pretty.str "i"]))]) @
berghofe@14104
   169
            mk_gen_of_def "and " xs
berghofe@14104
   170
          end
berghofe@13754
   171
berghofe@12445
   172
  in
berghofe@12445
   173
    ((Graph.add_edge_acyclic (dname, dep) gr
berghofe@12445
   174
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   175
         let
berghofe@12445
   176
           val gr1 = Graph.add_edge (dname, dep)
berghofe@16645
   177
             (Graph.new_node (dname, (NONE, "", "")) gr);
berghofe@12445
   178
           val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
berghofe@12445
   179
         in
berghofe@16645
   180
           Graph.map_node dname (K (NONE, thyname,
berghofe@12445
   181
             Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
berghofe@13754
   182
               [Pretty.str ";"])) ^ "\n\n" ^
berghofe@13754
   183
             (if "term_of" mem !mode then
berghofe@13754
   184
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@14104
   185
                  (mk_term_of_def "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@14104
   186
              else "") ^
berghofe@14104
   187
             (if "test" mem !mode then
berghofe@14104
   188
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@14104
   189
                  (mk_gen_of_def "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@13754
   190
              else ""))) gr2
berghofe@16645
   191
         end, thyname)
berghofe@12445
   192
  end;
berghofe@12445
   193
berghofe@12445
   194
berghofe@12445
   195
(**** case expressions ****)
berghofe@12445
   196
berghofe@16645
   197
fun pretty_case thy defs gr dep thyname brack constrs (c as Const (_, T)) ts =
berghofe@12445
   198
  let val i = length constrs
berghofe@12445
   199
  in if length ts <= i then
berghofe@16645
   200
       invoke_codegen thy defs dep thyname brack (gr, eta_expand c ts (i+1))
berghofe@12445
   201
    else
berghofe@12445
   202
      let
skalberg@15570
   203
        val ts1 = Library.take (i, ts);
skalberg@15570
   204
        val t :: ts2 = Library.drop (i, ts);
skalberg@15574
   205
        val names = foldr add_term_names
skalberg@15574
   206
          (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
skalberg@15570
   207
        val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
berghofe@12445
   208
berghofe@12445
   209
        fun pcase gr [] [] [] = ([], gr)
berghofe@12445
   210
          | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
berghofe@12445
   211
              let
berghofe@12445
   212
                val j = length cargs;
berghofe@12445
   213
                val xs = variantlist (replicate j "x", names);
skalberg@15570
   214
                val Us' = Library.take (j, fst (strip_type U));
berghofe@12445
   215
                val frees = map Free (xs ~~ Us');
berghofe@16645
   216
                val (gr0, cp) = invoke_codegen thy defs dep thyname false
berghofe@12445
   217
                  (gr, list_comb (Const (cname, Us' ---> dT), frees));
berghofe@12445
   218
                val t' = Envir.beta_norm (list_comb (t, frees));
berghofe@16645
   219
                val (gr1, p) = invoke_codegen thy defs dep thyname false (gr0, t');
berghofe@12445
   220
                val (ps, gr2) = pcase gr1 cs ts Us;
berghofe@12445
   221
              in
berghofe@12445
   222
                ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   223
              end;
berghofe@12445
   224
berghofe@12445
   225
        val (ps1, gr1) = pcase gr constrs ts1 Ts;
skalberg@15570
   226
        val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
berghofe@16645
   227
        val (gr2, p) = invoke_codegen thy defs dep thyname false (gr1, t);
berghofe@16645
   228
        val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep thyname true) (gr2, ts2)
berghofe@12445
   229
      in (gr3, (if not (null ts2) andalso brack then parens else I)
berghofe@12445
   230
        (Pretty.block (separate (Pretty.brk 1)
berghofe@12445
   231
          (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
berghofe@12445
   232
             Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
berghofe@12445
   233
      end
berghofe@12445
   234
  end;
berghofe@12445
   235
berghofe@12445
   236
berghofe@12445
   237
(**** constructors ****)
berghofe@12445
   238
berghofe@16645
   239
fun pretty_constr thy defs gr dep thyname brack args (c as Const (s, T)) ts =
berghofe@12445
   240
  let val i = length args
berghofe@12445
   241
  in if i > 1 andalso length ts < i then
berghofe@16645
   242
      invoke_codegen thy defs dep thyname brack (gr, eta_expand c ts i)
berghofe@12445
   243
     else
berghofe@12445
   244
       let
berghofe@16645
   245
         val thyname' = thyname_of_type (fst (dest_Type (body_type T))) thy;
berghofe@16645
   246
         val id = mk_const_id (sign_of thy) thyname thyname' s;
berghofe@16645
   247
         val (gr', ps) = foldl_map
berghofe@16645
   248
           (invoke_codegen thy defs dep thyname (i = 1)) (gr, ts);
berghofe@12445
   249
       in (case args of
berghofe@12445
   250
          _ :: _ :: _ => (gr', (if brack then parens else I)
berghofe@12445
   251
            (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
berghofe@12445
   252
        | _ => (gr', mk_app brack (Pretty.str id) ps))
berghofe@12445
   253
       end
berghofe@12445
   254
  end;
berghofe@12445
   255
berghofe@12445
   256
berghofe@12445
   257
(**** code generators for terms and types ****)
berghofe@12445
   258
berghofe@16645
   259
fun datatype_codegen thy defs gr dep thyname brack t = (case strip_comb t of
berghofe@12445
   260
   (c as Const (s, T), ts) =>
berghofe@12445
   261
       (case find_first (fn (_, {index, descr, case_name, ...}) =>
berghofe@12445
   262
         s = case_name orelse
skalberg@15570
   263
           isSome (assoc (#3 (valOf (assoc (descr, index))), s)))
berghofe@12445
   264
             (Symtab.dest (DatatypePackage.get_datatypes thy)) of
skalberg@15531
   265
          NONE => NONE
skalberg@15531
   266
        | SOME (tname, {index, descr, ...}) =>
skalberg@15570
   267
           if isSome (get_assoc_code thy s T) then NONE else
skalberg@15531
   268
           let val SOME (_, _, constrs) = assoc (descr, index)
berghofe@12822
   269
           in (case (assoc (constrs, s), strip_type T) of
berghofe@16645
   270
               (NONE, _) => SOME (pretty_case thy defs gr dep thyname brack
skalberg@15570
   271
                 (#3 (valOf (assoc (descr, index)))) c ts)
berghofe@16645
   272
             | (SOME args, (_, Type _)) => SOME (pretty_constr thy defs
berghofe@16645
   273
                 (fst (invoke_tycodegen thy defs dep thyname false
berghofe@16645
   274
                    (gr, snd (strip_type T))))
berghofe@16645
   275
                 dep thyname brack args c ts)
skalberg@15531
   276
             | _ => NONE)
berghofe@12445
   277
           end)
skalberg@15531
   278
 |  _ => NONE);
berghofe@12445
   279
berghofe@16645
   280
fun datatype_tycodegen thy defs gr dep thyname brack (Type (s, Ts)) =
berghofe@12445
   281
      (case Symtab.lookup (DatatypePackage.get_datatypes thy, s) of
skalberg@15531
   282
         NONE => NONE
skalberg@15531
   283
       | SOME {descr, ...} =>
skalberg@15570
   284
           if isSome (get_assoc_type thy s) then NONE else
berghofe@16645
   285
           let
berghofe@16645
   286
             val (gr', ps) = foldl_map
berghofe@16645
   287
               (invoke_tycodegen thy defs dep thyname false) (gr, Ts);
berghofe@16645
   288
             val (gr'', thyname') = add_dt_defs thy defs dep gr' descr
berghofe@16645
   289
           in SOME (gr'',
berghofe@12445
   290
             Pretty.block ((if null Ts then [] else
berghofe@12445
   291
               [mk_tuple ps, Pretty.str " "]) @
berghofe@16645
   292
               [Pretty.str (mk_type_id (sign_of thy) thyname thyname' s)]))
berghofe@12445
   293
           end)
berghofe@16645
   294
  | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
berghofe@12445
   295
berghofe@12445
   296
berghofe@12445
   297
val setup =
berghofe@12445
   298
  [add_codegen "datatype" datatype_codegen,
berghofe@12445
   299
   add_tycodegen "datatype" datatype_tycodegen];
berghofe@12445
   300
berghofe@12445
   301
end;