TExcelTAD

Starlark & Macros

Everything you write for Bazel (BUILD files, .bzl files, MODULE.bazel) is Starlark, a dialect of Python designed for configuration: deterministic, hermetic and parallel-friendly. It looks like Python but deliberately lacks what would make builds unpredictable.

Python has Starlark
while loops, recursion no: for over finite collections only, so evaluation always terminates
classes, import no classes; load("//path:file.bzl", "symbol") imports symbols from .bzl files
file and network I/O, time, random none (repository rules and module extensions have controlled I/O)
mutable global state values become frozen after the file that created them finishes loading
exceptions fail("message") stops evaluation with an error

Starlark has def, if, for, comprehensions, dicts, lists, struct, string formatting ("%s" % x, .format()), and a print() that shows up as a DEBUG line.

Two ways to extend Bazel

Macro Rule
What it is a function (or macro()) that instantiates existing rules during loading a new target type whose implementation runs during analysis and declares actions
Can create actions no, only targets yes (ctx.actions.run, run_shell, write, …)
Visible in bazel query no: query sees the targets it generated yes, as its own kind
Use it for conventions: "every service gets a binary, a test and an image" new kinds of build steps: a code generator, a packager, a language

Prefer a macro when existing rules can do the work; write a rule when you need new actions or new information passed between targets.

A legacy macro

The classic macro is a plain function in a .bzl file:

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_python", version = "2.4.5")' > MODULE.bazel
mkdir -p build_defs services/checkout
touch build_defs/BUILD.bazel
cat > build_defs/py_service.bzl <<'EOF'
load("@rules_python//python:defs.bzl", "py_binary", "py_test")

def py_service(name, srcs, test_srcs = [], deps = [], visibility = None):
    """A binary plus its test, with our team's conventions."""
    py_binary(
        name = name,
        srcs = srcs,
        main = srcs[0],
        deps = deps,
        visibility = visibility,
    )
    if test_srcs:
        py_test(
            name = name + "_test",
            size = "small",
            srcs = test_srcs + srcs,
            main = test_srcs[0],
            deps = deps,
        )
EOF
cat > services/checkout/BUILD.bazel <<'EOF'
load("//build_defs:py_service.bzl", "py_service")

py_service(
    name = "checkout",
    srcs = ["checkout.py"],
    test_srcs = ["checkout_test.py"],
)
EOF
printf 'def total(items):\n    return sum(items)\n\nif __name__ == "__main__":\n    print("checkout total:", total([5, 7]))\n' > services/checkout/checkout.py
printf 'import unittest\nfrom services.checkout.checkout import total\nclass T(unittest.TestCase):\n    def test(self):\n        self.assertEqual(total([1, 2]), 3)\nunittest.main()\n' > services/checkout/checkout_test.py
bazel query --output=label_kind //services/checkout:all 2>/dev/null
bazel query --output=build //services/checkout:checkout_test 2>/dev/null | grep -E 'generator|^py_test|size'
bazel test //services/checkout:all 2>&1 | grep -E 'PASSED|FAILED'
bazel run //services/checkout 2>/dev/null
py_binary rule //services/checkout:checkout
py_test rule //services/checkout:checkout_test
py_test(
  generator_name = "checkout",
  generator_function = "py_service",
  generator_location = "services/checkout/BUILD.bazel:3:11",
  size = "small",
//services/checkout:checkout_test                                        PASSED in 0.3s
checkout total: 12

The macro is invisible to Bazel after loading: query reports two ordinary targets, and only the generator_function/generator_name attributes remember where they came from. That's both the strength and the weakness of legacy macros. They're simple, but nothing checks their arguments (a typo in an argument name is an error only if the macro passes it on), and every target they create is public to anyone who knows its name.

Symbolic macros

Bazel 8 added symbolic macros, declared with macro(). They have typed attributes like a rule, and they enforce naming and visibility for the targets they create:

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p build_defs tools
touch build_defs/BUILD.bazel
cat > build_defs/cc_tool.bzl <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")

def _cc_tool_impl(name, visibility, srcs, test_srcs, deps):
    cc_binary(name = name, srcs = srcs, deps = deps, visibility = visibility)
    cc_test(name = name + "_test", size = "small", srcs = test_srcs, deps = deps)

cc_tool = macro(
    doc = "A C++ command-line tool and its test.",
    implementation = _cc_tool_impl,
    attrs = {
        "srcs": attr.label_list(mandatory = True, allow_files = [".cc"]),
        "test_srcs": attr.label_list(default = [], allow_files = [".cc"]),
        "deps": attr.label_list(default = []),
    },
)
EOF
cat > tools/BUILD.bazel <<'EOF'
load("//build_defs:cc_tool.bzl", "cc_tool")
cc_tool(name = "hasher", srcs = ["hasher.cc"], test_srcs = ["hasher_test.cc"])
EOF
echo 'int main() { return 0; }' > tools/hasher.cc
echo 'int main() { return 0; }' > tools/hasher_test.cc
bazel query --output=label_kind //tools:all 2>/dev/null
bazel test //tools:all 2>&1 | grep -E 'PASSED|FAILED'
echo "== a typo in an attribute"
sed -i 's/test_srcs = /tests_srcs = /' tools/BUILD.bazel
bazel query //tools:all 2>&1 | grep -E '^Error' | head -1
cc_binary rule //tools:hasher
cc_test rule //tools:hasher_test
//tools:hasher_test                                                      PASSED in 0.0s
== a typo in an attribute
Error: no such attribute 'tests_srcs' in 'cc_tool' macro (did you mean 'test_srcs'?)

What macro() gives you over a plain function:

  • Typed attributes: the misspelled tests_srcs is rejected at loading time, and labels are resolved relative to the package that calls the macro.
  • Naming rules: targets created inside must be called name or start with name_/name-/name., so macros can't silently collide.
  • Encapsulation: a target created by the macro is visible only inside the macro unless the macro passes visibility on; here only the binary is exported, so the test can't become anyone's dependency.

New macros should be symbolic; existing legacy macros keep working.

Where logic belongs

Logic Put it in
Lists of files, simple conventions the BUILD file (glob, list comprehensions)
A reusable bundle of targets a symbolic macro in //build_defs:*.bzl (or tools/build_defs, any name works)
New actions, new information between targets a rule (Writing a Rule)
Behaviour that depends on flags or platforms select() and config_setting (Platforms)
Fetching external code or tools a repository rule or module extension (Repositories)

Tip: Keep .bzl files free of side effects at load time and give public macros docstrings: stardoc turns them into reference docs, which is how rule sets on the BCR document themselves.

Test yourself

Why does Starlark have no while loops or recursion?

  1. Performance only
  2. So evaluation of BUILD and .bzl files always terminates and stays deterministic
  3. Python 2 compatibility
  4. They are reserved for rules

What does bazel query show for targets created by a macro?

  1. The macro as a target
  2. The ordinary targets the macro created (with generator_* attributes)
  3. Nothing
  4. An error

Which is an advantage of a symbolic macro (macro()) over a legacy function macro?

  1. It can run actions
  2. Typed attributes, enforced naming and visibility of the targets it creates
  3. It is faster at execution
  4. It works without load()