fork/rules_rust

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

UebelAndreDelete `rust_toolchain.rusrc_srcs` (#1807)2fc02f03

rust-analyzer
38.4 KiB900 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", "DEFAULT_NIGHTLY_ISO_DATE", "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_STATIC_RUST_URL_TEMPLATES",
16    "check_version_valid",
17    "includes_rust_analyzer_proc_macro_srv",
18    "load_cargo",
19    "load_clippy",
20    "load_llvm_tools",
21    "load_rust_compiler",
22    "load_rust_src",
23    "load_rust_stdlib",
24    "load_rustc_dev_nightly",
25    "load_rustfmt",
26    "select_rust_version",
27    _load_arbitrary_tool = "load_arbitrary_tool",
28)
29
30# Reexport `load_arbitrary_tool` as it's currently in use in https://github.com/google/cargo-raze
31load_arbitrary_tool = _load_arbitrary_tool
32
33# 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.
34DEFAULT_TOOLCHAIN_TRIPLES = {
35    "aarch64-apple-darwin": "rust_darwin_aarch64",
36    "aarch64-pc-windows-msvc": "rust_windows_aarch64",
37    "aarch64-unknown-linux-gnu": "rust_linux_aarch64",
38    "x86_64-apple-darwin": "rust_darwin_x86_64",
39    "x86_64-pc-windows-msvc": "rust_windows_x86_64",
40    "x86_64-unknown-freebsd": "rust_freebsd_x86_64",
41    "x86_64-unknown-linux-gnu": "rust_linux_x86_64",
42}
43
44def rules_rust_dependencies():
45    """Dependencies used in the implementation of `rules_rust`."""
46
47    maybe(
48        http_archive,
49        name = "platforms",
50        urls = [
51            "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.5/platforms-0.0.5.tar.gz",
52            "https://github.com/bazelbuild/platforms/releases/download/0.0.5/platforms-0.0.5.tar.gz",
53        ],
54        sha256 = "379113459b0feaf6bfbb584a91874c065078aa673222846ac765f86661c27407",
55    )
56    maybe(
57        http_archive,
58        name = "rules_cc",
59        urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.1/rules_cc-0.0.1.tar.gz"],
60        sha256 = "4dccbfd22c0def164c8f47458bd50e0c7148f3d92002cdb459c2a96a68498241",
61    )
62
63    maybe(
64        http_archive,
65        name = "bazel_skylib",
66        urls = [
67            "https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.0/bazel-skylib-1.2.0.tar.gz",
68            "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.0/bazel-skylib-1.2.0.tar.gz",
69        ],
70        sha256 = "af87959afe497dc8dfd4c6cb66e1279cb98ccc84284619ebfec27d9c09a903de",
71    )
72
73    # Make the iOS simulator constraint available, which is referenced in abi_to_constraints()
74    # rules_rust does not require this dependency; it is just imported as a convenience for users.
75    maybe(
76        http_archive,
77        name = "build_bazel_apple_support",
78        sha256 = "d94b7a0f49d735f196e1f36d2e6ef79c4e8e8b82132848dd8cd93cd82d9b12a8",
79        url = "https://github.com/bazelbuild/apple_support/releases/download/1.3.0/apple_support.1.3.0.tar.gz",
80    )
81
82    # process_wrapper needs a low-dependency way to process json.
83    maybe(
84        http_archive,
85        name = "rules_rust_tinyjson",
86        sha256 = "1a8304da9f9370f6a6f9020b7903b044aa9ce3470f300a1fba5bc77c78145a16",
87        url = "https://crates.io/api/v1/crates/tinyjson/2.3.0/download",
88        strip_prefix = "tinyjson-2.3.0",
89        type = "tar.gz",
90        build_file = "@rules_rust//util/process_wrapper:BUILD.tinyjson.bazel",
91    )
92
93_DEFAULT_NIGHTLY_VERSION = "nightly/{}".format(DEFAULT_NIGHTLY_ISO_DATE)
94
95_RUST_TOOLCHAIN_VERSIONS = [
96    rust_common.default_version,
97    _DEFAULT_NIGHTLY_VERSION,
98]
99
100# buildifier: disable=unnamed-macro
101def rust_register_toolchains(
102        dev_components = False,
103        edition = None,
104        allocator_library = None,
105        iso_date = None,
106        register_toolchains = True,
107        rustfmt_version = _DEFAULT_NIGHTLY_VERSION,
108        rust_analyzer_version = None,
109        sha256s = None,
110        extra_target_triples = ["wasm32-unknown-unknown", "wasm32-wasi"],
111        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES,
112        version = None,
113        versions = []):
114    """Emits a default set of toolchains for Linux, MacOS, and Freebsd
115
116    Skip this macro and call the `rust_repository_set` macros directly if you need a compiler for \
117    other hosts or for additional target triples.
118
119    The `sha256` attribute represents a dict associating tool subdirectories to sha256 hashes. As an example:
120    ```python
121    {
122        "rust-1.46.0-x86_64-unknown-linux-gnu": "e3b98bc3440fe92817881933f9564389eccb396f5f431f33d48b979fa2fbdcf5",
123        "rustfmt-1.4.12-x86_64-unknown-linux-gnu": "1894e76913303d66bf40885a601462844eec15fca9e76a6d13c390d7000d64b0",
124        "rust-std-1.46.0-x86_64-unknown-linux-gnu": "ac04aef80423f612c0079829b504902de27a6997214eb58ab0765d02f7ec1dbc",
125    }
126    ```
127    This would match for `exec_triple = "x86_64-unknown-linux-gnu"`.  If not specified, rules_rust pulls from a non-exhaustive \
128    list of known checksums..
129
130    See `load_arbitrary_tool` in `@rules_rust//rust:repositories.bzl` for more details.
131
132    Args:
133        dev_components (bool, optional): Whether to download the rustc-dev components (defaults to False). Requires version to be "nightly".
134        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.
135        allocator_library (str, optional): Target that provides allocator functions when rust_library targets are embedded in a cc_binary.
136        iso_date (str, optional):  **Deprecated**: Use `versions` instead.
137        register_toolchains (bool): If true, repositories will be generated to produce and register `rust_toolchain` targets.
138        rustfmt_version (str, optional): The version of rustfmt.
139        rust_analyzer_version (str, optional): The version of Rustc to pair with rust-analyzer.
140        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes.
141        extra_target_triples (list, optional): Additional rust-style targets that rust toolchains should support.
142        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).
143        version (str, optional): **Deprecated**: Use `versions` instead.
144        versions (list, optional): A list of toolchain versions to download. This paramter only accepts one versions
145            per channel. E.g. `["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"]`.
146    """
147    if version:
148        # buildifier: disable=print
149        print("`rust_register.toolchains.version` is deprecated. Please use `versions` instead: https://bazelbuild.github.io/rules_rust/flatten.html#rust_register_toolchains-versions")
150
151    if iso_date:
152        # buildifier: disable=print
153        print("`rust_register.toolchains.iso_date` is deprecated. Please use `versions` instead: https://bazelbuild.github.io/rules_rust/flatten.html#rust_register_toolchains-versions")
154
155    if rustfmt_version in ("nightly", "beta"):
156        # buildifier: disable=print
157        print("`rust_register.toolchains.rustfmt_version` now requires iso date to be included in the string. E.g. `nightly/2022-12-15`. This version will be assumed until this value is updated")
158        rustfmt_version = "{}/{}".format(rustfmt_version, DEFAULT_NIGHTLY_ISO_DATE)
159
160    if not versions:
161        if version:
162            versions = [version]
163        else:
164            versions = _RUST_TOOLCHAIN_VERSIONS
165
166    if dev_components:
167        has_nightly = False
168        for ver in versions:
169            if ver.startswith("nightly"):
170                has_nightly = True
171                break
172        if not has_nightly:
173            fail("rustc-dev components were requested but no \"nightly\" is being registered. Please update `versions` to include a nightly version.")
174
175    if not rust_analyzer_version:
176        rust_analyzer_version = select_rust_version(versions)
177
178    rust_analyzer_repo_name = "rust_analyzer_{}".format(rust_analyzer_version.replace("/", "-"))
179    rust_analyzer_iso_date = None
180    if rust_analyzer_version.startswith(("beta", "nightly")):
181        rust_analyzer_version, _, rust_analyzer_iso_date = rustfmt_version.partition("/")
182
183    maybe(
184        rust_analyzer_toolchain_repository,
185        name = rust_analyzer_repo_name,
186        version = rust_analyzer_version,
187        urls = urls,
188        sha256s = sha256s,
189        iso_date = rust_analyzer_iso_date,
190    )
191
192    if register_toolchains:
193        native.register_toolchains("@{}//:toolchain".format(
194            rust_analyzer_repo_name,
195        ))
196
197    rustfmt_iso_date = None
198    rustfmt_version_or_channel = rustfmt_version
199    if rustfmt_version.startswith(("beta", "nightly")):
200        rustfmt_version_or_channel, _, rustfmt_iso_date = rustfmt_version.partition("/")
201
202    for exec_triple, name in DEFAULT_TOOLCHAIN_TRIPLES.items():
203        maybe(
204            rust_repository_set,
205            name = name,
206            dev_components = dev_components,
207            edition = edition,
208            exec_triple = exec_triple,
209            extra_target_triples = extra_target_triples,
210            allocator_library = allocator_library,
211            iso_date = iso_date,
212            register_toolchain = register_toolchains,
213            rustfmt_version = rustfmt_version,
214            sha256s = sha256s,
215            urls = urls,
216            version = version,
217            versions = versions,
218        )
219
220        rustfmt_repo_name = "rustfmt_{}__{}".format(rustfmt_version.replace("/", "-"), exec_triple)
221
222        maybe(
223            rustfmt_toolchain_repository,
224            name = rustfmt_repo_name,
225            version = rustfmt_version_or_channel,
226            urls = urls,
227            sha256s = sha256s,
228            iso_date = rustfmt_iso_date,
229            exec_triple = exec_triple,
230        )
231
232        if register_toolchains:
233            native.register_toolchains("@{}//:toolchain".format(
234                rustfmt_repo_name,
235            ))
236
237# buildifier: disable=unnamed-macro
238def rust_repositories(**kwargs):
239    """**Deprecated**: Use [rules_rust_dependencies](#rules_rust_dependencies) \
240    and [rust_register_toolchains](#rust_register_toolchains) directly.
241
242    Args:
243        **kwargs (dict): Keyword arguments for the `rust_register_toolchains` macro.
244    """
245    rules_rust_dependencies()
246
247    rust_register_toolchains(**kwargs)
248
249def _rust_toolchain_tools_repository_impl(ctx):
250    """The implementation of the rust toolchain tools repository rule."""
251
252    check_version_valid(ctx.attr.version, ctx.attr.iso_date)
253
254    exec_triple = triple(ctx.attr.exec_triple)
255
256    build_components = [
257        load_rust_compiler(
258            ctx = ctx,
259            iso_date = ctx.attr.iso_date,
260            target_triple = exec_triple,
261            version = ctx.attr.version,
262        ),
263        load_clippy(
264            ctx = ctx,
265            iso_date = ctx.attr.iso_date,
266            target_triple = exec_triple,
267            version = ctx.attr.version,
268        ),
269        load_cargo(
270            ctx = ctx,
271            iso_date = ctx.attr.iso_date,
272            target_triple = exec_triple,
273            version = ctx.attr.version,
274        ),
275    ]
276
277    if ctx.attr.rustfmt_version:
278        rustfmt_version = ctx.attr.rustfmt_version
279        rustfmt_iso_date = None
280        if rustfmt_version in ("nightly", "beta"):
281            if ctx.attr.iso_date:
282                rustfmt_iso_date = ctx.attr.iso_date
283            else:
284                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(
285                    ctx.name,
286                ))
287        elif rustfmt_version.startswith(("nightly", "beta")):
288            rustfmt_version, _, rustfmt_iso_date = rustfmt_version.partition("/")
289        build_components.append(load_rustfmt(
290            ctx = ctx,
291            target_triple = triple(ctx.attr.exec_triple),
292            version = rustfmt_version,
293            iso_date = rustfmt_iso_date,
294        ))
295
296    # Rust 1.45.0 and nightly builds after 2020-05-22 need the llvm-tools gzip to get the libLLVM dylib
297    include_llvm_tools = ctx.attr.version >= "1.45.0" or (ctx.attr.version == "nightly" and ctx.attr.iso_date > "2020-05-22")
298    if include_llvm_tools:
299        build_components.append(load_llvm_tools(
300            ctx = ctx,
301            target_triple = exec_triple,
302        ))
303
304    target_triple = triple(ctx.attr.target_triple)
305    build_components.append(load_rust_stdlib(
306        ctx = ctx,
307        target_triple = target_triple,
308    ))
309
310    stdlib_linkflags = None
311    if "BAZEL_RUST_STDLIB_LINKFLAGS" in ctx.os.environ:
312        stdlib_linkflags = ctx.os.environ["BAZEL_RUST_STDLIB_LINKFLAGS"].split(":")
313
314    build_components.append(BUILD_for_rust_toolchain(
315        name = "rust_toolchain",
316        exec_triple = exec_triple,
317        allocator_library = ctx.attr.allocator_library,
318        target_triple = target_triple,
319        stdlib_linkflags = stdlib_linkflags,
320        workspace_name = ctx.attr.name,
321        default_edition = ctx.attr.edition,
322        include_rustfmt = not (not ctx.attr.rustfmt_version),
323        include_llvm_tools = include_llvm_tools,
324    ))
325
326    # Not all target triples are expected to have dev components
327    if ctx.attr.dev_components:
328        load_rustc_dev_nightly(ctx, ctx.attr.target_triple)
329
330    ctx.file("WORKSPACE.bazel", "")
331    ctx.file("BUILD.bazel", "\n".join(build_components))
332
333rust_toolchain_tools_repository = repository_rule(
334    doc = (
335        "Composes a single workspace containing the toolchain components for compiling on a given " +
336        "platform to a series of target platforms.\n" +
337        "\n" +
338        "A given instance of this rule should be accompanied by a toolchain_repository_proxy " +
339        "invocation to declare its toolchains to Bazel; the indirection allows separating toolchain " +
340        "selection from toolchain fetching."
341    ),
342    attrs = {
343        "allocator_library": attr.string(
344            doc = "Target that provides allocator functions when rust_library targets are embedded in a cc_binary.",
345        ),
346        "auth": attr.string_dict(
347            doc = (
348                "Auth object compatible with repository_ctx.download to use when downloading files. " +
349                "See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details."
350            ),
351        ),
352        "dev_components": attr.bool(
353            doc = "Whether to download the rustc-dev components (defaults to False). Requires version to be \"nightly\".",
354            default = False,
355        ),
356        "edition": attr.string(
357            doc = (
358                "The rust edition to be used by default (2015, 2018, or 2021). " +
359                "If absent, every rule is required to specify its `edition` attribute."
360            ),
361        ),
362        "exec_triple": attr.string(
363            doc = "The Rust-style target that this compiler runs on",
364            mandatory = True,
365        ),
366        "iso_date": attr.string(
367            doc = "The date of the tool (or None, if the version is a specific version).",
368        ),
369        "rustfmt_version": attr.string(
370            doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.",
371        ),
372        "sha256s": attr.string_dict(
373            doc = "A dict associating tool subdirectories to sha256 hashes. See [rust_repositories](#rust_repositories) for more details.",
374        ),
375        "target_triple": attr.string(
376            doc = "The Rust-style target that this compiler builds for.",
377            mandatory = True,
378        ),
379        "urls": attr.string_list(
380            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).",
381            default = DEFAULT_STATIC_RUST_URL_TEMPLATES,
382        ),
383        "version": attr.string(
384            doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.",
385            mandatory = True,
386        ),
387    },
388    implementation = _rust_toolchain_tools_repository_impl,
389)
390
391def _toolchain_repository_proxy_impl(repository_ctx):
392    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
393        repository_ctx.name,
394    ))
395
396    repository_ctx.file("BUILD.bazel", BUILD_for_toolchain(
397        name = "toolchain",
398        toolchain = repository_ctx.attr.toolchain,
399        target_settings = repository_ctx.attr.target_settings,
400        toolchain_type = repository_ctx.attr.toolchain_type,
401        target_compatible_with = repository_ctx.attr.target_compatible_with,
402        exec_compatible_with = repository_ctx.attr.exec_compatible_with,
403    ))
404
405toolchain_repository_proxy = repository_rule(
406    doc = (
407        "Generates a toolchain-bearing repository that declares the toolchains from some other " +
408        "rust_toolchain_repository."
409    ),
410    attrs = {
411        "exec_compatible_with": attr.string_list(
412            doc = "A list of constraints for the execution platform for this toolchain.",
413        ),
414        "target_compatible_with": attr.string_list(
415            doc = "A list of constraints for the target platform for this toolchain.",
416        ),
417        "target_settings": attr.string_list(
418            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.",
419        ),
420        "toolchain": attr.string(
421            doc = "The name of the toolchain implementation target.",
422            mandatory = True,
423        ),
424        "toolchain_type": attr.string(
425            doc = "The toolchain type of the toolchain to declare",
426            mandatory = True,
427        ),
428    },
429    implementation = _toolchain_repository_proxy_impl,
430)
431
432# For legacy support
433rust_toolchain_repository_proxy = toolchain_repository_proxy
434
435# N.B. A "proxy repository" is needed to allow for registering the toolchain (with constraints)
436# without actually downloading the toolchain.
437def rust_toolchain_repository(
438        name,
439        version,
440        exec_triple,
441        target_triple,
442        exec_compatible_with = None,
443        target_compatible_with = None,
444        target_settings = [],
445        channel = None,
446        allocator_library = None,
447        iso_date = None,
448        rustfmt_version = None,
449        edition = None,
450        dev_components = False,
451        sha256s = None,
452        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES,
453        auth = None):
454    """Assembles a remote repository for the given toolchain params, produces a proxy repository \
455    to contain the toolchain declaration, and registers the toolchains.
456
457    Args:
458        name (str): The name of the generated repository
459        version (str): The version of the tool among "nightly", "beta", or an exact version.
460        exec_triple (str): The Rust-style target that this compiler runs on.
461        target_triple (str): The Rust-style target to build for.
462        channel (str, optional): The channel of the Rust toolchain.
463        exec_compatible_with (list, optional): A list of constraints for the execution platform for this toolchain.
464        target_compatible_with (list, optional): A list of constraints for the target platform for this toolchain.
465        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.
466        allocator_library (str, optional): Target that provides allocator functions when rust_library targets are embedded in a cc_binary.
467        iso_date (str, optional): The date of the tool.
468        rustfmt_version (str, optional):  The version of rustfmt to be associated with the
469            toolchain.
470        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.
471        dev_components (bool, optional): Whether to download the rustc-dev components.
472            Requires version to be "nightly". Defaults to False.
473        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
474            [rust_repositories](#rust_repositories) for more details.
475        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.gz']
476        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
477            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
478
479    Returns:
480        str: The name of the registerable toolchain created by this rule.
481    """
482
483    if rustfmt_version in ("nightly", "beta"):
484        # buildifier: disable=print
485        print("`rust_toolchain_repository.rustfmt_version` now requires iso date to be included in the string. E.g. `nightly/2022-12-15`. This version will be assumed until this value is updated")
486        rustfmt_version = "{}/{}".format(rustfmt_version, DEFAULT_NIGHTLY_ISO_DATE)
487
488    if exec_compatible_with == None:
489        exec_compatible_with = triple_to_constraint_set(exec_triple)
490
491    if target_compatible_with == None:
492        target_compatible_with = triple_to_constraint_set(target_triple)
493
494    tools_repo_name = "{}_tools".format(name)
495
496    rust_toolchain_tools_repository(
497        name = tools_repo_name,
498        exec_triple = exec_triple,
499        allocator_library = allocator_library,
500        target_triple = target_triple,
501        iso_date = iso_date,
502        version = version,
503        rustfmt_version = rustfmt_version,
504        edition = edition,
505        dev_components = dev_components,
506        sha256s = sha256s,
507        urls = urls,
508        auth = auth,
509    )
510
511    channel_target_settings = ["@rules_rust//rust/toolchain/channel:{}".format(channel)] if channel else []
512
513    toolchain_repository_proxy(
514        name = name,
515        toolchain = "@{}//:rust_toolchain".format(tools_repo_name),
516        target_settings = channel_target_settings + target_settings,
517        toolchain_type = "@rules_rust//rust:toolchain",
518        exec_compatible_with = exec_compatible_with,
519        target_compatible_with = target_compatible_with,
520    )
521
522    return "@{name}//:toolchain".format(
523        name = name,
524    )
525
526def _rust_analyzer_toolchain_tools_repository_impl(repository_ctx):
527    load_rust_src(
528        ctx = repository_ctx,
529        iso_date = repository_ctx.attr.iso_date,
530        version = repository_ctx.attr.version,
531    )
532
533    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
534        repository_ctx.name,
535    ))
536
537    host_triple = get_host_triple(repository_ctx)
538    build_contents = [
539        load_rust_compiler(
540            ctx = repository_ctx,
541            iso_date = repository_ctx.attr.iso_date,
542            target_triple = host_triple,
543            version = repository_ctx.attr.version,
544        ),
545    ]
546    rustc = "//:rustc"
547
548    proc_macro_srv = None
549    if includes_rust_analyzer_proc_macro_srv(repository_ctx.attr.version, repository_ctx.attr.iso_date):
550        build_contents.append(BUILD_for_rust_analyzer_proc_macro_srv(host_triple))
551        proc_macro_srv = "//:rust_analyzer_proc_macro_srv"
552
553    build_contents.append(BUILD_for_rust_analyzer_toolchain(
554        name = "rust_analyzer_toolchain",
555        rustc = rustc,
556        proc_macro_srv = proc_macro_srv,
557    ))
558
559    repository_ctx.file("BUILD.bazel", "\n".join(build_contents))
560    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
561        repository_ctx.name,
562    ))
563
564rust_analyzer_toolchain_tools_repository = repository_rule(
565    doc = "A repository rule for defining a rust_analyzer_toolchain with a `rust-src` artifact.",
566    attrs = {
567        "auth": attr.string_dict(
568            doc = (
569                "Auth object compatible with repository_ctx.download to use when downloading files. " +
570                "See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details."
571            ),
572        ),
573        "iso_date": attr.string(
574            doc = "The date of the tool (or None, if the version is a specific version).",
575        ),
576        "sha256s": attr.string_dict(
577            doc = "A dict associating tool subdirectories to sha256 hashes. See [rust_repositories](#rust_repositories) for more details.",
578        ),
579        "urls": attr.string_list(
580            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).",
581            default = DEFAULT_STATIC_RUST_URL_TEMPLATES,
582        ),
583        "version": attr.string(
584            doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.",
585            mandatory = True,
586        ),
587    },
588    implementation = _rust_analyzer_toolchain_tools_repository_impl,
589)
590
591def rust_analyzer_toolchain_repository(
592        name,
593        version,
594        exec_compatible_with = [],
595        target_compatible_with = [],
596        iso_date = None,
597        sha256s = None,
598        urls = None,
599        auth = None):
600    """Assemble a remote rust_analyzer_toolchain target based on the given params.
601
602    Args:
603        name (str): The name of the toolchain proxy repository contianing the registerable toolchain.
604        version (str): The version of the tool among "nightly", "beta', or an exact version.
605        exec_compatible_with (list, optional): A list of constraints for the execution platform for this toolchain.
606        target_compatible_with (list, optional): A list of constraints for the target platform for this toolchain.
607        iso_date (str, optional): The date of the tool.
608        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
609            [rust_repositories](#rust_repositories) for more details.
610        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.gz']
611        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
612            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
613
614    Returns:
615        str: The name of a registerable rust_analyzer_toolchain.
616    """
617    rust_analyzer_toolchain_tools_repository(
618        name = name + "_tools",
619        version = version,
620        iso_date = iso_date,
621        sha256s = sha256s,
622        urls = urls,
623        auth = auth,
624    )
625
626    toolchain_repository_proxy(
627        name = name,
628        toolchain = "@{}//:{}".format(name + "_tools", "rust_analyzer_toolchain"),
629        toolchain_type = "@rules_rust//rust/rust_analyzer:toolchain_type",
630        exec_compatible_with = exec_compatible_with,
631        target_compatible_with = target_compatible_with,
632    )
633
634    return "@{}//:toolchain".format(
635        name,
636    )
637
638def _rustfmt_toolchain_tools_repository_impl(repository_ctx):
639    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
640        repository_ctx.name,
641    ))
642
643    rustfmt = "//:rustfmt_bin"
644    rustc = "//:rustc"
645    rustc_lib = "//:rustc_lib"
646
647    exec_triple = triple(repository_ctx.attr.exec_triple)
648
649    build_contents = [
650        load_rust_compiler(
651            ctx = repository_ctx,
652            iso_date = repository_ctx.attr.iso_date,
653            target_triple = exec_triple,
654            version = repository_ctx.attr.version,
655        ),
656        load_rustfmt(
657            ctx = repository_ctx,
658            iso_date = repository_ctx.attr.iso_date,
659            target_triple = exec_triple,
660            version = repository_ctx.attr.version,
661        ),
662        BUILD_for_rustfmt_toolchain(
663            name = "rustfmt_toolchain",
664            rustfmt = rustfmt,
665            rustc = rustc,
666            rustc_lib = rustc_lib,
667        ),
668    ]
669
670    repository_ctx.file("BUILD.bazel", "\n".join(build_contents))
671    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
672        repository_ctx.name,
673    ))
674
675rustfmt_toolchain_tools_repository = repository_rule(
676    doc = "A repository rule for defining a rustfmt_toolchain.",
677    attrs = {
678        "auth": attr.string_dict(
679            doc = (
680                "Auth object compatible with repository_ctx.download to use when downloading files. " +
681                "See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details."
682            ),
683        ),
684        "exec_triple": attr.string(
685            doc = "The Rust-style triple Rustfmt is expected to run on.",
686            mandatory = True,
687        ),
688        "iso_date": attr.string(
689            doc = "The date of the tool (or None, if the version is a specific version).",
690        ),
691        "sha256s": attr.string_dict(
692            doc = "A dict associating tool subdirectories to sha256 hashes. See [rust_repositories](#rust_repositories) for more details.",
693        ),
694        "urls": attr.string_list(
695            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).",
696            default = DEFAULT_STATIC_RUST_URL_TEMPLATES,
697        ),
698        "version": attr.string(
699            doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.",
700            mandatory = True,
701        ),
702    },
703    implementation = _rustfmt_toolchain_tools_repository_impl,
704)
705
706def rustfmt_toolchain_repository(
707        name,
708        version,
709        exec_triple,
710        exec_compatible_with = None,
711        target_compatible_with = None,
712        iso_date = None,
713        channel = None,
714        sha256s = None,
715        urls = None,
716        auth = None):
717    """Assemble a remote rustfmt_toolchain target based on the given params.
718
719    Args:
720        name (str): The name of the toolchain proxy repository contianing the registerable toolchain.
721        version (str): The version of the tool among "nightly", "beta', or an exact version.
722        exec_triple (str): The platform triple Rustfmt is expected to run on.
723        exec_compatible_with (list, optional): A list of constraints for the execution platform for this toolchain.
724        target_compatible_with (list, optional): A list of constraints for the target platform for this toolchain.
725        iso_date (str, optional): The date of the tool.
726        channel (str, optional): The channel value to with which to constrain the toolchain.
727        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
728            [rust_repositories](#rust_repositories) for more details.
729        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.gz']
730        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
731            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
732
733    Returns:
734        str: The name of a registerable rustfmt_toolchain.
735    """
736    if exec_compatible_with == None:
737        exec_compatible_with = triple_to_constraint_set(exec_triple)
738
739    rustfmt_toolchain_tools_repository(
740        name = name + "_tools",
741        version = version,
742        iso_date = iso_date,
743        sha256s = sha256s,
744        urls = urls,
745        auth = auth,
746        exec_triple = exec_triple,
747    )
748
749    toolchain_repository_proxy(
750        name = name,
751        toolchain = "@{}//:{}".format(name + "_tools", "rustfmt_toolchain"),
752        toolchain_type = "@rules_rust//rust/rustfmt:toolchain_type",
753        target_settings = ["@rules_rust//rust/toolchain/channel:{}".format(channel)] if channel else None,
754        exec_compatible_with = exec_compatible_with,
755        target_compatible_with = target_compatible_with,
756    )
757
758    return "@{}//:toolchain".format(
759        name,
760    )
761
762def _rust_toolchain_set_repository_impl(repository_ctx):
763    repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format(
764        repository_ctx.name,
765    ))
766
767    repository_ctx.file("BUILD.bazel", """exports_files(["defs.bzl"])""")
768    repository_ctx.file("defs.bzl", "ALL_TOOLCHAINS = {}\n".format(
769        json.encode_indent(repository_ctx.attr.toolchains, indent = " " * 4),
770    ))
771
772rust_toolchain_set_repository = repository_rule(
773    doc = (
774        "Generates a toolchain-bearing repository that declares the toolchains from some other " +
775        "rust_toolchain_repository."
776    ),
777    attrs = {
778        "toolchains": attr.string_list(
779            doc = "The list of all toolchains created by the current `rust_toolchain_set`",
780            mandatory = True,
781        ),
782    },
783    implementation = _rust_toolchain_set_repository_impl,
784)
785
786def rust_repository_set(
787        name,
788        exec_triple,
789        target_settings = [],
790        version = None,
791        versions = [],
792        allocator_library = None,
793        extra_target_triples = [],
794        iso_date = None,
795        rustfmt_version = None,
796        edition = None,
797        dev_components = False,
798        sha256s = None,
799        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES,
800        auth = None,
801        register_toolchain = True):
802    """Assembles a remote repository for the given toolchain params, produces a proxy repository \
803    to contain the toolchain declaration, and registers the toolchains.
804
805    Args:
806        name (str): The name of the generated repository
807        exec_triple (str): The Rust-style target that this compiler runs on
808        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.
809        version (str): The version of the tool among "nightly", "beta', or an exact version.
810        versions (list, optional): A list of toolchain versions to download. This paramter only accepts one versions
811            per channel. E.g. `["1.65.0", "nightly/2022-11-02", "beta/2020-12-30"]`.
812        allocator_library (str, optional): Target that provides allocator functions when rust_library targets are
813            embedded in a cc_binary.
814        extra_target_triples (list, optional): Additional rust-style targets that this set of
815            toolchains should support.
816        iso_date (str, optional): The date of the tool.
817        rustfmt_version (str, optional):  The version of rustfmt to be associated with the
818            toolchain.
819        edition (str, optional): The rust edition to be used by default (2015, 2018, or 2021). If absent, every rule is
820            required to specify its `edition` attribute.
821        dev_components (bool, optional): Whether to download the rustc-dev components.
822            Requires version to be "nightly".
823        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
824            [rust_repositories](#rust_repositories) for more details.
825        urls (list, optional): A list of mirror urls containing the tools from the Rust-lang static file server. These
826            must contain the '{}' used to substitute the tool being fetched (using .format).
827        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
828            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
829        register_toolchain (bool): If True, the generated `rust_toolchain` target will become a registered toolchain.
830    """
831
832    if version and versions:
833        fail("`version` and `versions` attributes are mutually exclusive. Update {} to use one".format(
834            name,
835        ))
836
837    if not version and not versions:
838        fail("`version` or `versions` attributes are required. Update {} to use one".format(
839            name,
840        ))
841
842    if version:
843        # buildifier: disable=print
844        print("`rust_repository_set.version` is deprecated. Instead use `rust_repository_set.versions`")
845
846    if version and not versions:
847        versions = [version]
848
849    all_toolchain_names = []
850    for target_triple in [exec_triple] + extra_target_triples:
851        # Parse all provided versions while checking for duplicates
852        channels = {}
853        for version in versions:
854            if version.startswith(("beta", "nightly")):
855                channel, _, date = version.partition("/")
856                ver = channel
857            else:
858                channel = "stable"
859                date = iso_date
860                ver = version
861
862            if channel in channels:
863                fail("Duplicate {} channels provided for {}: {}".format(channel, name, versions))
864
865            channels.update({channel: struct(
866                iso_date = date,
867                version = ver,
868            )})
869
870        # Define toolchains for each requested version
871        for channel, info in channels.items():
872            toolchain_name = "{}__{}__{}".format(name, target_triple, channel)
873
874            all_toolchain_names.append(rust_toolchain_repository(
875                name = toolchain_name,
876                allocator_library = allocator_library,
877                auth = auth,
878                channel = channel,
879                dev_components = dev_components,
880                edition = edition,
881                exec_triple = exec_triple,
882                target_settings = target_settings,
883                iso_date = info.iso_date,
884                rustfmt_version = rustfmt_version,
885                sha256s = sha256s,
886                target_triple = target_triple,
887                urls = urls,
888                version = info.version,
889            ))
890
891    # This repository exists to allow `rust_repository_set` to work with the `maybe` wrapper.
892    rust_toolchain_set_repository(
893        name = name,
894        toolchains = all_toolchain_names,
895    )
896
897    # Register toolchains
898    if register_toolchain:
899        native.register_toolchains(*all_toolchain_names)
900        native.register_toolchains(str(Label("//rust/private/dummy_cc_toolchain:dummy_cc_wasm32_toolchain")))