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