src/HOL/Tools/datatype_codegen.ML
author berghofe
Fri Jul 11 14:57:00 2003 +0200 (2003-07-11 ago)
changeset 14104 29f726e36e5c
parent 13754 021cf00435a9
child 14981 e73f8140af78
permissions -rw-r--r--
Added generator for test case generators.
berghofe@12446
     1
(*  Title:      HOL/datatype_codegen.ML
berghofe@12445
     2
    ID:         $Id$
berghofe@12445
     3
    Author:     Stefan Berghofer, TU Muenchen
berghofe@12445
     4
    License:    GPL (GNU GENERAL PUBLIC LICENSE)
berghofe@12445
     5
berghofe@12445
     6
Code generator for inductive datatypes.
berghofe@12445
     7
*)
berghofe@12445
     8
berghofe@12445
     9
signature DATATYPE_CODEGEN =
berghofe@12445
    10
sig
berghofe@12445
    11
  val setup: (theory -> theory) list
berghofe@12445
    12
end;
berghofe@12445
    13
berghofe@12445
    14
structure DatatypeCodegen : DATATYPE_CODEGEN =
berghofe@12445
    15
struct
berghofe@12445
    16
berghofe@12445
    17
open Codegen;
berghofe@12445
    18
berghofe@12445
    19
fun mk_tuple [p] = p
berghofe@12445
    20
  | mk_tuple ps = Pretty.block (Pretty.str "(" ::
berghofe@12445
    21
      flat (separate [Pretty.str ",", Pretty.brk 1] (map single ps)) @
berghofe@12445
    22
        [Pretty.str ")"]);
berghofe@12445
    23
berghofe@12445
    24
(**** datatype definition ****)
berghofe@12445
    25
berghofe@14104
    26
(* find shortest path to constructor with no recursive arguments *)
berghofe@14104
    27
berghofe@14104
    28
fun find_nonempty (descr: DatatypeAux.descr) is i =
berghofe@14104
    29
  let
berghofe@14104
    30
    val (_, _, constrs) = the (assoc (descr, i));
berghofe@14104
    31
    fun arg_nonempty (_, DatatypeAux.DtRec i) = if i mem is then None
berghofe@14104
    32
          else apsome (curry op + 1 o snd) (find_nonempty descr (i::is) i)
berghofe@14104
    33
      | arg_nonempty _ = Some 0;
berghofe@14104
    34
    fun max xs = foldl
berghofe@14104
    35
      (fn (None, _) => None
berghofe@14104
    36
        | (Some i, Some j) => Some (Int.max (i, j))
berghofe@14104
    37
        | (_, None) => None) (Some 0, xs);
berghofe@14104
    38
    val xs = sort (int_ord o pairself snd)
berghofe@14104
    39
      (mapfilter (fn (s, dts) => apsome (pair s)
berghofe@14104
    40
        (max (map (arg_nonempty o DatatypeAux.strip_dtyp) dts))) constrs)
berghofe@14104
    41
  in case xs of [] => None | x :: _ => Some x end;
berghofe@14104
    42
wenzelm@12890
    43
fun add_dt_defs thy dep gr (descr: DatatypeAux.descr) =
berghofe@12445
    44
  let
berghofe@12445
    45
    val sg = sign_of thy;
berghofe@12445
    46
    val tab = DatatypePackage.get_datatypes thy;
berghofe@12445
    47
berghofe@12445
    48
    val descr' = filter (can (map DatatypeAux.dest_DtTFree o #2 o snd)) descr;
berghofe@14104
    49
    val rtnames = map (#1 o snd) (filter (fn (_, (_, _, cs)) =>
berghofe@14104
    50
      exists (exists DatatypeAux.is_rec_type o snd) cs) descr');
berghofe@12445
    51
berghofe@12445
    52
    val (_, (_, _, (cname, _) :: _)) :: _ = descr';
