1load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
2
3def _pico_sdk_define_impl(ctx):
4    val = ctx.attr.from_flag[BuildSettingInfo].value
5
6    if type(val) == "string":
7        # Strings need quotes.
8        val = "\"{}\"".format(val)
9    elif type(val) == "bool":
10        # Convert bools to 0 or 1.
11        val = 1 if val else 0
12    cc_ctx = cc_common.create_compilation_context(
13        defines = depset(
14            direct = ["{}={}".format(ctx.attr.define_name, val)],
15        ),
16    )
17    return [CcInfo(compilation_context = cc_ctx)]
18
19pico_sdk_define = rule(
20    implementation = _pico_sdk_define_impl,
21    doc = """A simple rule that offers a skylib flag as a define.
22
23These can be listed in the `deps` attribute of a `cc_library` to get access
24to the value of a define.
25
26Example:
27
28    bool_flag(
29        name = "my_flag",
30        build_setting_default = False,
31    )
32
33    pico_sdk_define(
34        name = "flag_define",
35        define_name = "MY_FLAG_DEFINE",
36        from_flag = ":my_flag",
37    )
38""",
39    attrs = {
40        "define_name": attr.string(mandatory = True),
41        "from_flag": attr.label(mandatory = True),
42    },
43)
44