fork/rules_rust

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

UebelAndreAdded `rust_analyzer_toolchain` and repository rules for creating one (#1455)0e86b9dd

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