| """Module extensions for using rules_rust with bzlmod""" | |
| load("@bazel_features//:features.bzl", "bazel_features") | |
| load("//rust:defs.bzl", "rust_common") | |
| load("//rust/platform:triple.bzl", "get_host_triple") | |
| load("//rust/private:channel_manifest.bzl", "CHANNEL_MANIFEST_FACTS_KEY", "resolve_sha256s", "sha256_request") | |
| load( | |
| "//rust/private:repositories.bzl", | |
| "DEFAULT_TOOLCHAIN_TRIPLES", | |
| "rust_register_toolchains", | |
| "rust_repository_set", | |
| "rust_toolchain_tools_repository", | |
| ) | |
| load( | |
| "//rust/private:repository_utils.bzl", | |
| "DEFAULT_EXTRA_TARGET_TRIPLES", | |
| "DEFAULT_NIGHTLY_VERSION", | |
| "DEFAULT_STATIC_RUST_URL_TEMPLATES", | |
| "select_rust_version", | |
| ) | |
| load("//rust/private:toolchain_file.bzl", "TOOLCHAIN_CHANNEL_FACTS_KEY", "toolchain_file_settings") | |
| _RUST_TOOLCHAIN_VERSIONS = [ | |
| rust_common.default_version, | |
| DEFAULT_NIGHTLY_VERSION, | |
| ] | |
| def _find_modules(module_ctx): | |
| root = None | |
| our_module = None | |
| for mod in module_ctx.modules: | |
| if mod.is_root: | |
| root = mod | |
| if mod.name == "rules_rust": | |
| our_module = mod | |
| if root == None: | |
| root = our_module | |
| if our_module == None: | |
| fail("Unable to find rules_rust module") | |
| return root, our_module | |
| def _empty_repository_impl(repository_ctx): | |
| repository_ctx.file("WORKSPACE.bazel", """workspace(name = "{}")""".format( | |
| repository_ctx.name, | |
| )) | |
| repository_ctx.file("BUILD.bazel", "") | |
| if hasattr(repository_ctx, "repo_metadata"): | |
| return repository_ctx.repo_metadata(reproducible = True) | |
| return None | |
| _empty_repository = repository_rule( | |
| doc = "Declare an empty repository.", | |
| implementation = _empty_repository_impl, | |
| ) | |
| def _channel_manifest_facts(module_ctx): | |
| """The `channel_manifests` facts recorded by a previous evaluation, or `None` without facts support.""" | |
| if not bazel_features.external_deps.has_facts: | |
| return None | |
| return dict(module_ctx.facts.get(CHANNEL_MANIFEST_FACTS_KEY, {})) | |
| def _channel_facts(module_ctx): | |
| """The `channels` facts recorded by a previous evaluation, or `None` without facts support.""" | |
| if not bazel_features.external_deps.has_facts: | |
| return None | |
| return dict(module_ctx.facts.get(TOOLCHAIN_CHANNEL_FACTS_KEY, {})) | |
| def _extension_metadata(module_ctx, facts, channels = None): | |
| metadata_kwargs = {} | |
| if bazel_features.external_deps.extension_metadata_has_reproducible: | |
| metadata_kwargs["reproducible"] = True | |
| if facts != None: | |
| metadata_kwargs["facts"] = {CHANNEL_MANIFEST_FACTS_KEY: facts} | |
| if channels: | |
| metadata_kwargs["facts"][TOOLCHAIN_CHANNEL_FACTS_KEY] = channels | |
| return module_ctx.extension_metadata(**metadata_kwargs) | |
| def _rust_impl(module_ctx): | |
| # Toolchain configuration is only allowed in the root module, or in | |
| # rules_rust. | |
| # See https://github.com/bazelbuild/bazel/discussions/22024 for discussion. | |
| root, rules_rust = _find_modules(module_ctx) | |
| # Hashes of archives outside `known_shas.bzl`, read back from the lockfile | |
| # and extended as versions and platforms are requested. | |
| facts = _channel_manifest_facts(module_ctx) | |
| # Releases resolved for the channels of toolchain files (`stable`, | |
| # `1.99`), read back from the lockfile so the first resolution sticks. | |
| channel_facts = _channel_facts(module_ctx) | |
| channels = {} if channel_facts != None else None | |
| toolchain_triples = dict(DEFAULT_TOOLCHAIN_TRIPLES) | |
| grouped_repository_sets = {} | |
| for repository_set in root.tags.repository_set: | |
| if repository_set.name not in grouped_repository_sets: | |
| grouped_repository_sets[repository_set.name] = { | |
| "allocator_library": str(repository_set.allocator_library) if repository_set.allocator_library else None, | |
| "auth": repository_set.auth if repository_set.auth else None, | |
| "auth_patterns": repository_set.auth_patterns if repository_set.auth_patterns else None, | |
| "dev_components": repository_set.dev_components, | |
| "dlltool": str(repository_set.dlltool) if repository_set.dlltool else None, | |
| "edition": repository_set.edition, | |
| "exec_compatible_with": [str(v) for v in repository_set.exec_compatible_with] if repository_set.exec_compatible_with else None, | |
| "exec_triple": repository_set.exec_triple, | |
| "extra_exec_rustc_flags": repository_set.extra_exec_rustc_flags if repository_set.extra_exec_rustc_flags else None, | |
| "extra_rustc_flags": repository_set.extra_rustc_flags if repository_set.extra_rustc_flags else None, | |
| "extra_target_triples": {repository_set.target_triple: [str(v) for v in repository_set.target_compatible_with]}, | |
| "global_allocator_library": str(repository_set.global_allocator_library) if repository_set.global_allocator_library else None, | |
| "name": repository_set.name, | |
| "netrc": repository_set.netrc if repository_set.netrc else None, | |
| "opt_level": {repository_set.target_triple: repository_set.opt_level} if repository_set.opt_level else None, | |
| "sha256s": repository_set.sha256s, | |
| "strip_level": {repository_set.target_triple: repository_set.strip_level} if repository_set.strip_level else None, | |
| "target_settings": [str(v) for v in repository_set.target_settings], | |
| "urls": repository_set.urls, | |
| "versions": repository_set.versions, | |
| } | |
| else: | |
| for attr_name in _RUST_REPOSITORY_SET_TAG_ATTRS.keys(): | |
| if attr_name in ["extra_target_triples", "name", "target_compatible_with", "target_triple", "opt_level", "strip_level"]: | |
| continue | |
| attr_value = getattr(repository_set, attr_name, None) | |
| if attr_value: | |
| default_value = _COMMON_TAG_DEFAULTS.get(attr_name, None) | |
| if not default_value or attr_value != default_value: | |
| fail("You must only set `{}` on the first call to `repository_set` for a particular name but it was set multiple times for `{}`".format(attr_name, repository_set.name)) | |
| grouped_repository_sets[repository_set.name]["extra_target_triples"][repository_set.target_triple] = [str(v) for v in repository_set.target_compatible_with] | |
| if repository_set.opt_level: | |
| if grouped_repository_sets[repository_set.name]["opt_level"] == None: | |
| grouped_repository_sets[repository_set.name]["opt_level"] = {} | |
| grouped_repository_sets[repository_set.name]["opt_level"][repository_set.target_triple] = repository_set.opt_level | |
| if repository_set.strip_level: | |
| if grouped_repository_sets[repository_set.name]["strip_level"] == None: | |
| grouped_repository_sets[repository_set.name]["strip_level"] = {} | |
| grouped_repository_sets[repository_set.name]["strip_level"][repository_set.target_triple] = repository_set.strip_level | |
| extra_toolchain_infos = {} | |
| for repository_set in grouped_repository_sets.values(): | |
| set_targets = [repository_set["exec_triple"]] + list(repository_set["extra_target_triples"].keys()) | |
| repository_set["sha256s"] = resolve_sha256s( | |
| module_ctx, | |
| requests = [ | |
| sha256_request(version = version, targets = set_targets) | |
| for version in repository_set["versions"] | |
| ], | |
| urls = repository_set["urls"], | |
| sha256s = repository_set["sha256s"] or {}, | |
| facts = facts, | |
| ) | |
| toolchain_infos = rust_repository_set( | |
| **repository_set | |
| ) | |
| extra_toolchain_infos.update(**toolchain_infos) | |
| if toolchain_triples.get(repository_set["exec_triple"]) == repository_set["name"]: | |
| toolchain_triples.pop(repository_set["exec_triple"], None) | |
| toolchains = root.tags.toolchain or rules_rust.tags.toolchain | |
| for toolchain in toolchains: | |
| if toolchain.extra_rustc_flags and toolchain.extra_rustc_flags_triples: | |
| fail("Cannot define both extra_rustc_flags and extra_rustc_flags_triples") | |
| if toolchain.extra_exec_rustc_flags and toolchain.extra_exec_rustc_flags_triples: | |
| fail("Cannot define both extra_exec_rustc_flags and extra_exec_rustc_flags_triples") | |
| versions = toolchain.versions | |
| extra_target_triples = toolchain.extra_target_triples | |
| manifests = {} | |
| if toolchain.file: | |
| settings = toolchain_file_settings( | |
| module_ctx, | |
| toolchain.file, | |
| versions = versions, | |
| extra_target_triples = extra_target_triples, | |
| urls = toolchain.urls, | |
| facts = channel_facts, | |
| channels = channels, | |
| ) | |
| versions = settings.versions | |
| extra_target_triples = settings.extra_target_triples | |
| manifests = settings.manifests | |
| if len(versions) == 0: | |
| # If the root module has asked for rules_rust to not register default | |
| # toolchains, an empty repository named `rust_toolchains` is created | |
| # so that the `register_toolchains()` in MODULES.bazel is still | |
| # valid. | |
| _empty_repository(name = "rust_toolchains") | |
| else: | |
| extra_rustc_flags = toolchain.extra_rustc_flags if toolchain.extra_rustc_flags else toolchain.extra_rustc_flags_triples | |
| extra_exec_rustc_flags = toolchain.extra_exec_rustc_flags if toolchain.extra_exec_rustc_flags else toolchain.extra_exec_rustc_flags_triples | |
| # Every platform the registration below downloads for: the exec | |
| # platforms of the Rust, rustfmt and Cargo toolchains and the | |
| # extra targets, at every version involved. | |
| exec_triples = {triple: True for triple in list(toolchain_triples.keys()) + list(DEFAULT_TOOLCHAIN_TRIPLES.keys()) + list(toolchain.rustfmt_toolchain_triples.keys())}.keys() | |
| all_triples = {triple: True for triple in list(exec_triples) + list(extra_target_triples)}.keys() | |
| sha256s = resolve_sha256s( | |
| module_ctx, | |
| requests = [ | |
| sha256_request(version = version, targets = all_triples) | |
| for version in versions | |
| ] + [ | |
| sha256_request(version = toolchain.rustfmt_version, targets = exec_triples), | |
| sha256_request(version = toolchain.rust_analyzer_version or select_rust_version(versions), targets = exec_triples), | |
| sha256_request(version = rust_common.default_version, targets = exec_triples), | |
| ], | |
| urls = toolchain.urls, | |
| sha256s = toolchain.sha256s, | |
| facts = facts, | |
| manifests = manifests, | |
| ) | |
| rust_register_toolchains( | |
| hub_name = "rust_toolchains", | |
| dev_components = toolchain.dev_components, | |
| edition = toolchain.edition, | |
| extra_rustc_flags = extra_rustc_flags, | |
| extra_exec_rustc_flags = extra_exec_rustc_flags, | |
| allocator_library = str(toolchain.allocator_library) if toolchain.allocator_library else None, | |
| global_allocator_library = str(toolchain.global_allocator_library) if toolchain.global_allocator_library else None, | |
| dlltool = str(toolchain.dlltool) if toolchain.dlltool else None, | |
| rustfmt_version = toolchain.rustfmt_version, | |
| rust_analyzer_version = toolchain.rust_analyzer_version, | |
| sha256s = sha256s, | |
| extra_target_triples = extra_target_triples, | |
| opt_level = toolchain.opt_level if toolchain.opt_level else None, | |
| strip_level = toolchain.strip_level if toolchain.strip_level else None, | |
| urls = toolchain.urls, | |
| versions = versions, | |
| compact_windows_names = True, | |
| aliases = toolchain.aliases, | |
| toolchain_triples = toolchain_triples, | |
| rustfmt_toolchain_triples = toolchain.rustfmt_toolchain_triples if toolchain.rustfmt_toolchain_triples else DEFAULT_TOOLCHAIN_TRIPLES, | |
| target_settings = [str(v) for v in toolchain.target_settings], | |
| extra_toolchain_infos = extra_toolchain_infos, | |
| ) | |
| return _extension_metadata(module_ctx, facts, channels) | |
| _COMMON_TAG_DEFAULTS = { | |
| "rustfmt_version": DEFAULT_NIGHTLY_VERSION, | |
| "urls": DEFAULT_STATIC_RUST_URL_TEMPLATES, | |
| } | |
| _COMMON_TAG_KWARGS = { | |
| "allocator_library": attr.label( | |
| doc = "Target that provides allocator functions when rust_library targets are embedded in a cc_binary.", | |
| ), | |
| "dev_components": attr.bool( | |
| doc = "Whether to download the rustc-dev components (defaults to False). Requires version to be \"nightly\".", | |
| default = False, | |
| ), | |
| "dlltool": attr.label( | |
| doc = "Target that provides the `dlltool` binary used to generate import libraries. Defaults to the `dlltool.exe` shipped in `rust-mingw` when both the exec and target triples are `*-pc-windows-gnu`. See `rust_toolchain.dlltool`.", | |
| ), | |
| "edition": attr.string( | |
| doc = ( | |
| "The rust edition to be used by default (2015, 2018, 2021, or 2024). " + | |
| "If absent, every rule is required to specify its `edition` attribute." | |
| ), | |
| ), | |
| "global_allocator_library": attr.label( | |
| doc = "Target that provides allocator functions when global allocator is used with cc_common.link.", | |
| ), | |
| "rustfmt_version": attr.string( | |
| doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.", | |
| default = _COMMON_TAG_DEFAULTS["rustfmt_version"], | |
| ), | |
| "sha256s": attr.string_dict( | |
| doc = "A dict associating tool subdirectories to sha256 hashes.", | |
| ), | |
| "urls": attr.string_list( | |
| 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), and their extension " + | |
| "picks the archive format. The default is `.tar.xz`, which the Rust project asks for. " + | |
| "`rules_rust` ships the checksums of the `.tar.xz` archives of the platforms it registers by " + | |
| "default; others are resolved from the release's channel manifest like any version or platform " + | |
| "outside the table." | |
| ), | |
| default = _COMMON_TAG_DEFAULTS["urls"], | |
| ), | |
| } | |
| _RUST_REPOSITORY_SET_TAG_ATTRS = { | |
| "auth": attr.string_dict( | |
| doc = "Auth object compatible with repository_ctx.download to use when downloading files.", | |
| ), | |
| "auth_patterns": attr.string_dict( | |
| doc = "Override mapping of hostnames to authorization patterns; mirrors the eponymous attribute from http_archive.", | |
| ), | |
| "exec_compatible_with": attr.label_list( | |
| doc = "A list of constraints for the execution platform for this toolchain.", | |
| ), | |
| "exec_triple": attr.string( | |
| doc = "Exec triple for this repository_set.", | |
| ), | |
| "extra_exec_rustc_flags": attr.string_list( | |
| doc = "Extra flags to pass to rustc in exec configuration.", | |
| ), | |
| "extra_rustc_flags": attr.string_list( | |
| doc = "Extra flags to pass to rustc in non-exec configuration.", | |
| ), | |
| "name": attr.string( | |
| doc = "Name of the repository_set - if you're looking to replace default toolchains you must use the exact name you're replacing.", | |
| ), | |
| "netrc": attr.string( | |
| doc = ".netrc file to use for authentication; mirrors the eponymous attribute from http_archive.", | |
| ), | |
| "opt_level": attr.string_dict( | |
| doc = "Rustc optimization levels. For more details see the documentation for `rust_toolchain.opt_level`.", | |
| ), | |
| "strip_level": attr.string_dict( | |
| doc = "Rustc strip levels. For more details see the documentation for `rust_toolchain.strip_level`.", | |
| ), | |
| "target_compatible_with": attr.label_list( | |
| doc = "List of platform constraints this toolchain produces, for the particular target_triple this call is for.", | |
| ), | |
| "target_settings": attr.label_list( | |
| 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.", | |
| ), | |
| "target_triple": attr.string( | |
| doc = "target_triple to configure.", | |
| ), | |
| "versions": attr.string_list( | |
| doc = ( | |
| "A list of toolchain versions to download. This parameter only accepts one version " + | |
| "per channel. E.g. `[\"1.65.0\", \"nightly/2022-11-02\", \"beta/2020-12-30\"]`. " + | |
| "May be set to an empty list (`[]`) to inhibit `rules_rust` from registering toolchains." | |
| ), | |
| ), | |
| } | _COMMON_TAG_KWARGS | |
| _RUST_REPOSITORY_SET_TAG = tag_class( | |
| doc = "Tags for defining rust repository sets (where toolchains are defined).", | |
| attrs = _RUST_REPOSITORY_SET_TAG_ATTRS, | |
| ) | |
| _RUST_TOOLCHAIN_TAG = tag_class( | |
| doc = "Tags for defining rust toolchains (where toolchain tools are fetched).", | |
| attrs = { | |
| "aliases": attr.string_dict( | |
| doc = ( | |
| "Map of full toolchain repository name to an alias. If any repository is created by this " + | |
| "extension matches a key in this dictionary, the name of the created repository will be " + | |
| "remapped to the value instead. This may be required to work around path length limits " + | |
| "on Windows." | |
| ), | |
| default = {}, | |
| ), | |
| "extra_exec_rustc_flags": attr.string_list( | |
| doc = "Extra flags to pass to rustc in exec configuration", | |
| ), | |
| "extra_exec_rustc_flags_triples": attr.string_list_dict( | |
| doc = "Extra flags to pass to rustc in exec configuration. Key is the triple, value is the flag.", | |
| ), | |
| "extra_rustc_flags": attr.string_list( | |
| doc = "Extra flags to pass to rustc in non-exec configuration", | |
| ), | |
| "extra_rustc_flags_triples": attr.string_list_dict( | |
| doc = "Extra flags to pass to rustc in non-exec configuration. Key is the triple, value is the flag.", | |
| ), | |
| "extra_target_triples": attr.string_list( | |
| doc = "Additional Rust target triples to fetch and register toolchains for.", | |
| default = DEFAULT_EXTRA_TARGET_TRIPLES, | |
| ), | |
| "file": attr.label( | |
| doc = ( | |
| "A rustup toolchain file (`rust-toolchain.toml` or the legacy `rust-toolchain`) to take the " + | |
| "toolchain from. Its `channel` stands in for the version of the same channel in `versions` " + | |
| "and its `targets` are added to `extra_target_triples`; `components` and `profile` are ignored, " + | |
| "the rules fetching what they need (`rustc-dev` and `llvm-tools` through `dev_components`). " + | |
| "Channels naming no exact release (`stable`, `beta`, " + | |
| "`nightly`, `1.65`) are resolved from their channel manifest once and the release found is " + | |
| "recorded as a `channels` fact in `MODULE.bazel.lock`; remove that entry to move to the " + | |
| "current release of the channel." | |
| ), | |
| ), | |
| "opt_level": attr.string_dict( | |
| doc = "Rustc optimization levels. For more details see the documentation for `rust_toolchain.opt_level`.", | |
| ), | |
| "rust_analyzer_version": attr.string( | |
| doc = "The version of Rustc to pair with rust-analyzer.", | |
| ), | |
| "rustfmt_toolchain_triples": attr.string_dict( | |
| doc = "Like toolchain_triples, but for rustfmt toolchains. Mapping of rust target triple to repository name.", | |
| ), | |
| "strip_level": attr.string_dict( | |
| doc = "Rustc strip levels. For more details see the documentation for `rust_toolchain.strip_level`.", | |
| ), | |
| "target_settings": attr.label_list( | |
| 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.", | |
| ), | |
| "versions": attr.string_list( | |
| doc = ( | |
| "A list of toolchain versions to download. This parameter only accepts one version " + | |
| "per channel. E.g. `[\"1.65.0\", \"nightly/2022-11-02\", \"beta/2020-12-30\"]`. " + | |
| "May be set to an empty list (`[]`) to inhibit `rules_rust` from registering toolchains." | |
| ), | |
| default = _RUST_TOOLCHAIN_VERSIONS, | |
| ), | |
| } | _COMMON_TAG_KWARGS, | |
| ) | |
| rust = module_extension( | |
| doc = "Rust toolchain extension.", | |
| implementation = _rust_impl, | |
| tag_classes = { | |
| "repository_set": _RUST_REPOSITORY_SET_TAG, | |
| "toolchain": _RUST_TOOLCHAIN_TAG, | |
| }, | |
| ) | |
| _RUST_HOST_TOOLS_TAG = tag_class( | |
| attrs = { | |
| "name": attr.string( | |
| doc = "The name of the module to create", | |
| default = "rust_host_tools", | |
| ), | |
| "version": attr.string( | |
| doc = "The version of Rust to use for tools executed on the Bazel host.", | |
| default = rust_common.default_version, | |
| ), | |
| } | _COMMON_TAG_KWARGS, | |
| ) | |
| # This is a separate module extension so that only the host tools are | |
| # marked as reproducible and os and arch dependent | |
| def _rust_host_tools_impl(module_ctx): | |
| host_triple = get_host_triple(module_ctx) | |
| facts = _channel_manifest_facts(module_ctx) | |
| for mod in module_ctx.modules: | |
| for host_tools in mod.tags.host_tools: | |
| attrs = {key: getattr(host_tools, key) for key in dir(host_tools)} | |
| # rustfmt is not a host tool; `rustfmt_toolchain` has its own repository. | |
| attrs.pop("rustfmt_version") | |
| # Label attrs must be stringified for the repository rule. | |
| for label_attr in ("allocator_library", "global_allocator_library"): | |
| if label_attr in attrs: | |
| attrs[label_attr] = str(attrs[label_attr]) if attrs[label_attr] else None | |
| # Allow shorthand versions to follow the defaults | |
| # defined by rules_rust. | |
| if attrs["version"] == "nightly": | |
| attrs["version"] = DEFAULT_NIGHTLY_VERSION | |
| attrs["sha256s"] = resolve_sha256s( | |
| module_ctx, | |
| requests = [ | |
| sha256_request(version = attrs["version"], targets = [host_triple.str]), | |
| ], | |
| urls = attrs["urls"], | |
| sha256s = attrs["sha256s"], | |
| facts = facts, | |
| ) | |
| rust_toolchain_tools_repository( | |
| exec_triple = host_triple.str, | |
| target_triple = host_triple.str, | |
| **attrs | |
| ) | |
| return _extension_metadata(module_ctx, facts) | |
| _conditional_rust_host_tools_args = { | |
| "arch_dependent": True, | |
| "os_dependent": True, | |
| } if bazel_features.external_deps.module_extension_has_os_arch_dependent else {} | |
| rust_host_tools = module_extension( | |
| doc = "An extension which exposes Rust tools compatible with the current host platform.", | |
| implementation = _rust_host_tools_impl, | |
| tag_classes = { | |
| "host_tools": _RUST_HOST_TOOLS_TAG, | |
| }, | |
| **_conditional_rust_host_tools_args | |
| ) |