xref: /aosp_15_r20/external/skia/bazel/rust_cxx_bridge.bzl (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1"""
2This file specifies a macro that generates a C++ .h and .cc file
3based on a rust file. It uses the cxx crate [1], specifically the
4cxxbridge executable. This is based off of the example provided in [2].
5
6
7[1] https://cxx.rs/build/bazel.html
8[2] https://github.com/dtolnay/cxx/blob/e7576dc938f60512edfd1f7525e649b959b9dee6/tools/bazel/rust_cxx_bridge.bzl
9"""
10
11load("@rules_cc//cc:defs.bzl", "cc_library")
12load("//bazel:run_cxxbridge_cmd.bzl", "run_cxxbridge_cmd")
13load("//bazel:skia_rules.bzl", "skia_filegroup")
14
15def rust_cxx_bridge(name, src, deps = [], visibility = [], crate_features = []):
16    """Creates rules for CXX C++/Rust bridging.
17
18    Takes a Rust source file to generate binding code from a section that is marked with `#[cxx::bridge]`.
19
20    Args:
21      name: Name of the CXX bridge rule, used for sub-rules.
22      src: Source file that contains CXX bridge definitions.
23      deps: Rules this rule depends on.
24      visibility: Visibility of the generated sub-rules.
25      crate_features: Feature flags to enable for codegen. See https://doc.rust-lang.org/cargo/reference/features.html.
26    """
27    out_h = "%s.h" % src
28    out_cc = "%s.cc" % src
29
30    run_cxxbridge_cmd(
31        name = "%s/generated" % name,
32        srcs = [src],
33        outs = [out_h, out_cc],
34        args = [
35            "$(location %s)" % src,
36            "-o",
37            "$(location %s)" % out_h,
38            "-o",
39            "$(location %s)" % out_cc,
40        ],
41        crate_features = crate_features,
42    )
43
44    skia_filegroup(
45        name = "%s/filegroup" % name,
46        srcs = [out_cc],
47        visibility = visibility,
48    )
49
50    cc_library(
51        name = name,
52        srcs = [out_cc],
53        hdrs = [out_h],
54        deps = deps + ["%s/include" % name],
55        visibility = visibility,
56    )
57
58    cc_library(
59        name = "%s/include" % name,
60        hdrs = [out_h],
61        visibility = visibility,
62    )
63