fork/rules_rust

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

Roberto Bampipipelining: add the ability to disable pipelining for a single rule. (#1499)6c389346

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