fork/rules_rust

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

Chris FredricksonRemove unnecessary `crate_name` usage in `rust_test_suite`. (#1345)421d30e4

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