blob: 6214d67ff44dd8afa34a43e754da5aaf12ce121f [file] [log] [blame]
Brian Silvermancc09f182022-03-09 15:40:20 -08001"""The rust_toolchain rule definition and implementation."""
2
3load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
Adam Snaider1c095c92023-07-08 02:09:58 -04004load("//rust/platform:triple.bzl", "triple")
Brian Silvermancc09f182022-03-09 15:40:20 -08005load("//rust/private:common.bzl", "rust_common")
Brian Silverman5f6f2762022-08-13 19:30:05 -07006load("//rust/private:rust_analyzer.bzl", _rust_analyzer_toolchain = "rust_analyzer_toolchain")
Adam Snaider1c095c92023-07-08 02:09:58 -04007load(
8 "//rust/private:rustfmt.bzl",
9 _current_rustfmt_toolchain = "current_rustfmt_toolchain",
10 _rustfmt_toolchain = "rustfmt_toolchain",
11)
12load(
13 "//rust/private:utils.bzl",
14 "dedent",
15 "dedup_expand_location",
16 "find_cc_toolchain",
17 "make_static_lib_symlink",
18)
Brian Silvermancc09f182022-03-09 15:40:20 -080019
Brian Silverman5f6f2762022-08-13 19:30:05 -070020rust_analyzer_toolchain = _rust_analyzer_toolchain
Adam Snaider1c095c92023-07-08 02:09:58 -040021rustfmt_toolchain = _rustfmt_toolchain
22current_rustfmt_toolchain = _current_rustfmt_toolchain
Brian Silverman5f6f2762022-08-13 19:30:05 -070023
Brian Silvermancc09f182022-03-09 15:40:20 -080024def _rust_stdlib_filegroup_impl(ctx):
25 rust_std = ctx.files.srcs
26 dot_a_files = []
27 between_alloc_and_core_files = []
28 core_files = []
29 between_core_and_std_files = []
30 std_files = []
Brian Silverman5f6f2762022-08-13 19:30:05 -070031 test_files = []
32 memchr_files = []
Brian Silvermancc09f182022-03-09 15:40:20 -080033 alloc_files = []
34 self_contained_files = [
35 file
36 for file in rust_std
37 if file.basename.endswith(".o") and "self-contained" in file.path
38 ]
Adam Snaider1c095c92023-07-08 02:09:58 -040039 panic_files = []
Brian Silvermancc09f182022-03-09 15:40:20 -080040
41 std_rlibs = [f for f in rust_std if f.basename.endswith(".rlib")]
42 if std_rlibs:
Brian Silverman5f6f2762022-08-13 19:30:05 -070043 # test depends on std
44 # std depends on everything except test
Brian Silvermancc09f182022-03-09 15:40:20 -080045 #
46 # core only depends on alloc, but we poke adler in there
47 # because that needs to be before miniz_oxide
48 #
Adam Snaider1c095c92023-07-08 02:09:58 -040049 # panic_unwind depends on unwind, alloc, cfg_if, compiler_builtins, core, libc
50 # panic_abort depends on alloc, cfg_if, compiler_builtins, core, libc
51 #
Brian Silvermancc09f182022-03-09 15:40:20 -080052 # alloc depends on the allocator_library if it's configured, but we
53 # do that later.
54 dot_a_files = [make_static_lib_symlink(ctx.actions, f) for f in std_rlibs]
55
56 alloc_files = [f for f in dot_a_files if "alloc" in f.basename and "std" not in f.basename]
57 between_alloc_and_core_files = [f for f in dot_a_files if "compiler_builtins" in f.basename]
58 core_files = [f for f in dot_a_files if ("core" in f.basename or "adler" in f.basename) and "std" not in f.basename]
Adam Snaider1c095c92023-07-08 02:09:58 -040059 panic_files = [f for f in dot_a_files if f.basename in ["cfg_if", "libc", "panic_abort", "panic_unwind", "unwind"]]
Brian Silvermancc09f182022-03-09 15:40:20 -080060 between_core_and_std_files = [
61 f
62 for f in dot_a_files
Brian Silverman5f6f2762022-08-13 19:30:05 -070063 if "alloc" not in f.basename and "compiler_builtins" not in f.basename and "core" not in f.basename and "adler" not in f.basename and "std" not in f.basename and "memchr" not in f.basename and "test" not in f.basename
Brian Silvermancc09f182022-03-09 15:40:20 -080064 ]
Brian Silverman5f6f2762022-08-13 19:30:05 -070065 memchr_files = [f for f in dot_a_files if "memchr" in f.basename]
Brian Silvermancc09f182022-03-09 15:40:20 -080066 std_files = [f for f in dot_a_files if "std" in f.basename]
Brian Silverman5f6f2762022-08-13 19:30:05 -070067 test_files = [f for f in dot_a_files if "test" in f.basename]
Brian Silvermancc09f182022-03-09 15:40:20 -080068
Brian Silverman5f6f2762022-08-13 19:30:05 -070069 partitioned_files_len = len(alloc_files) + len(between_alloc_and_core_files) + len(core_files) + len(between_core_and_std_files) + len(memchr_files) + len(std_files) + len(test_files)
Brian Silvermancc09f182022-03-09 15:40:20 -080070 if partitioned_files_len != len(dot_a_files):
Brian Silverman5f6f2762022-08-13 19:30:05 -070071 partitioned = alloc_files + between_alloc_and_core_files + core_files + between_core_and_std_files + memchr_files + std_files + test_files
Brian Silvermancc09f182022-03-09 15:40:20 -080072 for f in sorted(partitioned):
73 # buildifier: disable=print
74 print("File partitioned: {}".format(f.basename))
75 fail("rust_toolchain couldn't properly partition rlibs in rust_std. Partitioned {} out of {} files. This is probably a bug in the rule implementation.".format(partitioned_files_len, len(dot_a_files)))
76
77 return [
78 DefaultInfo(
79 files = depset(ctx.files.srcs),
Adam Snaider1c095c92023-07-08 02:09:58 -040080 runfiles = ctx.runfiles(ctx.files.srcs),
Brian Silvermancc09f182022-03-09 15:40:20 -080081 ),
82 rust_common.stdlib_info(
83 std_rlibs = std_rlibs,
84 dot_a_files = dot_a_files,
85 between_alloc_and_core_files = between_alloc_and_core_files,
86 core_files = core_files,
87 between_core_and_std_files = between_core_and_std_files,
88 std_files = std_files,
Brian Silverman5f6f2762022-08-13 19:30:05 -070089 test_files = test_files,
90 memchr_files = memchr_files,
Brian Silvermancc09f182022-03-09 15:40:20 -080091 alloc_files = alloc_files,
92 self_contained_files = self_contained_files,
Adam Snaider1c095c92023-07-08 02:09:58 -040093 panic_files = panic_files,
Brian Silvermancc09f182022-03-09 15:40:20 -080094 srcs = ctx.attr.srcs,
95 ),
96 ]
97
98rust_stdlib_filegroup = rule(
99 doc = "A dedicated filegroup-like rule for Rust stdlib artifacts.",
100 implementation = _rust_stdlib_filegroup_impl,
101 attrs = {
102 "srcs": attr.label_list(
103 allow_files = True,
104 doc = "The list of targets/files that are components of the rust-stdlib file group",
105 mandatory = True,
106 ),
107 },
108)
109
110def _ltl(library, ctx, cc_toolchain, feature_configuration):
111 """A helper to generate `LibraryToLink` objects
112
113 Args:
114 library (File): A rust library file to link.
115 ctx (ctx): The rule's context object.
116 cc_toolchain (CcToolchainInfo): A cc toolchain provider to be used.
117 feature_configuration (feature_configuration): feature_configuration to be queried.
118
119 Returns:
120 LibraryToLink: A provider containing information about libraries to link.
121 """
122 return cc_common.create_library_to_link(
123 actions = ctx.actions,
124 feature_configuration = feature_configuration,
125 cc_toolchain = cc_toolchain,
126 static_library = library,
127 pic_static_library = library,
128 )
129
Adam Snaider1c095c92023-07-08 02:09:58 -0400130def _make_libstd_and_allocator_ccinfo(ctx, rust_std, allocator_library, std = "std"):
Brian Silvermancc09f182022-03-09 15:40:20 -0800131 """Make the CcInfo (if possible) for libstd and allocator libraries.
132
133 Args:
134 ctx (ctx): The rule's context object.
135 rust_std: The Rust standard library.
136 allocator_library: The target to use for providing allocator functions.
Adam Snaider1c095c92023-07-08 02:09:58 -0400137 std: Standard library flavor. Currently only "std" and "no_std_with_alloc" are supported,
138 accompanied with the default panic behavior.
Brian Silvermancc09f182022-03-09 15:40:20 -0800139
140
141 Returns:
142 A CcInfo object for the required libraries, or None if no such libraries are available.
143 """
144 cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
145 cc_infos = []
146
147 if not rust_common.stdlib_info in rust_std:
148 fail(dedent("""\
149 {} --
150 The `rust_lib` ({}) must be a target providing `rust_common.stdlib_info`
151 (typically `rust_stdlib_filegroup` rule from @rules_rust//rust:defs.bzl).
152 See https://github.com/bazelbuild/rules_rust/pull/802 for more information.
153 """).format(ctx.label, rust_std))
154 rust_stdlib_info = rust_std[rust_common.stdlib_info]
155
156 if rust_stdlib_info.self_contained_files:
157 compilation_outputs = cc_common.create_compilation_outputs(
158 objects = depset(rust_stdlib_info.self_contained_files),
159 )
160
161 linking_context, _linking_outputs = cc_common.create_linking_context_from_compilation_outputs(
162 name = ctx.label.name,
163 actions = ctx.actions,
164 feature_configuration = feature_configuration,
165 cc_toolchain = cc_toolchain,
166 compilation_outputs = compilation_outputs,
167 )
168
169 cc_infos.append(CcInfo(
170 linking_context = linking_context,
171 ))
172
173 if rust_stdlib_info.std_rlibs:
174 alloc_inputs = depset(
175 [_ltl(f, ctx, cc_toolchain, feature_configuration) for f in rust_stdlib_info.alloc_files],
176 )
177 between_alloc_and_core_inputs = depset(
178 [_ltl(f, ctx, cc_toolchain, feature_configuration) for f in rust_stdlib_info.between_alloc_and_core_files],
179 transitive = [alloc_inputs],
180 order = "topological",
181 )
182 core_inputs = depset(
183 [_ltl(f, ctx, cc_toolchain, feature_configuration) for f in rust_stdlib_info.core_files],
184 transitive = [between_alloc_and_core_inputs],
185 order = "topological",
186 )
187
188 # The libraries panic_abort and panic_unwind are alternatives.
189 # The std by default requires panic_unwind.
190 # Exclude panic_abort if panic_unwind is present.
191 # TODO: Provide a setting to choose between panic_abort and panic_unwind.
192 filtered_between_core_and_std_files = rust_stdlib_info.between_core_and_std_files
193 has_panic_unwind = [
194 f
195 for f in filtered_between_core_and_std_files
196 if "panic_unwind" in f.basename
197 ]
198 if has_panic_unwind:
199 filtered_between_core_and_std_files = [
200 f
201 for f in filtered_between_core_and_std_files
Adam Snaider1c095c92023-07-08 02:09:58 -0400202 if "abort" not in f.basename
Brian Silvermancc09f182022-03-09 15:40:20 -0800203 ]
Adam Snaider1c095c92023-07-08 02:09:58 -0400204 core_alloc_and_panic_inputs = depset(
205 [
206 _ltl(f, ctx, cc_toolchain, feature_configuration)
207 for f in rust_stdlib_info.panic_files
208 if "unwind" not in f.basename
209 ],
210 transitive = [core_inputs],
211 order = "topological",
212 )
213 else:
214 core_alloc_and_panic_inputs = depset(
215 [
216 _ltl(f, ctx, cc_toolchain, feature_configuration)
217 for f in rust_stdlib_info.panic_files
218 if "unwind" not in f.basename
219 ],
220 transitive = [core_inputs],
221 order = "topological",
222 )
Brian Silverman5f6f2762022-08-13 19:30:05 -0700223 memchr_inputs = depset(
224 [
225 _ltl(f, ctx, cc_toolchain, feature_configuration)
226 for f in rust_stdlib_info.memchr_files
227 ],
228 transitive = [core_inputs],
229 order = "topological",
230 )
Brian Silvermancc09f182022-03-09 15:40:20 -0800231 between_core_and_std_inputs = depset(
232 [
233 _ltl(f, ctx, cc_toolchain, feature_configuration)
234 for f in filtered_between_core_and_std_files
235 ],
Brian Silverman5f6f2762022-08-13 19:30:05 -0700236 transitive = [memchr_inputs],
Brian Silvermancc09f182022-03-09 15:40:20 -0800237 order = "topological",
238 )
239 std_inputs = depset(
240 [
241 _ltl(f, ctx, cc_toolchain, feature_configuration)
242 for f in rust_stdlib_info.std_files
243 ],
244 transitive = [between_core_and_std_inputs],
245 order = "topological",
246 )
Brian Silverman5f6f2762022-08-13 19:30:05 -0700247 test_inputs = depset(
248 [
249 _ltl(f, ctx, cc_toolchain, feature_configuration)
250 for f in rust_stdlib_info.test_files
251 ],
252 transitive = [std_inputs],
253 order = "topological",
254 )
Brian Silvermancc09f182022-03-09 15:40:20 -0800255
Adam Snaider1c095c92023-07-08 02:09:58 -0400256 if std == "std":
257 link_inputs = cc_common.create_linker_input(
258 owner = rust_std.label,
259 libraries = test_inputs,
260 )
261 elif std == "no_std_with_alloc":
262 link_inputs = cc_common.create_linker_input(
263 owner = rust_std.label,
264 libraries = core_alloc_and_panic_inputs,
265 )
266 else:
267 fail("Requested '{}' std mode is currently not supported.".format(std))
Brian Silvermancc09f182022-03-09 15:40:20 -0800268
269 allocator_inputs = None
270 if allocator_library:
271 allocator_inputs = [allocator_library[CcInfo].linking_context.linker_inputs]
272
273 cc_infos.append(CcInfo(
274 linking_context = cc_common.create_linking_context(
275 linker_inputs = depset(
276 [link_inputs],
277 transitive = allocator_inputs,
278 order = "topological",
279 ),
280 ),
281 ))
282
283 if cc_infos:
284 return cc_common.merge_cc_infos(
285 direct_cc_infos = cc_infos,
286 )
287 return None
288
289def _symlink_sysroot_tree(ctx, name, target):
290 """Generate a set of symlinks to files from another target
291
292 Args:
293 ctx (ctx): The toolchain's context object
294 name (str): The name of the sysroot directory (typically `ctx.label.name`)
295 target (Target): A target owning files to symlink
296
297 Returns:
298 depset[File]: A depset of the generated symlink files
299 """
300 tree_files = []
301 for file in target.files.to_list():
302 # Parse the path to the file relative to the workspace root so a
303 # symlink matching this path can be created within the sysroot.
304
305 # The code blow attempts to parse any workspace names out of the
306 # path. For local targets, this code is a noop.
307 if target.label.workspace_root:
308 file_path = file.path.split(target.label.workspace_root, 1)[-1]
309 else:
310 file_path = file.path
311
312 symlink = ctx.actions.declare_file("{}/{}".format(name, file_path.lstrip("/")))
313
314 ctx.actions.symlink(
315 output = symlink,
316 target_file = file,
317 )
318
319 tree_files.append(symlink)
320
321 return depset(tree_files)
322
323def _symlink_sysroot_bin(ctx, name, directory, target):
324 """Crete a symlink to a target file.
325
326 Args:
327 ctx (ctx): The rule's context object
328 name (str): A common name for the output directory
329 directory (str): The directory under `name` to put the file in
330 target (File): A File object to symlink to
331
332 Returns:
333 File: A newly generated symlink file
334 """
335 symlink = ctx.actions.declare_file("{}/{}/{}".format(
336 name,
337 directory,
338 target.basename,
339 ))
340
341 ctx.actions.symlink(
342 output = symlink,
343 target_file = target,
344 is_executable = True,
345 )
346
347 return symlink
348
349def _generate_sysroot(
350 ctx,
351 rustc,
352 rustdoc,
353 rustc_lib,
354 cargo = None,
355 clippy = None,
356 llvm_tools = None,
357 rust_std = None,
358 rustfmt = None):
359 """Generate a rust sysroot from collection of toolchain components
360
361 Args:
362 ctx (ctx): A context object from a `rust_toolchain` rule.
363 rustc (File): The path to a `rustc` executable.
364 rustdoc (File): The path to a `rustdoc` executable.
365 rustc_lib (Target): A collection of Files containing dependencies of `rustc`.
366 cargo (File, optional): The path to a `cargo` executable.
367 clippy (File, optional): The path to a `clippy-driver` executable.
368 llvm_tools (Target, optional): A collection of llvm tools used by `rustc`.
369 rust_std (Target, optional): A collection of Files containing Rust standard library components.
370 rustfmt (File, optional): The path to a `rustfmt` executable.
371
372 Returns:
373 struct: A struct of generated files representing the new sysroot
374 """
375 name = ctx.label.name
376
377 # Define runfiles
378 direct_files = []
379 transitive_file_sets = []
380
381 # Rustc
382 sysroot_rustc = _symlink_sysroot_bin(ctx, name, "bin", rustc)
383 direct_files.extend([sysroot_rustc])
384
385 # Rustc dependencies
386 sysroot_rustc_lib = None
387 if rustc_lib:
388 sysroot_rustc_lib = _symlink_sysroot_tree(ctx, name, rustc_lib)
389 transitive_file_sets.extend([sysroot_rustc_lib])
390
391 # Rustdoc
392 sysroot_rustdoc = _symlink_sysroot_bin(ctx, name, "bin", rustdoc)
393 direct_files.extend([sysroot_rustdoc])
394
395 # Clippy
396 sysroot_clippy = None
397 if clippy:
398 sysroot_clippy = _symlink_sysroot_bin(ctx, name, "bin", clippy)
399 direct_files.extend([sysroot_clippy])
400
401 # Cargo
402 sysroot_cargo = None
403 if cargo:
404 sysroot_cargo = _symlink_sysroot_bin(ctx, name, "bin", cargo)
405 direct_files.extend([sysroot_cargo])
406
407 # Rustfmt
408 sysroot_rustfmt = None
409 if rustfmt:
410 sysroot_rustfmt = _symlink_sysroot_bin(ctx, name, "bin", rustfmt)
411 direct_files.extend([sysroot_rustfmt])
412
413 # Llvm tools
414 sysroot_llvm_tools = None
415 if llvm_tools:
416 sysroot_llvm_tools = _symlink_sysroot_tree(ctx, name, llvm_tools)
417 transitive_file_sets.extend([sysroot_llvm_tools])
418
419 # Rust standard library
420 sysroot_rust_std = None
421 if rust_std:
422 sysroot_rust_std = _symlink_sysroot_tree(ctx, name, rust_std)
423 transitive_file_sets.extend([sysroot_rust_std])
424
425 # Declare a file in the root of the sysroot to make locating the sysroot easy
426 sysroot_anchor = ctx.actions.declare_file("{}/rust.sysroot".format(name))
427 ctx.actions.write(
428 output = sysroot_anchor,
429 content = "\n".join([
430 "cargo: {}".format(cargo),
431 "clippy: {}".format(clippy),
432 "llvm_tools: {}".format(llvm_tools),
433 "rust_std: {}".format(rust_std),
434 "rustc_lib: {}".format(rustc_lib),
435 "rustc: {}".format(rustc),
436 "rustdoc: {}".format(rustdoc),
437 "rustfmt: {}".format(rustfmt),
438 ]),
439 )
440
441 # Create a depset of all sysroot files (symlinks and their real paths)
442 all_files = depset(direct_files, transitive = transitive_file_sets)
443
444 return struct(
445 all_files = all_files,
446 cargo = sysroot_cargo,
447 clippy = sysroot_clippy,
448 rust_std = sysroot_rust_std,
449 rustc = sysroot_rustc,
450 rustc_lib = sysroot_rustc_lib,
451 rustdoc = sysroot_rustdoc,
452 rustfmt = sysroot_rustfmt,
453 sysroot_anchor = sysroot_anchor,
454 )
455
456def _rust_toolchain_impl(ctx):
457 """The rust_toolchain implementation
458
459 Args:
460 ctx (ctx): The rule's context object
461
462 Returns:
463 list: A list containing the target's toolchain Provider info
464 """
465 compilation_mode_opts = {}
466 for k, v in ctx.attr.opt_level.items():
467 if not k in ctx.attr.debug_info:
468 fail("Compilation mode {} is not defined in debug_info but is defined opt_level".format(k))
469 compilation_mode_opts[k] = struct(debug_info = ctx.attr.debug_info[k], opt_level = v)
470 for k, v in ctx.attr.debug_info.items():
471 if not k in ctx.attr.opt_level:
472 fail("Compilation mode {} is not defined in opt_level but is defined debug_info".format(k))
473
Brian Silvermancc09f182022-03-09 15:40:20 -0800474 rename_first_party_crates = ctx.attr._rename_first_party_crates[BuildSettingInfo].value
475 third_party_dir = ctx.attr._third_party_dir[BuildSettingInfo].value
Brian Silverman5f6f2762022-08-13 19:30:05 -0700476 pipelined_compilation = ctx.attr._pipelined_compilation[BuildSettingInfo].value
Adam Snaider1c095c92023-07-08 02:09:58 -0400477 no_std = ctx.attr._no_std[BuildSettingInfo].value
Brian Silverman5f6f2762022-08-13 19:30:05 -0700478
479 experimental_use_cc_common_link = ctx.attr.experimental_use_cc_common_link[BuildSettingInfo].value
Adam Snaider1c095c92023-07-08 02:09:58 -0400480 experimental_use_global_allocator = ctx.attr._experimental_use_global_allocator[BuildSettingInfo].value
481 if experimental_use_cc_common_link:
482 if experimental_use_global_allocator and not ctx.attr.global_allocator_library:
483 fail("rust_toolchain.experimental_use_cc_common_link with --@rules_rust//rust/settings:experimental_use_global_allocator " +
484 "requires rust_toolchain.global_allocator_library to be set")
485 if not ctx.attr.allocator_library:
486 fail("rust_toolchain.experimental_use_cc_common_link requires rust_toolchain.allocator_library to be set")
487 if experimental_use_global_allocator and not experimental_use_cc_common_link:
488 fail(
489 "Using @rules_rust//rust/settings:experimental_use_global_allocator requires" +
490 "--@rules_rust//rust/settings:experimental_use_cc_common_link to be set",
491 )
Brian Silvermancc09f182022-03-09 15:40:20 -0800492
Adam Snaider1c095c92023-07-08 02:09:58 -0400493 rust_std = ctx.attr.rust_std
Brian Silvermancc09f182022-03-09 15:40:20 -0800494
495 sysroot = _generate_sysroot(
496 ctx = ctx,
497 rustc = ctx.file.rustc,
498 rustdoc = ctx.file.rust_doc,
499 rustc_lib = ctx.attr.rustc_lib,
500 rust_std = rust_std,
501 rustfmt = ctx.file.rustfmt,
502 clippy = ctx.file.clippy_driver,
503 cargo = ctx.file.cargo,
504 llvm_tools = ctx.attr.llvm_tools,
505 )
506
507 expanded_stdlib_linkflags = []
508 for flag in ctx.attr.stdlib_linkflags:
509 expanded_stdlib_linkflags.append(
Adam Snaider1c095c92023-07-08 02:09:58 -0400510 dedup_expand_location(
511 ctx,
Brian Silvermancc09f182022-03-09 15:40:20 -0800512 flag,
513 targets = rust_std[rust_common.stdlib_info].srcs,
514 ),
515 )
516
517 linking_context = cc_common.create_linking_context(
518 linker_inputs = depset([
519 cc_common.create_linker_input(
520 owner = ctx.label,
521 user_link_flags = depset(expanded_stdlib_linkflags),
522 ),
523 ]),
524 )
525
526 # Contains linker flags needed to link Rust standard library.
527 # These need to be added to linker command lines when the linker is not rustc
528 # (rustc does this automatically). Linker flags wrapped in an otherwise empty
529 # `CcInfo` to provide the flags in a way that doesn't duplicate them per target
530 # providing a `CcInfo`.
531 stdlib_linkflags_cc_info = CcInfo(
532 compilation_context = cc_common.create_compilation_context(),
533 linking_context = linking_context,
534 )
535
536 # Determine the path and short_path of the sysroot
537 sysroot_path = sysroot.sysroot_anchor.dirname
538 sysroot_short_path, _, _ = sysroot.sysroot_anchor.short_path.rpartition("/")
539
Brian Silverman5f6f2762022-08-13 19:30:05 -0700540 # Variables for make variable expansion
541 make_variables = {
542 "RUSTC": sysroot.rustc.path,
543 "RUSTDOC": sysroot.rustdoc.path,
544 "RUST_DEFAULT_EDITION": ctx.attr.default_edition or "",
545 "RUST_SYSROOT": sysroot_path,
546 }
547
548 if sysroot.cargo:
549 make_variables.update({
550 "CARGO": sysroot.cargo.path,
551 })
552
553 if sysroot.rustfmt:
554 make_variables.update({
555 "RUSTFMT": sysroot.rustfmt.path,
556 })
557
558 make_variable_info = platform_common.TemplateVariableInfo(make_variables)
559
Adam Snaider1c095c92023-07-08 02:09:58 -0400560 exec_triple = triple(ctx.attr.exec_triple)
561
562 if not exec_triple.system:
563 fail("No system was provided for the execution platform. Please update {}".format(
564 ctx.label,
565 ))
566
567 if ctx.attr.target_triple and ctx.attr.target_json:
568 fail("Do not specify both target_triple and target_json, either use a builtin triple or provide a custom specification file. Please update {}".format(
569 ctx.label,
570 ))
571
572 target_triple = None
573 target_json = None
574 target_arch = None
575 target_os = None
576
577 if ctx.attr.target_triple:
578 target_triple = triple(ctx.attr.target_triple)
579 target_arch = target_triple.arch
580 target_os = target_triple.system
581
582 elif ctx.attr.target_json:
583 # Ensure the data provided is valid json
584 target_json_content = json.decode(ctx.attr.target_json)
585 target_json = ctx.actions.declare_file("{}.target.json".format(ctx.label.name))
586
587 ctx.actions.write(
588 output = target_json,
589 content = json.encode_indent(target_json_content, indent = " " * 4),
590 )
591
592 if "arch" in target_json_content:
593 target_arch = target_json_content["arch"]
594 if "os" in target_json_content:
595 target_os = target_json_content["os"]
596 else:
597 fail("Either `target_triple` or `target_json` must be provided. Please update {}".format(
598 ctx.label,
599 ))
600
Brian Silvermancc09f182022-03-09 15:40:20 -0800601 toolchain = platform_common.ToolchainInfo(
602 all_files = sysroot.all_files,
603 binary_ext = ctx.attr.binary_ext,
604 cargo = sysroot.cargo,
605 clippy_driver = sysroot.clippy,
606 compilation_mode_opts = compilation_mode_opts,
607 crosstool_files = ctx.files._cc_toolchain,
608 default_edition = ctx.attr.default_edition,
609 dylib_ext = ctx.attr.dylib_ext,
Brian Silverman5f6f2762022-08-13 19:30:05 -0700610 env = ctx.attr.env,
Adam Snaider1c095c92023-07-08 02:09:58 -0400611 exec_triple = exec_triple,
612 libstd_and_allocator_ccinfo = _make_libstd_and_allocator_ccinfo(ctx, rust_std, ctx.attr.allocator_library, "std"),
613 libstd_and_global_allocator_ccinfo = _make_libstd_and_allocator_ccinfo(ctx, rust_std, ctx.attr.global_allocator_library, "std"),
614 nostd_and_global_allocator_cc_info = _make_libstd_and_allocator_ccinfo(ctx, rust_std, ctx.attr.global_allocator_library, "no_std_with_alloc"),
Brian Silverman5f6f2762022-08-13 19:30:05 -0700615 llvm_cov = ctx.file.llvm_cov,
616 llvm_profdata = ctx.file.llvm_profdata,
617 make_variables = make_variable_info,
Brian Silvermancc09f182022-03-09 15:40:20 -0800618 rust_doc = sysroot.rustdoc,
Brian Silvermancc09f182022-03-09 15:40:20 -0800619 rust_std = sysroot.rust_std,
620 rust_std_paths = depset([file.dirname for file in sysroot.rust_std.to_list()]),
621 rustc = sysroot.rustc,
622 rustc_lib = sysroot.rustc_lib,
Brian Silvermancc09f182022-03-09 15:40:20 -0800623 rustfmt = sysroot.rustfmt,
624 staticlib_ext = ctx.attr.staticlib_ext,
625 stdlib_linkflags = stdlib_linkflags_cc_info,
Adam Snaider1c095c92023-07-08 02:09:58 -0400626 extra_rustc_flags = ctx.attr.extra_rustc_flags,
627 extra_exec_rustc_flags = ctx.attr.extra_exec_rustc_flags,
628 per_crate_rustc_flags = ctx.attr.per_crate_rustc_flags,
Brian Silvermancc09f182022-03-09 15:40:20 -0800629 sysroot = sysroot_path,
630 sysroot_short_path = sysroot_short_path,
Adam Snaider1c095c92023-07-08 02:09:58 -0400631 target_arch = target_arch,
632 target_flag_value = target_json.path if target_json else target_triple.str,
633 target_json = target_json,
634 target_os = target_os,
635 target_triple = target_triple,
Brian Silvermancc09f182022-03-09 15:40:20 -0800636
637 # Experimental and incompatible flags
638 _rename_first_party_crates = rename_first_party_crates,
639 _third_party_dir = third_party_dir,
Brian Silverman5f6f2762022-08-13 19:30:05 -0700640 _pipelined_compilation = pipelined_compilation,
641 _experimental_use_cc_common_link = experimental_use_cc_common_link,
Adam Snaider1c095c92023-07-08 02:09:58 -0400642 _experimental_use_global_allocator = experimental_use_global_allocator,
643 _no_std = no_std,
Brian Silvermancc09f182022-03-09 15:40:20 -0800644 )
Brian Silverman5f6f2762022-08-13 19:30:05 -0700645 return [
646 toolchain,
647 make_variable_info,
648 ]
Brian Silvermancc09f182022-03-09 15:40:20 -0800649
650rust_toolchain = rule(
651 implementation = _rust_toolchain_impl,
652 fragments = ["cpp"],
653 attrs = {
654 "allocator_library": attr.label(
655 doc = "Target that provides allocator functions when rust_library targets are embedded in a cc_binary.",
656 ),
657 "binary_ext": attr.string(
658 doc = "The extension for binaries created from rustc.",
659 mandatory = True,
660 ),
661 "cargo": attr.label(
662 doc = "The location of the `cargo` binary. Can be a direct source or a filegroup containing one item.",
663 allow_single_file = True,
664 cfg = "exec",
665 ),
666 "clippy_driver": attr.label(
667 doc = "The location of the `clippy-driver` binary. Can be a direct source or a filegroup containing one item.",
668 allow_single_file = True,
669 cfg = "exec",
670 ),
671 "debug_info": attr.string_dict(
672 doc = "Rustc debug info levels per opt level",
673 default = {
674 "dbg": "2",
675 "fastbuild": "0",
676 "opt": "0",
677 },
678 ),
679 "default_edition": attr.string(
Brian Silverman5f6f2762022-08-13 19:30:05 -0700680 doc = (
681 "The edition to use for rust_* rules that don't specify an edition. " +
682 "If absent, every rule is required to specify its `edition` attribute."
683 ),
Brian Silvermancc09f182022-03-09 15:40:20 -0800684 ),
685 "dylib_ext": attr.string(
686 doc = "The extension for dynamic libraries created from rustc.",
687 mandatory = True,
688 ),
Brian Silverman5f6f2762022-08-13 19:30:05 -0700689 "env": attr.string_dict(
690 doc = "Environment variables to set in actions.",
691 ),
Brian Silvermancc09f182022-03-09 15:40:20 -0800692 "exec_triple": attr.string(
693 doc = (
694 "The platform triple for the toolchains execution environment. " +
695 "For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurations"
696 ),
697 mandatory = True,
698 ),
Brian Silverman5f6f2762022-08-13 19:30:05 -0700699 "experimental_use_cc_common_link": attr.label(
700 default = Label("//rust/settings:experimental_use_cc_common_link"),
701 doc = "Label to a boolean build setting that controls whether cc_common.link is used to link rust binaries.",
702 ),
Adam Snaider1c095c92023-07-08 02:09:58 -0400703 "extra_exec_rustc_flags": attr.string_list(
704 doc = "Extra flags to pass to rustc in exec configuration",
705 ),
706 "extra_rustc_flags": attr.string_list(
707 doc = "Extra flags to pass to rustc in non-exec configuration",
708 ),
709 "global_allocator_library": attr.label(
710 doc = "Target that provides allocator functions for when a global allocator is present.",
711 ),
Brian Silverman5f6f2762022-08-13 19:30:05 -0700712 "llvm_cov": attr.label(
713 doc = "The location of the `llvm-cov` binary. Can be a direct source or a filegroup containing one item. If None, rust code is not instrumented for coverage.",
714 allow_single_file = True,
715 cfg = "exec",
716 ),
717 "llvm_profdata": attr.label(
718 doc = "The location of the `llvm-profdata` binary. Can be a direct source or a filegroup containing one item. If `llvm_cov` is None, this can be None as well and rust code is not instrumented for coverage.",
719 allow_single_file = True,
720 cfg = "exec",
721 ),
Brian Silvermancc09f182022-03-09 15:40:20 -0800722 "llvm_tools": attr.label(
723 doc = "LLVM tools that are shipped with the Rust toolchain.",
724 allow_files = True,
725 ),
726 "opt_level": attr.string_dict(
727 doc = "Rustc optimization levels.",
728 default = {
729 "dbg": "0",
730 "fastbuild": "0",
731 "opt": "3",
732 },
733 ),
Adam Snaider1c095c92023-07-08 02:09:58 -0400734 "per_crate_rustc_flags": attr.string_list(
735 doc = "Extra flags to pass to rustc in non-exec configuration",
Brian Silvermancc09f182022-03-09 15:40:20 -0800736 ),
737 "rust_doc": attr.label(
738 doc = "The location of the `rustdoc` binary. Can be a direct source or a filegroup containing one item.",
739 allow_single_file = True,
740 cfg = "exec",
741 mandatory = True,
742 ),
Brian Silvermancc09f182022-03-09 15:40:20 -0800743 "rust_std": attr.label(
744 doc = "The Rust standard library.",
Adam Snaider1c095c92023-07-08 02:09:58 -0400745 mandatory = True,
Brian Silvermancc09f182022-03-09 15:40:20 -0800746 ),
747 "rustc": attr.label(
748 doc = "The location of the `rustc` binary. Can be a direct source or a filegroup containing one item.",
749 allow_single_file = True,
750 cfg = "exec",
751 mandatory = True,
752 ),
753 "rustc_lib": attr.label(
754 doc = "The libraries used by rustc during compilation.",
755 cfg = "exec",
756 ),
Brian Silvermancc09f182022-03-09 15:40:20 -0800757 "rustfmt": attr.label(
Adam Snaider1c095c92023-07-08 02:09:58 -0400758 doc = "**Deprecated**: Instead see [rustfmt_toolchain](#rustfmt_toolchain)",
Brian Silvermancc09f182022-03-09 15:40:20 -0800759 allow_single_file = True,
760 cfg = "exec",
761 ),
762 "staticlib_ext": attr.string(
763 doc = "The extension for static libraries created from rustc.",
764 mandatory = True,
765 ),
766 "stdlib_linkflags": attr.string_list(
767 doc = (
768 "Additional linker flags to use when Rust standard library is linked by a C++ linker " +
769 "(rustc will deal with these automatically). Subject to location expansion with respect " +
770 "to the srcs of the `rust_std` attribute."
771 ),
772 mandatory = True,
773 ),
Adam Snaider1c095c92023-07-08 02:09:58 -0400774 "target_json": attr.string(
Brian Silvermancc09f182022-03-09 15:40:20 -0800775 doc = ("Override the target_triple with a custom target specification. " +
776 "For more details see: https://doc.rust-lang.org/rustc/targets/custom.html"),
Brian Silvermancc09f182022-03-09 15:40:20 -0800777 ),
778 "target_triple": attr.string(
779 doc = (
780 "The platform triple for the toolchains target environment. " +
781 "For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurations"
782 ),
783 ),
784 "_cc_toolchain": attr.label(
Brian Silverman5f6f2762022-08-13 19:30:05 -0700785 default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
786 ),
Adam Snaider1c095c92023-07-08 02:09:58 -0400787 "_experimental_use_global_allocator": attr.label(
788 default = Label("//rust/settings:experimental_use_global_allocator"),
789 doc = (
790 "Label to a boolean build setting that informs the target build whether a global allocator is being used." +
791 "This flag is only relevant when used together with --@rules_rust//rust/settings:experimental_use_global_allocator."
792 ),
793 ),
794 "_no_std": attr.label(
795 default = Label("//:no_std"),
796 ),
Brian Silverman5f6f2762022-08-13 19:30:05 -0700797 "_pipelined_compilation": attr.label(
Adam Snaider1c095c92023-07-08 02:09:58 -0400798 default = Label("//rust/settings:pipelined_compilation"),
Brian Silvermancc09f182022-03-09 15:40:20 -0800799 ),
800 "_rename_first_party_crates": attr.label(
Brian Silverman5f6f2762022-08-13 19:30:05 -0700801 default = Label("//rust/settings:rename_first_party_crates"),
Brian Silvermancc09f182022-03-09 15:40:20 -0800802 ),
803 "_third_party_dir": attr.label(
Brian Silverman5f6f2762022-08-13 19:30:05 -0700804 default = Label("//rust/settings:third_party_dir"),
Brian Silvermancc09f182022-03-09 15:40:20 -0800805 ),
806 },
807 toolchains = [
808 "@bazel_tools//tools/cpp:toolchain_type",
809 ],
810 incompatible_use_toolchain_transition = True,
811 doc = """Declares a Rust toolchain for use.
812
813This is for declaring a custom toolchain, eg. for configuring a particular version of rust or supporting a new platform.
814
815Example:
816
817Suppose the core rust team has ported the compiler to a new target CPU, called `cpuX`. This \
818support can be used in Bazel by defining a new toolchain definition and declaration:
819
820```python
821load('@rules_rust//rust:toolchain.bzl', 'rust_toolchain')
822
823rust_toolchain(
824 name = "rust_cpuX_impl",
Adam Snaider1c095c92023-07-08 02:09:58 -0400825 binary_ext = "",
826 dylib_ext = ".so",
827 exec_triple = "cpuX-unknown-linux-gnu",
828 rust_doc = "@rust_cpuX//:rustdoc",
829 rust_std = "@rust_cpuX//:rust_std",
Brian Silvermancc09f182022-03-09 15:40:20 -0800830 rustc = "@rust_cpuX//:rustc",
831 rustc_lib = "@rust_cpuX//:rustc_lib",
Brian Silvermancc09f182022-03-09 15:40:20 -0800832 staticlib_ext = ".a",
Brian Silvermancc09f182022-03-09 15:40:20 -0800833 stdlib_linkflags = ["-lpthread", "-ldl"],
Adam Snaider1c095c92023-07-08 02:09:58 -0400834 target_triple = "cpuX-unknown-linux-gnu",
Brian Silvermancc09f182022-03-09 15:40:20 -0800835)
836
837toolchain(
838 name = "rust_cpuX",
839 exec_compatible_with = [
840 "@platforms//cpu:cpuX",
Adam Snaider1c095c92023-07-08 02:09:58 -0400841 "@platforms//os:linux",
Brian Silvermancc09f182022-03-09 15:40:20 -0800842 ],
843 target_compatible_with = [
844 "@platforms//cpu:cpuX",
Adam Snaider1c095c92023-07-08 02:09:58 -0400845 "@platforms//os:linux",
Brian Silvermancc09f182022-03-09 15:40:20 -0800846 ],
847 toolchain = ":rust_cpuX_impl",
848)
849```
850
851Then, either add the label of the toolchain rule to `register_toolchains` in the WORKSPACE, or pass \
852it to the `"--extra_toolchains"` flag for Bazel, and it will be used.
853
Adam Snaider1c095c92023-07-08 02:09:58 -0400854See `@rules_rust//rust:repositories.bzl` for examples of defining the `@rust_cpuX` repository \
Brian Silvermancc09f182022-03-09 15:40:20 -0800855with the actual binaries and libraries.
856""",
857)