berghofe@12445
    53
    val dname = mk_const_id sg cname;
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@12445
    61
            val (gr', ps) = foldl_map (fn (gr, (cname, cargs)) =>
berghofe@12445
    62
              apsnd (pair cname) (foldl_map
berghofe@12445
    63
                (invoke_tycodegen thy dname false) (gr, cargs))) (gr, cs');
berghofe@12445
    64
            val (gr'', rest) = mk_dtdef gr' "and " xs
berghofe@12445
    65
          in
berghofe@12445
    66
            (gr'',
berghofe@12445
    67
             Pretty.block (Pretty.str prfx ::
berghofe@12445
    68
               (if null tvs then [] else
berghofe@12445
    69
                  [mk_tuple (map Pretty.str tvs), Pretty.str " "]) @
berghofe@12445
    70
               [Pretty.str (mk_type_id sg tname ^ " ="), Pretty.brk 1] @
berghofe@12445
    71
               flat (separate [Pretty.brk 1, Pretty.str "| "]
berghofe@12445
    72
                 (map (fn (cname, ps') => [Pretty.block
berghofe@12445
    73
                   (Pretty.str (mk_const_id sg cname) ::
berghofe@12445
    74
                    (if null ps' then [] else
berghofe@12445
    75
                     flat ([Pretty.str " of", Pretty.brk 1] ::
berghofe@12445
    76
                       separate [Pretty.str " *", Pretty.brk 1]
berghofe@12445
    77
                         (map single ps'))))]) ps))) :: rest)
berghofe@13754
    78
          end;
berghofe@13754
    79
berghofe@13754
    80
    fun mk_term_of_def prfx [] = []
berghofe@13754
    81
      | mk_term_of_def prfx ((_, (tname, dts, cs)) :: xs) =
berghofe@13754
    82
          let
berghofe@13754
    83
            val tvs = map DatatypeAux.dest_DtTFree dts;
berghofe@13754
    84
            val sorts = map (rpair []) tvs;
berghofe@13754
    85
            val cs' = map (apsnd (map (DatatypeAux.typ_of_dtyp descr sorts))) cs;
berghofe@13754
    86
            val dts' = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@13754
    87
            val T = Type (tname, dts');
berghofe@13754
    88
            val rest = mk_term_of_def "and " xs;
berghofe@13754
    89
            val (_, eqs) = foldl_map (fn (prfx, (cname, Ts)) =>
berghofe@13754
    90
              let val args = map (fn i =>
berghofe@13754
    91
                Pretty.str ("x" ^ string_of_int i)) (1 upto length Ts)
berghofe@13754
    92
              in ("  | ", Pretty.blk (4,
berghofe@13754
    93
                [Pretty.str prfx, mk_term_of sg false T, Pretty.brk 1,
berghofe@13754
    94
                 if null Ts then Pretty.str (mk_const_id sg cname)
berghofe@13754
    95
                 else parens (Pretty.block [Pretty.str (mk_const_id sg cname),
berghofe@13754
    96
                    Pretty.brk 1, mk_tuple args]),
berghofe@13754
    97
                 Pretty.str " =", Pretty.brk 1] @
berghofe@13754
    98
                 flat (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@13754
   101
                    map (fn (x, U) => [Pretty.block [mk_term_of sg 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) =
berghofe@14104
   112
              partition (exists DatatypeAux.is_rec_type o snd) cs;
berghofe@14104
   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@14104
   118
            fun mk_constr s (cname, dts) =
berghofe@14104
   119
              let
berghofe@14104
   120
                val Ts = map (DatatypeAux.typ_of_dtyp descr sorts) dts;
berghofe@14104
   121
                val gs = map (fn T => mk_app false (mk_gen sg false rtnames s T)
berghofe@14104
   122
                  [Pretty.str "j"]) Ts;
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@14104
   130
            fun mk_choice [c] = mk_constr "(i-1)" 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@14104
   134
                    (map (single o mk_delay o mk_constr "(i-1)") 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@14104
   158
                   mk_constr "0" (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)
berghofe@12445
   176
             (Graph.new_node (dname, (None, "")) gr);
berghofe@12445
   177
           val (gr2, dtdef) = mk_dtdef gr1 "datatype " descr';
berghofe@12445
   178
         in
berghofe@12445
   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
berghofe@12445
   262
          None => None
berghofe@12445
   263
        | Some (tname, {index, descr, ...}) =>
berghofe@12445
   264
           if is_some (get_assoc_code thy s T) then None else
berghofe@12445
   265
           let val Some (_, _, constrs) = assoc (descr, index)
berghofe@12822
   266
           in (case (assoc (constrs, s), strip_type T) of
berghofe@12822
   267
               (None, _) => Some (pretty_case thy gr dep brack
berghofe@12445
   268
                 (#3 (the (assoc (descr, index)))) c ts)
berghofe@12822
   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)
berghofe@12822
   272
             | _ => None)
berghofe@12445
   273
           end)
berghofe@12445
   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
berghofe@12445
   278
         None => None
berghofe@12445
   279
       | Some {descr, ...} =>
berghofe@12445
   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)
berghofe@12445
   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)
berghofe@12445
   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;