fork/rules_rust

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

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

rust-analyzer
25.7 KiB776 linesraw
1"""Utility macros for use in rules_rust repository rules"""
2
3load("//rust:known_shas.bzl", "FILE_KEY_TO_SHA")
4load(
5    "//rust/platform:triple_mappings.bzl",
6    "system_to_binary_ext",
7    "system_to_dylib_ext",
8    "system_to_staticlib_ext",
9    "system_to_stdlib_linkflags",
10)
11
12DEFAULT_TOOLCHAIN_NAME_PREFIX = "toolchain_for"
13DEFAULT_STATIC_RUST_URL_TEMPLATES = ["https://static.rust-lang.org/dist/{}.tar.gz"]
14
15_build_file_for_compiler_template = """\
16filegroup(
17    name = "rustc",
18    srcs = ["bin/rustc{binary_ext}"],
19    visibility = ["//visibility:public"],
20)
21
22filegroup(
23    name = "rustc_lib",
24    srcs = glob(
25        [
26            "bin/*{dylib_ext}",
27            "lib/*{dylib_ext}",
28            "lib/rustlib/{target_triple}/codegen-backends/*{dylib_ext}",
29            "lib/rustlib/{target_triple}/bin/rust-lld{binary_ext}",
30            "lib/rustlib/{target_triple}/lib/*{dylib_ext}",
31        ],
32        allow_empty = True,
33    ),
34    visibility = ["//visibility:public"],
35)
36
37filegroup(
38    name = "rustdoc",
39    srcs = ["bin/rustdoc{binary_ext}"],
40    visibility = ["//visibility:public"],
41)
42"""
43
44def BUILD_for_compiler(target_triple):
45    """Emits a BUILD file the compiler archive.
46
47    Args:
48        target_triple (str): The triple of the target platform
49
50    Returns:
51        str: The contents of a BUILD file
52    """
53    return _build_file_for_compiler_template.format(
54        binary_ext = system_to_binary_ext(target_triple.system),
55        staticlib_ext = system_to_staticlib_ext(target_triple.system),
56        dylib_ext = system_to_dylib_ext(target_triple.system),
57        target_triple = target_triple.str,
58    )
59
60_build_file_for_cargo_template = """\
61filegroup(
62    name = "cargo",
63    srcs = ["bin/cargo{binary_ext}"],
64    visibility = ["//visibility:public"],
65)"""
66
67def BUILD_for_cargo(target_triple):
68    """Emits a BUILD file the cargo archive.
69
70    Args:
71        target_triple (str): The triple of the target platform
72
73    Returns:
74        str: The contents of a BUILD file
75    """
76    return _build_file_for_cargo_template.format(
77        binary_ext = system_to_binary_ext(target_triple.system),
78    )
79
80_build_file_for_rustfmt_template = """\
81filegroup(
82    name = "rustfmt_bin",
83    srcs = ["bin/rustfmt{binary_ext}"],
84    visibility = ["//visibility:public"],
85)
86
87sh_binary(
88    name = "rustfmt",
89    srcs = [":rustfmt_bin"],
90    visibility = ["//visibility:public"],
91)
92"""
93
94def BUILD_for_rustfmt(target_triple):
95    """Emits a BUILD file the rustfmt archive.
96
97    Args:
98        target_triple (str): The triple of the target platform
99
100    Returns:
101        str: The contents of a BUILD file
102    """
103    return _build_file_for_rustfmt_template.format(
104        binary_ext = system_to_binary_ext(target_triple.system),
105    )
106
107_build_file_for_clippy_template = """\
108filegroup(
109    name = "clippy_driver_bin",
110    srcs = ["bin/clippy-driver{binary_ext}"],
111    visibility = ["//visibility:public"],
112)
113"""
114
115_build_file_for_rust_analyzer_proc_macro_srv = """\
116filegroup(
117   name = "rust_analyzer_proc_macro_srv",
118   srcs = ["libexec/rust-analyzer-proc-macro-srv{binary_ext}"],
119   visibility = ["//visibility:public"],
120)
121"""
122
123def BUILD_for_rust_analyzer_proc_macro_srv(exec_triple):
124    """Emits a BUILD file the rust_analyzer_proc_macro_srv archive.
125
126    Args:
127        exec_triple (str): The triple of the exec platform
128    Returns:
129        str: The contents of a BUILD file
130    """
131    return _build_file_for_rust_analyzer_proc_macro_srv.format(
132        binary_ext = system_to_binary_ext(exec_triple.system),
133    )
134
135def BUILD_for_clippy(target_triple):
136    """Emits a BUILD file the clippy archive.
137
138    Args:
139        target_triple (str): The triple of the target platform
140
141    Returns:
142        str: The contents of a BUILD file
143    """
144    return _build_file_for_clippy_template.format(
145        binary_ext = system_to_binary_ext(target_triple.system),
146    )
147
148_build_file_for_llvm_tools = """\
149filegroup(
150    name = "llvm_cov_bin",
151    srcs = ["lib/rustlib/{target_triple}/bin/llvm-cov{binary_ext}"],
152    visibility = ["//visibility:public"],
153)
154
155filegroup(
156    name = "llvm_profdata_bin",
157    srcs = ["lib/rustlib/{target_triple}/bin/llvm-profdata{binary_ext}"],
158    visibility = ["//visibility:public"],
159)
160"""
161
162def BUILD_for_llvm_tools(target_triple):
163    """Emits a BUILD file the llvm-tools binaries.
164
165    Args:
166        target_triple (struct): The triple of the target platform
167
168    Returns:
169        str: The contents of a BUILD file
170    """
171    return _build_file_for_llvm_tools.format(
172        binary_ext = system_to_binary_ext(target_triple.system),
173        target_triple = target_triple.str,
174    )
175
176_build_file_for_stdlib_template = """\
177load("@rules_rust//rust:toolchain.bzl", "rust_stdlib_filegroup")
178
179rust_stdlib_filegroup(
180    name = "rust_std-{target_triple}",
181    srcs = glob(
182        [
183            "lib/rustlib/{target_triple}/lib/*.rlib",
184            "lib/rustlib/{target_triple}/lib/*{dylib_ext}",
185            "lib/rustlib/{target_triple}/lib/*{staticlib_ext}",
186            "lib/rustlib/{target_triple}/lib/self-contained/**",
187        ],
188        # Some patterns (e.g. `lib/*.a`) don't match anything, see https://github.com/bazelbuild/rules_rust/pull/245
189        allow_empty = True,
190    ),
191    visibility = ["//visibility:public"],
192)
193
194# For legacy support
195alias(
196    name = "rust_lib-{target_triple}",
197    actual = "rust_std-{target_triple}",
198    visibility = ["//visibility:public"],
199)
200"""
201
202def BUILD_for_stdlib(target_triple):
203    """Emits a BUILD file the stdlib archive.
204
205    Args:
206        target_triple (triple): The triple of the target platform
207
208    Returns:
209        str: The contents of a BUILD file
210    """
211    return _build_file_for_stdlib_template.format(
212        binary_ext = system_to_binary_ext(target_triple.system),
213        staticlib_ext = system_to_staticlib_ext(target_triple.system),
214        dylib_ext = system_to_dylib_ext(target_triple.system),
215        target_triple = target_triple.str,
216    )
217
218_build_file_for_rust_toolchain_template = """\
219load("@rules_rust//rust:toolchain.bzl", "rust_toolchain")
220
221rust_toolchain(
222    name = "{toolchain_name}",
223    rust_doc = "@{workspace_name}//:rustdoc",
224    rust_std = "@{workspace_name}//:rust_std-{target_triple}",
225    rustc = "@{workspace_name}//:rustc",
226    rustfmt = {rustfmt_label},
227    cargo = "@{workspace_name}//:cargo",
228    clippy_driver = "@{workspace_name}//:clippy_driver_bin",
229    llvm_cov = {llvm_cov_label},
230    llvm_profdata = {llvm_profdata_label},
231    rustc_lib = "@{workspace_name}//:rustc_lib",
232    allocator_library = {allocator_library},
233    binary_ext = "{binary_ext}",
234    staticlib_ext = "{staticlib_ext}",
235    dylib_ext = "{dylib_ext}",
236    stdlib_linkflags = [{stdlib_linkflags}],
237    os = "{system}",
238    default_edition = "{default_edition}",
239    exec_triple = "{exec_triple}",
240    target_triple = "{target_triple}",
241    visibility = ["//visibility:public"],
242)
243"""
244
245def BUILD_for_rust_toolchain(
246        workspace_name,
247        name,
248        exec_triple,
249        target_triple,
250        allocator_library,
251        default_edition,
252        include_rustfmt,
253        include_llvm_tools,
254        stdlib_linkflags = None):
255    """Emits a toolchain declaration to match an existing compiler and stdlib.
256
257    Args:
258        workspace_name (str): The name of the workspace that this toolchain resides in
259        name (str): The name of the toolchain declaration
260        exec_triple (triple): The rust-style target that this compiler runs on
261        target_triple (triple): The rust-style target triple of the tool
262        allocator_library (str, optional): Target that provides allocator functions when rust_library targets are embedded in a cc_binary.
263        default_edition (str): Default Rust edition.
264        include_rustfmt (bool): Whether rustfmt is present in the toolchain.
265        include_llvm_tools (bool): Whether llvm-tools are present in the toolchain.
266        stdlib_linkflags (list, optional): Overriden flags needed for linking to rust
267                                           stdlib, akin to BAZEL_LINKLIBS. Defaults to
268                                           None.
269
270
271    Returns:
272        str: A rendered template of a `rust_toolchain` declaration
273    """
274    if stdlib_linkflags == None:
275        stdlib_linkflags = ", ".join(['"%s"' % x for x in system_to_stdlib_linkflags(target_triple.system)])
276
277    rustfmt_label = "None"
278    if include_rustfmt:
279        rustfmt_label = "\"@{workspace_name}//:rustfmt_bin\"".format(workspace_name = workspace_name)
280    llvm_cov_label = "None"
281    llvm_profdata_label = "None"
282    if include_llvm_tools:
283        llvm_cov_label = "\"@{workspace_name}//:llvm_cov_bin\"".format(workspace_name = workspace_name)
284        llvm_profdata_label = "\"@{workspace_name}//:llvm_profdata_bin\"".format(workspace_name = workspace_name)
285    allocator_library_label = "None"
286    if allocator_library:
287        allocator_library_label = "\"{allocator_library}\"".format(allocator_library = allocator_library)
288
289    return _build_file_for_rust_toolchain_template.format(
290        toolchain_name = name,
291        workspace_name = workspace_name,
292        binary_ext = system_to_binary_ext(target_triple.system),
293        staticlib_ext = system_to_staticlib_ext(target_triple.system),
294        dylib_ext = system_to_dylib_ext(target_triple.system),
295        allocator_library = allocator_library_label,
296        stdlib_linkflags = stdlib_linkflags,
297        system = target_triple.system,
298        default_edition = default_edition,
299        exec_triple = exec_triple.str,
300        target_triple = target_triple.str,
301        rustfmt_label = rustfmt_label,
302        llvm_cov_label = llvm_cov_label,
303        llvm_profdata_label = llvm_profdata_label,
304    )
305
306_build_file_for_toolchain_template = """\
307toolchain(
308    name = "{name}",
309    exec_compatible_with = {exec_constraint_sets_serialized},
310    target_compatible_with = {target_constraint_sets_serialized},
311    toolchain = "{toolchain}",
312    toolchain_type = "{toolchain_type}",
313    {target_settings}
314)
315"""
316
317def BUILD_for_toolchain(
318        name,
319        toolchain,
320        toolchain_type,
321        target_settings,
322        target_compatible_with,
323        exec_compatible_with):
324    target_settings_value = "target_settings = {},".format(json.encode(target_settings)) if target_settings else "# target_settings = []"
325
326    return _build_file_for_toolchain_template.format(
327        name = name,
328        exec_constraint_sets_serialized = json.encode(exec_compatible_with),
329        target_constraint_sets_serialized = json.encode(target_compatible_with),
330        toolchain = toolchain,
331        toolchain_type = toolchain_type,
332        target_settings = target_settings_value,
333    )
334
335def load_rustfmt(ctx, target_triple, version, iso_date):
336    """Loads a rustfmt binary and yields corresponding BUILD for it
337
338    Args:
339        ctx (repository_ctx): The repository rule's context object.
340        target_triple (struct): The platform triple to download rustfmt for.
341        version (str): The version or channel of rustfmt.
342        iso_date (str): The date of the tool (or None, if the version is a specific version).
343
344    Returns:
345        str: The BUILD file contents for this rustfmt binary
346    """
347
348    load_arbitrary_tool(
349        ctx,
350        iso_date = iso_date,
351        target_triple = target_triple,
352        tool_name = "rustfmt",
353        tool_subdirectories = ["rustfmt-preview"],
354        version = version,
355    )
356
357    return BUILD_for_rustfmt(target_triple)
358
359def load_rust_compiler(ctx, iso_date, target_triple, version):
360    """Loads a rust compiler and yields corresponding BUILD for it
361
362    Args:
363        ctx (repository_ctx): A repository_ctx.
364        iso_date (str): The date of the tool (or None, if the version is a specific version).
365        target_triple (struct): The Rust-style target that this compiler runs on.
366        version (str): The version of the tool among \"nightly\", \"beta\", or an exact version.
367
368    Returns:
369        str: The BUILD file contents for this compiler and compiler library
370    """
371
372    load_arbitrary_tool(
373        ctx,
374        iso_date = iso_date,
375        target_triple = target_triple,
376        tool_name = "rustc",
377        tool_subdirectories = ["rustc"],
378        version = version,
379    )
380
381    return BUILD_for_compiler(target_triple)
382
383def load_clippy(ctx, iso_date, target_triple, version):
384    """Loads Clippy and yields corresponding BUILD for it
385
386    Args:
387        ctx (repository_ctx): A repository_ctx.
388        iso_date (str): The date of the tool (or None, if the version is a specific version).
389        target_triple (struct): The Rust-style target that this compiler runs on.
390        version (str): The version of the tool among \"nightly\", \"beta\", or an exact version.
391
392    Returns:
393        str: The BUILD file contents for Clippy
394    """
395    load_arbitrary_tool(
396        ctx,
397        iso_date = iso_date,
398        target_triple = target_triple,
399        tool_name = "clippy",
400        tool_subdirectories = ["clippy-preview"],
401        version = version,
402    )
403
404    return BUILD_for_clippy(target_triple)
405
406def load_cargo(ctx, iso_date, target_triple, version):
407    """Loads Cargo and yields corresponding BUILD for it
408
409    Args:
410        ctx (repository_ctx): A repository_ctx.
411        iso_date (str): The date of the tool (or None, if the version is a specific version).
412        target_triple (struct): The Rust-style target that this compiler runs on.
413        version (str): The version of the tool among \"nightly\", \"beta\", or an exact version.
414
415    Returns:
416        str: The BUILD file contents for Cargo
417    """
418
419    load_arbitrary_tool(
420        ctx,
421        iso_date = iso_date,
422        target_triple = target_triple,
423        tool_name = "cargo",
424        tool_subdirectories = ["cargo"],
425        version = version,
426    )
427
428    return BUILD_for_cargo(target_triple)
429
430def includes_rust_analyzer_proc_macro_srv(version, iso_date):
431    """Determine whether or not the rust_analyzer_proc_macro_srv binary in available in the given version of Rust.
432
433    Args:
434        version (str): The version of the tool among \"nightly\", \"beta\", or an exact version.
435        iso_date (str): The date of the tool (or None, if the version is a specific version).
436
437    Returns:
438        bool: Whether or not the binary is expected to be included
439    """
440
441    if version == "nightly":
442        return iso_date >= "2022-09-21"
443    elif version == "beta":
444        return False
445    elif version >= "1.64.0":
446        return True
447
448    return False
449
450def load_rust_src(ctx, iso_date, version, sha256 = ""):
451    """Loads the rust source code. Used by the rust-analyzer rust-project.json generator.
452
453    Args:
454        ctx (ctx): A repository_ctx.
455        version (str): The version of the tool among "nightly", "beta', or an exact version.
456        iso_date (str): The date of the tool (or None, if the version is a specific version).
457        sha256 (str): The sha256 value for the `rust-src` artifact
458    """
459    tool_suburl = produce_tool_suburl("rust-src", None, version, iso_date)
460    url = ctx.attr.urls[0].format(tool_suburl)
461
462    tool_path = produce_tool_path("rust-src", version, None)
463    archive_path = tool_path + _get_tool_extension(getattr(ctx.attr, "urls", None))
464    sha256 = sha256 or getattr(ctx.attr, "sha256s", {}).get(archive_path) or FILE_KEY_TO_SHA.get(archive_path) or ""
465    ctx.download_and_extract(
466        url,
467        output = "lib/rustlib/src",
468        sha256 = sha256,
469        auth = _make_auth_dict(ctx, [url]),
470        stripPrefix = "{}/rust-src/lib/rustlib/src/rust".format(tool_path),
471    )
472    ctx.file(
473        "lib/rustlib/src/BUILD.bazel",
474        """\
475filegroup(
476    name = "rustc_srcs",
477    srcs = glob(["**/*"]),
478    visibility = ["//visibility:public"],
479)""",
480    )
481
482_build_file_for_rust_analyzer_toolchain_template = """\
483load("@rules_rust//rust:toolchain.bzl", "rust_analyzer_toolchain")
484
485rust_analyzer_toolchain(
486    name = "{name}",
487    proc_macro_srv = {proc_macro_srv},
488    rustc = "{rustc}",
489    rustc_srcs = "//lib/rustlib/src:rustc_srcs",
490    visibility = ["//visibility:public"],
491)
492"""
493
494def BUILD_for_rust_analyzer_toolchain(name, rustc, proc_macro_srv):
495    return _build_file_for_rust_analyzer_toolchain_template.format(
496        name = name,
497        rustc = rustc,
498        proc_macro_srv = repr(proc_macro_srv),
499    )
500
501_build_file_for_rustfmt_toolchain_template = """\
502load("@rules_rust//rust:toolchain.bzl", "rustfmt_toolchain")
503
504rustfmt_toolchain(
505    name = "{name}",
506    rustfmt = "{rustfmt}",
507    rustc = "{rustc}",
508    rustc_lib = "{rustc_lib}",
509    visibility = ["//visibility:public"],
510)
511"""
512
513def BUILD_for_rustfmt_toolchain(name, rustfmt, rustc, rustc_lib):
514    return _build_file_for_rustfmt_toolchain_template.format(
515        name = name,
516        rustfmt = rustfmt,
517        rustc = rustc,
518        rustc_lib = rustc_lib,
519    )
520
521def load_rust_stdlib(ctx, target_triple):
522    """Loads a rust standard library and yields corresponding BUILD for it
523
524    Args:
525        ctx (repository_ctx): A repository_ctx.
526        target_triple (struct): The rust-style target triple of the tool
527
528    Returns:
529        str: The BUILD file contents for this stdlib
530    """
531
532    load_arbitrary_tool(
533        ctx,
534        iso_date = ctx.attr.iso_date,
535        target_triple = target_triple,
536        tool_name = "rust-std",
537        tool_subdirectories = ["rust-std-{}".format(target_triple.str)],
538        version = ctx.attr.version,
539    )
540
541    return BUILD_for_stdlib(target_triple)
542
543def load_rustc_dev_nightly(ctx, target_triple):
544    """Loads the nightly rustc dev component
545
546    Args:
547        ctx: A repository_ctx.
548        target_triple: The rust-style target triple of the tool
549    """
550
551    subdir_name = "rustc-dev"
552    if ctx.attr.iso_date < "2020-12-24":
553        subdir_name = "rustc-dev-{}".format(target_triple)
554
555    load_arbitrary_tool(
556        ctx,
557        iso_date = ctx.attr.iso_date,
558        target_triple = target_triple,
559        tool_name = "rustc-dev",
560        tool_subdirectories = [subdir_name],
561        version = ctx.attr.version,
562    )
563
564def load_llvm_tools(ctx, target_triple):
565    """Loads the llvm tools
566
567    Args:
568        ctx: A repository_ctx.
569        target_triple: The rust-style target triple of the tool
570    """
571    load_arbitrary_tool(
572        ctx,
573        iso_date = ctx.attr.iso_date,
574        target_triple = target_triple,
575        tool_name = "llvm-tools",
576        tool_subdirectories = ["llvm-tools-preview"],
577        version = ctx.attr.version,
578    )
579
580    return BUILD_for_llvm_tools(target_triple)
581
582def check_version_valid(version, iso_date, param_prefix = ""):
583    """Verifies that the provided rust version and iso_date make sense.
584
585    Args:
586        version (str): The rustc version
587        iso_date (str): The rustc nightly version's iso date
588        param_prefix (str, optional): The name of the tool who's version is being checked.
589    """
590
591    if not version and iso_date:
592        fail("{param_prefix}iso_date must be paired with a {param_prefix}version".format(param_prefix = param_prefix))
593
594    if version in ("beta", "nightly") and not iso_date:
595        fail("{param_prefix}iso_date must be specified if version is 'beta' or 'nightly'".format(param_prefix = param_prefix))
596
597def produce_tool_suburl(tool_name, target_triple, version, iso_date = None):
598    """Produces a fully qualified Rust tool name for URL
599
600    Args:
601        tool_name (str): The name of the tool per `static.rust-lang.org`.
602        target_triple (struct): The rust-style target triple of the tool.
603        version (str): The version of the tool among "nightly", "beta', or an exact version.
604        iso_date (str): The date of the tool (or None, if the version is a specific version).
605
606    Returns:
607        str: The fully qualified url path for the specified tool.
608    """
609    path = produce_tool_path(tool_name, version, target_triple)
610    return iso_date + "/" + path if (iso_date and version in ("beta", "nightly")) else path
611
612def produce_tool_path(tool_name, version, target_triple = None):
613    """Produces a qualified Rust tool name
614
615    Args:
616        tool_name (str): The name of the tool per static.rust-lang.org
617        version (str): The version of the tool among "nightly", "beta', or an exact version.
618        target_triple (struct, optional): The rust-style target triple of the tool
619
620    Returns:
621        str: The qualified path for the specified tool.
622    """
623    if not tool_name:
624        fail("No tool name was provided")
625    if not version:
626        fail("No tool version was provided")
627
628    # Not all tools require a triple. E.g. `rustc_src` (Rust source files for rust-analyzer).
629    platform_triple = None
630    if target_triple:
631        platform_triple = target_triple.str
632
633    return "-".join([e for e in [tool_name, version, platform_triple] if e])
634
635def lookup_tool_sha256(ctx, tool_name, target_triple, version, iso_date, sha256):
636    """Looks up the sha256 hash of a specific tool archive.
637
638    The lookup order is:
639
640    1. The sha256s dict in the context attributes;
641    2. The list of sha256 hashes populated in //rust:known_shas.bzl;
642    3. The sha256 argument to the function
643
644    Args:
645        ctx (repository_ctx): A repository_ctx (no attrs required).
646        tool_name (str): The name of the given tool per the archive naming.
647        target_triple (struct): The rust-style target triple of the tool.
648        version (str): The version of the tool among "nightly", "beta', or an exact version.
649        iso_date (str): The date of the tool (ignored if the version is a specific version).
650        sha256 (str): The expected hash of hash of the Rust tool.
651
652    Returns:
653        str: The sha256 of the tool archive, or an empty string if the hash could not be found.
654    """
655    tool_suburl = produce_tool_suburl(tool_name, target_triple, version, iso_date)
656    archive_path = tool_suburl + _get_tool_extension(getattr(ctx.attr, "urls", None))
657    return getattr(ctx.attr, "sha256s", dict()).get(archive_path) or FILE_KEY_TO_SHA.get(archive_path) or sha256
658
659def load_arbitrary_tool(ctx, tool_name, tool_subdirectories, version, iso_date, target_triple, sha256 = ""):
660    """Loads a Rust tool, downloads, and extracts into the common workspace.
661
662    This function sources the tool from the Rust-lang static file server. The index is available at:
663    - https://static.rust-lang.org/dist/channel-rust-stable.toml
664    - https://static.rust-lang.org/dist/channel-rust-beta.toml
665    - https://static.rust-lang.org/dist/channel-rust-nightly.toml
666
667    Args:
668        ctx (repository_ctx): A repository_ctx (no attrs required).
669        tool_name (str): The name of the given tool per the archive naming.
670        tool_subdirectories (str): The subdirectories of the tool files (at a level below the root directory of
671            the archive). The root directory of the archive is expected to match
672            $TOOL_NAME-$VERSION-$TARGET_TRIPLE.
673            Example:
674            tool_name
675            |    version
676            |    |      target_triple
677            v    v      v
678            rust-1.39.0-x86_64-unknown-linux-gnu/clippy-preview
679                                             .../rustc
680                                             .../etc
681            tool_subdirectories = ["clippy-preview", "rustc"]
682        version (str): The version of the tool among "nightly", "beta', or an exact version.
683        iso_date (str): The date of the tool (ignored if the version is a specific version).
684        target_triple (struct): The rust-style target triple of the tool.
685        sha256 (str, optional): The expected hash of hash of the Rust tool. Defaults to "".
686    """
687    check_version_valid(version, iso_date, param_prefix = tool_name + "_")
688
689    # View the indices mentioned in the docstring to find the tool_suburl for a given
690    # tool.
691    tool_suburl = produce_tool_suburl(tool_name, target_triple, version, iso_date)
692    urls = []
693
694    for url in getattr(ctx.attr, "urls", DEFAULT_STATIC_RUST_URL_TEMPLATES):
695        new_url = url.format(tool_suburl)
696        if new_url not in urls:
697            urls.append(new_url)
698
699    tool_path = produce_tool_path(tool_name, version, target_triple)
700
701    sha256 = lookup_tool_sha256(ctx, tool_name, target_triple, version, iso_date, sha256)
702
703    for subdirectory in tool_subdirectories:
704        # As long as the sha256 value is consistent accross calls here the
705        # cost of downloading an artifact is negated as by Bazel's caching.
706        result = ctx.download_and_extract(
707            urls,
708            sha256 = sha256,
709            auth = _make_auth_dict(ctx, urls),
710            stripPrefix = "{}/{}".format(tool_path, subdirectory),
711        )
712
713        # In the event no sha256 was provided, set it to the value of the first
714        # downloaded item so subsequent downloads use a cached artifact.
715        if not sha256:
716            sha256 = result.sha256
717
718def _make_auth_dict(ctx, urls):
719    auth = getattr(ctx.attr, "auth", {})
720    if not auth:
721        return {}
722    ret = {}
723    for url in urls:
724        ret[url] = auth
725    return ret
726
727def _get_tool_extension(urls = None):
728    if urls == None:
729        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES
730    if urls[0][-7:] == ".tar.gz":
731        return ".tar.gz"
732    elif urls[0][-7:] == ".tar.xz":
733        return ".tar.xz"
734    else:
735        return ""
736
737def select_rust_version(versions):
738    """Select the highest priorty version for a list of Rust versions
739
740    Priority order: `stable > nightly > beta`
741
742    Note that duplicate channels are unexpected in `versions`.
743
744    Args:
745        versions (list): A list of Rust versions. E.g. [`1.66.0`, `nightly/2022-12-15`]
746
747    Returns:
748        str: The highest ranking value from `versions`
749    """
750    if not versions:
751        fail("No versions were provided")
752
753    current = versions[0]
754
755    for ver in versions:
756        if ver.startswith("beta"):
757            if current[0].isdigit() or current.startswith("nightly"):
758                continue
759            if current.startswith("beta") and ver > current:
760                current = ver
761                continue
762
763            current = ver
764        elif ver.startswith("nightly"):
765            if current[0].isdigit():
766                continue
767            if current.startswith("nightly") and ver > current:
768                current = ver
769                continue
770
771            current = ver
772
773        else:
774            current = ver
775
776    return current