fork/rules_rust

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

Keith SmileyUpdate apple_support (#1346)9770b0dd

0.5.0
18.0 KiB391 linesraw
1# buildifier: disable=module-docstring
2load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
3load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
4load("//rust/private:common.bzl", "rust_common")
5load(
6    "//rust/private:repository_utils.bzl",
7    "BUILD_for_toolchain",
8    "DEFAULT_STATIC_RUST_URL_TEMPLATES",
9    "DEFAULT_TOOLCHAIN_NAME_PREFIX",
10    "check_version_valid",
11    "load_llvm_tools",
12    "load_rust_compiler",
13    "load_rust_src",
14    "load_rust_stdlib",
15    "load_rustc_dev_nightly",
16    "load_rustfmt",
17    "should_include_rustc_srcs",
18    _load_arbitrary_tool = "load_arbitrary_tool",
19)
20
21# Reexport `load_arbitrary_tool` as it's currently in use in https://github.com/google/cargo-raze
22load_arbitrary_tool = _load_arbitrary_tool
23
24# 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.
25DEFAULT_TOOLCHAIN_TRIPLES = {
26    "aarch64-apple-darwin": "rust_darwin_aarch64",
27    "aarch64-unknown-linux-gnu": "rust_linux_aarch64",
28    "x86_64-apple-darwin": "rust_darwin_x86_64",
29    "x86_64-pc-windows-msvc": "rust_windows_x86_64",
30    "x86_64-unknown-freebsd": "rust_freebsd_x86_64",
31    "x86_64-unknown-linux-gnu": "rust_linux_x86_64",
32}
33
34def rules_rust_dependencies():
35    """Dependencies used in the implementation of `rules_rust`."""
36
37    maybe(
38        http_archive,
39        name = "platforms",
40        urls = [
41            "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.5/platforms-0.0.5.tar.gz",
42            "https://github.com/bazelbuild/platforms/releases/download/0.0.5/platforms-0.0.5.tar.gz",
43        ],
44        sha256 = "379113459b0feaf6bfbb584a91874c065078aa673222846ac765f86661c27407",
45    )
46    maybe(
47        http_archive,
48        name = "rules_cc",
49        urls = ["https://github.com/bazelbuild/rules_cc/releases/download/0.0.1/rules_cc-0.0.1.tar.gz"],
50        sha256 = "4dccbfd22c0def164c8f47458bd50e0c7148f3d92002cdb459c2a96a68498241",
51    )
52
53    maybe(
54        http_archive,
55        name = "bazel_skylib",
56        urls = [
57            "https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.0/bazel-skylib-1.2.0.tar.gz",
58            "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.0/bazel-skylib-1.2.0.tar.gz",
59        ],
60        sha256 = "af87959afe497dc8dfd4c6cb66e1279cb98ccc84284619ebfec27d9c09a903de",
61    )
62
63    # Make the iOS simulator constraint available, which is referenced in abi_to_constraints()
64    # rules_rust does not require this dependency; it is just imported as a convenience for users.
65    maybe(
66        http_archive,
67        name = "build_bazel_apple_support",
68        sha256 = "5bbce1b2b9a3d4b03c0697687023ef5471578e76f994363c641c5f50ff0c7268",
69        url = "https://github.com/bazelbuild/apple_support/releases/download/0.13.0/apple_support.0.13.0.tar.gz",
70    )
71
72    # process_wrapper needs a low-dependency way to process json.
73    maybe(
74        http_archive,
75        name = "rules_rust_tinyjson",
76        sha256 = "1a8304da9f9370f6a6f9020b7903b044aa9ce3470f300a1fba5bc77c78145a16",
77        url = "https://crates.io/api/v1/crates/tinyjson/2.3.0/download",
78        strip_prefix = "tinyjson-2.3.0",
79        type = "tar.gz",
80        build_file = "@rules_rust//util/process_wrapper:BUILD.tinyjson.bazel",
81    )
82
83# buildifier: disable=unnamed-macro
84def rust_register_toolchains(
85        dev_components = False,
86        edition = None,
87        include_rustc_srcs = False,
88        iso_date = None,
89        register_toolchains = True,
90        rustfmt_version = None,
91        sha256s = None,
92        extra_target_triples = ["wasm32-unknown-unknown", "wasm32-wasi"],
93        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES,
94        version = rust_common.default_version):
95    """Emits a default set of toolchains for Linux, MacOS, and Freebsd
96
97    Skip this macro and call the `rust_repository_set` macros directly if you need a compiler for \
98    other hosts or for additional target triples.
99
100    The `sha256` attribute represents a dict associating tool subdirectories to sha256 hashes. As an example:
101    ```python
102    {
103        "rust-1.46.0-x86_64-unknown-linux-gnu": "e3b98bc3440fe92817881933f9564389eccb396f5f431f33d48b979fa2fbdcf5",
104        "rustfmt-1.4.12-x86_64-unknown-linux-gnu": "1894e76913303d66bf40885a601462844eec15fca9e76a6d13c390d7000d64b0",
105        "rust-std-1.46.0-x86_64-unknown-linux-gnu": "ac04aef80423f612c0079829b504902de27a6997214eb58ab0765d02f7ec1dbc",
106    }
107    ```
108    This would match for `exec_triple = "x86_64-unknown-linux-gnu"`.  If not specified, rules_rust pulls from a non-exhaustive \
109    list of known checksums..
110
111    See `load_arbitrary_tool` in `@rules_rust//rust:repositories.bzl` for more details.
112
113    Args:
114        dev_components (bool, optional): Whether to download the rustc-dev components (defaults to False). Requires version to be "nightly".
115        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.
116        include_rustc_srcs (bool, optional): Whether to download rustc's src code. This is required in order to use rust-analyzer support.
117            See [rust_toolchain_repository.include_rustc_srcs](#rust_toolchain_repository-include_rustc_srcs). for more details
118        iso_date (str, optional): The date of the nightly or beta release (ignored if the version is a specific version).
119        register_toolchains (bool): If true, repositories will be generated to produce and register `rust_toolchain` targets.
120        rustfmt_version (str, optional): The version of rustfmt. Either "nightly", "beta", or an exact version. Defaults to `version` if not specified.
121        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes.
122        extra_target_triples (list, optional): Additional rust-style targets that rust toolchains should support.
123        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).
124        version (str, optional): The version of Rust. Either "nightly", "beta", or an exact version. Defaults to a modern version.
125    """
126    if dev_components and version != "nightly":
127        fail("Rust version must be set to \"nightly\" to enable rustc-dev components")
128
129    if not rustfmt_version:
130        rustfmt_version = version
131
132    for exec_triple, name in DEFAULT_TOOLCHAIN_TRIPLES.items():
133        maybe(
134            rust_repository_set,
135            name = name,
136            dev_components = dev_components,
137            edition = edition,
138            exec_triple = exec_triple,
139            extra_target_triples = extra_target_triples,
140            include_rustc_srcs = include_rustc_srcs,
141            iso_date = iso_date,
142            register_toolchain = register_toolchains,
143            rustfmt_version = rustfmt_version,
144            sha256s = sha256s,
145            urls = urls,
146            version = version,
147        )
148
149# buildifier: disable=unnamed-macro
150def rust_repositories(**kwargs):
151    """**Deprecated**: Use [rules_rust_dependencies](#rules_rust_dependencies) \
152    and [rust_register_toolchains](#rust_register_toolchains) directly.
153
154    Args:
155        **kwargs (dict): Keyword arguments for the `rust_register_toolchains` macro.
156    """
157    rules_rust_dependencies()
158
159    rust_register_toolchains(**kwargs)
160
161def _rust_toolchain_repository_impl(ctx):
162    """The implementation of the rust toolchain repository rule."""
163
164    check_version_valid(ctx.attr.version, ctx.attr.iso_date)
165
166    # Conditionally download rustc sources. Generally used for `rust-analyzer`
167    if should_include_rustc_srcs(ctx):
168        load_rust_src(ctx)
169
170    build_components = [load_rust_compiler(ctx)]
171
172    if ctx.attr.rustfmt_version:
173        build_components.append(load_rustfmt(ctx))
174
175    # Rust 1.45.0 and nightly builds after 2020-05-22 need the llvm-tools gzip to get the libLLVM dylib
176    if ctx.attr.version >= "1.45.0" or (ctx.attr.version == "nightly" and ctx.attr.iso_date > "2020-05-22"):
177        load_llvm_tools(ctx, ctx.attr.exec_triple)
178
179    for target_triple in [ctx.attr.exec_triple] + ctx.attr.extra_target_triples:
180        build_components.append(load_rust_stdlib(ctx, target_triple))
181
182        # extra_target_triples contains targets such as wasm, which don't have rustc_dev components
183        if ctx.attr.dev_components and target_triple not in ctx.attr.extra_target_triples:
184            load_rustc_dev_nightly(ctx, target_triple)
185
186    ctx.file("WORKSPACE.bazel", "")
187    ctx.file("BUILD.bazel", "\n".join(build_components))
188
189def _rust_toolchain_repository_proxy_impl(ctx):
190    build_components = []
191    for target_triple in [ctx.attr.exec_triple] + ctx.attr.extra_target_triples:
192        build_components.append(BUILD_for_toolchain(
193            name = "{toolchain_prefix}_{target_triple}".format(
194                toolchain_prefix = ctx.attr.toolchain_name_prefix,
195                target_triple = target_triple,
196            ),
197            exec_triple = ctx.attr.exec_triple,
198            parent_workspace_name = ctx.attr.parent_workspace_name,
199            target_triple = target_triple,
200        ))
201
202    ctx.file("WORKSPACE.bazel", "")
203    ctx.file("BUILD.bazel", "\n".join(build_components))
204
205rust_toolchain_repository = repository_rule(
206    doc = (
207        "Composes a single workspace containing the toolchain components for compiling on a given " +
208        "platform to a series of target platforms.\n" +
209        "\n" +
210        "A given instance of this rule should be accompanied by a rust_toolchain_repository_proxy " +
211        "invocation to declare its toolchains to Bazel; the indirection allows separating toolchain " +
212        "selection from toolchain fetching."
213    ),
214    attrs = {
215        "auth": attr.string_dict(
216            doc = (
217                "Auth object compatible with repository_ctx.download to use when downloading files. " +
218                "See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details."
219            ),
220        ),
221        "dev_components": attr.bool(
222            doc = "Whether to download the rustc-dev components (defaults to False). Requires version to be \"nightly\".",
223            default = False,
224        ),
225        "edition": attr.string(
226            doc = (
227                "The rust edition to be used by default (2015, 2018, or 2021). " +
228                "If absent, every rule is required to specify its `edition` attribute."
229            ),
230        ),
231        "exec_triple": attr.string(
232            doc = "The Rust-style target that this compiler runs on",
233            mandatory = True,
234        ),
235        "extra_target_triples": attr.string_list(
236            doc = "Additional rust-style targets that this set of toolchains should support.",
237        ),
238        "include_rustc_srcs": attr.bool(
239            doc = (
240                "Whether to download and unpack the rustc source files. These are very large, and " +
241                "slow to unpack, but are required to support rust analyzer. An environment variable " +
242                "`RULES_RUST_TOOLCHAIN_INCLUDE_RUSTC_SRCS` can also be used to control this attribute. " +
243                "This variable will take precedence over the hard coded attribute. Setting it to `true` to " +
244                "activates this attribute where all other values deactivate it."
245            ),
246            default = False,
247        ),
248        "iso_date": attr.string(
249            doc = "The date of the tool (or None, if the version is a specific version).",
250        ),
251        "rustfmt_version": attr.string(
252            doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.",
253        ),
254        "sha256s": attr.string_dict(
255            doc = "A dict associating tool subdirectories to sha256 hashes. See [rust_repositories](#rust_repositories) for more details.",
256        ),
257        "toolchain_name_prefix": attr.string(
258            doc = "The per-target prefix expected for the rust_toolchain declarations in the parent workspace.",
259        ),
260        "urls": attr.string_list(
261            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).",
262            default = DEFAULT_STATIC_RUST_URL_TEMPLATES,
263        ),
264        "version": attr.string(
265            doc = "The version of the tool among \"nightly\", \"beta\", or an exact version.",
266            mandatory = True,
267        ),
268    },
269    implementation = _rust_toolchain_repository_impl,
270    environ = ["RULES_RUST_TOOLCHAIN_INCLUDE_RUSTC_SRCS"],
271)
272
273rust_toolchain_repository_proxy = repository_rule(
274    doc = (
275        "Generates a toolchain-bearing repository that declares the toolchains from some other " +
276        "rust_toolchain_repository."
277    ),
278    attrs = {
279        "exec_triple": attr.string(
280            doc = "The Rust-style target triple for the compilation platform",
281            mandatory = True,
282        ),
283        "extra_target_triples": attr.string_list(
284            doc = "The Rust-style triples for extra compilation targets",
285        ),
286        "parent_workspace_name": attr.string(
287            doc = "The name of the other rust_toolchain_repository",
288            mandatory = True,
289        ),
290        "toolchain_name_prefix": attr.string(
291            doc = "The per-target prefix expected for the rust_toolchain declarations in the parent workspace.",
292        ),
293    },
294    implementation = _rust_toolchain_repository_proxy_impl,
295)
296
297def rust_repository_set(
298        name,
299        version,
300        exec_triple,
301        include_rustc_srcs = False,
302        extra_target_triples = [],
303        iso_date = None,
304        rustfmt_version = None,
305        edition = None,
306        dev_components = False,
307        sha256s = None,
308        urls = DEFAULT_STATIC_RUST_URL_TEMPLATES,
309        auth = None,
310        register_toolchain = True):
311    """Assembles a remote repository for the given toolchain params, produces a proxy repository \
312    to contain the toolchain declaration, and registers the toolchains.
313
314    N.B. A "proxy repository" is needed to allow for registering the toolchain (with constraints) \
315    without actually downloading the toolchain.
316
317    Args:
318        name (str): The name of the generated repository
319        version (str): The version of the tool among "nightly", "beta', or an exact version.
320        exec_triple (str): The Rust-style target that this compiler runs on
321        include_rustc_srcs (bool, optional): Whether to download rustc's src code. This is required in order to use rust-analyzer support. Defaults to False.
322        extra_target_triples (list, optional): Additional rust-style targets that this set of
323            toolchains should support. Defaults to [].
324        iso_date (str, optional): The date of the tool. Defaults to None.
325        rustfmt_version (str, optional):  The version of rustfmt to be associated with the
326            toolchain. Defaults to None.
327        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.
328        dev_components (bool, optional): Whether to download the rustc-dev components.
329            Requires version to be "nightly". Defaults to False.
330        sha256s (str, optional): A dict associating tool subdirectories to sha256 hashes. See
331            [rust_repositories](#rust_repositories) for more details.
332        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']
333        auth (dict): Auth object compatible with repository_ctx.download to use when downloading files.
334            See [repository_ctx.download](https://docs.bazel.build/versions/main/skylark/lib/repository_ctx.html#download) for more details.
335        register_toolchain (bool): If True, the generated `rust_toolchain` target will become a registered toolchain.
336    """
337
338    rust_toolchain_repository(
339        name = name,
340        exec_triple = exec_triple,
341        include_rustc_srcs = include_rustc_srcs,
342        extra_target_triples = extra_target_triples,
343        iso_date = iso_date,
344        toolchain_name_prefix = DEFAULT_TOOLCHAIN_NAME_PREFIX,
345        version = version,
346        rustfmt_version = rustfmt_version,
347        edition = edition,
348        dev_components = dev_components,
349        sha256s = sha256s,
350        urls = urls,
351        auth = auth,
352    )
353
354    rust_toolchain_repository_proxy(
355        name = name + "_toolchains",
356        exec_triple = exec_triple,
357        extra_target_triples = extra_target_triples,
358        parent_workspace_name = name,
359        toolchain_name_prefix = DEFAULT_TOOLCHAIN_NAME_PREFIX,
360    )
361
362    all_toolchain_names = []
363    for target_triple in [exec_triple] + extra_target_triples:
364        all_toolchain_names.append("@{name}_toolchains//:{toolchain_name_prefix}_{triple}".format(
365            name = name,
366            toolchain_name_prefix = DEFAULT_TOOLCHAIN_NAME_PREFIX,
367            triple = target_triple,
368        ))
369
370    # Register toolchains
371    if register_toolchain:
372        native.register_toolchains(*all_toolchain_names)
373        native.register_toolchains(str(Label("//rust/private/dummy_cc_toolchain:dummy_cc_wasm32_toolchain")))
374
375    # Inform users that they should be using the canonical name if it's not detected
376    if "rules_rust" not in native.existing_rules():
377        message = "\n" + ("=" * 79) + "\n"
378        message += (
379            "It appears that you are trying to import rules_rust without using its\n" +
380            "canonical name, \"@rules_rust\" Please change your WORKSPACE file to\n" +
381            "import this repo with `name = \"rules_rust\"` instead."
382        )
383
384        if "io_bazel_rules_rust" in native.existing_rules():
385            message += "\n\n" + (
386                "Note that the previous name of \"@io_bazel_rules_rust\" is deprecated.\n" +
387                "See https://github.com/bazelbuild/rules_rust/issues/499 for context."
388            )
389
390        message += "\n" + ("=" * 79)
391        fail(message)