fork/rules_rust

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

UebelAndreMigrate all settings labels from aliases to using settings package (#3032)c3d71edd

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