fork/rules_rust

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

Brian SilvermanSet CARGO_MANIFEST_DIR at runtime for tests (#1559)48927127

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