src/HOL/Tools/datatype_codegen.ML
author haftmann
Fri Feb 10 09:09:07 2006 +0100 (2006-02-10)
changeset 19008 14c1b2f5dda4
parent 18963 3adfc9dfb30a
child 19346 c4c003abd830
permissions -rw-r--r--
improved code generator devarification
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
wenzelm@18708
    10
  val setup: theory -> theory
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
haftmann@17521
    29
    val (_, _, constrs) = valOf (AList.lookup (op =) 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@17144
    42
fun add_dt_defs thy defs dep module 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@17144
    51
    val (_, (tname, _, _)) :: _ = descr';
berghofe@17144
    52
    val node_id = tname ^ " (type)";
berghofe@17144
    53
    val module' = if_library (thyname_of_type tname thy) module;
berghofe@12445
    54
berghofe@12445
    55
    fun mk_dtdef gr prfx [] = (gr, [])
berghofe@12445
    56
      | mk_dtdef gr prfx ((_, (tname, dts, cs))::xs) =
berghofe@12445
    57
          let
berghofe@12445
    58
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@12445
    59
            val sorts = map (rpair []) tvs;
berghofe@12445
    60
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@17144
    61
            val (gr', (_, type_id)) = mk_type_id module' tname gr;
berghofe@17144
    62
            val (gr'', ps) =
berghofe@17144
    63
              foldl_map (fn (gr, (cname, cargs)) =>
berghofe@17144
    64
                foldl_map (invoke_tycodegen thy defs node_id module' false)
berghofe@17144
    65
                  (gr, cargs) |>>>
berghofe@17144
    66
                mk_const_id module' cname) (gr', cs');
berghofe@17144
    67
            val (gr''', rest) = mk_dtdef gr'' "and " xs
berghofe@12445
    68
          in
berghofe@17144
    69
            (gr''',
berghofe@12445
    70
             Pretty.block (Pretty.str prfx ::
berghofe@12445
    71
               (if null tvs then [] else
berghofe@12445
    72
                  [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
berghofe@17144
    73
               [Pretty.str (type_id ^ " ="), Pretty.brk 1] @
skalberg@15570
    74
               List.concat (separate [Pretty.brk 1, Pretty.str "| "]
berghofe@17144
    75
                 (map (fn (ps', (_, cname)) => [Pretty.block
berghofe@17144
    76
                   (Pretty.str cname ::
berghofe@12445
    77
                    (if null ps' then [] else
skalberg@15570
    78
                     List.concat ([Pretty.str " of", Pretty.brk 1] ::
berghofe@12445
    79
                       separate [Pretty.str " *", Pretty.brk 1]
berghofe@12445
    80
                         (map single ps'))))]) ps))) :: rest)
berghofe@13754
    81
          end;
berghofe@13754
    82
berghofe@17144
    83
    fun mk_term_of_def gr prfx [] = []
berghofe@17144
    84
      | mk_term_of_def gr prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
    85
          let
berghofe@13754
    86
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@13754
    87
            val sorts = map (rpair []) tvs;
berghofe@13754
    88
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@13754
    89
            val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@13754
    90
            val T = Type (tname, dts');
berghofe@17144
    91
            val rest = mk_term_of_def gr "and " xs;
berghofe@13754
    92
            val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
berghofe@13754
    93
              let val args = map (fn i =>
berghofe@13754
    94
                Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
berghofe@13754
    95
              in ("  | ", Pretty.blk (4,
berghofe@17144
    96
                [Pretty.str prfx, mk_term_of gr module' false T, Pretty.brk 1,
berghofe@17144
    97
                 if null Ts then Pretty.str (snd (get_const_id cname gr))
berghofe@16645
    98
                 else parens (Pretty.block
berghofe@17144
    99
                   [Pretty.str (snd (get_const_id cname gr)),
berghofe@13754
   100
                    Pretty.brk 1, mk_tuple args]),
berghofe@13754
   101
                 Pretty.str " =", Pretty.brk 1] @
skalberg@15570
   102
                 List.concat (separate [Pretty.str " $", Pretty.brk 1]
berghofe@13754
   103
                   ([Pretty.str ("Const (\"" ^ cname ^ "\","), Pretty.brk 1,
berghofe@13754
   104
                     mk_type false (Ts ---> T), Pretty.str ")"] ::
berghofe@17144
   105
                    map (fn (x, U) => [Pretty.block [mk_term_of gr module' false U,
berghofe@13754
   106
                      Pretty.brk 1, x]]) (args ~~ Ts)))))
berghofe@13754
   107
              end) (prfx, cs')
berghofe@14104
   108
          in eqs @ rest end;
berghofe@14104
   109
berghofe@17144
   110
    fun mk_gen_of_def gr prfx [] = []
berghofe@17144
   111
      | mk_gen_of_def gr prfx ((i, (tname, dts, cs)) :: xs) =
berghofe@14104
   112
          let
berghofe@14104
   113
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@14104
   114
            val sorts = map (rpair []) tvs;
berghofe@14104
   115
            val (cs1, cs2) =
skalberg@15570
   116
              List.partition (exists DatatypeAux.is_rec_type o snd) cs;
skalberg@15531
   117
            val SOME (cname, _) = find_nonempty descr [i] i;
berghofe@14104
   118
berghofe@14104
   119
            fun mk_delay p = Pretty.block
berghofe@14104
   120
              [Pretty.str "fn () =>", Pretty.brk 1, p];
berghofe@14104
   121
berghofe@15397
   122
            fun mk_constr s b (cname, dts) =
berghofe@14104
   123
              let
berghofe@17144
   124
                val gs = map (fn dt => mk_app false (mk_gen gr module' false rtnames s
berghofe@15397
   125
                    (DatatypeAux.typ_of_dtyp descr sorts dt))
berghofe@15397
   126
                  [Pretty.str (if b andalso DatatypeAux.is_rec_type dt then "0"
berghofe@15397
   127
                     else "j")]) dts;
berghofe@17144
   128
                val (_, id) = get_const_id cname gr
berghofe@14104
   129
              in case gs of
berghofe@14104
   130
                  _ :: _ :: _ => Pretty.block
berghofe@14104
   131
                    [Pretty.str id, Pretty.brk 1, mk_tuple gs]
berghofe@14104
   132
                | _ => mk_app false (Pretty.str id) (map parens gs)
berghofe@14104
   133
              end;
berghofe@14104
   134
berghofe@15397
   135
            fun mk_choice [c] = mk_constr "(i-1)" false c
berghofe@14104
   136
              | mk_choice cs = Pretty.block [Pretty.str "one_of",
berghofe@14104
   137
                  Pretty.brk 1, Pretty.blk (1, Pretty.str "[" ::
skalberg@15570
   138
                  List.concat (separate [Pretty.str ",", Pretty.fbrk]
berghofe@15397
   139
                    (map (single o mk_delay o mk_constr "(i-1)" false) cs)) @
berghofe@14104
   140
                  [Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"];
berghofe@14104
   141
berghofe@14104
   142
            val gs = map (Pretty.str o suffix "G" o strip_tname) tvs;
berghofe@17144
   143
            val gen_name = "gen_" ^ snd (get_type_id tname gr)
berghofe@14104
   144
berghofe@14104
   145
          in
berghofe@14104
   146
            Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   147
                (Pretty.str (prfx ^ gen_name ^
berghofe@14104
   148
                   (if null cs1 then "" else "'")) :: gs @
berghofe@14104
   149
                 (if null cs1 then [] else [Pretty.str "i"]) @
berghofe@14104
   150
                 [Pretty.str "j"]) @
berghofe@14104
   151
              [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   152
              (if not (null cs1) andalso not (null cs2)
berghofe@14104
   153
               then [Pretty.str "frequency", Pretty.brk 1,
berghofe@14104
   154
                 Pretty.blk (1, [Pretty.str "[",
berghofe@14104
   155
                   mk_tuple [Pretty.str "i", mk_delay (mk_choice cs1)],
berghofe@14104
   156
                   Pretty.str ",", Pretty.fbrk,
berghofe@14104
   157
                   mk_tuple [Pretty.str "1", mk_delay (mk_choice cs2)],
berghofe@14104
   158
                   Pretty.str "]"]), Pretty.brk 1, Pretty.str "()"]
berghofe@14104
   159
               else if null cs2 then
berghofe@14104
   160
                 [Pretty.block [Pretty.str "(case", Pretty.brk 1,
berghofe@14104
   161
                   Pretty.str "i", Pretty.brk 1, Pretty.str "of",
berghofe@14104
   162
                   Pretty.brk 1, Pretty.str "0 =>", Pretty.brk 1,
haftmann@17521
   163
                   mk_constr "0" true (cname, valOf (AList.lookup (op =) cs cname)),
berghofe@14104
   164
                   Pretty.brk 1, Pretty.str "| _ =>", Pretty.brk 1,
berghofe@14104
   165
                   mk_choice cs1, Pretty.str ")"]]
berghofe@14104
   166
               else [mk_choice cs2])) ::
berghofe@14104
   167
            (if null cs1 then []
berghofe@14104
   168
             else [Pretty.blk (4, separate (Pretty.brk 1) 
berghofe@14104
   169
                 (Pretty.str ("and " ^ gen_name) :: gs @ [Pretty.str "i"]) @
berghofe@14104
   170
               [Pretty.str " =", Pretty.brk 1] @
berghofe@14104
   171
               separate (Pretty.brk 1) (Pretty.str (gen_name ^ "'") :: gs @
berghofe@14104
   172
                 [Pretty.str "i", Pretty.str "i"]))]) @
berghofe@17144
   173
            mk_gen_of_def gr "and " xs
berghofe@14104
   174
          end
berghofe@13754
   175
berghofe@12445
   176
  in
berghofe@17144
   177
    (add_edge_acyclic (node_id, dep) gr
berghofe@12445
   178
        handle Graph.CYCLES _ => gr) handle Graph.UNDEF _ =>
berghofe@12445
   179
         let
berghofe@17144
   180
           val gr1 = add_edge (node_id, dep)
berghofe@17144
   181
             (new_node (node_id, (NONE, "", "")) gr);
berghofe@12445
   182
           val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
berghofe@12445
   183
         in
berghofe@17144
   184
           map_node node_id (K (NONE, module',
berghofe@12445
   185
             Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk dtdef @
berghofe@13754
   186
               [Pretty.str ";"])) ^ "\n\n" ^
berghofe@13754
   187
             (if "term_of" mem !mode then
berghofe@13754
   188
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@17144
   189
                  (mk_term_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@14104
   190
              else "") ^
berghofe@14104
   191
             (if "test" mem !mode then
berghofe@14104
   192
                Pretty.string_of (Pretty.blk (0, separate Pretty.fbrk
berghofe@17144
   193
                  (mk_gen_of_def gr2 "fun " descr') @ [Pretty.str ";"])) ^ "\n\n"
berghofe@13754
   194
              else ""))) gr2
berghofe@17144
   195
         end
berghofe@12445
   196
  end;
berghofe@12445
   197
berghofe@12445
   198
berghofe@12445
   199
(**** case expressions ****)
berghofe@12445
   200
berghofe@17144
   201
fun pretty_case thy defs gr dep module brack constrs (c as Const (_, T)) ts =
berghofe@12445
   202
  let val i = length constrs
berghofe@12445
   203
  in if length ts <= i then
berghofe@17144
   204
       invoke_codegen thy defs dep module brack (gr, eta_expand c ts (i+1))
berghofe@12445
   205
    else
berghofe@12445
   206
      let
skalberg@15570
   207
        val ts1 = Library.take (i, ts);
skalberg@15570
   208
        val t :: ts2 = Library.drop (i, ts);
skalberg@15574
   209
        val names = foldr add_term_names
skalberg@15574
   210
          (map (fst o fst o dest_Var) (foldr add_term_vars [] ts1)) ts1;
skalberg@15570
   211
        val (Ts, dT) = split_last (Library.take (i+1, fst (strip_type T)));
berghofe@12445
   212
berghofe@12445
   213
        fun pcase gr [] [] [] = ([], gr)
berghofe@12445
   214
          | pcase gr ((cname, cargs)::cs) (t::ts) (U::Us) =
berghofe@12445
   215
              let
berghofe@12445
   216
                val j = length cargs;
berghofe@12445
   217
                val xs = variantlist (replicate j "x", names);
skalberg@15570
   218
                val Us' = Library.take (j, fst (strip_type U));
berghofe@12445
   219
                val frees = map Free (xs ~~ Us');
berghofe@17144
   220
                val (gr0, cp) = invoke_codegen thy defs dep module false
berghofe@12445
   221
                  (gr, list_comb (Const (cname, Us' ---> dT), frees));
berghofe@12445
   222
                val t' = Envir.beta_norm (list_comb (t, frees));
berghofe@17144
   223
                val (gr1, p) = invoke_codegen thy defs dep module false (gr0, t');
berghofe@12445
   224
                val (ps, gr2) = pcase gr1 cs ts Us;
berghofe@12445
   225
              in
berghofe@12445
   226
                ([Pretty.block [cp, Pretty.str " =>", Pretty.brk 1, p]] :: ps, gr2)
berghofe@12445
   227
              end;
berghofe@12445
   228
berghofe@12445
   229
        val (ps1, gr1) = pcase gr constrs ts1 Ts;
skalberg@15570
   230
        val ps = List.concat (separate [Pretty.brk 1, Pretty.str "| "] ps1);
berghofe@17144
   231
        val (gr2, p) = invoke_codegen thy defs dep module false (gr1, t);
berghofe@17144
   232
        val (gr3, ps2) = foldl_map (invoke_codegen thy defs dep module true) (gr2, ts2)
berghofe@12445
   233
      in (gr3, (if not (null ts2) andalso brack then parens else I)
berghofe@12445
   234
        (Pretty.block (separate (Pretty.brk 1)
berghofe@12445
   235
          (Pretty.block ([Pretty.str "(case ", p, Pretty.str " of",
berghofe@12445
   236
             Pretty.brk 1] @ ps @ [Pretty.str ")"]) :: ps2))))
berghofe@12445
   237
      end
berghofe@12445
   238
  end;
berghofe@12445
   239
berghofe@12445
   240
berghofe@12445
   241
(**** constructors ****)
berghofe@12445
   242
berghofe@17144
   243
fun pretty_constr thy defs gr dep module brack args (c as Const (s, T)) ts =
berghofe@12445
   244
  let val i = length args
berghofe@12445
   245
  in if i > 1 andalso length ts < i then
berghofe@17144
   246
      invoke_codegen thy defs dep module brack (gr, eta_expand c ts i)
berghofe@12445
   247
     else
berghofe@12445
   248
       let
berghofe@17144
   249
         val id = mk_qual_id module (get_const_id s gr);
berghofe@16645
   250
         val (gr', ps) = foldl_map
berghofe@17144
   251
           (invoke_codegen thy defs dep module (i = 1)) (gr, ts);
berghofe@12445
   252
       in (case args of
berghofe@12445
   253
          _ :: _ :: _ => (gr', (if brack then parens else I)
berghofe@12445
   254
            (Pretty.block [Pretty.str id, Pretty.brk 1, mk_tuple ps]))
berghofe@12445
   255
        | _ => (gr', mk_app brack (Pretty.str id) ps))
berghofe@12445
   256
       end
berghofe@12445
   257
  end;
berghofe@12445
   258
berghofe@12445
   259
berghofe@12445
   260
(**** code generators for terms and types ****)
berghofe@12445
   261
berghofe@17144
   262
fun datatype_codegen thy defs gr dep module brack t = (case strip_comb t of
berghofe@12445
   263
   (c as Const (s, T), ts) =>
haftmann@18247
   264
       (case Library.find_first (fn (_, {index, descr, case_name, ...}) =>
berghofe@12445
   265
         s = case_name orelse
haftmann@17521
   266
           AList.defined (op =) ((#3 o the o AList.lookup (op =) descr) index) s)
berghofe@12445
   267
             (Symtab.dest (DatatypePackage.get_datatypes thy)) of
skalberg@15531
   268
          NONE => NONE
skalberg@15531
   269
        | SOME (tname, {index, descr, ...}) =>
haftmann@18247
   270
           if is_some (get_assoc_code thy s T) then NONE else
haftmann@17521
   271
           let val SOME (_, _, constrs) = AList.lookup (op =) descr index
haftmann@17521
   272
           in (case (AList.lookup (op =) constrs s, strip_type T) of
berghofe@17144
   273
               (NONE, _) => SOME (pretty_case thy defs gr dep module brack
haftmann@18247
   274
                 ((#3 o the o AList.lookup (op =) descr) index) c ts)
berghofe@16645
   275
             | (SOME args, (_, Type _)) => SOME (pretty_constr thy defs
berghofe@17144
   276
                 (fst (invoke_tycodegen thy defs dep module false
berghofe@16645
   277
                    (gr, snd (strip_type T))))
berghofe@17144
   278
                 dep module brack args c ts)
skalberg@15531
   279
             | _ => NONE)
berghofe@12445
   280
           end)
skalberg@15531
   281
 |  _ => NONE);
berghofe@12445
   282
berghofe@17144
   283
fun datatype_tycodegen thy defs gr dep module brack (Type (s, Ts)) =
wenzelm@17412
   284
      (case Symtab.lookup (DatatypePackage.get_datatypes thy) s of
skalberg@15531
   285
         NONE => NONE
skalberg@15531
   286
       | SOME {descr, ...} =>
skalberg@15570
   287
           if isSome (get_assoc_type thy s) then NONE else
berghofe@16645
   288
           let
berghofe@16645
   289
             val (gr', ps) = foldl_map
berghofe@17144
   290
               (invoke_tycodegen thy defs dep module false) (gr, Ts);
berghofe@17144
   291
             val gr'' = add_dt_defs thy defs dep module gr' descr
berghofe@16645
   292
           in SOME (gr'',
berghofe@12445
   293
             Pretty.block ((if null Ts then [] else
berghofe@12445
   294
               [mk_tuple ps, Pretty.str " "]) @
berghofe@17144
   295
               [Pretty.str (mk_qual_id module (get_type_id s gr''))]))
berghofe@12445
   296
           end)
berghofe@16645
   297
  | datatype_tycodegen _ _ _ _ _ _ _ = NONE;
berghofe@12445
   298
haftmann@18247
   299
haftmann@19008
   300
val setup = 
wenzelm@18708
   301
  add_codegen "datatype" datatype_codegen #>
wenzelm@18708
   302
  add_tycodegen "datatype" datatype_tycodegen #>
haftmann@18963
   303
  CodegenPackage.set_get_datatype
haftmann@18963
   304
    DatatypePackage.get_datatype #>
haftmann@18451
   305
  CodegenPackage.set_get_all_datatype_cons
wenzelm@18708
   306
    DatatypePackage.get_all_datatype_cons #>
haftmann@19008
   307
  (fn thy => thy |> CodegenPackage.add_eqextr_default ("equality",
haftmann@19008
   308
    (CodegenPackage.eqextr_eq
haftmann@19008
   309
      DatatypePackage.get_eq_equations
haftmann@19008
   310
      (Sign.read_term thy "False")))) #>
haftmann@18518
   311
  CodegenPackage.ensure_datatype_case_consts
haftmann@18518
   312
    DatatypePackage.get_datatype_case_consts
wenzelm@18708
   313
    DatatypePackage.get_case_const_data;
berghofe@12445
   314
berghofe@12445
   315
end;