blob: ee8b4d4acd6d14002c82d0ee981ee8e5bfc7cbf0 [file] [log] [blame]
Brian Silvermanc270a4d2022-07-23 16:08:06 -07001load("@rules_rust//rust:defs.bzl", "rust_library")
2load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain")
3load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
4
5def _cc_toolchain_flags(ctx, cc_toolchain):
6 feature_configuration = cc_common.configure_features(
7 ctx = ctx,
8 cc_toolchain = cc_toolchain,
9 requested_features = ctx.features,
10 unsupported_features = ctx.disabled_features,
11 )
12 compiler_path = cc_common.get_tool_for_action(
13 feature_configuration = feature_configuration,
14 action_name = ACTION_NAMES.cpp_compile,
15 )
16 compile_variables = cc_common.create_compile_variables(
17 feature_configuration = feature_configuration,
18 cc_toolchain = cc_toolchain,
19 user_compile_flags = ctx.fragments.cpp.copts + ctx.fragments.cpp.cxxopts,
20 )
21 command_line = cc_common.get_memory_inefficient_command_line(
22 feature_configuration = feature_configuration,
23 action_name = ACTION_NAMES.cpp_compile,
24 variables = compile_variables,
25 )
26 env = cc_common.get_environment_variables(
27 feature_configuration = feature_configuration,
28 action_name = ACTION_NAMES.cpp_compile,
29 variables = compile_variables,
30 )
31 return command_line, env
32
33# All the stuff about AUTOCXX_RS_FILE and--fix-rs-include-name only applies when
34# using --gen-rs-include. We use --gen-rs-archive so none of that matters.
35#
36# The generated .rs file uses `include!` on the top-level C++ headers imported
37# via `#include` in `include_cpp!`. This always operates relative to the source
38# file (I don't see any way to change it), nor does autocxx have a way to change
39# the path. There are headers involved which use `#pragma once`, so just copying
40# them is a bad idea. Instead, we generate forwarding headers.
41def _autocxx_library_gen_impl(ctx):
42 rust_toolchain = ctx.toolchains[Label("@rules_rust//rust:toolchain")]
43
44 # TODO(Brian): Provide some way to override this globally in WORKSPACE? Need
45 # a real strategy for coordinating toolchains and flags, see the TODO below
46 # where cc_command_line is used for details.
47 if ctx.attr.override_cc_toolchain:
48 cc_toolchain = ctx.attr.override_cc_toolchain[cc_common.CcToolchainInfo]
49 else:
50 cc_toolchain = find_cc_toolchain(ctx)
51
52 # The directory where we generate files. Needs to be unique and in our package.
53 gendir = ctx.label.name + "__dir"
54
55 cc_command_line, cc_env = _cc_toolchain_flags(ctx, cc_toolchain)
56
57 includes = []
58 in_headers = []
59 forwarding_headers = []
60 for lib in ctx.attr.libs:
61 compilation = lib[CcInfo].compilation_context
62
63 # TODO(Brian): How should we be juggling includes, quote_includes, and system_includes?
64 includes.append(compilation.includes)
65 includes.append(compilation.quote_includes)
66 includes.append(compilation.system_includes)
67 in_headers.append(compilation.headers)
68 for header in compilation.direct_public_headers:
69 # TODO(Brian): This doesn't work if it's being `#include`ed (via
70 # `include_cpp!`) using one of the includes paths. Maybe we should
71 # add each `includes` prefixed with `gendir` to solve that?
72 forwarding = ctx.actions.declare_file("%s/%s" % (gendir, header.short_path))
73 forwarding_headers.append(forwarding)
74 ctx.actions.write(forwarding, '#include "%s"' % header.short_path)
75 includes = depset(transitive = includes)
76 action_inputs = depset(
77 direct = ctx.files.srcs + ctx.files.cxxbridge_srcs,
78 transitive = in_headers + [cc_toolchain.all_files],
79 )
80
81 # This is always the name with --gen-rs-archive, regardless of other flags.
82 out_rs_json = ctx.actions.declare_file("%s/gen.rs.json" % gendir)
83 out_env_file = ctx.actions.declare_file("%s/rustc_env" % gendir)
84 ctx.actions.write(
85 output = out_env_file,
86 content = "AUTOCXX_RS_JSON_ARCHIVE=%s" % out_rs_json.path,
87 )
88
89 out_h = ctx.actions.declare_file("%s_cxxgen.h" % ctx.label.name.rstrip("__gen"))
90 out_h_guard = out_h.short_path.replace("/", "_").replace(".", "_")
91 out_h_contents = [
92 "#ifndef %s" % out_h_guard,
93 "#define %s" % out_h_guard,
94 "// GENERATED FILE, DO NOT EDIT",
95 "//",
96 "// #includes all of the declarations exported to C++ from %s" % ctx.label,
97 ]
98 out_cc = []
99
100 # See `gen --help` for details on the naming of these outputs.
101 for cc_index in range(ctx.attr.sections_to_generate):
102 out_cc.append(ctx.actions.declare_file("%s/gen%d.cc" % (gendir, cc_index)))
103 gen_h = ctx.actions.declare_file("%s/gen%d.h" % (gendir, cc_index))
104 out_cc.append(gen_h)
105 out_h_contents.append("#include \"%s\"" % gen_h.short_path)
106 autocxxgen_h = ctx.actions.declare_file("%s/autocxxgen%d.h" % (gendir, cc_index))
107 out_cc.append(autocxxgen_h)
108 out_h_contents.append("#include \"%s\"" % autocxxgen_h.short_path)
109
110 cxxbridge_cc_srcs = []
111 for src in ctx.files.cxxbridge_srcs:
112 cxxbridge_cc = ctx.actions.declare_file("%s/cxxbridge.cc" % gendir)
113 cxxbridge_cc_srcs.append(cxxbridge_cc)
114 cxxbridge_h = ctx.actions.declare_file("%s/cxxbridge.h" % gendir)
115 cxxbridge_cc_srcs.append(cxxbridge_h)
116 out_h_contents.append("#include \"%s\"" % cxxbridge_h.short_path)
117 ctx.actions.run(
118 mnemonic = "CxxCodegen",
119 executable = ctx.executable._cxx_codegen,
120 inputs = [src],
121 outputs = [cxxbridge_cc, cxxbridge_h],
122 arguments = [src.path, "--output", cxxbridge_h.path, "--output", cxxbridge_cc.path],
123 )
124
125 out_h_contents.append("#endif // %s" % out_h_guard)
126 ctx.actions.write(
127 output = out_h,
128 content = "\n".join(out_h_contents),
129 )
130
131 gen_rs = ctx.actions.args()
132 gen_rs.add_all(["--outdir", out_rs_json.dirname])
133 gen_rs.add("--gen-rs-archive")
134 gen_rs.add("--gen-cpp")
135
136 gen_rs.add_all(["--generate-exact", ctx.attr.sections_to_generate])
137
138 gen_rs.add_all(ctx.files.srcs)
139 gen_rs.add_all(ctx.files.cxxbridge_srcs)
140
141 # TODO: Do these go before or after the --? They're partially redundant with
142 # cc_command_line too.
143 gen_rs.add_all(includes, before_each = "-I")
144 gen_rs.add("--")
145
146 # TODO: These are flags for the cc_toolchain, not the libclang they're being passed to.
147 # Figure out how to handle that nicely. Maybe just require they're compatible, and direct
148 # people to overriding the toolchain in use instead?
149 gen_rs.add_all(cc_command_line)
150
151 gen_rs.add("-Wno-unused-private-field")
152 env = dict(cc_env)
153 env.update(
154 LIBCLANG_PATH = ctx.file._libclang.path,
155 )
156 if ctx.attr.gen_debug:
157 env.update(
158 RUST_BACKTRACE = "full",
159 RUST_LOG = "autocxx_engine=info",
160 )
161 ctx.actions.run(
162 arguments = [gen_rs],
163 outputs = [out_rs_json] + out_cc,
164 tools = [ctx.file._libclang],
165 inputs = action_inputs,
166 env = env,
167 executable = ctx.executable._autocxx_gen,
168 mnemonic = "AutocxxGen",
169 )
170
171 return [
172 OutputGroupInfo(
173 cc_srcs = out_cc + cxxbridge_cc_srcs,
174 hdr_srcs = [out_h],
175 compile_data = forwarding_headers + [out_rs_json],
176 env_files = [out_env_file],
177 ),
178 ]
179
180_autocxx_library_gen = rule(
181 implementation = _autocxx_library_gen_impl,
182 attrs = {
183 "libs": attr.label_list(
184 mandatory = True,
185 providers = [CcInfo],
186 doc = "C++ libraries to let Rust use headers from",
187 ),
188 "srcs": attr.label_list(
189 allow_files = [".rs"],
190 mandatory = False,
191 doc = "Rust sources with `include_cpp!` macros",
192 default = [],
193 ),
194 # TODO(Brian): Do we need to support this? Or just throw them in srcs?
195 "cxxbridge_srcs": attr.label_list(
196 allow_files = [".rs"],
197 mandatory = False,
198 doc = "Rust sources with only [cxx::bridge] annotations",
199 default = [],
200 ),
201 "sections_to_generate": attr.int(
202 default = 20,
203 doc = (
204 "The number of `cxx::bridge` sections to support," +
205 " including ones created by `autocxx::include_cpp!`." +
206 " The default is sufficient for most use cases." +
207 " Setting this too large has a small performance impact, setting it" +
208 " too low will result in a build failure."
209 ),
210 ),
211 "gen_debug": attr.bool(
212 default = False,
213 doc = "Print (lots of) debug info about autocxx's codegen at build time.",
214 ),
215 "_autocxx_gen": attr.label(
216 executable = True,
217 default = Label("@//third_party/autocxx/gen/cmd:gen"),
218 cfg = "exec",
219 ),
220 "_cxx_codegen": attr.label(
221 executable = True,
222 default = Label("@//third_party/cargo:cargo_bin_cxxbridge"),
223 cfg = "exec",
224 ),
225 "_libclang": attr.label(
226 cfg = "exec",
227 default = Label("@llvm_k8//:libclang"),
228 allow_single_file = True,
229 ),
230 "override_cc_toolchain": attr.label(mandatory = False, providers = [cc_common.CcToolchainInfo]),
231 "_cc_toolchain": attr.label(default = Label("@bazel_tools//tools/cpp:current_cc_toolchain")),
232 },
233 toolchains = [
234 "@rules_rust//rust:toolchain",
235 "@bazel_tools//tools/cpp:toolchain_type",
236 ],
237 fragments = ["cpp"],
238)
239
240def autocxx_library(
241 name,
242 visibility = None,
243 target_compatible_with = None,
244 libs = [],
245 srcs = [],
246 cxxbridge_srcs = [],
247 override_cc_toolchain = None,
248 deps = [],
249 rs_deps = [],
250 testonly = None,
251 crate_features = None,
252 crate_name = None,
253 gen_debug = None):
254 """A macro to generate Rust <-> C++ interop code with autocxx.
255
256 Creates the following rules:
257 * A rust_library with the given name, which includes the given srcs. Note that it will not
258 include them directly due to how autocxx works, instead they will be copied into a
259 generated file along with changes from autocxx.
260 * A cc_library with the given name + `_cc`. This is for C++ code that wants to use APIs
261 from the given Rust code. Rust dependencies should _not_ depend on this. The header for C++
262 to #include will be named by the given name + `_cxxgen.h`.
263
264 `deps` is for other `autocxx_library` rules. `rs_deps` is for dependencies of the Rust code.
265 """
266 library_gen_name = "%s__gen" % name
267 _autocxx_library_gen(
268 name = library_gen_name,
269 visibility = ["//visibility:private"],
270 target_compatible_with = target_compatible_with,
271 testonly = testonly,
272 libs = libs,
273 srcs = srcs,
274 cxxbridge_srcs = cxxbridge_srcs,
275 override_cc_toolchain = override_cc_toolchain,
276 gen_debug = gen_debug,
277 )
278 gen_cc_srcs_name = "%s__cc_srcs" % name
279 native.filegroup(
280 name = gen_cc_srcs_name,
281 visibility = ["//visibility:private"],
282 target_compatible_with = target_compatible_with,
283 testonly = testonly,
284 srcs = [library_gen_name],
285 output_group = "cc_srcs",
286 )
287 gen_hdr_srcs_name = "%s__hdr_srcs" % name
288 native.filegroup(
289 name = gen_hdr_srcs_name,
290 visibility = ["//visibility:private"],
291 target_compatible_with = target_compatible_with,
292 testonly = testonly,
293 srcs = [library_gen_name],
294 output_group = "hdr_srcs",
295 )
296 gen_compile_data_name = "%s__compile_data" % name
297 native.filegroup(
298 name = gen_compile_data_name,
299 visibility = ["//visibility:private"],
300 target_compatible_with = target_compatible_with,
301 testonly = testonly,
302 srcs = [library_gen_name],
303 output_group = "compile_data",
304 )
305 gen_env_files_name = "%s__env_files" % name
306 native.filegroup(
307 name = gen_env_files_name,
308 visibility = ["//visibility:private"],
309 target_compatible_with = target_compatible_with,
310 testonly = testonly,
311 srcs = [library_gen_name],
312 output_group = "env_files",
313 )
314 cc_library_name = "%s__cc" % name
315 native.cc_library(
316 name = cc_library_name,
317 visibility = visibility,
318 target_compatible_with = target_compatible_with,
319 testonly = testonly,
320 deps = deps + libs + [
321 "//third_party/cargo:cxx_cc",
322 ],
323 srcs = [gen_cc_srcs_name],
324 hdrs = [gen_hdr_srcs_name],
325 )
326
327 rust_library(
328 name = name,
329 visibility = visibility,
330 target_compatible_with = target_compatible_with,
331 testonly = testonly,
332 srcs = srcs + cxxbridge_srcs,
333 proc_macro_deps = [
334 "//third_party/cargo:cxxbridge_macro",
335 ],
336 crate_features = crate_features,
337 crate_name = crate_name,
338 deps = deps + rs_deps + [
339 cc_library_name,
340 "//third_party/cargo:cxx",
341 "//third_party/autocxx",
342 ],
343 compile_data = [gen_compile_data_name],
344 rustc_env_files = [gen_env_files_name],
345 )