xref: /aosp_15_r20/external/skia/bazel/run_cxxbridge_cmd.bzl (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1"""
2The run_cxxbridge_cmd rule is a variant of the run_binary rule defined in
3`@bazel_skylib//rules:run_binary.bzl` that specifically runs `@cxxbridge_cmd//:cxxbridge` and
4provides a `crate_features` attribute that gets expanded into `--cfg` arguments to cxxbuild.
5
6Defining this as a rule (rather than a macro that thinly wraps `run_binary`) allows `crate_features`
7to be evaluated as a "select" [1], which is not possible for macro parameters [2].
8
9[1] https://bazel.build/docs/configurable-attributes#select-and-dependencies
10[2] https://bazel.build/docs/configurable-attributes#faq-select-macro
11"""
12
13def _run_cxxbridge_cmd_impl(ctx):
14    tool_as_list = [ctx.attr._cxxbridge]
15    args = [
16        # https://bazel.build/rules/lib/builtins/ctx#expand_location
17        ctx.expand_location(a, tool_as_list)
18        for a in ctx.attr.args
19    ]
20    for f in ctx.attr.crate_features:
21        args.append("--cfg")
22        args.append("feature=\"%s\"" % f)
23
24    # https://bazel.build/rules/lib/builtins/ctx#resolve_tools
25    tool_inputs, tool_input_manifests = ctx.resolve_tools(tools = tool_as_list)
26
27    # https://bazel.build/rules/lib/builtins/actions.html#run
28    ctx.actions.run(
29        outputs = ctx.outputs.outs,
30        inputs = ctx.files.srcs,
31        tools = tool_inputs,
32        executable = ctx.executable._cxxbridge,
33        arguments = args,
34        mnemonic = "RunCxxbridgeCmd",
35        input_manifests = tool_input_manifests,
36    )
37
38    return DefaultInfo(
39        files = depset(ctx.outputs.outs),
40        runfiles = ctx.runfiles(ctx.outputs.outs),
41    )
42
43run_cxxbridge_cmd = rule(
44    implementation = _run_cxxbridge_cmd_impl,
45    attrs = {
46        "srcs": attr.label_list(
47            doc = "Source dependencies for this rule",
48            allow_files = True,
49            mandatory = True,
50        ),
51        "outs": attr.output_list(
52            doc = "C++ output files generated by cxxbridge_cmd.",
53            mandatory = True,
54        ),
55        "args": attr.string_list(
56            doc = "Arguments to `cxxbridge_cmd`.",
57            mandatory = True,
58        ),
59        "crate_features": attr.string_list(
60            doc = "Optional list of cargo features that CXX bridge definitions may depend on.",
61        ),
62        "_cxxbridge": attr.label(
63            default = Label("@cxxbridge_cmd//:cxxbridge"),
64            allow_single_file = True,
65            executable = True,
66            cfg = "exec",
67        ),
68    },
69)
70