fork/rules_rust

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

scentiniFix `rust_binary_without_process_wrapper` build with `--stamp` (#1473)9a8e878d

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