fork/rules_rust

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

Cameron MulhernUpdates rust_test to use main.rs as the root when use_libtest_harness is false (#1518)f5ed797e

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