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