fork/rules_rust

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

scentiniSupport crates that have mix of generated and nongenerated inputs (#1340)c7cb5bd7

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