src/HOL/Tools/datatype_codegen.ML
author skalberg
Sun Feb 13 17:15:14 2005 +0100 (2005-02-13 ago)
changeset 15531 08c8dad8e399
parent 15397 5260ac75e07c
child 15570 8d8c70b41bab
permissions -rw-r--r--
Deleted Library.option type.
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 "(" ::
berghofe@12445
    20
      flat (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
berghofe@14104
    29
    val (_, _, constrs) = the (assoc (descr, i));
skalberg@15531
    30
    fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then NONE
berghofe@14104
    31
          else apsome (curry op + 1 o snd) (find_nonempty descr (i::is) i)
skalberg@15531
    32
      | arg_nonempty _ = SOME 0;
berghofe@14104
    33
    fun max xs = 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)
berghofe@14104
    38
      (mapfilter (fn (s, dts) => apsome (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
wenzelm@12890
    42
fun add_dt_defs thy 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
berghofe@12445
    47
    val descr' = filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
berghofe@14104
    48
    val rtnames = map (#1 o snd) (filter (fn (_, (_, _, cs)) =>
berghofe@14104
    49
      exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
berghofe@12445
    50
berghofe@12445
    51
    val (_, (_, _, (cname, _) :: _)) :: _ = descr';
berghofe@12445
    52
    val dname = mk_const_id sg cname;
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@12445
    62
                (invoke_tycodegen thy dname 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@12445
    69
               [Pretty.str (mk_type_id sg tname ^ " ="), Pretty.brk 1] @
berghofe@12445
    70
               flat (separate [Pretty.brk 1, Pretty.str "| "]
berghofe@12445
    71
                 (map (fn (cname, ps') => [Pretty.block
berghofe@12445
    72
                   (Pretty.str (mk_const_id sg cname) ::
berghofe@12445
    73
                    (if null ps' then [] else
berghofe@12445
    74
                     flat ([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@13754
    92
                [Pretty.str prfx, mk_term_of sg false T, Pretty.brk 1,
berghofe@13754
    93
                 if null Ts then Pretty.str (mk_const_id sg cname)
berghofe@13754
    94
                 else parens (Pretty.block [Pretty.str (mk_const_id sg cname),
berghofe@13754
    95
                    Pretty.brk 1, mk_tuple args]),
berghofe@13754
    96
                 Pretty.str " =", Pretty.brk 1] @
berghofe@13754
    97
                 flat (separate [Pretty.str " $", Pretty.brk 1]
berghofe@13754
    98
                   ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
berghofe@13754
    99
                     mk_type false (Ts ---> T), Pretty.str ")"] ::
berghofe@13754
   100
                    map (fn (x, U) => [Pretty.block [mk_term_of sg false U,
berghofe@13754
   101
                      Pretty.brk 1, x]]) (args ~~ Ts)))))
berghofe@13754
   102
              end) (prfx, cs')
berghofe@14104
   103
          in eqs @ rest end;
berghofe@14104
   104
berghofe@14104
   105
    fun mk_gen_of_def prfx [] = []
berghofe@14104
   106
      | mk_gen_of_def prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   107
          let
berghofe@14104
   108
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@14104
   109
            val sorts = map (rpair []) tvs;
berghofe@14104
   110
            val (cs1, cs2) =
berghofe@14104
   111
              partition (exists DatatypeAux.is_rec_type o snd) cs;
skalberg@15531
   112
            val SOME (cname, _) = find_nonempty descr [i] i;
berghofe@14104
   113
berghofe@14104
   114
            fun mk_delay p = Pretty.block
berghofe@14104
   115
              [Pretty.str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   116
berghofe@15397
   117
            fun mk_constr s b (cname, dts) =
berghofe@14104
   118
              let
berghofe@15397
   119
                val gs = map (fn dt => mk_app false (mk_gen sg false rtnames s
berghofe@15397
   120
                    (DatatypeAux.typ_of_dtyp descr sorts dt))
berghofe@15397
   121
                  [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
berghofe@15397
   122
                     else "j")]) dts;
berghofe@14104
   123
                val id = mk_const_id sg cname
berghofe@14104
   124
              in case gs of
berghofe@14104
   125
                  _ :: _ :: _ => Pretty.block
berghofe@14104
   126
                    [Pretty.str id, Pretty.brk 1, mk_tuple gs]
berghofe@14104
   127
                | _ => mk_app false (Pretty.str id) (map parens gs)
berghofe@14104
   128
              end;
berghofe@14104
   129
berghofe@15397
   130
            fun mk_choice [c] = mk_constr "(i-1)" false c
berghofe@14104
   131
              | mk_choice cs = Pretty.block [Pretty.str "one_of",
berghofe@14104
   132
                  Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
berghofe@14104
   133
                  flat (separate [Pretty.str ",", Pretty.fbrk]
berghofe@15397
   134
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
berghofe@14104
   135
                  [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
berghofe@14104
   136
berghofe@14104
   137
            val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
berghofe@14104
   138
            val gen_name = "gen_" ^ mk_type_id sg tname
berghofe@14104
   139
berghofe@14104
   140
          in
berghofe@14104
   141
            Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   142
                (Pretty.str (prfx ^ gen_name ^
berghofe@14104
   143
                   (if null cs1 then "" else "'")) :: gs @
berghofe@14104
   144
                 (if null cs1 then [] else [Pretty.str "i"]) @
berghofe@14104
   145
                 [Pretty.str "j"]) @
berghofe@14104
   146
              [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   147
              (if not (null cs1) andalso not (null cs2)
berghofe@14104
   148
               then [Pretty.str "frequency", Pretty.brk 1,
berghofe@14104
   149
                 Pretty.blk (1, [Pretty.str "[",
berghofe@14104
   150
                   mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
berghofe@14104
   151
                   Pretty.str ",", Pretty.fbrk,
berghofe@14104
   152
                   mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
berghofe@14104
   153
                   Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
berghofe@14104
   154
               else if null cs2 then
berghofe@14104
   155
                 [Pretty.block [Pretty.str "(case", Pretty.brk 1,
berghofe@14104
   156
                   Pretty.str "i", Pretty.brk 1, Pretty.str "of",
berghofe@14104
   157
                   Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
berghofe@15397
   158
                   mk_constr "0" true (cname, the (assoc (cs, cname))),
berghofe@14104
   159
                   Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
berghofe@14104
   160
                   mk_choice cs1, Pretty.str ")"]]
berghofe@14104
   161
               else [mk_choice cs2])) ::
berghofe@14104
   162
            (if null cs1 then []
berghofe@14104
   163
             else [Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   164
                 (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
berghofe@14104
   165
               [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   166
               separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
berghofe@14104
   167
                 [Pretty.str "i", Pretty.str "i"]))]) @
berghofe@14104
   168
            mk_gen_of_def "and " xs
berghofe@14104
   169
          end
berghofe@13754
   170
berghofe@12445
   171
  in
berghofe@12445
   172
    ((Graph.add_edge_acyclic (dname, dep) gr
berghofe@12445
   173
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   174
         let
berghofe@12445
   175
           val gr1 = Graph.add_edge (dname, dep)
skalberg@15531
   176
             (Graph.new_node (dname, (NONE, "")) gr);
berghofe@12445
   177
           val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
berghofe@12445
   178
         in
skalberg@15531
   179
           Graph.map_node dname (K (NONE,
berghofe@12445
   180
             Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
berghofe@13754
   181
               [Pretty.str ";"])) ^ "\n\n" ^
berghofe@13754
   182
             (if "term_of" mem !mode then
berghofe@13754
   183
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@14104
   184
                  (mk_term_of_def "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@14104
   185
              else "") ^
berghofe@14104
   186
             (if "test" mem !mode then
berghofe@14104
   187
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@14104
   188
                  (mk_gen_of_def "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@13754
   189
              else ""))) gr2
berghofe@12445
   190
         end)
berghofe@12445
   191
  end;
berghofe@12445
   192
berghofe@12445
   193
berghofe@12445
   194
(**** case expressions ****)
berghofe@12445
   195
berghofe@12445
   196
fun pretty_case thy gr dep brack constrs (c as Const (_, T)) ts =
berghofe@12445
   197
  let val i = length constrs
berghofe@12445
   198
  in if length ts <= i then
berghofe@12445
   199
       invoke_codegen thy dep brack (gr, eta_expand c ts (i+1))
berghofe@12445
   200
    else
berghofe@12445
   201
      let
berghofe@12445
   202
        val ts1 = take (i, ts);
berghofe@12445
   203
        val t :: ts2 = drop (i, ts);
berghofe@12445
   204
        val names = foldr add_term_names (ts1,
berghofe@12445
   205
          map (fst o fst o dest_Var) (foldr add_term_vars (ts1, [])));
berghofe@12445
   206
        val (Ts, dT) = split_last (take (i+1, fst (strip_type T)));
berghofe@12445
   207
berghofe@12445
   208
        fun pcase gr [] [] [] = ([], gr)
berghofe@12445
   209
          | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
berghofe@12445
   210
              let
berghofe@12445
   211
                val j = length cargs;
berghofe@12445
   212
                val xs = variantlist (replicate j "x", names);
berghofe@12445
   213
                val Us' = take (j, fst (strip_type U));
berghofe@12445
   214
                val frees = map Free (xs ~~ Us');
berghofe@12445
   215
                val (gr0, cp) = invoke_codegen thy dep false
berghofe@12445
   216
                  (gr, list_comb (Const (cname, Us' ---> dT), frees));
berghofe@12445
   217
                val t' = Envir.beta_norm (list_comb (t, frees));
berghofe@12445
   218
                val (gr1, p) = invoke_codegen thy dep false (gr0, t');
berghofe@12445
   219
                val (ps, gr2) = pcase gr1 cs ts Us;
berghofe@12445
   220
              in
berghofe@12445
   221
                ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   222
              end;
berghofe@12445
   223
berghofe@12445
   224
        val (ps1, gr1) = pcase gr constrs ts1 Ts;
berghofe@12445
   225
        val ps = flat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
berghofe@12445
   226
        val (gr2, p) = invoke_codegen thy dep false (gr1, t);
berghofe@12445
   227
        val (gr3, ps2) = foldl_map (invoke_codegen thy dep true) (gr2, ts2)
berghofe@12445
   228
      in (gr3, (if not (null ts2) andalso brack then parens else I)
berghofe@12445
   229
        (Pretty.block (separate (Pretty.brk 1)
berghofe@12445
   230
          (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
berghofe@12445
   231
             Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
berghofe@12445
   232
      end
berghofe@12445
   233
  end;
berghofe@12445
   234
berghofe@12445
   235
berghofe@12445
   236
(**** constructors ****)
berghofe@12445
   237
berghofe@12445
   238
fun pretty_constr thy gr dep brack args (c as Const (s, _)) ts =
berghofe@12445
   239
  let val i = length args
berghofe@12445
   240
  in if i > 1 andalso length ts < i then
berghofe@12445
   241
      invoke_codegen thy dep brack (gr, eta_expand c ts i)
berghofe@12445
   242
     else
berghofe@12445
   243
       let
berghofe@12445
   244
         val id = mk_const_id (sign_of thy) s;
berghofe@12445
   245
         val (gr', ps) = foldl_map (invoke_codegen thy dep (i = 1)) (gr, ts);
berghofe@12445
   246
       in (case args of
berghofe@12445
   247
          _ :: _ :: _ => (gr', (if brack then parens else I)
berghofe@12445
   248
            (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
berghofe@12445
   249
        | _ => (gr', mk_app brack (Pretty.str id) ps))
berghofe@12445
   250
       end
berghofe@12445
   251
  end;
berghofe@12445
   252
berghofe@12445
   253
berghofe@12445
   254
(**** code generators for terms and types ****)
berghofe@12445
   255
berghofe@12445
   256
fun datatype_codegen thy gr dep brack t = (case strip_comb t of
berghofe@12445
   257
   (c as Const (s, T), ts) =>
berghofe@12445
   258
       (case find_first (fn (_, {index, descr, case_name, ...}) =>
berghofe@12445
   259
         s = case_name orelse
berghofe@12445
   260
           is_some (assoc (#3 (the (assoc (descr, index))), s)))
berghofe@12445
   261
             (Symtab.dest (DatatypePackage.get_datatypes thy)) of
skalberg@15531
   262
          NONE => NONE
skalberg@15531
   263
        | SOME (tname, {index, descr, ...}) =>
skalberg@15531
   264
           if is_some (get_assoc_code thy s T) then NONE else
skalberg@15531
   265
           let val SOME (_, _, constrs) = assoc (descr, index)
berghofe@12822
   266
           in (case (assoc (constrs, s), strip_type T) of
skalberg@15531
   267
               (NONE, _) => SOME (pretty_case thy gr dep brack
berghofe@12445
   268
                 (#3 (the (assoc (descr, index)))) c ts)
skalberg@15531
   269
             | (SOME args, (_, Type _)) => SOME (pretty_constr thy
berghofe@12445
   270
                 (fst (invoke_tycodegen thy dep false (gr, snd (strip_type T))))
berghofe@12822
   271
                 dep brack args c ts)
skalberg@15531
   272
             | _ => NONE)
berghofe@12445
   273
           end)
skalberg@15531
   274
 |  _ => NONE);
berghofe@12445
   275
berghofe@12445
   276
fun datatype_tycodegen thy gr dep brack (Type (s, Ts)) =
berghofe@12445
   277
      (case Symtab.lookup (DatatypePackage.get_datatypes thy, s) of
skalberg@15531
   278
         NONE => NONE
skalberg@15531
   279
       | SOME {descr, ...} =>
skalberg@15531
   280
           if is_some (get_assoc_type thy s) then NONE else
berghofe@12445
   281
           let val (gr', ps) = foldl_map
berghofe@12445
   282
             (invoke_tycodegen thy dep false) (gr, Ts)
skalberg@15531
   283
           in SOME (add_dt_defs thy dep gr' descr,
berghofe@12445
   284
             Pretty.block ((if null Ts then [] else
berghofe@12445
   285
               [mk_tuple ps, Pretty.str " "]) @
berghofe@12445
   286
               [Pretty.str (mk_type_id (sign_of thy) s)]))
berghofe@12445
   287
           end)
skalberg@15531
   288
  | datatype_tycodegen _ _ _ _ _ = NONE;
berghofe@12445
   289
berghofe@12445
   290
berghofe@12445
   291
val setup =
berghofe@12445
   292
  [add_codegen "datatype" datatype_codegen,
berghofe@12445
   293
   add_tycodegen "datatype" datatype_tycodegen];
berghofe@12445
   294
berghofe@12445
   295
end;