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