fork/rules_rust

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

UebelAndreVarious cleanups (#1828)9adfdca9

rust-analyzer
45.4 KiB1339 linesraw
1# Copyright 2015 The Bazel Authors. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#    http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Rust rule implementations"""
16
17load("@bazel_skylib//lib:paths.bzl", "paths")
18load("//rust/private:common.bzl", "rust_common")
19load("//rust/private:rustc.bzl", "rustc_compile_action")
20load(
21    "//rust/private:utils.bzl",
22    "can_build_metadata",
23    "compute_crate_name",
24    "crate_root_src",
25    "dedent",
26    "determine_output_hash",
27    "expand_dict_value_locations",
28    "find_toolchain",
29    "get_import_macro_deps",
30    "transform_deps",
31)
32# TODO(marco): Separate each rule into its own file.
33
34def _assert_no_deprecated_attributes(_ctx):
35    """Forces a failure if any deprecated attributes were specified
36
37    Args:
38        _ctx (ctx): The current rule's context object
39    """
40    pass
41
42def _assert_correct_dep_mapping(ctx):
43    """Forces a failure if proc_macro_deps and deps are mixed inappropriately
44
45    Args:
46        ctx (ctx): The current rule's context object
47    """
48    for dep in ctx.attr.deps:
49        if rust_common.crate_info in dep:
50            if dep[rust_common.crate_info].type == "proc-macro":
51                fail(
52                    "{} listed {} in its deps, but it is a proc-macro. It should instead be in the bazel property proc_macro_deps.".format(
53                        ctx.label,
54                        dep.label,
55                    ),
56                )
57    for dep in ctx.attr.proc_macro_deps:
58        type = dep[rust_common.crate_info].type
59        if type != "proc-macro":
60            fail(
61                "{} listed {} in its proc_macro_deps, but it is not proc-macro, it is a {}. It should probably instead be listed in deps.".format(
62                    ctx.label,
63                    dep.label,
64                    type,
65                ),
66            )
67
68def _determine_lib_name(name, crate_type, toolchain, lib_hash = None):
69    """See https://github.com/bazelbuild/rules_rust/issues/405
70
71    Args:
72        name (str): The name of the current target
73        crate_type (str): The `crate_type`
74        toolchain (rust_toolchain): The current `rust_toolchain`
75        lib_hash (str, optional): The hashed crate root path
76
77    Returns:
78        str: A unique library name
79    """
80    extension = None
81    prefix = ""
82    if crate_type in ("dylib", "cdylib", "proc-macro"):
83        extension = toolchain.dylib_ext
84    elif crate_type == "staticlib":
85        extension = toolchain.staticlib_ext
86    elif crate_type in ("lib", "rlib"):
87        # All platforms produce 'rlib' here
88        extension = ".rlib"
89        prefix = "lib"
90    elif crate_type == "bin":
91        fail("crate_type of 'bin' was detected in a rust_library. Please compile " +
92             "this crate as a rust_binary instead.")
93
94    if not extension:
95        fail(("Unknown crate_type: {}. If this is a cargo-supported crate type, " +
96              "please file an issue!").format(crate_type))
97
98    prefix = "lib"
99    if toolchain.target_triple and toolchain.target_triple.system == "windows" and crate_type not in ("lib", "rlib"):
100        prefix = ""
101    if toolchain.target_arch == "wasm32" and crate_type == "cdylib":
102        prefix = ""
103
104    return "{prefix}{name}{lib_hash}{extension}".format(
105        prefix = prefix,
106        name = name,
107        lib_hash = "-" + lib_hash if lib_hash else "",
108        extension = extension,
109    )
110
111def get_edition(attr, toolchain, label):
112    """Returns the Rust edition from either the current rule's attirbutes or the current `rust_toolchain`
113
114    Args:
115        attr (struct): The current rule's attributes
116        toolchain (rust_toolchain): The `rust_toolchain` for the current target
117        label (Label): The label of the target being built
118
119    Returns:
120        str: The target Rust edition
121    """
122    if getattr(attr, "edition"):
123        return attr.edition
124    elif not toolchain.default_edition:
125        fail("Attribute `edition` is required for {}.".format(label))
126    else:
127        return toolchain.default_edition
128
129def _transform_sources(ctx, srcs, crate_root):
130    """Creates symlinks of the source files if needed.
131
132    Rustc assumes that the source files are located next to the crate root.
133    In case of a mix between generated and non-generated source files, this
134    we violate this assumption, as part of the sources will be located under
135    bazel-out/... . In order to allow for targets that contain both generated
136    and non-generated source files, we generate symlinks for all non-generated
137    files.
138
139    Args:
140        ctx (struct): The current rule's context.
141        srcs (List[File]): The sources listed in the `srcs` attribute
142        crate_root (File): The file specified in the `crate_root` attribute,
143                           if it exists, otherwise None
144
145    Returns:
146        Tuple(List[File], File): The transformed srcs and crate_root
147    """
148    has_generated_sources = len([src for src in srcs if not src.is_source]) > 0
149
150    if not has_generated_sources:
151        return srcs, crate_root
152
153    generated_sources = []
154
155    generated_root = crate_root
156    package_root = paths.dirname(ctx.build_file_path)
157
158    if crate_root and (crate_root.is_source or crate_root.root.path != ctx.bin_dir.path):
159        generated_root = ctx.actions.declare_file(paths.relativize(crate_root.short_path, package_root))
160        ctx.actions.symlink(
161            output = generated_root,
162            target_file = crate_root,
163            progress_message = "Creating symlink to source file: {}".format(crate_root.path),
164        )
165    if generated_root:
166        generated_sources.append(generated_root)
167
168    for src in srcs:
169        # We took care of the crate root above.
170        if src == crate_root:
171            continue
172        if src.is_source or src.root.path != ctx.bin_dir.path:
173            src_symlink = ctx.actions.declare_file(paths.relativize(src.short_path, package_root))
174            ctx.actions.symlink(
175                output = src_symlink,
176                target_file = src,
177                progress_message = "Creating symlink to source file: {}".format(src.path),
178            )
179            generated_sources.append(src_symlink)
180        else:
181            generated_sources.append(src)
182
183    return generated_sources, generated_root
184
185def _rust_library_impl(ctx):
186    """The implementation of the `rust_library` rule.
187
188    This rule provides CcInfo, so it can be used everywhere Bazel
189    expects rules_cc, but care must be taken to have the correct
190    dependencies on an allocator and std implemetation as needed.
191
192    Args:
193        ctx (ctx): The rule's context object
194
195    Returns:
196        list: A list of providers.
197    """
198    return _rust_library_common(ctx, "rlib")
199
200def _rust_static_library_impl(ctx):
201    """The implementation of the `rust_static_library` rule.
202
203    This rule provides CcInfo, so it can be used everywhere Bazel
204    expects rules_cc.
205
206    Args:
207        ctx (ctx): The rule's context object
208
209    Returns:
210        list: A list of providers.
211    """
212    return _rust_library_common(ctx, "staticlib")
213
214def _rust_shared_library_impl(ctx):
215    """The implementation of the `rust_shared_library` rule.
216
217    This rule provides CcInfo, so it can be used everywhere Bazel
218    expects rules_cc.
219
220    On Windows, a PDB file containing debugging information is available under
221    the key `pdb_file` in `OutputGroupInfo`. Similarly on macOS, a dSYM folder
222    is available under the key `dsym_folder` in `OutputGroupInfo`.
223
224    Args:
225        ctx (ctx): The rule's context object
226
227    Returns:
228        list: A list of providers.
229    """
230    return _rust_library_common(ctx, "cdylib")
231
232def _rust_proc_macro_impl(ctx):
233    """The implementation of the `rust_proc_macro` rule.
234
235    Args:
236        ctx (ctx): The rule's context object
237
238    Returns:
239        list: A list of providers.
240    """
241    return _rust_library_common(ctx, "proc-macro")
242
243def _rust_library_common(ctx, crate_type):
244    """The common implementation of the library-like rules.
245
246    Args:
247        ctx (ctx): The rule's context object
248        crate_type (String): one of lib|rlib|dylib|staticlib|cdylib|proc-macro
249
250    Returns:
251        list: A list of providers. See `rustc_compile_action`
252    """
253
254    srcs, crate_root = _transform_sources(ctx, ctx.files.srcs, getattr(ctx.file, "crate_root", None))
255    if not crate_root:
256        crate_root = crate_root_src(ctx.attr.name, srcs, "lib")
257    _assert_no_deprecated_attributes(ctx)
258    _assert_correct_dep_mapping(ctx)
259
260    toolchain = find_toolchain(ctx)
261
262    # Determine unique hash for this rlib.
263    # Note that we don't include a hash for `cdylib` and `staticlib` since they are meant to be consumed externally
264    # and having a deterministic name is important since it ends up embedded in the executable. This is problematic
265    # when one needs to include the library with a specific filename into a larger application.
266    # (see https://github.com/bazelbuild/rules_rust/issues/405#issuecomment-993089889 for more details)
267    if crate_type in ["cdylib", "staticlib"]:
268        output_hash = None
269    else:
270        output_hash = determine_output_hash(crate_root, ctx.label)
271
272    crate_name = compute_crate_name(ctx.workspace_name, ctx.label, toolchain, ctx.attr.crate_name)
273    rust_lib_name = _determine_lib_name(
274        crate_name,
275        crate_type,
276        toolchain,
277        output_hash,
278    )
279    rust_lib = ctx.actions.declare_file(rust_lib_name)
280
281    rust_metadata = None
282    if can_build_metadata(toolchain, ctx, crate_type) and not ctx.attr.disable_pipelining:
283        rust_metadata = ctx.actions.declare_file(
284            paths.replace_extension(rust_lib_name, ".rmeta"),
285            sibling = rust_lib,
286        )
287
288    deps = transform_deps(ctx.attr.deps)
289    proc_macro_deps = transform_deps(ctx.attr.proc_macro_deps + get_import_macro_deps(ctx))
290
291    return rustc_compile_action(
292        ctx = ctx,
293        attr = ctx.attr,
294        toolchain = toolchain,
295        crate_info = rust_common.create_crate_info(
296            name = crate_name,
297            type = crate_type,
298            root = crate_root,
299            srcs = depset(srcs),
300            deps = depset(deps),
301            proc_macro_deps = depset(proc_macro_deps),
302            aliases = ctx.attr.aliases,
303            output = rust_lib,
304            metadata = rust_metadata,
305            edition = get_edition(ctx.attr, toolchain, ctx.label),
306            rustc_env = ctx.attr.rustc_env,
307            rustc_env_files = ctx.files.rustc_env_files,
308            is_test = False,
309            compile_data = depset(ctx.files.compile_data),
310            compile_data_targets = depset(ctx.attr.compile_data),
311            owner = ctx.label,
312        ),
313        output_hash = output_hash,
314    )
315
316def _rust_binary_impl(ctx):
317    """The implementation of the `rust_binary` rule
318
319    Args:
320        ctx (ctx): The rule's context object
321
322    Returns:
323        list: A list of providers. See `rustc_compile_action`
324    """
325    toolchain = find_toolchain(ctx)
326    crate_name = compute_crate_name(ctx.workspace_name, ctx.label, toolchain, ctx.attr.crate_name)
327    _assert_correct_dep_mapping(ctx)
328
329    output = ctx.actions.declare_file(ctx.label.name + toolchain.binary_ext)
330
331    deps = transform_deps(ctx.attr.deps)
332    proc_macro_deps = transform_deps(ctx.attr.proc_macro_deps + get_import_macro_deps(ctx))
333
334    srcs, crate_root = _transform_sources(ctx, ctx.files.srcs, getattr(ctx.file, "crate_root", None))
335    if not crate_root:
336        crate_root = crate_root_src(ctx.attr.name, srcs, ctx.attr.crate_type)
337
338    return rustc_compile_action(
339        ctx = ctx,
340        attr = ctx.attr,
341        toolchain = toolchain,
342        crate_info = rust_common.create_crate_info(
343            name = crate_name,
344            type = ctx.attr.crate_type,
345            root = crate_root,
346            srcs = depset(srcs),
347            deps = depset(deps),
348            proc_macro_deps = depset(proc_macro_deps),
349            aliases = ctx.attr.aliases,
350            output = output,
351            edition = get_edition(ctx.attr, toolchain, ctx.label),
352            rustc_env = ctx.attr.rustc_env,
353            rustc_env_files = ctx.files.rustc_env_files,
354            is_test = False,
355            compile_data = depset(ctx.files.compile_data),
356            compile_data_targets = depset(ctx.attr.compile_data),
357            owner = ctx.label,
358        ),
359    )
360
361def _rust_test_impl(ctx):
362    """The implementation of the `rust_test` rule.
363
364    Args:
365        ctx (ctx): The ctx object for the current target.
366
367    Returns:
368        list: The list of providers. See `rustc_compile_action`
369    """
370    _assert_no_deprecated_attributes(ctx)
371    _assert_correct_dep_mapping(ctx)
372
373    toolchain = find_toolchain(ctx)
374
375    srcs, crate_root = _transform_sources(ctx, ctx.files.srcs, getattr(ctx.file, "crate_root", None))
376    crate_type = "bin"
377
378    deps = transform_deps(ctx.attr.deps)
379    proc_macro_deps = transform_deps(ctx.attr.proc_macro_deps + get_import_macro_deps(ctx))
380
381    if ctx.attr.crate:
382        # Target is building the crate in `test` config
383        crate = ctx.attr.crate[rust_common.crate_info] if rust_common.crate_info in ctx.attr.crate else ctx.attr.crate[rust_common.test_crate_info].crate
384
385        output_hash = determine_output_hash(crate.root, ctx.label)
386        output = ctx.actions.declare_file(
387            "test-%s/%s%s" % (
388                output_hash,
389                ctx.label.name,
390                toolchain.binary_ext,
391            ),
392        )
393
394        # Optionally join compile data
395        if crate.compile_data:
396            compile_data = depset(ctx.files.compile_data, transitive = [crate.compile_data])
397        else:
398            compile_data = depset(ctx.files.compile_data)
399        if crate.compile_data_targets:
400            compile_data_targets = depset(ctx.attr.compile_data, transitive = [crate.compile_data_targets])
401        else:
402            compile_data_targets = depset(ctx.attr.compile_data)
403        rustc_env_files = ctx.files.rustc_env_files + crate.rustc_env_files
404        rustc_env = dict(crate.rustc_env)
405        rustc_env.update(**ctx.attr.rustc_env)
406
407        # Build the test binary using the dependency's srcs.
408        crate_info = rust_common.create_crate_info(
409            name = crate.name,
410            type = crate_type,
411            root = crate.root,
412            srcs = depset(srcs, transitive = [crate.srcs]),
413            deps = depset(deps, transitive = [crate.deps]),
414            proc_macro_deps = depset(proc_macro_deps, transitive = [crate.proc_macro_deps]),
415            aliases = ctx.attr.aliases,
416            output = output,
417            edition = crate.edition,
418            rustc_env = rustc_env,
419            rustc_env_files = rustc_env_files,
420            is_test = True,
421            compile_data = compile_data,
422            compile_data_targets = compile_data_targets,
423            wrapped_crate_type = crate.type,
424            owner = ctx.label,
425        )
426    else:
427        if not crate_root:
428            crate_root_type = "lib" if ctx.attr.use_libtest_harness else "bin"
429            crate_root = crate_root_src(ctx.attr.name, ctx.files.srcs, crate_root_type)
430
431        output_hash = determine_output_hash(crate_root, ctx.label)
432        output = ctx.actions.declare_file(
433            "test-%s/%s%s" % (
434                output_hash,
435                ctx.label.name,
436                toolchain.binary_ext,
437            ),
438        )
439
440        # Target is a standalone crate. Build the test binary as its own crate.
441        crate_info = rust_common.create_crate_info(
442            name = compute_crate_name(ctx.workspace_name, ctx.label, toolchain, ctx.attr.crate_name),
443            type = crate_type,
444            root = crate_root,
445            srcs = depset(srcs),
446            deps = depset(deps),
447            proc_macro_deps = depset(proc_macro_deps),
448            aliases = ctx.attr.aliases,
449            output = output,
450            edition = get_edition(ctx.attr, toolchain, ctx.label),
451            rustc_env = ctx.attr.rustc_env,
452            rustc_env_files = ctx.files.rustc_env_files,
453            is_test = True,
454            compile_data = depset(ctx.files.compile_data),
455            compile_data_targets = depset(ctx.attr.compile_data),
456            owner = ctx.label,
457        )
458
459    providers = rustc_compile_action(
460        ctx = ctx,
461        attr = ctx.attr,
462        toolchain = toolchain,
463        crate_info = crate_info,
464        rust_flags = ["--test"] if ctx.attr.use_libtest_harness else ["--cfg", "test"],
465    )
466    data = getattr(ctx.attr, "data", [])
467
468    env = expand_dict_value_locations(
469        ctx,
470        getattr(ctx.attr, "env", {}),
471        data,
472    )
473    if toolchain.llvm_cov and ctx.configuration.coverage_enabled:
474        if not toolchain.llvm_profdata:
475            fail("toolchain.llvm_profdata is required if toolchain.llvm_cov is set.")
476
477        env["RUST_LLVM_COV"] = toolchain.llvm_cov.path
478        env["RUST_LLVM_PROFDATA"] = toolchain.llvm_profdata.path
479    components = "{}/{}".format(ctx.label.workspace_root, ctx.label.package).split("/")
480    env["CARGO_MANIFEST_DIR"] = "/".join([c for c in components if c])
481    providers.append(testing.TestEnvironment(env))
482
483    return providers
484
485def _stamp_attribute(default_value):
486    return attr.int(
487        doc = dedent("""\
488            Whether to encode build information into the `Rustc` action. Possible values:
489
490            - `stamp = 1`: Always stamp the build information into the `Rustc` action, even in \
491            [--nostamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) builds. \
492            This setting should be avoided, since it potentially kills remote caching for the target and \
493            any downstream actions that depend on it.
494
495            - `stamp = 0`: Always replace build information by constant values. This gives good build result caching.
496
497            - `stamp = -1`: Embedding of build information is controlled by the \
498            [--[no]stamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) flag.
499
500            Stamped targets are not rebuilt unless their dependencies change.
501
502            For example if a `rust_library` is stamped, and a `rust_binary` depends on that library, the stamped
503            library won't be rebuilt when we change sources of the `rust_binary`. This is different from how
504            [`cc_library.linkstamps`](https://docs.bazel.build/versions/main/be/c-cpp.html#cc_library.linkstamp)
505            behaves.
506        """),
507        default = default_value,
508        values = [1, 0, -1],
509    )
510
511_common_attrs = {
512    "aliases": attr.label_keyed_string_dict(
513        doc = dedent("""\
514            Remap crates to a new name or moniker for linkage to this target
515
516            These are other `rust_library` targets and will be presented as the new name given.
517        """),
518    ),
519    "compile_data": attr.label_list(
520        doc = dedent("""\
521            List of files used by this rule at compile time.
522
523            This attribute can be used to specify any data files that are embedded into
524            the library, such as via the
525            [`include_str!`](https://doc.rust-lang.org/std/macro.include_str!.html)
526            macro.
527        """),
528        allow_files = True,
529    ),
530    "crate_features": attr.string_list(
531        doc = dedent("""\
532            List of features to enable for this crate.
533
534            Features are defined in the code using the `#[cfg(feature = "foo")]`
535            configuration option. The features listed here will be passed to `rustc`
536            with `--cfg feature="${feature_name}"` flags.
537        """),
538    ),
539    "crate_name": attr.string(
540        doc = dedent("""\
541            Crate name to use for this target.
542
543            This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores.
544            Defaults to the target name, with any hyphens replaced by underscores.
545        """),
546    ),
547    "crate_root": attr.label(
548        doc = dedent("""\
549            The file that will be passed to `rustc` to be used for building this crate.
550
551            If `crate_root` is not set, then this rule will look for a `lib.rs` file (or `main.rs` for rust_binary)
552            or the single file in `srcs` if `srcs` contains only one file.
553        """),
554        allow_single_file = [".rs"],
555    ),
556    "data": attr.label_list(
557        doc = dedent("""\
558            List of files used by this rule at compile time and runtime.
559
560            If including data at compile time with include_str!() and similar,
561            prefer `compile_data` over `data`, to prevent the data also being included
562            in the runfiles.
563        """),
564        allow_files = True,
565    ),
566    "deps": attr.label_list(
567        doc = dedent("""\
568            List of other libraries to be linked to this library target.
569
570            These can be either other `rust_library` targets or `cc_library` targets if
571            linking a native library.
572        """),
573    ),
574    "edition": attr.string(
575        doc = "The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.",
576    ),
577    # Previously `proc_macro_deps` were a part of `deps`, and then proc_macro_host_transition was
578    # used into cfg="host" using `@local_config_platform//:host`.
579    # This fails for remote execution, which needs cfg="exec", and there isn't anything like
580    # `@local_config_platform//:exec` exposed.
581    "proc_macro_deps": attr.label_list(
582        doc = dedent("""\
583            List of `rust_library` targets with kind `proc-macro` used to help build this library target.
584        """),
585        cfg = "exec",
586        providers = [rust_common.crate_info],
587    ),
588    "rustc_env": attr.string_dict(
589        doc = dedent("""\
590            Dictionary of additional `"key": "value"` environment variables to set for rustc.
591
592            rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the
593            location of a generated file or external tool. Cargo build scripts that wish to
594            expand locations should use cargo_build_script()'s build_script_env argument instead,
595            as build scripts are run in a different environment - see cargo_build_script()'s
596            documentation for more.
597        """),
598    ),
599    "rustc_env_files": attr.label_list(
600        doc = dedent("""\
601            Files containing additional environment variables to set for rustc.
602
603            These files should  contain a single variable per line, of format
604            `NAME=value`, and newlines may be included in a value by ending a
605            line with a trailing back-slash (`\\\\`).
606
607            The order that these files will be processed is unspecified, so
608            multiple definitions of a particular variable are discouraged.
609
610            Note that the variables here are subject to 
611            [workspace status](https://docs.bazel.build/versions/main/user-manual.html#workspace_status)
612            stamping should the `stamp` attribute be enabled. Stamp variables
613            should be wrapped in brackets in order to be resolved. E.g.
614            `NAME={WORKSPACE_STATUS_VARIABLE}`.
615        """),
616        allow_files = True,
617    ),
618    "rustc_flags": attr.string_list(
619        doc = dedent("""\
620            List of compiler flags passed to `rustc`.
621
622            These strings are subject to Make variable expansion for predefined
623            source/output path variables like `$location`, `$execpath`, and 
624            `$rootpath`. This expansion is useful if you wish to pass a generated
625            file of arguments to rustc: `@$(location //package:target)`.
626        """),
627    ),
628    # TODO(stardoc): How do we provide additional documentation to an inherited attribute?
629    # "name": attr.string(
630    #     doc = "This name will also be used as the name of the crate built by this rule.",
631    # `),
632    "srcs": attr.label_list(
633        doc = dedent("""\
634            List of Rust `.rs` source files used to build the library.
635
636            If `srcs` contains more than one file, then there must be a file either
637            named `lib.rs`. Otherwise, `crate_root` must be set to the source file that
638            is the root of the crate to be passed to rustc to build this crate.
639        """),
640        allow_files = [".rs"],
641    ),
642    "stamp": _stamp_attribute(default_value = 0),
643    "version": attr.string(
644        doc = "A version to inject in the cargo environment variable.",
645        default = "0.0.0",
646    ),
647    "_cc_toolchain": attr.label(
648        doc = (
649            "In order to use find_cc_toolchain, your rule has to depend " +
650            "on C++ toolchain. See `@rules_cc//cc:find_cc_toolchain.bzl` " +
651            "docs for details."
652        ),
653        default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
654    ),
655    "_collect_cc_coverage": attr.label(
656        default = Label("//util:collect_coverage"),
657        executable = True,
658        cfg = "exec",
659    ),
660    "_error_format": attr.label(
661        default = Label("//:error_format"),
662    ),
663    "_extra_exec_rustc_flag": attr.label(
664        default = Label("//:extra_exec_rustc_flag"),
665    ),
666    "_extra_exec_rustc_flags": attr.label(
667        default = Label("//:extra_exec_rustc_flags"),
668    ),
669    "_extra_rustc_flag": attr.label(
670        default = Label("//:extra_rustc_flag"),
671    ),
672    "_extra_rustc_flags": attr.label(
673        default = Label("//:extra_rustc_flags"),
674    ),
675    "_import_macro_dep": attr.label(
676        default = Label("//util/import"),
677        cfg = "exec",
678    ),
679    "_is_proc_macro_dep": attr.label(
680        default = Label("//:is_proc_macro_dep"),
681    ),
682    "_is_proc_macro_dep_enabled": attr.label(
683        default = Label("//:is_proc_macro_dep_enabled"),
684    ),
685    "_process_wrapper": attr.label(
686        doc = "A process wrapper for running rustc on all platforms.",
687        default = Label("//util/process_wrapper"),
688        executable = True,
689        allow_single_file = True,
690        cfg = "exec",
691    ),
692    "_stamp_flag": attr.label(
693        doc = "A setting used to determine whether or not the `--stamp` flag is enabled",
694        default = Label("//rust/private:stamp"),
695    ),
696}
697
698_experimental_use_cc_common_link_attrs = {
699    "experimental_use_cc_common_link": attr.int(
700        doc = (
701            "Whether to use cc_common.link to link rust binaries. " +
702            "Possible values: [-1, 0, 1]. " +
703            "-1 means use the value of the toolchain.experimental_use_cc_common_link " +
704            "boolean build setting to determine. " +
705            "0 means do not use cc_common.link (use rustc instead). " +
706            "1 means use cc_common.link."
707        ),
708        values = [-1, 0, 1],
709        default = -1,
710    ),
711}
712
713_rust_test_attrs = dict({
714    "crate": attr.label(
715        mandatory = False,
716        doc = dedent("""\
717            Target inline tests declared in the given crate
718
719            These tests are typically those that would be held out under
720            `#[cfg(test)]` declarations.
721        """),
722    ),
723    "env": attr.string_dict(
724        mandatory = False,
725        doc = dedent("""\
726            Specifies additional environment variables to set when the test is executed by bazel test.
727            Values are subject to `$(rootpath)`, `$(execpath)`, location, and
728            ["Make variable"](https://docs.bazel.build/versions/master/be/make-variables.html) substitution.
729        """),
730    ),
731    "use_libtest_harness": attr.bool(
732        mandatory = False,
733        default = True,
734        doc = dedent("""\
735            Whether to use `libtest`. For targets using this flag, individual tests can be run by using the 
736            [--test_arg](https://docs.bazel.build/versions/4.0.0/command-line-reference.html#flag--test_arg) flag.
737            E.g. `bazel test //src:rust_test --test_arg=foo::test::test_fn`.
738        """),
739    ),
740    "_grep_includes": attr.label(
741        allow_single_file = True,
742        cfg = "exec",
743        default = Label("@bazel_tools//tools/cpp:grep-includes"),
744        executable = True,
745    ),
746}.items() + _experimental_use_cc_common_link_attrs.items())
747
748_common_providers = [
749    rust_common.crate_info,
750    rust_common.dep_info,
751    DefaultInfo,
752]
753
754rust_library = rule(
755    implementation = _rust_library_impl,
756    provides = _common_providers,
757    attrs = dict(_common_attrs.items() + {
758        "disable_pipelining": attr.bool(
759            default = False,
760            doc = dedent("""\
761                Disables pipelining for this rule if it is globally enabled.
762                This will cause this rule to not produce a `.rmeta` file and all the dependent
763                crates will instead use the `.rlib` file.
764            """),
765        ),
766    }.items()),
767    fragments = ["cpp"],
768    host_fragments = ["cpp"],
769    toolchains = [
770        str(Label("//rust:toolchain_type")),
771        "@bazel_tools//tools/cpp:toolchain_type",
772    ],
773    incompatible_use_toolchain_transition = True,
774    doc = dedent("""\
775        Builds a Rust library crate.
776
777        Example:
778
779        Suppose you have the following directory structure for a simple Rust library crate:
780
781        ```output
782        [workspace]/
783            WORKSPACE
784            hello_lib/
785                BUILD
786                src/
787                    greeter.rs
788                    lib.rs
789        ```
790
791        `hello_lib/src/greeter.rs`:
792        ```rust
793        pub struct Greeter {
794            greeting: String,
795        }
796
797        impl Greeter {
798            pub fn new(greeting: &str) -> Greeter {
799                Greeter { greeting: greeting.to_string(), }
800            }
801
802            pub fn greet(&self, thing: &str) {
803                println!("{} {}", &self.greeting, thing);
804            }
805        }
806        ```
807
808        `hello_lib/src/lib.rs`:
809
810        ```rust
811        pub mod greeter;
812        ```
813
814        `hello_lib/BUILD`:
815        ```python
816        package(default_visibility = ["//visibility:public"])
817
818        load("@rules_rust//rust:defs.bzl", "rust_library")
819
820        rust_library(
821            name = "hello_lib",
822            srcs = [
823                "src/greeter.rs",
824                "src/lib.rs",
825            ],
826        )
827        ```
828
829        Build the library:
830        ```output
831        $ bazel build //hello_lib
832        INFO: Found 1 target...
833        Target //examples/rust/hello_lib:hello_lib up-to-date:
834        bazel-bin/examples/rust/hello_lib/libhello_lib.rlib
835        INFO: Elapsed time: 1.245s, Critical Path: 1.01s
836        ```
837        """),
838)
839
840rust_static_library = rule(
841    implementation = _rust_static_library_impl,
842    attrs = dict(_common_attrs.items()),
843    fragments = ["cpp"],
844    host_fragments = ["cpp"],
845    toolchains = [
846        str(Label("//rust:toolchain_type")),
847        "@bazel_tools//tools/cpp:toolchain_type",
848    ],
849    incompatible_use_toolchain_transition = True,
850    doc = dedent("""\
851        Builds a Rust static library.
852
853        This static library will contain all transitively reachable crates and native objects.
854        It is meant to be used when producing an artifact that is then consumed by some other build system
855        (for example to produce an archive that Python program links against).
856
857        This rule provides CcInfo, so it can be used everywhere Bazel expects `rules_cc`.
858
859        When building the whole binary in Bazel, use `rust_library` instead.
860        """),
861)
862
863rust_shared_library = rule(
864    implementation = _rust_shared_library_impl,
865    attrs = dict(
866        _common_attrs.items() + _experimental_use_cc_common_link_attrs.items() + {
867            "_grep_includes": attr.label(
868                allow_single_file = True,
869                cfg = "exec",
870                default = Label("@bazel_tools//tools/cpp:grep-includes"),
871                executable = True,
872            ),
873        }.items(),
874    ),
875    fragments = ["cpp"],
876    host_fragments = ["cpp"],
877    toolchains = [
878        str(Label("//rust:toolchain_type")),
879        "@bazel_tools//tools/cpp:toolchain_type",
880    ],
881    incompatible_use_toolchain_transition = True,
882    doc = dedent("""\
883        Builds a Rust shared library.
884
885        This shared library will contain all transitively reachable crates and native objects.
886        It is meant to be used when producing an artifact that is then consumed by some other build system
887        (for example to produce a shared library that Python program links against).
888
889        This rule provides CcInfo, so it can be used everywhere Bazel expects `rules_cc`.
890
891        When building the whole binary in Bazel, use `rust_library` instead.
892        """),
893)
894
895def _proc_macro_dep_transition_impl(settings, _attr):
896    if settings["//:is_proc_macro_dep_enabled"]:
897        return {"//:is_proc_macro_dep": True}
898    else:
899        return []
900
901_proc_macro_dep_transition = transition(
902    inputs = ["//:is_proc_macro_dep_enabled"],
903    outputs = ["//:is_proc_macro_dep"],
904    implementation = _proc_macro_dep_transition_impl,
905)
906
907rust_proc_macro = rule(
908    implementation = _rust_proc_macro_impl,
909    provides = _common_providers,
910    # Start by copying the common attributes, then override the `deps` attribute
911    # to apply `_proc_macro_dep_transition`. To add this transition we additionally
912    # need to declare `_allowlist_function_transition`, see
913    # https://docs.bazel.build/versions/main/skylark/config.html#user-defined-transitions.
914    attrs = dict(
915        _common_attrs.items(),
916        _allowlist_function_transition = attr.label(default = Label("//tools/allowlists/function_transition_allowlist")),
917        deps = attr.label_list(
918            doc = dedent("""\
919            List of other libraries to be linked to this library target.
920
921            These can be either other `rust_library` targets or `cc_library` targets if
922            linking a native library.
923        """),
924            cfg = _proc_macro_dep_transition,
925        ),
926    ),
927    fragments = ["cpp"],
928    host_fragments = ["cpp"],
929    toolchains = [
930        str(Label("//rust:toolchain_type")),
931        "@bazel_tools//tools/cpp:toolchain_type",
932    ],
933    incompatible_use_toolchain_transition = True,
934    doc = dedent("""\
935        Builds a Rust proc-macro crate.
936        """),
937)
938
939_rust_binary_attrs = dict({
940    "crate_type": attr.string(
941        doc = dedent("""\
942            Crate type that will be passed to `rustc` to be used for building this crate.
943
944            This option is a temporary workaround and should be used only when building
945            for WebAssembly targets (//rust/platform:wasi and //rust/platform:wasm).
946        """),
947        default = "bin",
948    ),
949    "linker_script": attr.label(
950        doc = dedent("""\
951            Link script to forward into linker via rustc options.
952        """),
953        cfg = "exec",
954        allow_single_file = True,
955    ),
956    "out_binary": attr.bool(
957        doc = (
958            "Force a target, regardless of it's `crate_type`, to always mark the " +
959            "file as executable. This attribute is only used to support wasm targets but is " +
960            "expected to be removed following a resolution to https://github.com/bazelbuild/rules_rust/issues/771."
961        ),
962        default = False,
963    ),
964    "stamp": _stamp_attribute(default_value = -1),
965    "_grep_includes": attr.label(
966        allow_single_file = True,
967        cfg = "exec",
968        default = Label("@bazel_tools//tools/cpp:grep-includes"),
969        executable = True,
970    ),
971}.items() + _experimental_use_cc_common_link_attrs.items())
972
973rust_binary = rule(
974    implementation = _rust_binary_impl,
975    provides = _common_providers,
976    attrs = dict(_common_attrs.items() + _rust_binary_attrs.items()),
977    executable = True,
978    fragments = ["cpp"],
979    host_fragments = ["cpp"],
980    toolchains = [
981        str(Label("//rust:toolchain_type")),
982        "@bazel_tools//tools/cpp:toolchain_type",
983    ],
984    incompatible_use_toolchain_transition = True,
985    doc = dedent("""\
986        Builds a Rust binary crate.
987
988        Example:
989
990        Suppose you have the following directory structure for a Rust project with a
991        library crate, `hello_lib`, and a binary crate, `hello_world` that uses the
992        `hello_lib` library:
993
994        ```output
995        [workspace]/
996            WORKSPACE
997            hello_lib/
998                BUILD
999                src/
1000                    lib.rs
1001            hello_world/
1002                BUILD
1003                src/
1004                    main.rs
1005        ```
1006
1007        `hello_lib/src/lib.rs`:
1008        ```rust
1009        pub struct Greeter {
1010            greeting: String,
1011        }
1012
1013        impl Greeter {
1014            pub fn new(greeting: &str) -> Greeter {
1015                Greeter { greeting: greeting.to_string(), }
1016            }
1017
1018            pub fn greet(&self, thing: &str) {
1019                println!("{} {}", &self.greeting, thing);
1020            }
1021        }
1022        ```
1023
1024        `hello_lib/BUILD`:
1025        ```python
1026        package(default_visibility = ["//visibility:public"])
1027
1028        load("@rules_rust//rust:defs.bzl", "rust_library")
1029
1030        rust_library(
1031            name = "hello_lib",
1032            srcs = ["src/lib.rs"],
1033        )
1034        ```
1035
1036        `hello_world/src/main.rs`:
1037        ```rust
1038        extern crate hello_lib;
1039
1040        fn main() {
1041            let hello = hello_lib::Greeter::new("Hello");
1042            hello.greet("world");
1043        }
1044        ```
1045
1046        `hello_world/BUILD`:
1047        ```python
1048        load("@rules_rust//rust:defs.bzl", "rust_binary")
1049
1050        rust_binary(
1051            name = "hello_world",
1052            srcs = ["src/main.rs"],
1053            deps = ["//hello_lib"],
1054        )
1055        ```
1056
1057        Build and run `hello_world`:
1058        ```
1059        $ bazel run //hello_world
1060        INFO: Found 1 target...
1061        Target //examples/rust/hello_world:hello_world up-to-date:
1062        bazel-bin/examples/rust/hello_world/hello_world
1063        INFO: Elapsed time: 1.308s, Critical Path: 1.22s
1064
1065        INFO: Running command line: bazel-bin/examples/rust/hello_world/hello_world
1066        Hello world
1067        ```
1068
1069        On Windows, a PDB file containing debugging information is available under
1070        the key `pdb_file` in `OutputGroupInfo`. Similarly on macOS, a dSYM folder
1071        is available under the key `dsym_folder` in `OutputGroupInfo`.
1072"""),
1073)
1074
1075def _common_attrs_for_binary_without_process_wrapper(attrs):
1076    new_attr = dict(attrs)
1077
1078    # use a fake process wrapper
1079    new_attr["_process_wrapper"] = attr.label(
1080        default = None,
1081        executable = True,
1082        allow_single_file = True,
1083        cfg = "exec",
1084    )
1085
1086    # fix stamp = 0
1087    new_attr["stamp"] = attr.int(
1088        doc = dedent("""\
1089            Fix `stamp = 0` as stamping is not supported when building without process_wrapper:
1090            https://github.com/bazelbuild/rules_rust/blob/8df4517d370b0c543a01ba38b63e1d5a4104b035/rust/private/rustc.bzl#L955
1091        """),
1092        default = 0,
1093        values = [0],
1094    )
1095
1096    return new_attr
1097
1098# Provides an internal rust_{binary,library} to use that we can use to build the process
1099# wrapper, this breaks the dependency of rust_* on the process wrapper by
1100# setting it to None, which the functions in rustc detect and build accordingly.
1101rust_binary_without_process_wrapper = rule(
1102    implementation = _rust_binary_impl,
1103    provides = _common_providers,
1104    attrs = _common_attrs_for_binary_without_process_wrapper(_common_attrs.items() + _rust_binary_attrs.items()),
1105    executable = True,
1106    fragments = ["cpp"],
1107    host_fragments = ["cpp"],
1108    toolchains = [
1109        str(Label("//rust:toolchain_type")),
1110        "@bazel_tools//tools/cpp:toolchain_type",
1111    ],
1112    incompatible_use_toolchain_transition = True,
1113)
1114
1115rust_library_without_process_wrapper = rule(
1116    implementation = _rust_library_impl,
1117    provides = _common_providers,
1118    attrs = dict(_common_attrs_for_binary_without_process_wrapper(_common_attrs).items()),
1119    fragments = ["cpp"],
1120    host_fragments = ["cpp"],
1121    toolchains = [
1122        str(Label("//rust:toolchain_type")),
1123        "@bazel_tools//tools/cpp:toolchain_type",
1124    ],
1125    incompatible_use_toolchain_transition = True,
1126)
1127
1128rust_test = rule(
1129    implementation = _rust_test_impl,
1130    provides = _common_providers,
1131    attrs = dict(_common_attrs.items() +
1132                 _rust_test_attrs.items()),
1133    executable = True,
1134    fragments = ["cpp"],
1135    host_fragments = ["cpp"],
1136    test = True,
1137    toolchains = [
1138        str(Label("//rust:toolchain_type")),
1139        "@bazel_tools//tools/cpp:toolchain_type",
1140    ],
1141    incompatible_use_toolchain_transition = True,
1142    doc = dedent("""\
1143        Builds a Rust test crate.
1144
1145        Examples:
1146
1147        Suppose you have the following directory structure for a Rust library crate \
1148        with unit test code in the library sources:
1149
1150        ```output
1151        [workspace]/
1152            WORKSPACE
1153            hello_lib/
1154                BUILD
1155                src/
1156                    lib.rs
1157        ```
1158
1159        `hello_lib/src/lib.rs`:
1160        ```rust
1161        pub struct Greeter {
1162            greeting: String,
1163        }
1164
1165        impl Greeter {
1166            pub fn new(greeting: &str) -> Greeter {
1167                Greeter { greeting: greeting.to_string(), }
1168            }
1169
1170            pub fn greet(&self, thing: &str) -> String {
1171                format!("{} {}", &self.greeting, thing)
1172            }
1173        }
1174
1175        #[cfg(test)]
1176        mod test {
1177            use super::Greeter;
1178
1179            #[test]
1180            fn test_greeting() {
1181                let hello = Greeter::new("Hi");
1182                assert_eq!("Hi Rust", hello.greet("Rust"));
1183            }
1184        }
1185        ```
1186
1187        To build and run the tests, simply add a `rust_test` rule with no `srcs`
1188        and only depends on the `hello_lib` `rust_library` target via the
1189        `crate` attribute:
1190
1191        `hello_lib/BUILD`:
1192        ```python
1193        load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
1194
1195        rust_library(
1196            name = "hello_lib",
1197            srcs = ["src/lib.rs"],
1198        )
1199
1200        rust_test(
1201            name = "hello_lib_test",
1202            crate = ":hello_lib",
1203            # You may add other deps that are specific to the test configuration
1204            deps = ["//some/dev/dep"],
1205        ```
1206
1207        Run the test with `bazel test //hello_lib:hello_lib_test`. The crate
1208        will be built using the same crate name as the underlying ":hello_lib"
1209        crate.
1210
1211        ### Example: `test` directory
1212
1213        Integration tests that live in the [`tests` directory][int-tests], they are \
1214        essentially built as separate crates. Suppose you have the following directory \
1215        structure where `greeting.rs` is an integration test for the `hello_lib` \
1216        library crate:
1217
1218        [int-tests]: http://doc.rust-lang.org/book/testing.html#the-tests-directory
1219
1220        ```output
1221        [workspace]/
1222            WORKSPACE
1223            hello_lib/
1224                BUILD
1225                src/
1226                    lib.rs
1227                tests/
1228                    greeting.rs
1229        ```
1230
1231        `hello_lib/tests/greeting.rs`:
1232        ```rust
1233        extern crate hello_lib;
1234
1235        use hello_lib;
1236
1237        #[test]
1238        fn test_greeting() {
1239            let hello = greeter::Greeter::new("Hello");
1240            assert_eq!("Hello world", hello.greeting("world"));
1241        }
1242        ```
1243
1244        To build the `greeting.rs` integration test, simply add a `rust_test` target
1245        with `greeting.rs` in `srcs` and a dependency on the `hello_lib` target:
1246
1247        `hello_lib/BUILD`:
1248        ```python
1249        load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")
1250
1251        rust_library(
1252            name = "hello_lib",
1253            srcs = ["src/lib.rs"],
1254        )
1255
1256        rust_test(
1257            name = "greeting_test",
1258            srcs = ["tests/greeting.rs"],
1259            deps = [":hello_lib"],
1260        )
1261        ```
1262
1263        Run the test with `bazel test //hello_lib:greeting_test`.
1264"""),
1265)
1266
1267def rust_test_suite(name, srcs, **kwargs):
1268    """A rule for creating a test suite for a set of `rust_test` targets.
1269
1270    This rule can be used for setting up typical rust [integration tests][it]. Given the following
1271    directory structure:
1272
1273    ```text
1274    [crate]/
1275        BUILD.bazel
1276        src/
1277            lib.rs
1278            main.rs
1279        tests/
1280            integrated_test_a.rs
1281            integrated_test_b.rs
1282            integrated_test_c.rs
1283            patterns/
1284                fibonacci_test.rs
1285    ```
1286
1287    The rule can be used to generate [rust_test](#rust_test) targets for each source file under `tests`
1288    and a [test_suite][ts] which encapsulates all tests.
1289
1290    ```python
1291    load("//rust:defs.bzl", "rust_binary", "rust_library", "rust_test_suite")
1292
1293    rust_library(
1294        name = "math_lib",
1295        srcs = ["src/lib.rs"],
1296    )
1297
1298    rust_binary(
1299        name = "math_bin",
1300        srcs = ["src/main.rs"],
1301    )
1302
1303    rust_test_suite(
1304        name = "integrated_tests_suite",
1305        srcs = glob(["tests/**"]),
1306        deps = [":math_lib"],
1307    )
1308    ```
1309
1310    [it]: https://doc.rust-lang.org/rust-by-example/testing/integration_testing.html
1311    [ts]: https://docs.bazel.build/versions/master/be/general.html#test_suite
1312
1313    Args:
1314        name (str): The name of the `test_suite`.
1315        srcs (list): All test sources, typically `glob(["tests/**/*.rs"])`.
1316        **kwargs (dict): Additional keyword arguments for the underyling [rust_test](#rust_test) targets. The
1317            `tags` argument is also passed to the generated `test_suite` target.
1318    """
1319    tests = []
1320
1321    for src in srcs:
1322        if not src.endswith(".rs"):
1323            fail("srcs should have `.rs` extensions")
1324
1325        # Prefixed with `name` to allow parameterization with macros
1326        # The test name should not end with `.rs`
1327        test_name = name + "_" + src[:-3]
1328        rust_test(
1329            name = test_name,
1330            srcs = [src],
1331            **kwargs
1332        )
1333        tests.append(test_name)
1334
1335    native.test_suite(
1336        name = name,
1337        tests = tests,
1338        tags = kwargs.get("tags", None),
1339    )