fork/rules_rust

git clone https://git.julia.blue/fork/rules_rust

UebelAndreVarious cleanups (#1828)9adfdca9

rust-analyzer
28.8 KiB788 linesraw
1"""The rust_toolchain rule definition and implementation."""
2
3load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
4load("//rust/platform:triple.bzl", "triple")
5load("//rust/private:common.bzl", "rust_common")
6load("//rust/private:rust_analyzer.bzl", _rust_analyzer_toolchain = "rust_analyzer_toolchain")
7load(
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)
19
20rust_analyzer_toolchain = _rust_analyzer_toolchain
21rustfmt_toolchain = _rustfmt_toolchain
22current_rustfmt_toolchain = _current_rustfmt_toolchain
23
24def _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 = []
31    test_files = []
32    memchr_files = []
33    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    ]
39
40    std_rlibs = [f for f in rust_std if f.basename.endswith(".rlib")]
41    if std_rlibs:
42        # test depends on std
43        # std depends on everything except test
44        #
45        # core only depends on alloc, but we poke adler in there
46        # because that needs to be before miniz_oxide
47        #
48        # alloc depends on the allocator_library if it's configured, but we
49        # do that later.
50        dot_a_files = [make_static_lib_symlink(ctx.actions, f) for f in std_rlibs]
51
52        alloc_files = [f for f in dot_a_files if "alloc" in f.basename and "std" not in f.basename]
53        between_alloc_and_core_files = [f for f in dot_a_files if "compiler_builtins" in f.basename]
54        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]
55        between_core_and_std_files = [
56            f
57            for f in dot_a_files
58            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
59        ]
60        memchr_files = [f for f in dot_a_files if "memchr" in f.basename]
61        std_files = [f for f in dot_a_files if "std" in f.basename]
62        test_files = [f for f in dot_a_files if "test" in f.basename]
63
64        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)
65        if partitioned_files_len != len(dot_a_files):
66            partitioned = alloc_files + between_alloc_and_core_files + core_files + between_core_and_std_files + memchr_files + std_files + test_files
67            for f in sorted(partitioned):
68                # buildifier: disable=print
69                print("File partitioned: {}".format(f.basename))
70            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)))
71
72    return [
73        DefaultInfo(
74            files = depset(ctx.files.srcs),
75        ),
76        rust_common.stdlib_info(
77            std_rlibs = std_rlibs,
78            dot_a_files = dot_a_files,
79            between_alloc_and_core_files = between_alloc_and_core_files,
80            core_files = core_files,
81            between_core_and_std_files = between_core_and_std_files,
82            std_files = std_files,
83            test_files = test_files,
84            memchr_files = memchr_files,
85            alloc_files = alloc_files,
86            self_contained_files = self_contained_files,
87            srcs = ctx.attr.srcs,
88        ),
89    ]
90
91rust_stdlib_filegroup = rule(
92    doc = "A dedicated filegroup-like rule for Rust stdlib artifacts.",
93    implementation = _rust_stdlib_filegroup_impl,
94    attrs = {
95        "srcs": attr.label_list(
96            allow_files = True,
97            doc = "The list of targets/files that are components of the rust-stdlib file group",
98            mandatory = True,
99        ),
100    },
101)
102
103def _ltl(library, ctx, cc_toolchain, feature_configuration):
104    """A helper to generate `LibraryToLink` objects
105
106    Args:
107        library (File): A rust library file to link.
108        ctx (ctx): The rule's context object.
109        cc_toolchain (CcToolchainInfo): A cc toolchain provider to be used.
110        feature_configuration (feature_configuration): feature_configuration to be queried.
111
112    Returns:
113        LibraryToLink: A provider containing information about libraries to link.
114    """
115    return cc_common.create_library_to_link(
116        actions = ctx.actions,
117        feature_configuration = feature_configuration,
118        cc_toolchain = cc_toolchain,
119        static_library = library,
120        pic_static_library = library,
121    )
122
123def _make_libstd_and_allocator_ccinfo(ctx, rust_std, allocator_library):
124    """Make the CcInfo (if possible) for libstd and allocator libraries.
125
126    Args:
127        ctx (ctx): The rule's context object.
128        rust_std: The Rust standard library.
129        allocator_library: The target to use for providing allocator functions.
130
131
132    Returns:
133        A CcInfo object for the required libraries, or None if no such libraries are available.
134    """
135    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
136    cc_infos = []
137
138    if not rust_common.stdlib_info in rust_std:
139        fail(dedent("""\
140            {} --
141            The `rust_lib` ({}) must be a target providing `rust_common.stdlib_info`
142            (typically `rust_stdlib_filegroup` rule from @rules_rust//rust:defs.bzl).
143            See https://github.com/bazelbuild/rules_rust/pull/802 for more information.
144        """).format(ctx.label, rust_std))
145    rust_stdlib_info = rust_std[rust_common.stdlib_info]
146
147    if rust_stdlib_info.self_contained_files:
148        compilation_outputs = cc_common.create_compilation_outputs(
149            objects = depset(rust_stdlib_info.self_contained_files),
150        )
151
152        linking_context, _linking_outputs = cc_common.create_linking_context_from_compilation_outputs(
153            name = ctx.label.name,
154            actions = ctx.actions,
155            feature_configuration = feature_configuration,
156            cc_toolchain = cc_toolchain,
157            compilation_outputs = compilation_outputs,
158        )
159
160        cc_infos.append(CcInfo(
161            linking_context = linking_context,
162        ))
163
164    if rust_stdlib_info.std_rlibs:
165        alloc_inputs = depset(
166            [_ltl(f, ctx, cc_toolchain, feature_configuration) for f in rust_stdlib_info.alloc_files],
167        )
168        between_alloc_and_core_inputs = depset(
169            [_ltl(f, ctx, cc_toolchain, feature_configuration) for f in rust_stdlib_info.between_alloc_and_core_files],
170            transitive = [alloc_inputs],
171            order = "topological",
172        )
173        core_inputs = depset(
174            [_ltl(f, ctx, cc_toolchain, feature_configuration) for f in rust_stdlib_info.core_files],
175            transitive = [between_alloc_and_core_inputs],
176            order = "topological",
177        )
178
179        # The libraries panic_abort and panic_unwind are alternatives.
180        # The std by default requires panic_unwind.
181        # Exclude panic_abort if panic_unwind is present.
182        # TODO: Provide a setting to choose between panic_abort and panic_unwind.
183        filtered_between_core_and_std_files = rust_stdlib_info.between_core_and_std_files
184        has_panic_unwind = [
185            f
186            for f in filtered_between_core_and_std_files
187            if "panic_unwind" in f.basename
188        ]
189        if has_panic_unwind:
190            filtered_between_core_and_std_files = [
191                f
192                for f in filtered_between_core_and_std_files
193                if "panic_abort" not in f.basename
194            ]
195        memchr_inputs = depset(
196            [
197                _ltl(f, ctx, cc_toolchain, feature_configuration)
198                for f in rust_stdlib_info.memchr_files
199            ],
200            transitive = [core_inputs],
201            order = "topological",
202        )
203        between_core_and_std_inputs = depset(
204            [
205                _ltl(f, ctx, cc_toolchain, feature_configuration)
206                for f in filtered_between_core_and_std_files
207            ],
208            transitive = [memchr_inputs],
209            order = "topological",
210        )
211        std_inputs = depset(
212            [
213                _ltl(f, ctx, cc_toolchain, feature_configuration)
214                for f in rust_stdlib_info.std_files
215            ],
216            transitive = [between_core_and_std_inputs],
217            order = "topological",
218        )
219        test_inputs = depset(
220            [
221                _ltl(f, ctx, cc_toolchain, feature_configuration)
222                for f in rust_stdlib_info.test_files
223            ],
224            transitive = [std_inputs],
225            order = "topological",
226        )
227
228        link_inputs = cc_common.create_linker_input(
229            owner = rust_std.label,
230            libraries = test_inputs,
231        )
232
233        allocator_inputs = None
234        if allocator_library:
235            allocator_inputs = [allocator_library[CcInfo].linking_context.linker_inputs]
236
237        cc_infos.append(CcInfo(
238            linking_context = cc_common.create_linking_context(
239                linker_inputs = depset(
240                    [link_inputs],
241                    transitive = allocator_inputs,
242                    order = "topological",
243                ),
244            ),
245        ))
246
247    if cc_infos:
248        return cc_common.merge_cc_infos(
249            direct_cc_infos = cc_infos,
250        )
251    return None
252
253def _symlink_sysroot_tree(ctx, name, target):
254    """Generate a set of symlinks to files from another target
255
256    Args:
257        ctx (ctx): The toolchain's context object
258        name (str): The name of the sysroot directory (typically `ctx.label.name`)
259        target (Target): A target owning files to symlink
260
261    Returns:
262        depset[File]: A depset of the generated symlink files
263    """
264    tree_files = []
265    for file in target.files.to_list():
266        # Parse the path to the file relative to the workspace root so a
267        # symlink matching this path can be created within the sysroot.
268
269        # The code blow attempts to parse any workspace names out of the
270        # path. For local targets, this code is a noop.
271        if target.label.workspace_root:
272            file_path = file.path.split(target.label.workspace_root, 1)[-1]
273        else:
274            file_path = file.path
275
276        symlink = ctx.actions.declare_file("{}/{}".format(name, file_path.lstrip("/")))
277
278        ctx.actions.symlink(
279            output = symlink,
280            target_file = file,
281        )
282
283        tree_files.append(symlink)
284
285    return depset(tree_files)
286
287def _symlink_sysroot_bin(ctx, name, directory, target):
288    """Crete a symlink to a target file.
289
290    Args:
291        ctx (ctx): The rule's context object
292        name (str): A common name for the output directory
293        directory (str): The directory under `name` to put the file in
294        target (File): A File object to symlink to
295
296    Returns:
297        File: A newly generated symlink file
298    """
299    symlink = ctx.actions.declare_file("{}/{}/{}".format(
300        name,
301        directory,
302        target.basename,
303    ))
304
305    ctx.actions.symlink(
306        output = symlink,
307        target_file = target,
308        is_executable = True,
309    )
310
311    return symlink
312
313def _generate_sysroot(
314        ctx,
315        rustc,
316        rustdoc,
317        rustc_lib,
318        cargo = None,
319        clippy = None,
320        llvm_tools = None,
321        rust_std = None,
322        rustfmt = None):
323    """Generate a rust sysroot from collection of toolchain components
324
325    Args:
326        ctx (ctx): A context object from a `rust_toolchain` rule.
327        rustc (File): The path to a `rustc` executable.
328        rustdoc (File): The path to a `rustdoc` executable.
329        rustc_lib (Target): A collection of Files containing dependencies of `rustc`.
330        cargo (File, optional): The path to a `cargo` executable.
331        clippy (File, optional): The path to a `clippy-driver` executable.
332        llvm_tools (Target, optional): A collection of llvm tools used by `rustc`.
333        rust_std (Target, optional): A collection of Files containing Rust standard library components.
334        rustfmt (File, optional): The path to a `rustfmt` executable.
335
336    Returns:
337        struct: A struct of generated files representing the new sysroot
338    """
339    name = ctx.label.name
340
341    # Define runfiles
342    direct_files = []
343    transitive_file_sets = []
344
345    # Rustc
346    sysroot_rustc = _symlink_sysroot_bin(ctx, name, "bin", rustc)
347    direct_files.extend([sysroot_rustc])
348
349    # Rustc dependencies
350    sysroot_rustc_lib = None
351    if rustc_lib:
352        sysroot_rustc_lib = _symlink_sysroot_tree(ctx, name, rustc_lib)
353        transitive_file_sets.extend([sysroot_rustc_lib])
354
355    # Rustdoc
356    sysroot_rustdoc = _symlink_sysroot_bin(ctx, name, "bin", rustdoc)
357    direct_files.extend([sysroot_rustdoc])
358
359    # Clippy
360    sysroot_clippy = None
361    if clippy:
362        sysroot_clippy = _symlink_sysroot_bin(ctx, name, "bin", clippy)
363        direct_files.extend([sysroot_clippy])
364
365    # Cargo
366    sysroot_cargo = None
367    if cargo:
368        sysroot_cargo = _symlink_sysroot_bin(ctx, name, "bin", cargo)
369        direct_files.extend([sysroot_cargo])
370
371    # Rustfmt
372    sysroot_rustfmt = None
373    if rustfmt:
374        sysroot_rustfmt = _symlink_sysroot_bin(ctx, name, "bin", rustfmt)
375        direct_files.extend([sysroot_rustfmt])
376
377    # Llvm tools
378    sysroot_llvm_tools = None
379    if llvm_tools:
380        sysroot_llvm_tools = _symlink_sysroot_tree(ctx, name, llvm_tools)
381        transitive_file_sets.extend([sysroot_llvm_tools])
382
383    # Rust standard library
384    sysroot_rust_std = None
385    if rust_std:
386        sysroot_rust_std = _symlink_sysroot_tree(ctx, name, rust_std)
387        transitive_file_sets.extend([sysroot_rust_std])
388
389    # Declare a file in the root of the sysroot to make locating the sysroot easy
390    sysroot_anchor = ctx.actions.declare_file("{}/rust.sysroot".format(name))
391    ctx.actions.write(
392        output = sysroot_anchor,
393        content = "\n".join([
394            "cargo: {}".format(cargo),
395            "clippy: {}".format(clippy),
396            "llvm_tools: {}".format(llvm_tools),
397            "rust_std: {}".format(rust_std),
398            "rustc_lib: {}".format(rustc_lib),
399            "rustc: {}".format(rustc),
400            "rustdoc: {}".format(rustdoc),
401            "rustfmt: {}".format(rustfmt),
402        ]),
403    )
404
405    # Create a depset of all sysroot files (symlinks and their real paths)
406    all_files = depset(direct_files, transitive = transitive_file_sets)
407
408    return struct(
409        all_files = all_files,
410        cargo = sysroot_cargo,
411        clippy = sysroot_clippy,
412        rust_std = sysroot_rust_std,
413        rustc = sysroot_rustc,
414        rustc_lib = sysroot_rustc_lib,
415        rustdoc = sysroot_rustdoc,
416        rustfmt = sysroot_rustfmt,
417        sysroot_anchor = sysroot_anchor,
418    )
419
420def _rust_toolchain_impl(ctx):
421    """The rust_toolchain implementation
422
423    Args:
424        ctx (ctx): The rule's context object
425
426    Returns:
427        list: A list containing the target's toolchain Provider info
428    """
429    compilation_mode_opts = {}
430    for k, v in ctx.attr.opt_level.items():
431        if not k in ctx.attr.debug_info:
432            fail("Compilation mode {} is not defined in debug_info but is defined opt_level".format(k))
433        compilation_mode_opts[k] = struct(debug_info = ctx.attr.debug_info[k], opt_level = v)
434    for k, v in ctx.attr.debug_info.items():
435        if not k in ctx.attr.opt_level:
436            fail("Compilation mode {} is not defined in opt_level but is defined debug_info".format(k))
437
438    rename_first_party_crates = ctx.attr._rename_first_party_crates[BuildSettingInfo].value
439    third_party_dir = ctx.attr._third_party_dir[BuildSettingInfo].value
440    pipelined_compilation = ctx.attr._pipelined_compilation[BuildSettingInfo].value
441
442    experimental_use_cc_common_link = ctx.attr.experimental_use_cc_common_link[BuildSettingInfo].value
443    if experimental_use_cc_common_link and not ctx.attr.allocator_library:
444        fail("rust_toolchain.experimental_use_cc_common_link requires rust_toolchain.allocator_library to be set")
445
446    rust_std = ctx.attr.rust_std
447
448    sysroot = _generate_sysroot(
449        ctx = ctx,
450        rustc = ctx.file.rustc,
451        rustdoc = ctx.file.rust_doc,
452        rustc_lib = ctx.attr.rustc_lib,
453        rust_std = rust_std,
454        rustfmt = ctx.file.rustfmt,
455        clippy = ctx.file.clippy_driver,
456        cargo = ctx.file.cargo,
457        llvm_tools = ctx.attr.llvm_tools,
458    )
459
460    expanded_stdlib_linkflags = []
461    for flag in ctx.attr.stdlib_linkflags:
462        expanded_stdlib_linkflags.append(
463            dedup_expand_location(
464                ctx,
465                flag,
466                targets = rust_std[rust_common.stdlib_info].srcs,
467            ),
468        )
469
470    linking_context = cc_common.create_linking_context(
471        linker_inputs = depset([
472            cc_common.create_linker_input(
473                owner = ctx.label,
474                user_link_flags = depset(expanded_stdlib_linkflags),
475            ),
476        ]),
477    )
478
479    # Contains linker flags needed to link Rust standard library.
480    # These need to be added to linker command lines when the linker is not rustc
481    # (rustc does this automatically). Linker flags wrapped in an otherwise empty
482    # `CcInfo` to provide the flags in a way that doesn't duplicate them per target
483    # providing a `CcInfo`.
484    stdlib_linkflags_cc_info = CcInfo(
485        compilation_context = cc_common.create_compilation_context(),
486        linking_context = linking_context,
487    )
488
489    # Determine the path and short_path of the sysroot
490    sysroot_path = sysroot.sysroot_anchor.dirname
491    sysroot_short_path, _, _ = sysroot.sysroot_anchor.short_path.rpartition("/")
492
493    # Variables for make variable expansion
494    make_variables = {
495        "RUSTC": sysroot.rustc.path,
496        "RUSTDOC": sysroot.rustdoc.path,
497        "RUST_DEFAULT_EDITION": ctx.attr.default_edition or "",
498        "RUST_SYSROOT": sysroot_path,
499    }
500
501    if sysroot.cargo:
502        make_variables.update({
503            "CARGO": sysroot.cargo.path,
504        })
505
506    if sysroot.rustfmt:
507        make_variables.update({
508            "RUSTFMT": sysroot.rustfmt.path,
509        })
510
511    make_variable_info = platform_common.TemplateVariableInfo(make_variables)
512
513    exec_triple = triple(ctx.attr.exec_triple)
514
515    exec_os = ctx.attr.os
516    if not ctx.attr.os:
517        exec_os = exec_triple.system
518
519    if not exec_os:
520        fail("No system was provided for the execution platform. Please update {}".format(
521            ctx.label,
522        ))
523
524    if ctx.attr.target_triple and ctx.attr.target_json:
525        fail("Do not specify both target_triple and target_json, either use a builtin triple or provide a custom specification file. Please update {}".format(
526            ctx.label,
527        ))
528
529    target_triple = None
530    target_json = None
531    target_arch = None
532
533    if ctx.attr.target_triple:
534        target_triple = triple(ctx.attr.target_triple)
535        target_arch = target_triple.arch
536
537    elif ctx.attr.target_json:
538        # Ensure the data provided is valid json
539        target_json_content = json.decode(ctx.attr.target_json)
540        target_json = ctx.actions.declare_file("{}.target.json".format(ctx.label.name))
541
542        ctx.actions.write(
543            output = target_json,
544            content = json.encode_indent(target_json_content, indent = " " * 4),
545        )
546
547        if "arch" in target_json_content:
548            target_arch = target_json_content["arch"]
549    else:
550        fail("Either `target_triple` or `target_json` must be provided. Please update {}".format(
551            ctx.label,
552        ))
553
554    toolchain = platform_common.ToolchainInfo(
555        all_files = sysroot.all_files,
556        binary_ext = ctx.attr.binary_ext,
557        cargo = sysroot.cargo,
558        clippy_driver = sysroot.clippy,
559        compilation_mode_opts = compilation_mode_opts,
560        crosstool_files = ctx.files._cc_toolchain,
561        default_edition = ctx.attr.default_edition,
562        dylib_ext = ctx.attr.dylib_ext,
563        env = ctx.attr.env,
564        exec_triple = exec_triple,
565        libstd_and_allocator_ccinfo = _make_libstd_and_allocator_ccinfo(ctx, rust_std, ctx.attr.allocator_library),
566        llvm_cov = ctx.file.llvm_cov,
567        llvm_profdata = ctx.file.llvm_profdata,
568        make_variables = make_variable_info,
569        os = exec_os,
570        rust_doc = sysroot.rustdoc,
571        rust_std = sysroot.rust_std,
572        rust_std_paths = depset([file.dirname for file in sysroot.rust_std.to_list()]),
573        rustc = sysroot.rustc,
574        rustc_lib = sysroot.rustc_lib,
575        rustfmt = sysroot.rustfmt,
576        staticlib_ext = ctx.attr.staticlib_ext,
577        stdlib_linkflags = stdlib_linkflags_cc_info,
578        extra_rustc_flags = ctx.attr.extra_rustc_flags,
579        extra_exec_rustc_flags = ctx.attr.extra_exec_rustc_flags,
580        sysroot = sysroot_path,
581        sysroot_short_path = sysroot_short_path,
582        target_arch = target_arch,
583        target_flag_value = target_json.path if target_json else target_triple.str,
584        target_json = target_json,
585        target_triple = target_triple,
586
587        # Experimental and incompatible flags
588        _rename_first_party_crates = rename_first_party_crates,
589        _third_party_dir = third_party_dir,
590        _pipelined_compilation = pipelined_compilation,
591        _experimental_use_cc_common_link = experimental_use_cc_common_link,
592    )
593    return [
594        toolchain,
595        make_variable_info,
596    ]
597
598rust_toolchain = rule(
599    implementation = _rust_toolchain_impl,
600    fragments = ["cpp"],
601    attrs = {
602        "allocator_library": attr.label(
603            doc = "Target that provides allocator functions when rust_library targets are embedded in a cc_binary.",
604        ),
605        "binary_ext": attr.string(
606            doc = "The extension for binaries created from rustc.",
607            mandatory = True,
608        ),
609        "cargo": attr.label(
610            doc = "The location of the `cargo` binary. Can be a direct source or a filegroup containing one item.",
611            allow_single_file = True,
612            cfg = "exec",
613        ),
614        "clippy_driver": attr.label(
615            doc = "The location of the `clippy-driver` binary. Can be a direct source or a filegroup containing one item.",
616            allow_single_file = True,
617            cfg = "exec",
618        ),
619        "debug_info": attr.string_dict(
620            doc = "Rustc debug info levels per opt level",
621            default = {
622                "dbg": "2",
623                "fastbuild": "0",
624                "opt": "0",
625            },
626        ),
627        "default_edition": attr.string(
628            doc = (
629                "The edition to use for rust_* rules that don't specify an edition. " +
630                "If absent, every rule is required to specify its `edition` attribute."
631            ),
632        ),
633        "dylib_ext": attr.string(
634            doc = "The extension for dynamic libraries created from rustc.",
635            mandatory = True,
636        ),
637        "env": attr.string_dict(
638            doc = "Environment variables to set in actions.",
639        ),
640        "exec_triple": attr.string(
641            doc = (
642                "The platform triple for the toolchains execution environment. " +
643                "For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurations"
644            ),
645            mandatory = True,
646        ),
647        "experimental_use_cc_common_link": attr.label(
648            default = Label("//rust/settings:experimental_use_cc_common_link"),
649            doc = "Label to a boolean build setting that controls whether cc_common.link is used to link rust binaries.",
650        ),
651        "extra_exec_rustc_flags": attr.string_list(
652            doc = "Extra flags to pass to rustc in exec configuration",
653        ),
654        "extra_rustc_flags": attr.string_list(
655            doc = "Extra flags to pass to rustc in non-exec configuration",
656        ),
657        "llvm_cov": attr.label(
658            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.",
659            allow_single_file = True,
660            cfg = "exec",
661        ),
662        "llvm_profdata": attr.label(
663            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.",
664            allow_single_file = True,
665            cfg = "exec",
666        ),
667        "llvm_tools": attr.label(
668            doc = "LLVM tools that are shipped with the Rust toolchain.",
669            allow_files = True,
670        ),
671        "opt_level": attr.string_dict(
672            doc = "Rustc optimization levels.",
673            default = {
674                "dbg": "0",
675                "fastbuild": "0",
676                "opt": "3",
677            },
678        ),
679        "os": attr.string(
680            doc = "The operating system for the current toolchain",
681        ),
682        "rust_doc": attr.label(
683            doc = "The location of the `rustdoc` binary. Can be a direct source or a filegroup containing one item.",
684            allow_single_file = True,
685            cfg = "exec",
686            mandatory = True,
687        ),
688        "rust_std": attr.label(
689            doc = "The Rust standard library.",
690        ),
691        "rustc": attr.label(
692            doc = "The location of the `rustc` binary. Can be a direct source or a filegroup containing one item.",
693            allow_single_file = True,
694            cfg = "exec",
695            mandatory = True,
696        ),
697        "rustc_lib": attr.label(
698            doc = "The libraries used by rustc during compilation.",
699            cfg = "exec",
700        ),
701        "rustfmt": attr.label(
702            doc = "**Deprecated**: Instead see [rustfmt_toolchain](#rustfmt_toolchain)",
703            allow_single_file = True,
704            cfg = "exec",
705        ),
706        "staticlib_ext": attr.string(
707            doc = "The extension for static libraries created from rustc.",
708            mandatory = True,
709        ),
710        "stdlib_linkflags": attr.string_list(
711            doc = (
712                "Additional linker flags to use when Rust standard library is linked by a C++ linker " +
713                "(rustc will deal with these automatically). Subject to location expansion with respect " +
714                "to the srcs of the `rust_std` attribute."
715            ),
716            mandatory = True,
717        ),
718        "target_json": attr.string(
719            doc = ("Override the target_triple with a custom target specification. " +
720                   "For more details see: https://doc.rust-lang.org/rustc/targets/custom.html"),
721        ),
722        "target_triple": attr.string(
723            doc = (
724                "The platform triple for the toolchains target environment. " +
725                "For more details see: https://docs.bazel.build/versions/master/skylark/rules.html#configurations"
726            ),
727        ),
728        "_cc_toolchain": attr.label(
729            default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
730        ),
731        "_pipelined_compilation": attr.label(
732            default = Label("//rust/settings:pipelined_compilation"),
733        ),
734        "_rename_first_party_crates": attr.label(
735            default = Label("//rust/settings:rename_first_party_crates"),
736        ),
737        "_third_party_dir": attr.label(
738            default = Label("//rust/settings:third_party_dir"),
739        ),
740    },
741    toolchains = [
742        "@bazel_tools//tools/cpp:toolchain_type",
743    ],
744    incompatible_use_toolchain_transition = True,
745    doc = """Declares a Rust toolchain for use.
746
747This is for declaring a custom toolchain, eg. for configuring a particular version of rust or supporting a new platform.
748
749Example:
750
751Suppose the core rust team has ported the compiler to a new target CPU, called `cpuX`. This \
752support can be used in Bazel by defining a new toolchain definition and declaration:
753
754```python
755load('@rules_rust//rust:toolchain.bzl', 'rust_toolchain')
756
757rust_toolchain(
758    name = "rust_cpuX_impl",
759    rustc = "@rust_cpuX//:rustc",
760    rustc_lib = "@rust_cpuX//:rustc_lib",
761    rust_std = "@rust_cpuX//:rust_std",
762    rust_doc = "@rust_cpuX//:rustdoc",
763    binary_ext = "",
764    staticlib_ext = ".a",
765    dylib_ext = ".so",
766    stdlib_linkflags = ["-lpthread", "-ldl"],
767    os = "linux",
768)
769
770toolchain(
771    name = "rust_cpuX",
772    exec_compatible_with = [
773        "@platforms//cpu:cpuX",
774    ],
775    target_compatible_with = [
776        "@platforms//cpu:cpuX",
777    ],
778    toolchain = ":rust_cpuX_impl",
779)
780```
781
782Then, either add the label of the toolchain rule to `register_toolchains` in the WORKSPACE, or pass \
783it to the `"--extra_toolchains"` flag for Bazel, and it will be used.
784
785See @rules_rust//rust:repositories.bzl for examples of defining the @rust_cpuX repository \
786with the actual binaries and libraries.
787""",
788)