Enums in Skylark

998 views
Skip to first unread message

Laurent Le Brun

unread,
Jun 8, 2018, 5:01:52 PM6/8/18
to bazel-dev
Hi,

Historically, we've avoided enums in Skylark.
For example, the size of the test is a string with multiple possible values: https://docs.bazel.build/versions/master/be/common-definitions.html#test.size
For example, the cfg attribute is a string, e.g. cfg="host".

The reasoning was that Skylark is a dynamic language. Whether we use a symbol or a string, we can only detect typos at runtime. We also wanted to limit the number of concepts and types.

But having an enum is still useful for tooling. Linters can detect typos statically, refactoring tools can do a much better job, IDEs can provide better completion. We can also have cross-references (e.g. to find users of a specific value, or to find the list of possible values).

It turns out, we don't really need a new type or a new function for that.
We can use providers:

_colorInfo = provider(fields = ["name"])

colors = struct(
  red = _colorInfo(name="red"),
  green = _colorInfo(name="green"),
  blue = _colorInfo(name="blue"),
)

Example of use:

load("//:colors.bzl", "colors")

_color_to_hex = {
    colors.red: "#ff0000",
    colors.green: "#00ff00",
    colors.blue: "#0000ff",
    colors.white: "#ffffff",
}

def print_name_and_hex(color):
  print(color.name, _color_to_hex[color])

print_name_and_hex(colors.red)


Is it a pattern we should recommend?

--
Laurent

Marcel Hlopko

unread,
Jun 12, 2018, 6:54:17 AM6/12/18
to Laurent Le Brun, Pedro LF, bazel-dev

--
You received this message because you are subscribed to the Google Groups "bazel-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to bazel-dev+...@googlegroups.com.
To post to this group, send email to baze...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/bazel-dev/CAFtxR%2Bkz3kmZDspPOH2ghj9zQvtb3mPY3dPZ05Pew%3DMnnOWJdg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


--
Marcel Hlopko | Software Engineer | hlo...@google.com | 

Google Germany GmbH | Erika-Mann-Str. 33  | 80636 München | Germany | Geschäftsführer: Geschäftsführer: Paul Manicle, Halimah DeLaine Prado | Registergericht und -nummer: Hamburg, HRB 86891
Reply all
Reply to author
Forward
0 new messages