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