fork/rules_rust

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

UebelAndreAdded support for compact windows repository names, avoiding MAX_PATH (#3023)8e962a16

main
51.2 KiB1179 linesraw
1"""Repository rules for defining Rust dependencies and toolchains"""
2
3load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
4load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
5load("//rust/platform:triple.bzl", "get_host_triple", "triple")
6load("//rust/platform:triple_mappings.bzl", "triple_to_constraint_set")
7load("//rust/private:common.bzl", "rust_common")
8load(
9    "//rust/private:repository_utils.bzl",
10    "BUILD_for_rust_analyzer_proc_macro_srv",
11    "BUILD_for_rust_analyzer_toolchain",
12    "BUILD_for_rust_toolchain",
13    "BUILD_for_rustfmt_toolchain",
14    "BUILD_for_toolchain",
15    "DEFAULT_EXTRA_TARGET_TRIPLES",
16    "DEFAULT_NIGHTLY_VERSION",
17    "DEFAULT_STATIC_RUST_URL_TEMPLATES",
18    "TINYJSON_KWARGS",
19    "check_version_valid",
20    "includes_rust_analyzer_proc_macro_srv",
21    "load_cargo",
22    "load_clippy",
23    "load_llvm_tools",
24    "load_rust_compiler",
25    "load_rust_src",
26    "load_rust_stdlib",
27    "load_rustc_dev_nightly",
28    "load_rustfmt",
29    "select_rust_version",
30    "toolchain_repository_hub",
31    _load_arbitrary_tool = "load_arbitrary_tool",
32)
33
34# Re-export `load_arbitrary_tool` as it's historically been used in external repositories.
35load_arbitrary_tool = _load_arbitrary_tool
36
37# Note: Code in `.github/workflows/crate_universe.yaml` looks for this line, if you remove it or change its format, you will also need to update that code.
38DEFAULT_TOOLCHAIN_TRIPLES = {
39    "aarch64-apple-darwin": "rust_darwin_aarch64",
40    "aarch64-pc-windows-msvc": "rust_windows_aarch64",
41    "aarch64-unknown-linux-gnu": "rust_linux_aarch64",
42    "s390x-unknown-linux-gnu": "rust_linux_s390x",
43    "x86_64-apple-darwin": "rust_darwin_x86_64",
44    "x86_64-pc-windows-msvc": "rust_windows_x86_64",
45    "x86_64-unknown-freebsd": "rust_freebsd_x86_64",
46    "x86_64-unknown-linux-gnu": "rust_linux_x86_64",
47}
48
49_COMPACT_WINDOWS_NAMES = True
50
51def rules_rust_dependencies():
52    """Dependencies used in the implementation of `rules_rust`."""
53
54    maybe(
55        http_archive,
56        name = "platforms",
57        urls = [
58            "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.10/platforms-0.0.10.tar.gz",
59            "https://github.com/bazelbuild/platforms/releases/download/0.0.10/platforms-0.0.10.tar.gz",
60        ],
61        sha256 = "218efe8ee736d26a3572663b374a253c012b716d8af0c07e842e82f238a0a7ee",
62    )
63
64    # Avoid the following issue https://github.com/bazelbuild/rules_cc/issues/274
65    rules_cc_kwargs = {}
66    if native.bazel_version.startswith(("6", "7")):
67        rules_cc_kwargs.update({
68            "patch_args": ["-p1"],
69            "patches": [Label("//rust/private/3rdparty:rules_cc.patch")],
70        })
71    maybe(
72        http_archive,
73        name = "rules_cc",
74        urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.17/rules_cc-0.0.17.tar.gz"],
75        sha256 = "abc605dd850f813bb37004b77db20106a19311a96b2da1c92b789da529d28fe1",
76        strip_prefix = "rules_cc-0.0.17",
77        **rules_cc_kwargs
78    )
79    maybe(
80        http_archive,
81        name = "rules_license",
82        urls = [
83            "https://mirror.bazel.build/github.com/bazelbuild/rules_license/releases/download/1.0.0/rules_license-1.0.0.tar.gz",
84            "https://github.com/bazelbuild/rules_license/releases/download/1.0.0/rules_license-1.0.0.tar.gz",
85        ],
86        sha256 = "26d4021f6898e23b82ef953078389dd49ac2b5618ac564ade4ef87cced147b38",
87    )
88    maybe(
89        http_archive,
90        name = "bazel_features",
91        sha256 = "af3d4fb1cf4f25942cb4a933b1ad93a0ea9fe9ee70c2af7f369fb72a67c266e5",
92        strip_prefix = "bazel_features-1.21.0",
93        url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.21.0/bazel_features-v1.21.0.tar.gz",
94    )
95
96    maybe(
97        http_archive,
98        name = "bazel_skylib",
99        sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f",
100        urls = [
101            "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz",
102            "https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz",
103        ],
104    )
105
106    # Make the iOS simulator constraint available, which is referenced in abi_to_constraints()
107    # rules_rust does not require this dependency; it is just imported as a convenience for users.
108    maybe(
109        http_archive,
110        name = "build_bazel_apple_support",
111        sha256 = "b53f6491e742549f13866628ddffcc75d1f3b2d6987dc4f14a16b242113c890b",
112        url = "https://github.com/bazelbuild/apple_support/releases/download/1.17.1/apple_support.1.17.1.tar.gz",
113    )
114
115    # process_wrapper needs a low-dependency way to process json.
116    maybe(
117        http_archive,
118        **TINYJSON_KWARGS
119    )
120
121_RUST_TOOLCHAIN_VERSIONS = [
122    rust_common.default_version,
123    DEFAULT_NIGHTLY_VERSION,
124]
125
126# buildifier: disable=unnamed-macro
127def rust_register_toolchains(
128        *,
129        dev_components = False,
130        edition = None,
131        allocator_library = None,
132        global_allocator_library = None,
133        register_toolchains = True,
134        rustfmt_version = None,
135        rust_analyzer_version = None,
136        sha256s = None,
137        extra_target_triples = DEFAULT_EXTRA_TARGET_TRIPLES,
138        extra_rustc_flags = None,
139        extra_exec_rustc_flags = None,
140        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES,
141        versions = _RUST_TOOLCHAIN_VERSIONS,
142        aliases = {},
143        hub_name = None,
144        compact_windows_names = _COMPACT_WINDOWS_NAMES):
145    """Emits a default set of toolchains for Linux, MacOS, and Freebsd
146
147    Skip this macro and call the `rust_repository_set` macros directly if you need a compiler for \
148    other hosts or for additional target triples.
149
150    The `sha256s` attribute represents a dict associating tool subdirectories to sha256 hashes. As an example:
151    ```python
152    {
153        "rust-1.46.0-x86_64-unknown-linux-gnu": "e3b98bc3440fe92817881933f9564389eccb396f5f431f33d48b979fa2fbdcf5",
154        "rustfmt-1.4.12-x86_64-unknown-linux-gnu": "1894e76913303d66bf40885a601462844eec15fca9e76a6d13c390d7000d64b0",
155        "rust-std-1.46.0-x86_64-unknown-linux-gnu": "ac04aef80423f612c0079829b504902de27a6997214eb58ab0765d02f7ec1dbc",
156    }
157    ```
158    This would match for `exec_triple = "x86_64-unknown-linux-gnu"`.  If not specified, rules_rust pulls from a non-exhaustive \
159    list of known checksums..
160
161    See `load_arbitrary_tool` in `@rules_rust//rust:repositories.bzl` for more details.
162
163    Args:
164        dev_components (bool, optional): Whether to download the rustc-dev components (defaults to False). Requires version to be "nightly".
165        edition (str, optional): The rust edition to be used by default (2015, 2018, or 2021). If absent, every target is required to specify its `edition` attribute.
166        allocator_library (str, optional): Target that provides allocator functions when rust_library targets are embedded in a cc_binary.
167        global_allocator_library (str, optional): Target that provides allocator functions when global allocator is used with cc_common.link.
168        register_toolchains (bool): If true, repositories will be generated to produce and register `rust_toolchain` targets.
169        rustfmt_version (str, optional): The version of rustfmt. If none is supplied and only a single version in `versions` is given, then this defaults to that version, otherwise will default to the default nightly version.
170        rust_analyzer_version (str, optional): The version of Rustc to pair with rust-analyzer.
171        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes.
172        extra_target_triples (list, optional): Additional rust-style targets that rust toolchains should support.
173        extra_rustc_flags (dict, list, optional): Dictionary of target triples to list of extra flags to pass to rustc in non-exec configuration.
174        extra_exec_rustc_flags (list, optional): Extra flags to pass to rustc in exec configuration.
175        urls (list, optional): A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format).
176        versions (list, optional): A list of toolchain versions to download. This parameter only accepts one versions
177            per channel. E.g. `["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"]`.
178        aliases (dict, optional): A mapping of "full" repository name to another name to use instead.
179        hub_name (str, optional): The name of the bzlmod hub repository for toolchains.
180        compact_windows_names (bool): Whether or not to produce compact repository names for windows
181            toolchains. This is to avoid MAX_PATH issues.
182    """
183    if not rustfmt_version:
184        if len(versions) == 1:
185            rustfmt_version = versions[0]
186        else:
187            rustfmt_version = DEFAULT_NIGHTLY_VERSION
188
189    if dev_components:
190        has_nightly = False
191        for ver in versions:
192            if ver.startswith("nightly"):
193                has_nightly = True
194                break
195        if not has_nightly:
196            fail("rustc-dev components were requested but no \"nightly\" is being registered. Please update `versions` to include a nightly version.")
197
198    if not rust_analyzer_version:
199        rust_analyzer_version = select_rust_version(versions)
200
201    # Convert to an unfrozen dict to remove mappings as they are used. This will allow us to determine if there
202    # are any unused aliases requested.
203    aliases = dict(aliases)
204
205    rust_analyzer_repo_name = "rust_analyzer_{}".format(rust_analyzer_version.replace("/", "-"))
206
207    toolchain_names = []
208    toolchain_labels = {}
209    toolchain_target_settings = {}
210    toolchain_types = {}
211    exec_compatible_with_by_toolchain = {}
212    target_compatible_with_by_toolchain = {}
213
214    maybe(
215        rust_analyzer_toolchain_repository,
216        name = rust_analyzer_repo_name,
217        version = rust_analyzer_version,
218        urls = urls,
219        sha256s = sha256s,
220    )
221
222    toolchain_names.append(rust_analyzer_repo_name)
223    toolchain_labels[rust_analyzer_repo_name] = "@{}_tools//:rust_analyzer_toolchain".format(
224        rust_analyzer_repo_name,
225    )
226    exec_compatible_with_by_toolchain[rust_analyzer_repo_name] = []
227    target_compatible_with_by_toolchain[rust_analyzer_repo_name] = []
228    toolchain_types[rust_analyzer_repo_name] = "@rules_rust//rust/rust_analyzer:toolchain_type"
229
230    if register_toolchains:
231        native.register_toolchains("@{}//:toolchain".format(
232            rust_analyzer_repo_name,
233        ))
234
235    for exec_triple, name in DEFAULT_TOOLCHAIN_TRIPLES.items():
236        maybe(
237            rust_repository_set,
238            name = name,
239            dev_components = dev_components,
240            edition = edition,
241            exec_triple = exec_triple,
242            extra_target_triples = extra_target_triples,
243            allocator_library = allocator_library,
244            global_allocator_library = global_allocator_library,
245            register_toolchain = register_toolchains,
246            rustfmt_version = rustfmt_version,
247            extra_rustc_flags = extra_rustc_flags,
248            extra_exec_rustc_flags = extra_exec_rustc_flags,
249            sha256s = sha256s,
250            urls = urls,
251            versions = versions,
252            aliases = aliases,
253        )
254
255        rustfmt_repo_name = "rustfmt_{}__{}".format(rustfmt_version.replace("/", "-"), exec_triple)
256        if rustfmt_repo_name in aliases:
257            rustfmt_repo_name = aliases.pop(rustfmt_repo_name)
258
259        maybe(
260            rustfmt_toolchain_repository,
261            name = rustfmt_repo_name,
262            version = rustfmt_version,
263            urls = urls,
264            sha256s = sha256s,
265            exec_triple = exec_triple,
266        )
267
268        if register_toolchains:
269            native.register_toolchains("@{}//:toolchain".format(
270                rustfmt_repo_name,
271            ))
272
273        for toolchain in _get_toolchain_repositories(
274            name = name,
275            exec_triple = exec_triple,
276            extra_target_triples = extra_target_triples,
277            versions = versions,
278            fallback_target_compatible_with = None,
279            aliases = aliases,
280            compact_windows_names = compact_windows_names,
281        ):
282            toolchain_names.append(toolchain.name)
283            toolchain_labels[toolchain.name] = "@{}//:{}".format(toolchain.name + "_tools", "rust_toolchain")
284            exec_compatible_with_by_toolchain[toolchain.name] = triple_to_constraint_set(exec_triple)
285            target_compatible_with_by_toolchain[toolchain.name] = toolchain.target_constraints
286            toolchain_types[toolchain.name] = "@rules_rust//rust:toolchain"
287            toolchain_target_settings[toolchain.name] = ["@rules_rust//rust/toolchain/channel:{}".format(toolchain.channel.name)]
288
289        toolchain_names.append(rustfmt_repo_name)
290        toolchain_labels[rustfmt_repo_name] = "@{}_tools//:rustfmt_toolchain".format(rustfmt_repo_name)
291        exec_compatible_with_by_toolchain[rustfmt_repo_name] = triple_to_constraint_set(exec_triple)
292        target_compatible_with_by_toolchain[rustfmt_repo_name] = []
293        toolchain_types[rustfmt_repo_name] = "@rules_rust//rust/rustfmt:toolchain_type"
294
295    if aliases:
296        fail("No repositories were created matching the requested names to alias:\n{}".format("\n".join(sorted(aliases))))
297
298    if hub_name:
299        toolchain_repository_hub(
300            name = hub_name,
301            toolchain_names = toolchain_names,
302            toolchain_labels = toolchain_labels,
303            toolchain_types = toolchain_types,
304            target_settings = toolchain_target_settings,
305            exec_compatible_with = exec_compatible_with_by_toolchain,
306            target_compatible_with = target_compatible_with_by_toolchain,
307        )
308
309# buildifier: disable=unnamed-macro
310def rust_repositories(**kwargs):
311    """**Deprecated**: Use [rules_rust_dependencies](#rules_rust_dependencies) \
312    and [rust_register_toolchains](#rust_register_toolchains) directly.
313
314    Args:
315        **kwargs (dict): Keyword arguments for the `rust_register_toolchains` macro.
316    """
317    rules_rust_dependencies()
318
319    rust_register_toolchains(**kwargs)
320
321_RUST_TOOLCHAIN_REPOSITORY_ATTRS = {
322    "allocator_library": attr.string(
323        doc = "Target that provides allocator functions when rust_library targets are embedded in a cc_binary.",
324        default = "@rules_rust//ffi/cc/allocator_library",
325    ),
326    "auth": attr.string_dict(
327        doc = (
328            "Auth object compatible with repository_ctx.download to use when downloading files. " +
329            "See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details."
330        ),
331    ),
332    "auth_patterns": attr.string_list(
333        doc = "A list of patterns to match against urls for which the auth object should be used.",
334    ),
335    "dev_components": attr.bool(
336        doc = "Whether to download the rustc-dev components (defaults to False). Requires version to be \"nightly\".",
337        default = False,
338    ),
339    "edition": attr.string(
340        doc = (
341            "The rust edition to be used by default (2015, 2018, or 2021). " +
342            "If absent, every rule is required to specify its `edition` attribute."
343        ),
344    ),
345    "exec_triple": attr.string(
346        doc = "The Rust-style target that this compiler runs on",
347        mandatory = True,
348    ),
349    "extra_exec_rustc_flags": attr.string_list(
350        doc = "Extra flags to pass to rustc in exec configuration",
351    ),
352    "extra_rustc_flags": attr.string_list(
353        doc = "Extra flags to pass to rustc in non-exec configuration",
354    ),
355    "global_allocator_library": attr.string(
356        doc = "Target that provides allocator functions when a global allocator is used with cc_common.link.",
357        default = "@rules_rust//ffi/cc/global_allocator_library",
358    ),
359    "netrc": attr.string(
360        doc = ".netrc file to use for authentication; mirrors the eponymous attribute from http_archive",
361    ),
362    "opt_level": attr.string_dict(
363        doc = "Rustc optimization levels. For more details see the documentation for `rust_toolchain.opt_level`.",
364    ),
365    "rustfmt_version": attr.string(
366        doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.",
367    ),
368    "sha256s": attr.string_dict(
369        doc = "A dict associating tool subdirectories to sha256 hashes. See [rust_register_toolchains](#rust_register_toolchains) for more details.",
370    ),
371    "target_triple": attr.string(
372        doc = "The Rust-style target that this compiler builds for.",
373        mandatory = True,
374    ),
375    "urls": attr.string_list(
376        doc = "A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format).",
377        default = DEFAULT_STATIC_RUST_URL_TEMPLATES,
378    ),
379    "version": attr.string(
380        doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.",
381        mandatory = True,
382    ),
383}
384
385def _rust_toolchain_tools_repository_impl(ctx):
386    """The implementation of the rust toolchain tools repository rule."""
387    sha256s = dict(ctx.attr.sha256s)
388    iso_date = None
389    version = ctx.attr.version
390    version_array = version.split("/")
391    if len(version_array) > 1:
392        version = version_array[0]
393        iso_date = version_array[1]
394
395    check_version_valid(ctx.attr.version, iso_date)
396
397    exec_triple = triple(ctx.attr.exec_triple)
398
399    rustc_content, rustc_sha256 = load_rust_compiler(
400        ctx = ctx,
401        iso_date = iso_date,
402        target_triple = exec_triple,
403        version = version,
404    )
405    clippy_content, clippy_sha256 = load_clippy(
406        ctx = ctx,
407        iso_date = iso_date,
408        target_triple = exec_triple,
409        version = version,
410    )
411    cargo_content, cargo_sha256 = load_cargo(
412        ctx = ctx,
413        iso_date = iso_date,
414        target_triple = exec_triple,
415        version = version,
416    )
417
418    build_components = [
419        rustc_content,
420        clippy_content,
421        cargo_content,
422    ]
423    sha256s.update(rustc_sha256 | clippy_sha256 | cargo_sha256)
424
425    if ctx.attr.rustfmt_version:
426        rustfmt_version = ctx.attr.rustfmt_version
427        rustfmt_iso_date = None
428        if rustfmt_version in ("nightly", "beta"):
429            if iso_date:
430                rustfmt_iso_date = iso_date
431            else:
432                fail("`rustfmt_version` does not include an iso_date. The following reposiotry should either set `iso_date` or update `rustfmt_version` to include an iso_date suffix: {}".format(
433                    ctx.name,
434                ))
435        elif rustfmt_version.startswith(("nightly", "beta")):
436            rustfmt_version, _, rustfmt_iso_date = rustfmt_version.partition("/")
437        rustfmt_content, rustfmt_sha256 = load_rustfmt(
438            ctx = ctx,
439            target_triple = triple(ctx.attr.exec_triple),
440            version = rustfmt_version,
441            iso_date = rustfmt_iso_date,
442        )
443        build_components.append(rustfmt_content)
444        sha256s.update(rustfmt_sha256)
445
446    # Rust 1.45.0 and nightly builds after 2020-05-22 need the llvm-tools gzip to get the libLLVM dylib
447    include_llvm_tools = version >= "1.45.0" or (version == "nightly" and iso_date > "2020-05-22")
448    if include_llvm_tools:
449        llvm_tools_content, llvm_tools_sha256 = load_llvm_tools(
450            ctx = ctx,
451            target_triple = exec_triple,
452            version = version,
453            iso_date = iso_date,
454        )
455        build_components.append(llvm_tools_content)
456        sha256s.update(llvm_tools_sha256)
457
458    target_triple = triple(ctx.attr.target_triple)
459    rust_stdlib_content, rust_stdlib_sha256 = load_rust_stdlib(
460        ctx = ctx,
461        target_triple = target_triple,
462        version = version,
463        iso_date = iso_date,
464    )
465    build_components.append(rust_stdlib_content)
466    sha256s.update(rust_stdlib_sha256)
467
468    stdlib_linkflags = None
469    if "BAZEL_RUST_STDLIB_LINKFLAGS" in ctx.os.environ:
470        stdlib_linkflags = ctx.os.environ["BAZEL_RUST_STDLIB_LINKFLAGS"].split(":")
471
472    build_components.append(BUILD_for_rust_toolchain(
473        name = "rust_toolchain",
474        exec_triple = exec_triple,
475        allocator_library = ctx.attr.allocator_library,
476        global_allocator_library = ctx.attr.global_allocator_library,
477        target_triple = target_triple,
478        stdlib_linkflags = stdlib_linkflags,
479        default_edition = ctx.attr.edition,
480        include_rustfmt = not (not ctx.attr.rustfmt_version),
481        include_llvm_tools = include_llvm_tools,
482        extra_rustc_flags = ctx.attr.extra_rustc_flags,
483        extra_exec_rustc_flags = ctx.attr.extra_exec_rustc_flags,
484        opt_level = ctx.attr.opt_level if ctx.attr.opt_level else None,
485        version = ctx.attr.version,
486    ))
487
488    # Not all target triples are expected to have dev components
489    if ctx.attr.dev_components:
490        rustc_dev_sha256 = load_rustc_dev_nightly(
491            ctx = ctx,
492            target_triple = target_triple,
493            version = version,
494            iso_date = iso_date,
495        )
496        sha256s.update(rustc_dev_sha256)
497
498    ctx.file("WORKSPACE.bazel", "")
499    ctx.file("BUILD.bazel", "\n".join(build_components))
500
501    repro = {"name": ctx.name}
502    for key in _RUST_TOOLCHAIN_REPOSITORY_ATTRS:
503        repro[key] = getattr(ctx.attr, key)
504    repro["sha256s"] = sha256s
505
506    return repro
507
508rust_toolchain_tools_repository = repository_rule(
509    doc = (
510        "Composes a single workspace containing the toolchain components for compiling on a given " +
511        "platform to a series of target platforms.\n" +
512        "\n" +
513        "A given instance of this rule should be accompanied by a toolchain_repository_proxy " +
514        "invocation to declare its toolchains to Bazel; the indirection allows separating toolchain " +
515        "selection from toolchain fetching."
516    ),
517    attrs = _RUST_TOOLCHAIN_REPOSITORY_ATTRS,
518    implementation = _rust_toolchain_tools_repository_impl,
519)
520
521def _toolchain_repository_proxy_impl(repository_ctx):
522    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
523        repository_ctx.name,
524    ))
525
526    repository_ctx.file("BUILD.bazel", BUILD_for_toolchain(
527        name = "toolchain",
528        toolchain = repository_ctx.attr.toolchain,
529        target_settings = repository_ctx.attr.target_settings,
530        toolchain_type = repository_ctx.attr.toolchain_type,
531        target_compatible_with = repository_ctx.attr.target_compatible_with,
532        exec_compatible_with = repository_ctx.attr.exec_compatible_with,
533    ))
534
535toolchain_repository_proxy = repository_rule(
536    doc = (
537        "Generates a toolchain-bearing repository that declares the toolchains from some other " +
538        "rust_toolchain_repository."
539    ),
540    attrs = {
541        "exec_compatible_with": attr.string_list(
542            doc = "A list of constraints for the execution platform for this toolchain.",
543        ),
544        "target_compatible_with": attr.string_list(
545            doc = "A list of constraints for the target platform for this toolchain.",
546        ),
547        "target_settings": attr.string_list(
548            doc = "A list of config_settings that must be satisfied by the target configuration in order for this toolchain to be selected during toolchain resolution.",
549        ),
550        "toolchain": attr.string(
551            doc = "The name of the toolchain implementation target.",
552            mandatory = True,
553        ),
554        "toolchain_type": attr.string(
555            doc = "The toolchain type of the toolchain to declare",
556            mandatory = True,
557        ),
558    },
559    implementation = _toolchain_repository_proxy_impl,
560)
561
562# For legacy support
563rust_toolchain_repository_proxy = toolchain_repository_proxy
564
565# N.B. A "proxy repository" is needed to allow for registering the toolchain (with constraints)
566# without actually downloading the toolchain.
567def rust_toolchain_repository(
568        name,
569        version,
570        exec_triple,
571        target_triple,
572        exec_compatible_with = None,
573        target_compatible_with = None,
574        target_settings = [],
575        channel = None,
576        allocator_library = None,
577        global_allocator_library = None,
578        rustfmt_version = None,
579        edition = None,
580        dev_components = False,
581        extra_rustc_flags = None,
582        extra_exec_rustc_flags = None,
583        opt_level = None,
584        sha256s = None,
585        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES,
586        auth = None,
587        netrc = None,
588        auth_patterns = None):
589    """Assembles a remote repository for the given toolchain params, produces a proxy repository \
590    to contain the toolchain declaration, and registers the toolchains.
591
592    Args:
593        name (str): The name of the generated repository
594        version (str): The version of the tool among "nightly", "beta", or an exact version.
595        exec_triple (str): The Rust-style target that this compiler runs on.
596        target_triple (str): The Rust-style target to build for.
597        channel (str, optional): The channel of the Rust toolchain.
598        exec_compatible_with (list, optional): A list of constraints for the execution platform for this toolchain.
599        target_compatible_with (list, optional): A list of constraints for the target platform for this toolchain.
600        target_settings (list, optional): A list of config_settings that must be satisfied by the target configuration in order for this toolchain to be selected during toolchain resolution.
601        allocator_library (str, optional): Target that provides allocator functions when rust_library targets are embedded in a cc_binary.
602        global_allocator_library (str, optional): Target that provides allocator functions when a global allocator is used with cc_common.link.
603        rustfmt_version (str, optional):  The version of rustfmt to be associated with the
604            toolchain.
605        edition (str, optional): The rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is required to specify its `edition` attribute.
606        dev_components (bool, optional): Whether to download the rustc-dev components.
607            Requires version to be "nightly". Defaults to False.
608        extra_rustc_flags (list, optional): Extra flags to pass to rustc in non-exec configuration.
609        extra_exec_rustc_flags (list, optional): Extra flags to pass to rustc in exec configuration.
610        opt_level (dict, optional): Optimization level config for this toolchain.
611        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
612            [rust_register_toolchains](#rust_register_toolchains) for more details.
613        urls (list, optional): A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format). Defaults to ['https://static.rust-lang.org/dist/{}.tar.xz']
614        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
615            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
616        netrc (str, optional): .netrc file to use for authentication; mirrors the eponymous attribute from http_archive
617        auth_patterns (list, optional): A list of patterns to match against urls for which the auth object should be used.
618
619    Returns:
620        str: The name of the registerable toolchain created by this rule.
621    """
622    if exec_compatible_with == None:
623        exec_compatible_with = triple_to_constraint_set(exec_triple)
624
625    if target_compatible_with == None:
626        target_compatible_with = triple_to_constraint_set(target_triple)
627
628    tools_repo_name = "{}_tools".format(name)
629
630    rust_toolchain_tools_repository(
631        name = tools_repo_name,
632        exec_triple = exec_triple,
633        allocator_library = allocator_library,
634        global_allocator_library = global_allocator_library,
635        target_triple = target_triple,
636        version = version,
637        rustfmt_version = rustfmt_version,
638        edition = edition,
639        dev_components = dev_components,
640        extra_rustc_flags = extra_rustc_flags,
641        extra_exec_rustc_flags = extra_exec_rustc_flags,
642        opt_level = opt_level,
643        sha256s = sha256s,
644        urls = urls,
645        auth = auth,
646        netrc = netrc,
647        auth_patterns = auth_patterns,
648    )
649
650    channel_target_settings = ["@rules_rust//rust/toolchain/channel:{}".format(channel)] if channel else []
651
652    toolchain_repository_proxy(
653        name = name,
654        toolchain = "@{}//:rust_toolchain".format(tools_repo_name),
655        target_settings = channel_target_settings + target_settings,
656        toolchain_type = "@rules_rust//rust:toolchain",
657        exec_compatible_with = exec_compatible_with,
658        target_compatible_with = target_compatible_with,
659    )
660
661    return "@{name}//:toolchain".format(
662        name = name,
663    )
664
665_RUST_ANALYZER_TOOLCHAIN_TOOLS_REPOSITORY_ATTRS = {
666    "auth": attr.string_dict(
667        doc = (
668            "Auth object compatible with repository_ctx.download to use when downloading files. " +
669            "See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details."
670        ),
671    ),
672    "auth_patterns": attr.string_list(
673        doc = "A list of patterns to match against urls for which the auth object should be used.",
674    ),
675    "netrc": attr.string(
676        doc = ".netrc file to use for authentication; mirrors the eponymous attribute from http_archive",
677    ),
678    "sha256s": attr.string_dict(
679        doc = "A dict associating tool subdirectories to sha256 hashes. See [rust_register_toolchains](#rust_register_toolchains) for more details.",
680    ),
681    "urls": attr.string_list(
682        doc = "A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format).",
683        default = DEFAULT_STATIC_RUST_URL_TEMPLATES,
684    ),
685    "version": attr.string(
686        doc = "The version of the tool among \"nightly\", \"beta\" with an iso date, or an exact version.",
687        mandatory = True,
688    ),
689}
690
691def _rust_analyzer_toolchain_tools_repository_impl(repository_ctx):
692    sha256s = dict(repository_ctx.attr.sha256s)
693
694    iso_date = None
695    version = repository_ctx.attr.version
696    version_array = version.split("/")
697    if len(version_array) > 1:
698        version = version_array[0]
699        iso_date = version_array[1]
700
701    sha256s.update(load_rust_src(
702        ctx = repository_ctx,
703        iso_date = iso_date,
704        version = version,
705    ))
706
707    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
708        repository_ctx.name,
709    ))
710
711    host_triple = get_host_triple(repository_ctx)
712    rustc_content, rustc_sha256 = load_rust_compiler(
713        ctx = repository_ctx,
714        iso_date = iso_date,
715        target_triple = host_triple,
716        version = version,
717    )
718    build_contents = [rustc_content]
719    sha256s.update(rustc_sha256)
720    rustc = "//:rustc"
721
722    proc_macro_srv = None
723    if includes_rust_analyzer_proc_macro_srv(version, iso_date):
724        build_contents.append(BUILD_for_rust_analyzer_proc_macro_srv(host_triple))
725        proc_macro_srv = "//:rust_analyzer_proc_macro_srv"
726
727    build_contents.append(BUILD_for_rust_analyzer_toolchain(
728        name = "rust_analyzer_toolchain",
729        rustc = rustc,
730        proc_macro_srv = proc_macro_srv,
731    ))
732
733    repository_ctx.file("BUILD.bazel", "\n".join(build_contents))
734    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
735        repository_ctx.name,
736    ))
737
738    repro = {"name": repository_ctx.name}
739    for key in _RUST_ANALYZER_TOOLCHAIN_TOOLS_REPOSITORY_ATTRS:
740        repro[key] = getattr(repository_ctx.attr, key)
741    repro["sha256s"] = sha256s
742
743    return repro
744
745rust_analyzer_toolchain_tools_repository = repository_rule(
746    doc = "A repository rule for defining a rust_analyzer_toolchain with a `rust-src` artifact.",
747    implementation = _rust_analyzer_toolchain_tools_repository_impl,
748    attrs = _RUST_ANALYZER_TOOLCHAIN_TOOLS_REPOSITORY_ATTRS,
749)
750
751def rust_analyzer_toolchain_repository(
752        name,
753        version,
754        exec_compatible_with = [],
755        target_compatible_with = [],
756        sha256s = None,
757        urls = None,
758        auth = None,
759        netrc = None,
760        auth_patterns = None):
761    """Assemble a remote rust_analyzer_toolchain target based on the given params.
762
763    Args:
764        name (str): The name of the toolchain proxy repository contianing the registerable toolchain.
765        version (str): The version of the tool among "nightly", "beta', or an exact version.
766        exec_compatible_with (list, optional): A list of constraints for the execution platform for this toolchain.
767        target_compatible_with (list, optional): A list of constraints for the target platform for this toolchain.
768        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
769            [rust_register_toolchains](#rust_register_toolchains) for more details.
770        urls (list, optional): A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format). Defaults to ['https://static.rust-lang.org/dist/{}.tar.xz']
771        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
772            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
773        netrc (str, optional): .netrc file to use for authentication; mirrors the eponymous attribute from http_archive
774        auth_patterns (dict, optional): Override mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archive
775
776    Returns:
777        str: The name of a registerable rust_analyzer_toolchain.
778    """
779    rust_analyzer_toolchain_tools_repository(
780        name = name + "_tools",
781        version = version,
782        sha256s = sha256s,
783        urls = urls,
784        auth = auth,
785        netrc = netrc,
786        auth_patterns = auth_patterns,
787    )
788
789    toolchain_repository_proxy(
790        name = name,
791        toolchain = "@{}//:{}".format(name + "_tools", "rust_analyzer_toolchain"),
792        toolchain_type = "@rules_rust//rust/rust_analyzer:toolchain_type",
793        exec_compatible_with = exec_compatible_with,
794        target_compatible_with = target_compatible_with,
795    )
796
797    return "@{}//:toolchain".format(
798        name,
799    )
800
801_RUSTFMT_TOOLCHAIN_TOOLS_ATTRS = {
802    "auth": attr.string_dict(
803        doc = (
804            "Auth object compatible with repository_ctx.download to use when downloading files. " +
805            "See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details."
806        ),
807    ),
808    "auth_patterns": attr.string_dict(
809        doc = "Override mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archive",
810    ),
811    "exec_triple": attr.string(
812        doc = "The Rust-style triple Rustfmt is expected to run on.",
813        mandatory = True,
814    ),
815    "netrc": attr.string(
816        doc = ".netrc file to use for authentication; mirrors the eponymous attribute from http_archive",
817    ),
818    "sha256s": attr.string_dict(
819        doc = "A dict associating tool subdirectories to sha256 hashes. See [rust_register_toolchains](#rust_register_toolchains) for more details.",
820    ),
821    "urls": attr.string_list(
822        doc = "A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format).",
823        default = DEFAULT_STATIC_RUST_URL_TEMPLATES,
824    ),
825    "version": attr.string(
826        doc = "The version of the tool among \"nightly\", \"beta\" with an iso date, or an exact version.",
827        mandatory = True,
828    ),
829}
830
831def _rustfmt_toolchain_tools_repository_impl(repository_ctx):
832    sha256s = dict(repository_ctx.attr.sha256s)
833    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
834        repository_ctx.name,
835    ))
836
837    iso_date = None
838    version = repository_ctx.attr.version
839    version_array = version.split("/")
840    if len(version_array) > 1:
841        version = version_array[0]
842        iso_date = version_array[1]
843
844    rustfmt = "//:rustfmt_bin"
845    rustc = "//:rustc"
846    rustc_lib = "//:rustc_lib"
847
848    exec_triple = triple(repository_ctx.attr.exec_triple)
849
850    rustc_content, rustc_sha256 = load_rust_compiler(
851        ctx = repository_ctx,
852        iso_date = iso_date,
853        target_triple = exec_triple,
854        version = version,
855    )
856    rustfmt_content, rustfmt_sha256 = load_rustfmt(
857        ctx = repository_ctx,
858        iso_date = iso_date,
859        target_triple = exec_triple,
860        version = version,
861    )
862
863    build_contents = [
864        rustc_content,
865        rustfmt_content,
866        BUILD_for_rustfmt_toolchain(
867            name = "rustfmt_toolchain",
868            rustfmt = rustfmt,
869            rustc = rustc,
870            rustc_lib = rustc_lib,
871        ),
872    ]
873    sha256s.update(rustc_sha256 | rustfmt_sha256)
874
875    repository_ctx.file("BUILD.bazel", "\n".join(build_contents))
876    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
877        repository_ctx.name,
878    ))
879
880    repro = {"name": repository_ctx.name}
881    for key in _RUSTFMT_TOOLCHAIN_TOOLS_ATTRS:
882        repro[key] = getattr(repository_ctx.attr, key)
883    repro["sha256s"] = sha256s
884
885    return repro
886
887rustfmt_toolchain_tools_repository = repository_rule(
888    doc = "A repository rule for defining a rustfmt_toolchain.",
889    attrs = _RUSTFMT_TOOLCHAIN_TOOLS_ATTRS,
890    implementation = _rustfmt_toolchain_tools_repository_impl,
891)
892
893def rustfmt_toolchain_repository(
894        name,
895        version,
896        exec_triple,
897        exec_compatible_with = None,
898        target_compatible_with = None,
899        channel = None,
900        sha256s = None,
901        urls = None,
902        auth = None,
903        netrc = None,
904        auth_patterns = None):
905    """Assemble a remote rustfmt_toolchain target based on the given params.
906
907    Args:
908        name (str): The name of the toolchain proxy repository contianing the registerable toolchain.
909        version (str): The version of the tool among "nightly", "beta', or an exact version.
910        exec_triple (str): The platform triple Rustfmt is expected to run on.
911        exec_compatible_with (list, optional): A list of constraints for the execution platform for this toolchain.
912        target_compatible_with (list, optional): A list of constraints for the target platform for this toolchain.
913        channel (str, optional): The channel value to with which to constrain the toolchain.
914        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
915            [rust_register_toolchains](#rust_register_toolchains) for more details.
916        urls (list, optional): A list of mirror urls containing the tools from the Rust-lang static file server. These must contain the '{}' used to substitute the tool being fetched (using .format). Defaults to ['https://static.rust-lang.org/dist/{}.tar.xz']
917        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
918            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
919        netrc (str, optional): .netrc file to use for authentication; mirrors the eponymous attribute from http_archive
920        auth_patterns (dict, optional): Override mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archive
921
922    Returns:
923        str: The name of a registerable rustfmt_toolchain.
924    """
925    if exec_compatible_with == None:
926        exec_compatible_with = triple_to_constraint_set(exec_triple)
927
928    rustfmt_toolchain_tools_repository(
929        name = name + "_tools",
930        version = version,
931        sha256s = sha256s,
932        urls = urls,
933        auth = auth,
934        netrc = netrc,
935        auth_patterns = auth_patterns,
936        exec_triple = exec_triple,
937    )
938
939    toolchain_repository_proxy(
940        name = name,
941        toolchain = "@{}//:{}".format(name + "_tools", "rustfmt_toolchain"),
942        toolchain_type = "@rules_rust//rust/rustfmt:toolchain_type",
943        target_settings = ["@rules_rust//rust/toolchain/channel:{}".format(channel)] if channel else None,
944        exec_compatible_with = exec_compatible_with,
945        target_compatible_with = target_compatible_with,
946    )
947
948    return "@{}//:toolchain".format(
949        name,
950    )
951
952def _rust_toolchain_set_repository_impl(repository_ctx):
953    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
954        repository_ctx.name,
955    ))
956
957    repository_ctx.file("BUILD.bazel", """exports_files(["defs.bzl"])""")
958    repository_ctx.file("defs.bzl", "ALL_TOOLCHAINS = {}\n".format(
959        json.encode_indent(repository_ctx.attr.toolchains, indent = " " * 4),
960    ))
961
962rust_toolchain_set_repository = repository_rule(
963    doc = (
964        "Generates a toolchain-bearing repository that declares the toolchains from some other " +
965        "rust_toolchain_repository."
966    ),
967    attrs = {
968        "toolchains": attr.string_list(
969            doc = "The list of all toolchains created by the current `rust_toolchain_set`",
970            mandatory = True,
971        ),
972    },
973    implementation = _rust_toolchain_set_repository_impl,
974)
975
976def _get_toolchain_repositories(
977        *,
978        name,
979        exec_triple,
980        extra_target_triples,
981        versions,
982        fallback_target_compatible_with,
983        compact_windows_names,
984        aliases):
985    """Collect structs represent toolchain repositories matching the given parameters.
986
987    Args:
988        name (str): The base name to use for toolchains.
989        exec_triple (triple): The execution triple associated with the toolchain.
990        extra_target_triples (list[triple]): Additional target triples to get toolchains for.
991            the `exec_triple` is a default `target_triple`.
992        versions (str): The version of rustc to use.
993        fallback_target_compatible_with (list): _description_
994        compact_windows_names (bool): Whether or not to produce compact repository names for windows
995            toolchains. This is to avoid MAX_PATH issues.
996        aliases (dict): Replacement names to use for toolchains created by this macro.
997
998    Returns:
999        list[struct]: A list of toolchain structs
1000            - name: The name of the toolchain repository.
1001            - target_triple: The target triple of the toolchain.
1002            - channel: The toolchain channel (nightly/stable).
1003            - target_constraints: Bazel constrants assicated with the toolchain.
1004    """
1005    extra_target_triples_list = extra_target_triples.keys() if type(extra_target_triples) == "dict" else extra_target_triples
1006
1007    toolchain_repos = {}
1008
1009    for target_triple in depset([exec_triple] + extra_target_triples_list).to_list():
1010        # Parse all provided versions while checking for duplicates
1011        channels = {}
1012        for version in versions:
1013            if version.startswith(("beta", "nightly")):
1014                channel, _, _ = version.partition("/")
1015            else:
1016                channel = "stable"
1017
1018            if channel in channels:
1019                fail("Duplicate {} channels provided for {}: {}".format(channel, name, versions))
1020
1021            channels.update({channel: struct(
1022                name = channel,
1023                version = version,
1024            )})
1025
1026        if type(extra_target_triples) == "dict" and target_triple in extra_target_triples:
1027            target_constraints = extra_target_triples[target_triple]
1028        elif fallback_target_compatible_with != None:
1029            target_constraints = fallback_target_compatible_with
1030        else:
1031            target_constraints = triple_to_constraint_set(target_triple)
1032
1033        # Define toolchains for each requested version
1034        for channel in channels.values():
1035            # Check if this toolchain is requested to be aliased.
1036            full_name = "{}__{}__{}".format(name, target_triple, channel.name)
1037            if full_name in aliases:
1038                full_name = aliases.pop(full_name)
1039            elif compact_windows_names and "windows" in exec_triple:
1040                full_name = "rw-{}".format(abs(hash(full_name)))
1041
1042            toolchain_repo = struct(
1043                name = full_name,
1044                target_triple = target_triple,
1045                channel = channel,
1046                target_constraints = target_constraints,
1047            )
1048
1049            if full_name in toolchain_repos:
1050                fail("Duplicate toolchain name of {} found in Rust toolchain repositories:\n{}\n{}".format(
1051                    full_name,
1052                    toolchain_repos[full_name],
1053                    toolchain_repo,
1054                ))
1055
1056            toolchain_repos[full_name] = toolchain_repo
1057
1058    return toolchain_repos.values()
1059
1060def rust_repository_set(
1061        *,
1062        name,
1063        versions,
1064        exec_triple,
1065        target_settings = [],
1066        allocator_library = None,
1067        global_allocator_library = None,
1068        extra_target_triples = {},
1069        rustfmt_version = None,
1070        edition = None,
1071        dev_components = False,
1072        extra_rustc_flags = None,
1073        extra_exec_rustc_flags = None,
1074        opt_level = None,
1075        sha256s = None,
1076        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES,
1077        auth = None,
1078        netrc = None,
1079        auth_patterns = None,
1080        register_toolchain = True,
1081        exec_compatible_with = None,
1082        default_target_compatible_with = None,
1083        aliases = {},
1084        compact_windows_names = _COMPACT_WINDOWS_NAMES):
1085    """Assembles a remote repository for the given toolchain params, produces a proxy repository \
1086    to contain the toolchain declaration, and registers the toolchains.
1087
1088    Args:
1089        name (str): The name of the generated repository
1090        versions (list, optional): A list of toolchain versions to download. This paramter only accepts one versions
1091            per channel. E.g. `["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"]`.
1092        exec_triple (str): The Rust-style target that this compiler runs on
1093        target_settings (list, optional): A list of config_settings that must be satisfied by the target configuration in order for this set of toolchains to be selected during toolchain resolution.
1094        allocator_library (str, optional): Target that provides allocator functions when rust_library targets are
1095            embedded in a cc_binary.
1096        global_allocator_library (str, optional): Target that provides allocator functions a global allocator is used with cc_common.link.
1097        extra_target_triples (list or map, optional): Additional rust-style targets that this set of
1098            toolchains should support. If a map, values should be (optional) target_compatible_with lists for that particular target triple.
1099        rustfmt_version (str, optional):  The version of rustfmt to be associated with the
1100            toolchain.
1101        edition (str, optional): The rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is
1102            required to specify its `edition` attribute.
1103        dev_components (bool, optional): Whether to download the rustc-dev components.
1104            Requires version to be "nightly".
1105        extra_rustc_flags (dict, list, optional): Dictionary of target triples to list of extra flags to pass to rustc in non-exec configuration.
1106        extra_exec_rustc_flags (list, optional): Extra flags to pass to rustc in exec configuration.
1107        opt_level (dict, dict, optional): Dictionary of target triples to optimiztion config.
1108        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
1109            [rust_register_toolchains](#rust_register_toolchains) for more details.
1110        urls (list, optional): A list of mirror urls containing the tools from the Rust-lang static file server. These
1111            must contain the '{}' used to substitute the tool being fetched (using .format).
1112        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
1113            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
1114        netrc (str, optional): .netrc file to use for authentication; mirrors the eponymous attribute from http_archive
1115        auth_patterns (dict, optional): Override mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archive
1116
1117        register_toolchain (bool): If True, the generated `rust_toolchain` target will become a registered toolchain.
1118        exec_compatible_with (list, optional): A list of constraints for the execution platform for this toolchain.
1119        default_target_compatible_with (list, optional): A list of constraints for the target platform for this toolchain when the exec platform is the same as the target platform.
1120        aliases (dict): Replacement names to use for toolchains created by this macro.
1121        compact_windows_names (bool): Whether or not to produce compact repository names for windows
1122            toolchains. This is to avoid MAX_PATH issues.
1123    """
1124
1125    all_toolchain_names = []
1126    for toolchain in _get_toolchain_repositories(
1127        name = name,
1128        exec_triple = exec_triple,
1129        extra_target_triples = extra_target_triples,
1130        versions = versions,
1131        fallback_target_compatible_with = default_target_compatible_with,
1132        aliases = aliases,
1133        compact_windows_names = compact_windows_names,
1134    ):
1135        # Infer toolchain-specific rustc flags depending on the type (list, dict, optional) of extra_rustc_flags
1136        if extra_rustc_flags == None:
1137            toolchain_extra_rustc_flags = []
1138        elif type(extra_rustc_flags) == "list":
1139            toolchain_extra_rustc_flags = extra_rustc_flags
1140        elif type(extra_rustc_flags) == "dict":
1141            toolchain_extra_rustc_flags = extra_rustc_flags.get(toolchain.target_triple)
1142        else:
1143            fail("extra_rustc_flags should be a list or a dict")
1144
1145        all_toolchain_names.append(rust_toolchain_repository(
1146            name = toolchain.name,
1147            allocator_library = allocator_library,
1148            global_allocator_library = global_allocator_library,
1149            auth = auth,
1150            netrc = netrc,
1151            auth_patterns = auth_patterns,
1152            channel = toolchain.channel.name,
1153            dev_components = dev_components,
1154            edition = edition,
1155            exec_triple = exec_triple,
1156            extra_exec_rustc_flags = extra_exec_rustc_flags,
1157            extra_rustc_flags = toolchain_extra_rustc_flags,
1158            opt_level = opt_level.get(toolchain.target_triple) if opt_level != None else None,
1159            target_settings = target_settings,
1160            rustfmt_version = rustfmt_version,
1161            sha256s = sha256s,
1162            target_triple = toolchain.target_triple,
1163            urls = urls,
1164            version = toolchain.channel.version,
1165            exec_compatible_with = exec_compatible_with,
1166            target_compatible_with = toolchain.target_constraints,
1167        ))
1168
1169    # This repository exists to allow `rust_repository_set` to work with the `maybe` wrapper.
1170    rust_toolchain_set_repository(
1171        name = name,
1172        toolchains = all_toolchain_names,
1173    )
1174
1175    # Register toolchains
1176    if register_toolchain:
1177        native.register_toolchains(*all_toolchain_names)
1178        native.register_toolchains(str(Label("//rust/private/dummy_cc_toolchain:dummy_cc_wasm32_toolchain")))
1179        native.register_toolchains(str(Label("//rust/private/dummy_cc_toolchain:dummy_cc_wasm64_toolchain")))