fork/rules_rust

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

scentiniDo not pass `--Clink-arg=-l` for libstd and libtest (#1500)4e5fac59

0.9.0
74.4 KiB1776 linesraw
1# Copyright 2018 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"""Functionality for constructing actions that invoke the Rust compiler"""
16
17load(
18    "@bazel_tools//tools/build_defs/cc:action_names.bzl",
19    "CPP_LINK_EXECUTABLE_ACTION_NAME",
20)
21load("//rust/private:common.bzl", "rust_common")
22load("//rust/private:providers.bzl", _BuildInfo = "BuildInfo")
23load("//rust/private:stamp.bzl", "is_stamping_enabled")
24load(
25    "//rust/private:utils.bzl",
26    "abs",
27    "expand_dict_value_locations",
28    "expand_list_element_locations",
29    "find_cc_toolchain",
30    "get_lib_name",
31    "get_preferred_artifact",
32    "is_exec_configuration",
33    "make_static_lib_symlink",
34    "relativize",
35)
36
37BuildInfo = _BuildInfo
38
39AliasableDepInfo = provider(
40    doc = "A provider mapping an alias name to a Crate's information.",
41    fields = {
42        "dep": "CrateInfo",
43        "name": "str",
44    },
45)
46
47_error_format_values = ["human", "json", "short"]
48
49ErrorFormatInfo = provider(
50    doc = "Set the --error-format flag for all rustc invocations",
51    fields = {"error_format": "(string) [" + ", ".join(_error_format_values) + "]"},
52)
53
54ExtraRustcFlagsInfo = provider(
55    doc = "Pass each value as an additional flag to non-exec rustc invocations",
56    fields = {"extra_rustc_flags": "List[string] Extra flags to pass to rustc in non-exec configuration"},
57)
58
59ExtraExecRustcFlagsInfo = provider(
60    doc = "Pass each value as an additional flag to exec rustc invocations",
61    fields = {"extra_exec_rustc_flags": "List[string] Extra flags to pass to rustc in exec configuration"},
62)
63
64IsProcMacroDepInfo = provider(
65    doc = "Records if this is a transitive dependency of a proc-macro.",
66    fields = {"is_proc_macro_dep": "Boolean"},
67)
68
69def _is_proc_macro_dep_impl(ctx):
70    return IsProcMacroDepInfo(is_proc_macro_dep = ctx.build_setting_value)
71
72is_proc_macro_dep = rule(
73    doc = "Records if this is a transitive dependency of a proc-macro.",
74    implementation = _is_proc_macro_dep_impl,
75    build_setting = config.bool(flag = True),
76)
77
78IsProcMacroDepEnabledInfo = provider(
79    doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro.",
80    fields = {"enabled": "Boolean"},
81)
82
83def _is_proc_macro_dep_enabled_impl(ctx):
84    return IsProcMacroDepEnabledInfo(enabled = ctx.build_setting_value)
85
86is_proc_macro_dep_enabled = rule(
87    doc = "Enables the feature to record if a library is a transitive dependency of a proc-macro.",
88    implementation = _is_proc_macro_dep_enabled_impl,
89    build_setting = config.bool(flag = True),
90)
91
92def _get_rustc_env(attr, toolchain, crate_name):
93    """Gathers rustc environment variables
94
95    Args:
96        attr (struct): The current target's attributes
97        toolchain (rust_toolchain): The current target's rust toolchain context
98        crate_name (str): The name of the crate to be compiled
99
100    Returns:
101        dict: Rustc environment variables
102    """
103    version = attr.version if hasattr(attr, "version") else "0.0.0"
104    major, minor, patch = version.split(".", 2)
105    if "-" in patch:
106        patch, pre = patch.split("-", 1)
107    else:
108        pre = ""
109    result = {
110        "CARGO_CFG_TARGET_ARCH": toolchain.target_arch,
111        "CARGO_CFG_TARGET_OS": toolchain.os,
112        "CARGO_CRATE_NAME": crate_name,
113        "CARGO_PKG_AUTHORS": "",
114        "CARGO_PKG_DESCRIPTION": "",
115        "CARGO_PKG_HOMEPAGE": "",
116        "CARGO_PKG_NAME": attr.name,
117        "CARGO_PKG_VERSION": version,
118        "CARGO_PKG_VERSION_MAJOR": major,
119        "CARGO_PKG_VERSION_MINOR": minor,
120        "CARGO_PKG_VERSION_PATCH": patch,
121        "CARGO_PKG_VERSION_PRE": pre,
122    }
123    if hasattr(attr, "_is_proc_macro_dep_enabled") and attr._is_proc_macro_dep_enabled[IsProcMacroDepEnabledInfo].enabled:
124        is_proc_macro_dep = "0"
125        if hasattr(attr, "_is_proc_macro_dep") and attr._is_proc_macro_dep[IsProcMacroDepInfo].is_proc_macro_dep:
126            is_proc_macro_dep = "1"
127        result["BAZEL_RULES_RUST_IS_PROC_MACRO_DEP"] = is_proc_macro_dep
128    return result
129
130def get_compilation_mode_opts(ctx, toolchain):
131    """Gathers rustc flags for the current compilation mode (opt/debug)
132
133    Args:
134        ctx (ctx): The current rule's context object
135        toolchain (rust_toolchain): The current rule's `rust_toolchain`
136
137    Returns:
138        struct: See `_rust_toolchain_impl` for more details
139    """
140    comp_mode = ctx.var["COMPILATION_MODE"]
141    if not comp_mode in toolchain.compilation_mode_opts:
142        fail("Unrecognized compilation mode {} for toolchain.".format(comp_mode))
143
144    return toolchain.compilation_mode_opts[comp_mode]
145
146def _are_linkstamps_supported(feature_configuration, has_grep_includes):
147    # Are linkstamps supported by the C++ toolchain?
148    return (cc_common.is_enabled(feature_configuration = feature_configuration, feature_name = "linkstamps") and
149            # Is Bazel recent enough to support Starlark linkstamps?
150            hasattr(cc_common, "register_linkstamp_compile_action") and
151            # The current rule doesn't define _grep_includes attribute; this
152            # attribute is required for compiling linkstamps.
153            has_grep_includes)
154
155def _should_use_pic(cc_toolchain, feature_configuration, crate_type):
156    """Whether or not [PIC][pic] should be enabled
157
158    [pic]: https://en.wikipedia.org/wiki/Position-independent_code
159
160    Args:
161        cc_toolchain (CcToolchainInfo): The current `cc_toolchain`.
162        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
163        crate_type (str): A Rust target's crate type.
164
165    Returns:
166        bool: Whether or not [PIC][pic] should be enabled.
167    """
168    if crate_type in ("cdylib", "dylib"):
169        return cc_toolchain.needs_pic_for_dynamic_libraries(feature_configuration = feature_configuration)
170    return False
171
172def _is_proc_macro(crate_info):
173    return "proc-macro" in (crate_info.type, crate_info.wrapped_crate_type)
174
175def collect_deps(
176        deps,
177        proc_macro_deps,
178        aliases,
179        are_linkstamps_supported = False):
180    """Walks through dependencies and collects the transitive dependencies.
181
182    Args:
183        deps (list): The deps from ctx.attr.deps.
184        proc_macro_deps (list): The proc_macro deps from ctx.attr.proc_macro_deps.
185        aliases (dict): A dict mapping aliased targets to their actual Crate information.
186        are_linkstamps_supported (bool): Whether the current rule and the toolchain support building linkstamps..
187
188    Returns:
189        tuple: Returns a tuple of:
190            DepInfo,
191            BuildInfo,
192            linkstamps (depset[CcLinkstamp]): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries.
193
194    """
195    direct_crates = []
196    transitive_crates = []
197    transitive_noncrates = []
198    transitive_build_infos = []
199    transitive_link_search_paths = []
200    build_info = None
201    linkstamps = []
202    transitive_crate_outputs = []
203    transitive_metadata_outputs = []
204
205    aliases = {k.label: v for k, v in aliases.items()}
206    for dep in depset(transitive = [deps, proc_macro_deps]).to_list():
207        (crate_info, dep_info) = _get_crate_and_dep_info(dep)
208        cc_info = _get_cc_info(dep)
209        dep_build_info = _get_build_info(dep)
210
211        if cc_info and are_linkstamps_supported:
212            linkstamps.append(cc_info.linking_context.linkstamps())
213
214        if crate_info:
215            # This dependency is a rust_library
216
217            # When crate_info.owner is set, we use it. When the dep type is Target we get the
218            # label from dep.label
219            owner = getattr(crate_info, "owner", dep.label if type(dep) == "Target" else None)
220
221            direct_crates.append(AliasableDepInfo(
222                name = aliases.get(owner, crate_info.name),
223                dep = crate_info,
224            ))
225
226            transitive_crates.append(
227                depset(
228                    [crate_info],
229                    transitive = [] if _is_proc_macro(crate_info) else [dep_info.transitive_crates],
230                ),
231            )
232
233            # If this dependency produces metadata, add it to the metadata outputs.
234            # If it doesn't (for example a custom library that exports crate_info),
235            # we depend on crate_info.output.
236            depend_on = crate_info.metadata
237            if not crate_info.metadata:
238                depend_on = crate_info.output
239
240            # If this dependency is a proc_macro, it still can be used for lib crates
241            # that produce metadata.
242            # In that case, we don't depend on its metadata dependencies.
243            transitive_metadata_outputs.append(
244                depset(
245                    [depend_on],
246                    transitive = [] if _is_proc_macro(crate_info) else [dep_info.transitive_metadata_outputs],
247                ),
248            )
249
250            transitive_crate_outputs.append(
251                depset(
252                    [crate_info.output],
253                    transitive = [] if _is_proc_macro(crate_info) else [dep_info.transitive_crate_outputs],
254                ),
255            )
256
257            if "proc-macro" not in [crate_info.type, crate_info.wrapped_crate_type]:
258                transitive_noncrates.append(dep_info.transitive_noncrates)
259                transitive_link_search_paths.append(dep_info.link_search_path_files)
260
261            transitive_build_infos.append(dep_info.transitive_build_infos)
262
263        elif cc_info:
264            # This dependency is a cc_library
265            transitive_noncrates.append(cc_info.linking_context.linker_inputs)
266        elif dep_build_info:
267            if build_info:
268                fail("Several deps are providing build information, " +
269                     "only one is allowed in the dependencies")
270            build_info = dep_build_info
271            transitive_build_infos.append(depset([build_info]))
272            transitive_link_search_paths.append(depset([build_info.link_search_paths]))
273        else:
274            fail("rust targets can only depend on rust_library, rust_*_library or cc_library " +
275                 "targets.")
276
277    transitive_crates_depset = depset(transitive = transitive_crates)
278
279    return (
280        rust_common.dep_info(
281            direct_crates = depset(direct_crates),
282            transitive_crates = transitive_crates_depset,
283            transitive_noncrates = depset(
284                transitive = transitive_noncrates,
285                order = "topological",  # dylib link flag ordering matters.
286            ),
287            transitive_crate_outputs = depset(transitive = transitive_crate_outputs),
288            transitive_metadata_outputs = depset(transitive = transitive_metadata_outputs),
289            transitive_build_infos = depset(transitive = transitive_build_infos),
290            link_search_path_files = depset(transitive = transitive_link_search_paths),
291            dep_env = build_info.dep_env if build_info else None,
292        ),
293        build_info,
294        depset(transitive = linkstamps),
295    )
296
297def _collect_libs_from_linker_inputs(linker_inputs, use_pic):
298    # TODO: We could let the user choose how to link, instead of always preferring to link static libraries.
299    return [
300        get_preferred_artifact(lib, use_pic)
301        for li in linker_inputs
302        for lib in li.libraries
303    ]
304
305def _get_crate_and_dep_info(dep):
306    if type(dep) == "Target" and rust_common.crate_info in dep:
307        return (dep[rust_common.crate_info], dep[rust_common.dep_info])
308    elif type(dep) == "struct" and hasattr(dep, "crate_info"):
309        return (dep.crate_info, dep.dep_info)
310    return (None, None)
311
312def _get_cc_info(dep):
313    if type(dep) == "Target" and CcInfo in dep:
314        return dep[CcInfo]
315    elif type(dep) == "struct" and hasattr(dep, "cc_info"):
316        return dep.cc_info
317    return None
318
319def _get_build_info(dep):
320    if type(dep) == "Target" and BuildInfo in dep:
321        return dep[BuildInfo]
322    elif type(dep) == "struct" and hasattr(dep, "build_info"):
323        return dep.build_info
324    return None
325
326def get_cc_user_link_flags(ctx):
327    """Get the current target's linkopt flags
328
329    Args:
330        ctx (ctx): The current rule's context object
331
332    Returns:
333        depset: The flags passed to Bazel by --linkopt option.
334    """
335    return ctx.fragments.cpp.linkopts
336
337def get_linker_and_args(ctx, attr, cc_toolchain, feature_configuration, rpaths):
338    """Gathers cc_common linker information
339
340    Args:
341        ctx (ctx): The current target's context object
342        attr (struct): Attributes to use in gathering linker args
343        cc_toolchain (CcToolchain): cc_toolchain for which we are creating build variables.
344        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
345        rpaths (depset): Depset of directories where loader will look for libraries at runtime.
346
347
348    Returns:
349        tuple: A tuple of the following items:
350            - (str): The tool path for given action.
351            - (sequence): A flattened command line flags for given action.
352            - (dict): Environment variables to be set for given action.
353    """
354    user_link_flags = get_cc_user_link_flags(ctx)
355
356    # Add linkopt's from dependencies. This includes linkopts from transitive
357    # dependencies since they get merged up.
358    for dep in getattr(attr, "deps", []):
359        if CcInfo in dep and dep[CcInfo].linking_context:
360            for linker_input in dep[CcInfo].linking_context.linker_inputs.to_list():
361                for flag in linker_input.user_link_flags:
362                    user_link_flags.append(flag)
363    link_variables = cc_common.create_link_variables(
364        feature_configuration = feature_configuration,
365        cc_toolchain = cc_toolchain,
366        is_linking_dynamic_library = False,
367        runtime_library_search_directories = rpaths,
368        user_link_flags = user_link_flags,
369    )
370    link_args = cc_common.get_memory_inefficient_command_line(
371        feature_configuration = feature_configuration,
372        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
373        variables = link_variables,
374    )
375    link_env = cc_common.get_environment_variables(
376        feature_configuration = feature_configuration,
377        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
378        variables = link_variables,
379    )
380    ld = cc_common.get_tool_for_action(
381        feature_configuration = feature_configuration,
382        action_name = CPP_LINK_EXECUTABLE_ACTION_NAME,
383    )
384
385    return ld, link_args, link_env
386
387def _process_build_scripts(
388        build_info,
389        dep_info,
390        compile_inputs):
391    """Gathers the outputs from a target's `cargo_build_script` action.
392
393    Args:
394        build_info (BuildInfo): The target Build's dependency info.
395        dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs.
396        compile_inputs (depset): A set of all files that will participate in the build.
397
398    Returns:
399        tuple: A tuple: A tuple of the following items:
400            - (depset[File]): A list of all build info `OUT_DIR` File objects
401            - (str): The `OUT_DIR` of the current build info
402            - (File): An optional path to a generated environment file from a `cargo_build_script` target
403            - (depset[File]): All direct and transitive build flags from the current build info.
404    """
405    extra_inputs, out_dir, build_env_file, build_flags_files = _create_extra_input_args(build_info, dep_info)
406    compile_inputs = depset(transitive = [extra_inputs, compile_inputs])
407    return compile_inputs, out_dir, build_env_file, build_flags_files
408
409def _symlink_for_ambiguous_lib(actions, toolchain, crate_info, lib):
410    """Constructs a disambiguating symlink for a library dependency.
411
412    Args:
413      actions (Actions): The rule's context actions object.
414      toolchain: The Rust toolchain object.
415      crate_info (CrateInfo): The target crate's info.
416      lib (File): The library to symlink to.
417
418    Returns:
419      (File): The disambiguating symlink for the library.
420    """
421    # FIXME: Once the relative order part of the native-link-modifiers rustc
422    # feature is stable, we should be able to eliminate the need to construct
423    # symlinks by passing the full paths to the libraries.
424    # https://github.com/rust-lang/rust/issues/81490.
425
426    # Take the absolute value of hash() since it could be negative.
427    path_hash = abs(hash(lib.path))
428    lib_name = get_lib_name(lib, for_windows = toolchain.os.startswith("windows"))
429
430    prefix = "lib"
431    extension = ".a"
432    if toolchain.os.startswith("windows"):
433        prefix = ""
434        extension = ".lib"
435
436    # Ensure the symlink follows the lib<name>.a pattern on Unix-like platforms
437    # or <name>.lib on Windows.
438    # Add a hash of the original library path to disambiguate libraries with the same basename.
439    symlink_name = "{}{}-{}{}".format(prefix, lib_name, path_hash, extension)
440
441    # Add the symlink to a target crate-specific _ambiguous_libs/ subfolder,
442    # to avoid possible collisions with sibling crates that may depend on the
443    # same ambiguous libraries.
444    symlink = actions.declare_file("_ambiguous_libs/" + crate_info.output.basename + "/" + symlink_name)
445    actions.symlink(
446        output = symlink,
447        target_file = lib,
448        progress_message = "Creating symlink to ambiguous lib: {}".format(lib.path),
449    )
450    return symlink
451
452def _disambiguate_libs(actions, toolchain, crate_info, dep_info, use_pic):
453    """Constructs disambiguating symlinks for ambiguous library dependencies.
454
455    The symlinks are all created in a _ambiguous_libs/ subfolder specific to
456    the target crate to avoid possible collisions with sibling crates that may
457    depend on the same ambiguous libraries.
458
459    Args:
460      actions (Actions): The rule's context actions object.
461      toolchain: The Rust toolchain object.
462      crate_info (CrateInfo): The target crate's info.
463      dep_info: (DepInfo): The target crate's dependency info.
464      use_pic: (boolean): Whether the build should use PIC.
465
466    Returns:
467      dict[String, File]: A mapping from ambiguous library paths to their
468        disambiguating symlink.
469    """
470    # FIXME: Once the relative order part of the native-link-modifiers rustc
471    # feature is stable, we should be able to eliminate the need to construct
472    # symlinks by passing the full paths to the libraries.
473    # https://github.com/rust-lang/rust/issues/81490.
474
475    # A dictionary from file paths of ambiguous libraries to the corresponding
476    # symlink.
477    ambiguous_libs = {}
478
479    # A dictionary maintaining a mapping from preferred library name to the
480    # last visited artifact with that name.
481    visited_libs = {}
482    for link_input in dep_info.transitive_noncrates.to_list():
483        for lib in link_input.libraries:
484            # FIXME: Dynamic libs are not disambiguated right now, there are
485            # cases where those have a non-standard name with version (e.g.,
486            # //test/unit/versioned_libs). We hope that the link modifiers
487            # stabilization will come before we need to make this work.
488            if _is_dylib(lib):
489                continue
490            artifact = get_preferred_artifact(lib, use_pic)
491            name = get_lib_name(artifact, for_windows = toolchain.os.startswith("windows"))
492
493            # On Linux-like platforms, normally library base names start with
494            # `lib`, following the pattern `lib[name].(a|lo)` and we pass
495            # -lstatic=name.
496            # On Windows, the base name looks like `name.lib` and we pass
497            # -lstatic=name.
498            # FIXME: Under the native-link-modifiers unstable rustc feature,
499            # we could use -lstatic:+verbatim instead.
500            needs_symlink_to_standardize_name = (
501                (toolchain.os.startswith("linux") or toolchain.os.startswith("mac") or toolchain.os.startswith("darwin")) and
502                artifact.basename.endswith(".a") and not artifact.basename.startswith("lib")
503            ) or (
504                toolchain.os.startswith("windows") and not artifact.basename.endswith(".lib")
505            )
506
507            # Detect cases where we need to disambiguate library dependencies
508            # by constructing symlinks.
509            if (
510                needs_symlink_to_standardize_name or
511                # We have multiple libraries with the same name.
512                (name in visited_libs and visited_libs[name].path != artifact.path)
513            ):
514                # Disambiguate the previously visited library (if we just detected
515                # that it is ambiguous) and the current library.
516                if name in visited_libs:
517                    old_path = visited_libs[name].path
518                    if old_path not in ambiguous_libs:
519                        ambiguous_libs[old_path] = _symlink_for_ambiguous_lib(actions, toolchain, crate_info, visited_libs[name])
520                ambiguous_libs[artifact.path] = _symlink_for_ambiguous_lib(actions, toolchain, crate_info, artifact)
521
522            visited_libs[name] = artifact
523    return ambiguous_libs
524
525def _depend_on_metadata(crate_info, force_depend_on_objects):
526    """Determines if we can depend on metadata for this crate.
527
528    By default (when pipelining is disabled or when the crate type needs to link against
529    objects) we depend on the set of object files (.rlib).
530    When pipelining is enabled and the crate type supports depending on metadata,
531    we depend on metadata files only (.rmeta).
532    In some rare cases, even if both of those conditions are true, we still want to
533    depend on objects. This is what force_depend_on_objects is.
534
535    Args:
536        crate_info (CrateInfo): The Crate to determine this for.
537        force_depend_on_objects (bool): if set we will not depend on metadata.
538
539    Returns:
540        Whether we can depend on metadata for this crate.
541    """
542    if force_depend_on_objects:
543        return False
544
545    return crate_info.type in ("rlib", "lib")
546
547def collect_inputs(
548        ctx,
549        file,
550        files,
551        linkstamps,
552        toolchain,
553        cc_toolchain,
554        feature_configuration,
555        crate_info,
556        dep_info,
557        build_info,
558        stamp = False,
559        force_depend_on_objects = False):
560    """Gather's the inputs and required input information for a rustc action
561
562    Args:
563        ctx (ctx): The rule's context object.
564        file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`.
565        files (list): A list of all inputs (`ctx.files`).
566        linkstamps (depset): A depset of CcLinkstamps that need to be compiled and linked into all linked binaries.
567        toolchain (rust_toolchain): The current `rust_toolchain`.
568        cc_toolchain (CcToolchainInfo): The current `cc_toolchain`.
569        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
570        crate_info (CrateInfo): The Crate information of the crate to process build scripts for.
571        dep_info (DepInfo): The target Crate's dependency information.
572        build_info (BuildInfo): The target Crate's build settings.
573        stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see
574            https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
575        force_depend_on_objects (bool, optional): Forces dependencies of this rule to be objects rather than
576            metadata, even for libraries. This is used in rustdoc tests.
577
578    Returns:
579        tuple: A tuple: A tuple of the following items:
580            - (list): A list of all build info `OUT_DIR` File objects
581            - (str): The `OUT_DIR` of the current build info
582            - (File): An optional path to a generated environment file from a `cargo_build_script` target
583            - (depset[File]): All direct and transitive build flag files from the current build info
584            - (list[File]): Linkstamp outputs
585            - (dict[String, File]): Ambiguous libs, see `_disambiguate_libs`.
586    """
587    linker_script = getattr(file, "linker_script") if hasattr(file, "linker_script") else None
588
589    linker_depset = cc_toolchain.all_files
590
591    use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_info.type)
592
593    # Pass linker inputs only for linking-like actions, not for example where
594    # the output is rlib. This avoids quadratic behavior where transitive noncrates are
595    # flattened on each transitive rust_library dependency.
596    additional_transitive_inputs = []
597    ambiguous_libs = {}
598    if crate_info.type in ("staticlib", "proc-macro"):
599        additional_transitive_inputs = _collect_libs_from_linker_inputs(
600            dep_info.transitive_noncrates.to_list(),
601            use_pic,
602        )
603    elif crate_info.type in ("bin", "dylib", "cdylib"):
604        linker_inputs = dep_info.transitive_noncrates.to_list()
605        ambiguous_libs = _disambiguate_libs(ctx.actions, toolchain, crate_info, dep_info, use_pic)
606        additional_transitive_inputs = _collect_libs_from_linker_inputs(linker_inputs, use_pic) + [
607            additional_input
608            for linker_input in linker_inputs
609            for additional_input in linker_input.additional_inputs
610        ] + ambiguous_libs.values()
611
612    # Compute linkstamps. Use the inputs of the binary as inputs to the
613    # linkstamp action to ensure linkstamps are rebuilt whenever binary inputs
614    # change.
615    linkstamp_outs = []
616
617    transitive_crate_outputs = dep_info.transitive_crate_outputs
618    if _depend_on_metadata(crate_info, force_depend_on_objects):
619        transitive_crate_outputs = dep_info.transitive_metadata_outputs
620
621    nolinkstamp_compile_inputs = depset(
622        getattr(files, "data", []) +
623        ([build_info.rustc_env, build_info.flags] if build_info else []) +
624        ([toolchain.target_json] if toolchain.target_json else []) +
625        ([] if linker_script == None else [linker_script]),
626        transitive = [
627            linker_depset,
628            crate_info.srcs,
629            transitive_crate_outputs,
630            depset(additional_transitive_inputs),
631            crate_info.compile_data,
632            toolchain.all_files,
633        ],
634    )
635
636    if crate_info.type in ("bin", "cdylib"):
637        # There is no other way to register an action for each member of a depset than
638        # flattening the depset as of 2021-10-12. Luckily, usually there is only one linkstamp
639        # in a build, and we only flatten the list on binary targets that perform transitive linking,
640        # so it's extremely unlikely that this call to `to_list()` will ever be a performance
641        # problem.
642        for linkstamp in linkstamps.to_list():
643            # The linkstamp output path is based on the binary crate
644            # name and the input linkstamp path. This is to disambiguate
645            # the linkstamp outputs produced by multiple binary crates
646            # that depend on the same linkstamp. We use the same pattern
647            # for the output name as the one used by native cc rules.
648            out_name = "_objs/" + crate_info.output.basename + "/" + linkstamp.file().path[:-len(linkstamp.file().extension)] + "o"
649            linkstamp_out = ctx.actions.declare_file(out_name)
650            linkstamp_outs.append(linkstamp_out)
651            cc_common.register_linkstamp_compile_action(
652                actions = ctx.actions,
653                cc_toolchain = cc_toolchain,
654                feature_configuration = feature_configuration,
655                grep_includes = ctx.file._grep_includes,
656                source_file = linkstamp.file(),
657                output_file = linkstamp_out,
658                compilation_inputs = linkstamp.hdrs(),
659                inputs_for_validation = nolinkstamp_compile_inputs,
660                label_replacement = str(ctx.label),
661                output_replacement = crate_info.output.path,
662            )
663
664    # If stamping is enabled include the volatile and stable status info file
665    stamp_info = [ctx.version_file, ctx.info_file] if stamp else []
666
667    compile_inputs = depset(
668        linkstamp_outs + stamp_info,
669        transitive = [
670            nolinkstamp_compile_inputs,
671        ],
672    )
673
674    build_env_files = getattr(files, "rustc_env_files", [])
675    compile_inputs, out_dir, build_env_file, build_flags_files = _process_build_scripts(build_info, dep_info, compile_inputs)
676    if build_env_file:
677        build_env_files = [f for f in build_env_files] + [build_env_file]
678    compile_inputs = depset(build_env_files, transitive = [compile_inputs])
679
680    return compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs
681
682def construct_arguments(
683        ctx,
684        attr,
685        file,
686        toolchain,
687        tool_path,
688        cc_toolchain,
689        feature_configuration,
690        crate_info,
691        dep_info,
692        linkstamp_outs,
693        ambiguous_libs,
694        output_hash,
695        rust_flags,
696        out_dir,
697        build_env_files,
698        build_flags_files,
699        emit = ["dep-info", "link"],
700        force_all_deps_direct = False,
701        force_link = False,
702        stamp = False,
703        remap_path_prefix = ".",
704        use_json_output = False,
705        build_metadata = False,
706        force_depend_on_objects = False):
707    """Builds an Args object containing common rustc flags
708
709    Args:
710        ctx (ctx): The rule's context object
711        attr (struct): The attributes for the target. These may be different from ctx.attr in an aspect context.
712        file (struct): A struct containing files defined in label type attributes marked as `allow_single_file`.
713        toolchain (rust_toolchain): The current target's `rust_toolchain`
714        tool_path (str): Path to rustc
715        cc_toolchain (CcToolchain): The CcToolchain for the current target.
716        feature_configuration (FeatureConfiguration): Class used to construct command lines from CROSSTOOL features.
717        crate_info (CrateInfo): The CrateInfo provider of the target crate
718        dep_info (DepInfo): The DepInfo provider of the target crate
719        linkstamp_outs (list): Linkstamp outputs of native dependencies
720        ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs`
721        output_hash (str): The hashed path of the crate root
722        rust_flags (list): Additional flags to pass to rustc
723        out_dir (str): The path to the output directory for the target Crate.
724        build_env_files (list): Files containing rustc environment variables, for instance from `cargo_build_script` actions.
725        build_flags_files (depset): The output files of a `cargo_build_script` actions containing rustc build flags
726        emit (list): Values for the --emit flag to rustc.
727        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
728            to the commandline as opposed to -L.
729        force_link (bool, optional): Whether to add link flags to the command regardless of `emit`.
730        stamp (bool, optional): Whether or not workspace status stamping is enabled. For more details see
731            https://docs.bazel.build/versions/main/user-manual.html#flag--stamp
732        remap_path_prefix (str, optional): A value used to remap `${pwd}` to. If set to a falsey value, no prefix will be set.
733        use_json_output (bool): Have rustc emit json and process_wrapper parse json messages to output rendered output.
734        build_metadata (bool): Generate CLI arguments for building *only* .rmeta files. This requires use_json_output.
735        force_depend_on_objects (bool): Force using `.rlib` object files instead of metadata (`.rmeta`) files even if they are available.
736
737    Returns:
738        tuple: A tuple of the following items
739            - (struct): A struct of arguments used to run the `Rustc` action
740                - process_wrapper_flags (Args): Arguments for the process wrapper
741                - rustc_path (Args): Arguments for invoking rustc via the process wrapper
742                - rustc_flags (Args): Rust flags for the Rust compiler
743                - all (list): A list of all `Args` objects in the order listed above.
744                    This is to be passed to the `arguments` parameter of actions
745            - (dict): Common rustc environment variables
746    """
747    if build_metadata and not use_json_output:
748        fail("build_metadata requires parse_json_output")
749
750    output_dir = getattr(crate_info.output, "dirname", None)
751    linker_script = getattr(file, "linker_script", None)
752
753    env = _get_rustc_env(attr, toolchain, crate_info.name)
754
755    # Wrapper args first
756    process_wrapper_flags = ctx.actions.args()
757
758    for build_env_file in build_env_files:
759        process_wrapper_flags.add("--env-file", build_env_file)
760
761    process_wrapper_flags.add_all(build_flags_files, before_each = "--arg-file")
762
763    # Certain rust build processes expect to find files from the environment
764    # variable `$CARGO_MANIFEST_DIR`. Examples of this include pest, tera,
765    # asakuma.
766    #
767    # The compiler and by extension proc-macros see the current working
768    # directory as the Bazel exec root. This is what `$CARGO_MANIFEST_DIR`
769    # would default to but is often the wrong value (e.g. if the source is in a
770    # sub-package or if we are building something in an external repository).
771    # Hence, we need to set `CARGO_MANIFEST_DIR` explicitly.
772    #
773    # Since we cannot get the `exec_root` from starlark, we cheat a little and
774    # use `${pwd}` which resolves the `exec_root` at action execution time.
775    process_wrapper_flags.add("--subst", "pwd=${pwd}")
776
777    # If stamping is enabled, enable the functionality in the process wrapper
778    if stamp:
779        process_wrapper_flags.add("--volatile-status-file", ctx.version_file)
780        process_wrapper_flags.add("--stable-status-file", ctx.info_file)
781
782    # Both ctx.label.workspace_root and ctx.label.package are relative paths
783    # and either can be empty strings. Avoid trailing/double slashes in the path.
784    components = "${{pwd}}/{}/{}".format(ctx.label.workspace_root, ctx.label.package).split("/")
785    env["CARGO_MANIFEST_DIR"] = "/".join([c for c in components if c])
786
787    if out_dir != None:
788        env["OUT_DIR"] = "${pwd}/" + out_dir
789
790    # Handle that the binary name and crate name may be different.
791    #
792    # If a target name contains a - then cargo (and rules_rust) will generate a
793    # crate name with _ instead.  Accordingly, rustc will generate a output
794    # file (executable, or rlib, or whatever) with _ not -.  But when cargo
795    # puts a binary in the target/${config} directory, and sets environment
796    # variables like `CARGO_BIN_EXE_${binary_name}` it will use the - version
797    # not the _ version.  So we rename the rustc-generated file (with _s) to
798    # have -s if needed.
799    emit_with_paths = emit
800    if crate_info.type == "bin" and crate_info.output != None:
801        generated_file = crate_info.name + toolchain.binary_ext
802        src = "/".join([crate_info.output.dirname, generated_file])
803        dst = crate_info.output.path
804        if src != dst:
805            emit_with_paths = [("link=" + dst if val == "link" else val) for val in emit]
806
807    # Arguments for launching rustc from the process wrapper
808    rustc_path = ctx.actions.args()
809    rustc_path.add("--")
810    rustc_path.add(tool_path)
811
812    # Rustc arguments
813    rustc_flags = ctx.actions.args()
814    rustc_flags.set_param_file_format("multiline")
815    rustc_flags.use_param_file("@%s", use_always = False)
816    rustc_flags.add(crate_info.root)
817    rustc_flags.add("--crate-name=" + crate_info.name)
818    rustc_flags.add("--crate-type=" + crate_info.type)
819
820    error_format = "human"
821    if hasattr(attr, "_error_format"):
822        error_format = attr._error_format[ErrorFormatInfo].error_format
823
824    if use_json_output:
825        # If --error-format was set to json, we just pass the output through
826        # Otherwise process_wrapper uses the "rendered" field.
827        process_wrapper_flags.add("--rustc-output-format", "json" if error_format == "json" else "rendered")
828
829        # Configure rustc json output by adding artifact notifications.
830        # These will always be filtered out by process_wrapper and will be use to terminate
831        # rustc when appropriate.
832        json = ["artifacts"]
833        if error_format == "short":
834            json.append("diagnostic-short")
835        elif error_format == "human" and toolchain.os != "windows":
836            # If the os is not windows, we can get colorized output.
837            json.append("diagnostic-rendered-ansi")
838
839        rustc_flags.add("--json=" + ",".join(json))
840
841        error_format = "json"
842
843    if build_metadata:
844        # Configure process_wrapper to terminate rustc when metadata are emitted
845        process_wrapper_flags.add("--rustc-quit-on-rmeta", "true")
846
847    rustc_flags.add("--error-format=" + error_format)
848
849    # Mangle symbols to disambiguate crates with the same name. This could
850    # happen only for non-final artifacts where we compute an output_hash,
851    # e.g., rust_library.
852    #
853    # For "final" artifacts and ones intended for distribution outside of
854    # Bazel, such as rust_binary, rust_static_library and rust_shared_library,
855    # where output_hash is None we don't need to add these flags.
856    if output_hash:
857        extra_filename = "-" + output_hash
858        rustc_flags.add("--codegen=metadata=" + extra_filename)
859        rustc_flags.add("--codegen=extra-filename=" + extra_filename)
860
861    if output_dir:
862        rustc_flags.add("--out-dir=" + output_dir)
863
864    compilation_mode = get_compilation_mode_opts(ctx, toolchain)
865    rustc_flags.add("--codegen=opt-level=" + compilation_mode.opt_level)
866    rustc_flags.add("--codegen=debuginfo=" + compilation_mode.debug_info)
867
868    # For determinism to help with build distribution and such
869    if remap_path_prefix:
870        rustc_flags.add("--remap-path-prefix=${{pwd}}={}".format(remap_path_prefix))
871
872    if emit:
873        rustc_flags.add("--emit=" + ",".join(emit_with_paths))
874    if error_format != "json":
875        # Color is not compatible with json output.
876        rustc_flags.add("--color=always")
877    rustc_flags.add("--target=" + toolchain.target_flag_value)
878    if hasattr(attr, "crate_features"):
879        rustc_flags.add_all(getattr(attr, "crate_features"), before_each = "--cfg", format_each = 'feature="%s"')
880    if linker_script:
881        rustc_flags.add(linker_script.path, format = "--codegen=link-arg=-T%s")
882
883    # Gets the paths to the folders containing the standard library (or libcore)
884    rust_std_paths = toolchain.rust_std_paths.to_list()
885
886    # Tell Rustc where to find the standard library
887    rustc_flags.add_all(rust_std_paths, before_each = "-L", format_each = "%s")
888    rustc_flags.add_all(rust_flags)
889
890    # Deduplicate data paths due to https://github.com/bazelbuild/bazel/issues/14681
891    data_paths = depset(direct = getattr(attr, "data", []) + getattr(attr, "compile_data", [])).to_list()
892
893    rustc_flags.add_all(
894        expand_list_element_locations(
895            ctx,
896            getattr(attr, "rustc_flags", []),
897            data_paths,
898        ),
899    )
900    add_edition_flags(rustc_flags, crate_info)
901
902    # Link!
903    if ("link" in emit and crate_info.type not in ["rlib", "lib"]) or force_link:
904        # Rust's built-in linker can handle linking wasm files. We don't want to attempt to use the cc
905        # linker since it won't understand.
906        if toolchain.target_arch != "wasm32":
907            if output_dir:
908                use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_info.type)
909                rpaths = _compute_rpaths(toolchain, output_dir, dep_info, use_pic)
910            else:
911                rpaths = depset([])
912            ld, link_args, link_env = get_linker_and_args(ctx, attr, cc_toolchain, feature_configuration, rpaths)
913            env.update(link_env)
914            rustc_flags.add("--codegen=linker=" + ld)
915            rustc_flags.add_joined("--codegen", link_args, join_with = " ", format_joined = "link-args=%s")
916
917        _add_native_link_flags(rustc_flags, dep_info, linkstamp_outs, ambiguous_libs, crate_info.type, toolchain, cc_toolchain, feature_configuration)
918
919    use_metadata = _depend_on_metadata(crate_info, force_depend_on_objects)
920
921    # These always need to be added, even if not linking this crate.
922    add_crate_link_flags(rustc_flags, dep_info, force_all_deps_direct, use_metadata)
923
924    needs_extern_proc_macro_flag = _is_proc_macro(crate_info) and crate_info.edition != "2015"
925    if needs_extern_proc_macro_flag:
926        rustc_flags.add("--extern")
927        rustc_flags.add("proc_macro")
928
929    if toolchain.llvm_cov and ctx.configuration.coverage_enabled:
930        rustc_flags.add("--codegen=instrument-coverage")
931
932    # Make bin crate data deps available to tests.
933    for data in getattr(attr, "data", []):
934        if rust_common.crate_info in data:
935            dep_crate_info = data[rust_common.crate_info]
936            if dep_crate_info.type == "bin":
937                # Trying to make CARGO_BIN_EXE_{} canonical across platform by strip out extension if exists
938                env_basename = dep_crate_info.output.basename[:-(1 + len(dep_crate_info.output.extension))] if len(dep_crate_info.output.extension) > 0 else dep_crate_info.output.basename
939                env["CARGO_BIN_EXE_" + env_basename] = dep_crate_info.output.short_path
940
941    # Add environment variables from the Rust toolchain.
942    env.update(toolchain.env)
943
944    # Update environment with user provided variables.
945    env.update(expand_dict_value_locations(
946        ctx,
947        crate_info.rustc_env,
948        data_paths,
949    ))
950
951    # Ensure the sysroot is set for the target platform
952    env["SYSROOT"] = toolchain.sysroot
953
954    if toolchain._rename_first_party_crates:
955        env["RULES_RUST_THIRD_PARTY_DIR"] = toolchain._third_party_dir
956
957    # extra_rustc_flags apply to the target configuration, not the exec configuration.
958    if hasattr(ctx.attr, "_extra_rustc_flags") and not is_exec_configuration(ctx):
959        rustc_flags.add_all(ctx.attr._extra_rustc_flags[ExtraRustcFlagsInfo].extra_rustc_flags)
960
961    if hasattr(ctx.attr, "_extra_rustc_flag") and not is_exec_configuration(ctx):
962        rustc_flags.add_all(ctx.attr._extra_rustc_flag[ExtraRustcFlagsInfo].extra_rustc_flags)
963
964    if hasattr(ctx.attr, "_extra_exec_rustc_flags") and is_exec_configuration(ctx):
965        rustc_flags.add_all(ctx.attr._extra_exec_rustc_flags[ExtraExecRustcFlagsInfo].extra_exec_rustc_flags)
966
967    if hasattr(ctx.attr, "_extra_exec_rustc_flag") and is_exec_configuration(ctx):
968        rustc_flags.add_all(ctx.attr._extra_exec_rustc_flag[ExtraExecRustcFlagsInfo].extra_exec_rustc_flags)
969
970    # Create a struct which keeps the arguments separate so each may be tuned or
971    # replaced where necessary
972    args = struct(
973        process_wrapper_flags = process_wrapper_flags,
974        rustc_path = rustc_path,
975        rustc_flags = rustc_flags,
976        all = [process_wrapper_flags, rustc_path, rustc_flags],
977    )
978
979    return args, env
980
981def rustc_compile_action(
982        ctx,
983        attr,
984        toolchain,
985        crate_info,
986        output_hash = None,
987        rust_flags = [],
988        force_all_deps_direct = False):
989    """Create and run a rustc compile action based on the current rule's attributes
990
991    Args:
992        ctx (ctx): The rule's context object
993        attr (struct): Attributes to use for the rust compile action
994        toolchain (rust_toolchain): The current `rust_toolchain`
995        crate_info (CrateInfo): The CrateInfo provider for the current target.
996        output_hash (str, optional): The hashed path of the crate root. Defaults to None.
997        rust_flags (list, optional): Additional flags to pass to rustc. Defaults to [].
998        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
999            to the commandline as opposed to -L.
1000
1001    Returns:
1002        list: A list of the following providers:
1003            - (CrateInfo): info for the crate we just built; same as `crate_info` parameter.
1004            - (DepInfo): The transitive dependencies of this crate.
1005            - (DefaultInfo): The output file for this crate, and its runfiles.
1006    """
1007    build_metadata = getattr(crate_info, "metadata", None)
1008
1009    cc_toolchain, feature_configuration = find_cc_toolchain(ctx)
1010
1011    dep_info, build_info, linkstamps = collect_deps(
1012        deps = crate_info.deps,
1013        proc_macro_deps = crate_info.proc_macro_deps,
1014        aliases = crate_info.aliases,
1015        are_linkstamps_supported = _are_linkstamps_supported(
1016            feature_configuration = feature_configuration,
1017            has_grep_includes = hasattr(ctx.attr, "_grep_includes"),
1018        ),
1019    )
1020
1021    # Determine if the build is currently running with --stamp
1022    stamp = is_stamping_enabled(attr)
1023
1024    compile_inputs, out_dir, build_env_files, build_flags_files, linkstamp_outs, ambiguous_libs = collect_inputs(
1025        ctx = ctx,
1026        file = ctx.file,
1027        files = ctx.files,
1028        linkstamps = linkstamps,
1029        toolchain = toolchain,
1030        cc_toolchain = cc_toolchain,
1031        feature_configuration = feature_configuration,
1032        crate_info = crate_info,
1033        dep_info = dep_info,
1034        build_info = build_info,
1035        stamp = stamp,
1036    )
1037
1038    # If we build metadata, we need to keep the command line of the two invocations
1039    # (rlib and rmeta) as similar as possible, otherwise rustc rejects the rmeta as
1040    # a candidate.
1041    # Because of that we need to add emit=metadata to both the rlib and rmeta invocation.
1042    emit = ["dep-info", "link"]
1043    if build_metadata:
1044        emit.append("metadata")
1045
1046    args, env_from_args = construct_arguments(
1047        ctx = ctx,
1048        attr = attr,
1049        file = ctx.file,
1050        toolchain = toolchain,
1051        tool_path = toolchain.rustc.path,
1052        cc_toolchain = cc_toolchain,
1053        emit = emit,
1054        feature_configuration = feature_configuration,
1055        crate_info = crate_info,
1056        dep_info = dep_info,
1057        linkstamp_outs = linkstamp_outs,
1058        ambiguous_libs = ambiguous_libs,
1059        output_hash = output_hash,
1060        rust_flags = rust_flags,
1061        out_dir = out_dir,
1062        build_env_files = build_env_files,
1063        build_flags_files = build_flags_files,
1064        force_all_deps_direct = force_all_deps_direct,
1065        stamp = stamp,
1066        use_json_output = bool(build_metadata),
1067    )
1068
1069    args_metadata = None
1070    if build_metadata:
1071        args_metadata, _ = construct_arguments(
1072            ctx = ctx,
1073            attr = attr,
1074            file = ctx.file,
1075            toolchain = toolchain,
1076            tool_path = toolchain.rustc.path,
1077            cc_toolchain = cc_toolchain,
1078            emit = emit,
1079            feature_configuration = feature_configuration,
1080            crate_info = crate_info,
1081            dep_info = dep_info,
1082            linkstamp_outs = linkstamp_outs,
1083            ambiguous_libs = ambiguous_libs,
1084            output_hash = output_hash,
1085            rust_flags = rust_flags,
1086            out_dir = out_dir,
1087            build_env_files = build_env_files,
1088            build_flags_files = build_flags_files,
1089            force_all_deps_direct = force_all_deps_direct,
1090            stamp = stamp,
1091            use_json_output = True,
1092            build_metadata = True,
1093        )
1094
1095    env = dict(ctx.configuration.default_shell_env)
1096    env.update(env_from_args)
1097
1098    if hasattr(attr, "version") and attr.version != "0.0.0":
1099        formatted_version = " v{}".format(attr.version)
1100    else:
1101        formatted_version = ""
1102
1103    outputs = [crate_info.output]
1104
1105    # For a cdylib that might be added as a dependency to a cc_* target on Windows, it is important to include the
1106    # interface library that rustc generates in the output files.
1107    interface_library = None
1108    if toolchain.os == "windows" and crate_info.type == "cdylib":
1109        # Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc
1110        # expects (see https://github.com/rust-lang/rust/pull/29520 for more context).
1111        interface_library = ctx.actions.declare_file(crate_info.output.basename + ".lib", sibling = crate_info.output)
1112        outputs.append(interface_library)
1113
1114    # The action might generate extra output that we don't want to include in the `DefaultInfo` files.
1115    action_outputs = list(outputs)
1116
1117    # Rustc generates a pdb file (on Windows) or a dsym folder (on macos) so provide it in an output group for crate
1118    # types that benefit from having debug information in a separate file.
1119    pdb_file = None
1120    dsym_folder = None
1121    if crate_info.type in ("cdylib", "bin") and not crate_info.is_test:
1122        if toolchain.os == "windows":
1123            pdb_file = ctx.actions.declare_file(crate_info.output.basename[:-len(crate_info.output.extension)] + "pdb", sibling = crate_info.output)
1124            action_outputs.append(pdb_file)
1125        elif toolchain.os == "darwin":
1126            dsym_folder = ctx.actions.declare_directory(crate_info.output.basename + ".dSYM", sibling = crate_info.output)
1127            action_outputs.append(dsym_folder)
1128
1129    if ctx.executable._process_wrapper:
1130        # Run as normal
1131        ctx.actions.run(
1132            executable = ctx.executable._process_wrapper,
1133            inputs = compile_inputs,
1134            outputs = action_outputs,
1135            env = env,
1136            arguments = args.all,
1137            mnemonic = "Rustc",
1138            progress_message = "Compiling Rust {} {}{} ({} files)".format(
1139                crate_info.type,
1140                ctx.label.name,
1141                formatted_version,
1142                len(crate_info.srcs.to_list()),
1143            ),
1144        )
1145        if args_metadata:
1146            ctx.actions.run(
1147                executable = ctx.executable._process_wrapper,
1148                inputs = compile_inputs,
1149                outputs = [build_metadata],
1150                env = env,
1151                arguments = args_metadata.all,
1152                mnemonic = "RustcMetadata",
1153                progress_message = "Compiling Rust metadata {} {}{} ({} files)".format(
1154                    crate_info.type,
1155                    ctx.label.name,
1156                    formatted_version,
1157                    len(crate_info.srcs.to_list()),
1158                ),
1159            )
1160    else:
1161        # Run without process_wrapper
1162        if build_env_files or build_flags_files or stamp or build_metadata:
1163            fail("build_env_files, build_flags_files, stamp, build_metadata are not supported when building without process_wrapper")
1164        ctx.actions.run(
1165            executable = toolchain.rustc,
1166            inputs = compile_inputs,
1167            outputs = action_outputs,
1168            env = env,
1169            arguments = [args.rustc_flags],
1170            mnemonic = "Rustc",
1171            progress_message = "Compiling Rust (without process_wrapper) {} {}{} ({} files)".format(
1172                crate_info.type,
1173                ctx.label.name,
1174                formatted_version,
1175                len(crate_info.srcs.to_list()),
1176            ),
1177        )
1178
1179    coverage_runfiles = []
1180    if toolchain.llvm_cov and ctx.configuration.coverage_enabled and crate_info.is_test:
1181        coverage_runfiles = [toolchain.llvm_cov, toolchain.llvm_profdata]
1182
1183    runfiles = ctx.runfiles(
1184        files = getattr(ctx.files, "data", []) + coverage_runfiles,
1185        collect_data = True,
1186    )
1187
1188    # TODO: Remove after some resolution to
1189    # https://github.com/bazelbuild/rules_rust/issues/771
1190    out_binary = getattr(attr, "out_binary", False)
1191
1192    providers = [
1193        DefaultInfo(
1194            # nb. This field is required for cc_library to depend on our output.
1195            files = depset(outputs),
1196            runfiles = runfiles,
1197            executable = crate_info.output if crate_info.type == "bin" or crate_info.is_test or out_binary else None,
1198        ),
1199        coverage_common.instrumented_files_info(
1200            ctx,
1201            dependency_attributes = ["deps", "crate"],
1202            extensions = ["rs"],
1203            source_attributes = ["srcs"],
1204        ),
1205    ]
1206
1207    if crate_info.type in ["staticlib", "cdylib"]:
1208        # These rules are not supposed to be depended on by other rust targets, and
1209        # as such they shouldn't provide a CrateInfo. However, one may still want to
1210        # write a rust_test for them, so we provide the CrateInfo wrapped in a provider
1211        # that rust_test understands.
1212        providers.extend([rust_common.test_crate_info(crate = crate_info), dep_info])
1213    else:
1214        providers.extend([crate_info, dep_info])
1215
1216    if toolchain.target_arch != "wasm32":
1217        providers += establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_configuration, interface_library)
1218    if pdb_file:
1219        providers.append(OutputGroupInfo(pdb_file = depset([pdb_file])))
1220    if dsym_folder:
1221        providers.append(OutputGroupInfo(dsym_folder = depset([dsym_folder])))
1222
1223    return providers
1224
1225def _is_dylib(dep):
1226    return not bool(dep.static_library or dep.pic_static_library)
1227
1228def _collect_nonstatic_linker_inputs(cc_info):
1229    shared_linker_inputs = []
1230    for linker_input in cc_info.linking_context.linker_inputs.to_list():
1231        dylibs = [
1232            lib
1233            for lib in linker_input.libraries
1234            if _is_dylib(lib)
1235        ]
1236        if dylibs:
1237            shared_linker_inputs.append(cc_common.create_linker_input(
1238                owner = linker_input.owner,
1239                libraries = depset(dylibs),
1240            ))
1241    return shared_linker_inputs
1242
1243def establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_configuration, interface_library):
1244    """If the produced crate is suitable yield a CcInfo to allow for interop with cc rules
1245
1246    Args:
1247        ctx (ctx): The rule's context object
1248        attr (struct): Attributes to use in gathering CcInfo
1249        crate_info (CrateInfo): The CrateInfo provider of the target crate
1250        toolchain (rust_toolchain): The current `rust_toolchain`
1251        cc_toolchain (CcToolchainInfo): The current `CcToolchainInfo`
1252        feature_configuration (FeatureConfiguration): Feature configuration to be queried.
1253        interface_library (File): Optional interface library for cdylib crates on Windows.
1254
1255    Returns:
1256        list: A list containing the CcInfo provider
1257    """
1258
1259    # A test will not need to produce CcInfo as nothing can depend on test targets
1260    if crate_info.is_test:
1261        return []
1262
1263    # Only generate CcInfo for particular crate types
1264    if crate_info.type not in ("staticlib", "cdylib", "rlib", "lib"):
1265        return []
1266
1267    # TODO: Remove after some resolution to
1268    # https://github.com/bazelbuild/rules_rust/issues/771
1269    if getattr(attr, "out_binary", False):
1270        return []
1271
1272    if crate_info.type == "staticlib":
1273        library_to_link = cc_common.create_library_to_link(
1274            actions = ctx.actions,
1275            feature_configuration = feature_configuration,
1276            cc_toolchain = cc_toolchain,
1277            static_library = crate_info.output,
1278            # TODO(hlopko): handle PIC/NOPIC correctly
1279            pic_static_library = crate_info.output,
1280        )
1281    elif crate_info.type in ("rlib", "lib"):
1282        # bazel hard-codes a check for endswith((".a", ".pic.a",
1283        # ".lib")) in create_library_to_link, so we work around that
1284        # by creating a symlink to the .rlib with a .a extension.
1285        dot_a = make_static_lib_symlink(ctx.actions, crate_info.output)
1286
1287        # TODO(hlopko): handle PIC/NOPIC correctly
1288        library_to_link = cc_common.create_library_to_link(
1289            actions = ctx.actions,
1290            feature_configuration = feature_configuration,
1291            cc_toolchain = cc_toolchain,
1292            static_library = dot_a,
1293            # TODO(hlopko): handle PIC/NOPIC correctly
1294            pic_static_library = dot_a,
1295        )
1296    elif crate_info.type == "cdylib":
1297        library_to_link = cc_common.create_library_to_link(
1298            actions = ctx.actions,
1299            feature_configuration = feature_configuration,
1300            cc_toolchain = cc_toolchain,
1301            dynamic_library = crate_info.output,
1302            interface_library = interface_library,
1303        )
1304    else:
1305        fail("Unexpected case")
1306
1307    link_input = cc_common.create_linker_input(
1308        owner = ctx.label,
1309        libraries = depset([library_to_link]),
1310    )
1311
1312    linking_context = cc_common.create_linking_context(
1313        # TODO - What to do for no_std?
1314        linker_inputs = depset([link_input]),
1315    )
1316
1317    cc_infos = [
1318        CcInfo(linking_context = linking_context),
1319        toolchain.stdlib_linkflags,
1320    ]
1321
1322    for dep in getattr(attr, "deps", []):
1323        if CcInfo in dep:
1324            # A Rust staticlib or shared library doesn't need to propagate linker inputs
1325            # of its dependencies, except for shared libraries.
1326            if crate_info.type in ["cdylib", "staticlib"]:
1327                shared_linker_inputs = _collect_nonstatic_linker_inputs(dep[CcInfo])
1328                if shared_linker_inputs:
1329                    linking_context = cc_common.create_linking_context(
1330                        linker_inputs = depset(shared_linker_inputs),
1331                    )
1332                    cc_infos.append(CcInfo(linking_context = linking_context))
1333            else:
1334                cc_infos.append(dep[CcInfo])
1335
1336    if crate_info.type in ("rlib", "lib") and toolchain.libstd_and_allocator_ccinfo:
1337        # TODO: if we already have an rlib in our deps, we could skip this
1338        cc_infos.append(toolchain.libstd_and_allocator_ccinfo)
1339
1340    return [cc_common.merge_cc_infos(cc_infos = cc_infos)]
1341
1342def add_edition_flags(args, crate):
1343    """Adds the Rust edition flag to an arguments object reference
1344
1345    Args:
1346        args (Args): A reference to an Args object
1347        crate (CrateInfo): A CrateInfo provider
1348    """
1349    if crate.edition != "2015":
1350        args.add("--edition={}".format(crate.edition))
1351
1352def _create_extra_input_args(build_info, dep_info):
1353    """Gather additional input arguments from transitive dependencies
1354
1355    Args:
1356        build_info (BuildInfo): The BuildInfo provider from the target Crate's set of inputs.
1357        dep_info (DepInfo): The Depinfo provider form the target Crate's set of inputs.
1358
1359    Returns:
1360        tuple: A tuple of the following items:
1361            - (depset[File]): A list of all build info `OUT_DIR` File objects
1362            - (str): The `OUT_DIR` of the current build info
1363            - (File): An optional generated environment file from a `cargo_build_script` target
1364            - (depset[File]): All direct and transitive build flag files from the current build info.
1365    """
1366    input_files = []
1367
1368    # Arguments to the commandline line wrapper that are going to be used
1369    # to create the final command line
1370    out_dir = None
1371    build_env_file = None
1372    build_flags_files = []
1373
1374    if build_info:
1375        out_dir = build_info.out_dir.path
1376        build_env_file = build_info.rustc_env
1377        build_flags_files.append(build_info.flags)
1378        build_flags_files.append(build_info.link_flags)
1379        input_files.append(build_info.out_dir)
1380        input_files.append(build_info.link_flags)
1381
1382    return (
1383        depset(input_files, transitive = [dep_info.link_search_path_files]),
1384        out_dir,
1385        build_env_file,
1386        depset(build_flags_files, transitive = [dep_info.link_search_path_files]),
1387    )
1388
1389def _compute_rpaths(toolchain, output_dir, dep_info, use_pic):
1390    """Determine the artifact's rpaths relative to the bazel root for runtime linking of shared libraries.
1391
1392    Args:
1393        toolchain (rust_toolchain): The current `rust_toolchain`
1394        output_dir (str): The output directory of the current target
1395        dep_info (DepInfo): The current target's dependency info
1396        use_pic: If set, prefers pic_static_library over static_library.
1397
1398    Returns:
1399        depset: A set of relative paths from the output directory to each dependency
1400    """
1401
1402    # Windows has no rpath equivalent, so always return an empty depset.
1403    if toolchain.os == "windows":
1404        return depset([])
1405
1406    dylibs = [
1407        get_preferred_artifact(lib, use_pic)
1408        for linker_input in dep_info.transitive_noncrates.to_list()
1409        for lib in linker_input.libraries
1410        if _is_dylib(lib)
1411    ]
1412    if not dylibs:
1413        return depset([])
1414
1415    # For darwin, dylibs compiled by Bazel will fail to be resolved at runtime
1416    # without a version of Bazel that includes
1417    # https://github.com/bazelbuild/bazel/pull/13427. This is known to not be
1418    # included in Bazel 4.1 and below.
1419    if toolchain.os != "linux" and toolchain.os != "darwin":
1420        fail("Runtime linking is not supported on {}, but found {}".format(
1421            toolchain.os,
1422            dep_info.transitive_noncrates,
1423        ))
1424
1425    # Multiple dylibs can be present in the same directory, so deduplicate them.
1426    return depset([
1427        relativize(lib_dir, output_dir)
1428        for lib_dir in _get_dir_names(dylibs)
1429    ])
1430
1431def _get_dir_names(files):
1432    """Returns a list of directory names from the given list of File objects
1433
1434    Args:
1435        files (list): A list of File objects
1436
1437    Returns:
1438        list: A list of directory names for all files
1439    """
1440    dirs = {}
1441    for f in files:
1442        dirs[f.dirname] = None
1443    return dirs.keys()
1444
1445def add_crate_link_flags(args, dep_info, force_all_deps_direct = False, use_metadata = False):
1446    """Adds link flags to an Args object reference
1447
1448    Args:
1449        args (Args): An arguments object reference
1450        dep_info (DepInfo): The current target's dependency info
1451        force_all_deps_direct (bool, optional): Whether to pass the transitive rlibs with --extern
1452            to the commandline as opposed to -L.
1453        use_metadata (bool, optional): Build command line arugments using metadata for crates that provide it.
1454    """
1455
1456    direct_crates = depset(
1457        transitive = [
1458            dep_info.direct_crates,
1459            dep_info.transitive_crates,
1460        ],
1461    ) if force_all_deps_direct else dep_info.direct_crates
1462
1463    crate_to_link_flags = _crate_to_link_flag_metadata if use_metadata else _crate_to_link_flag
1464    args.add_all(direct_crates, uniquify = True, map_each = crate_to_link_flags)
1465
1466    args.add_all(
1467        dep_info.transitive_crates,
1468        map_each = _get_crate_dirname,
1469        uniquify = True,
1470        format_each = "-Ldependency=%s",
1471    )
1472
1473def _crate_to_link_flag_metadata(crate):
1474    """A helper macro used by `add_crate_link_flags` for adding crate link flags to a Arg object
1475
1476    Args:
1477        crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider
1478
1479    Returns:
1480        list: Link flags for the given provider
1481    """
1482
1483    # This is AliasableDepInfo, we should use the alias as a crate name
1484    if hasattr(crate, "dep"):
1485        name = crate.name
1486        crate_info = crate.dep
1487    else:
1488        name = crate.name
1489        crate_info = crate
1490
1491    lib_or_meta = crate_info.metadata
1492    if not crate_info.metadata:
1493        lib_or_meta = crate_info.output
1494    return ["--extern={}={}".format(name, lib_or_meta.path)]
1495
1496def _crate_to_link_flag(crate):
1497    """A helper macro used by `add_crate_link_flags` for adding crate link flags to a Arg object
1498
1499    Args:
1500        crate (CrateInfo|AliasableDepInfo): A CrateInfo or an AliasableDepInfo provider
1501
1502    Returns:
1503        list: Link flags for the given provider
1504    """
1505
1506    # This is AliasableDepInfo, we should use the alias as a crate name
1507    if hasattr(crate, "dep"):
1508        name = crate.name
1509        crate_info = crate.dep
1510    else:
1511        name = crate.name
1512        crate_info = crate
1513    return ["--extern={}={}".format(name, crate_info.output.path)]
1514
1515def _get_crate_dirname(crate):
1516    """A helper macro used by `add_crate_link_flags` for getting the directory name of the current crate's output path
1517
1518    Args:
1519        crate (CrateInfo): A CrateInfo provider from the current rule
1520
1521    Returns:
1522        str: The directory name of the the output File that will be produced.
1523    """
1524    return crate.output.dirname
1525
1526def _portable_link_flags(lib, use_pic, ambiguous_libs, for_windows = False):
1527    artifact = get_preferred_artifact(lib, use_pic)
1528    if ambiguous_libs and artifact.path in ambiguous_libs:
1529        artifact = ambiguous_libs[artifact.path]
1530    if lib.static_library or lib.pic_static_library:
1531        # To ensure appropriate linker library argument order, in the presence
1532        # of both native libraries that depend on rlibs and rlibs that depend
1533        # on native libraries, we use an approach where we "sandwich" the
1534        # rust libraries between two similar sections of all of native
1535        # libraries:
1536        # n1 n2 ... r1 r2 ... n1 n2 ...
1537        # A         B         C
1538        # This way any dependency from a native library to a rust library
1539        # is resolved from A to B, and any dependency from a rust library to
1540        # a native one is resolved from B to C.
1541        # The question of resolving dependencies from a native library from A
1542        # to any rust library is addressed in a different place, where we
1543        # create symlinks to the rlibs, pretending they are native libraries,
1544        # and adding references to these symlinks in the native section A.
1545        # We rely in the behavior of -Clink-arg to put the linker args
1546        # at the end of the linker invocation constructed by rustc.
1547
1548        # We skip adding `-Clink-arg=-l` for libstd and libtest from the standard library, as
1549        # these two libraries are present both as an `.rlib` and a `.so` format.
1550        # On linux, Rustc adds a -Bdynamic to the linker command line before the libraries specified
1551        # with `-Clink-arg`, which leads to us linking against the `.so`s but not putting the
1552        # corresponding value to the runtime library search paths, which results in a
1553        # "cannot open shared object file: No such file or directory" error at exectuion time.
1554        # We can fix this by adding a `-Clink-arg=-Bstatic` on linux, but we don't have that option for
1555        # macos. The proper solution for this issue would be to remove `libtest-{hash}.so` and `libstd-{hash}.so`
1556        # from the toolchain. However, it is not enough to change the toolchain's `rust_std_{...}` filegroups
1557        # here: https://github.com/bazelbuild/rules_rust/blob/a9d5d894ad801002d007b858efd154e503796b9f/rust/private/repository_utils.bzl#L144
1558        # because rustc manages to escape the sandbox and still finds them at linking time.
1559        # We need to modify the repository rules to erase those files completely.
1560        if "lib/rustlib" in artifact.path and (
1561            artifact.basename.startswith("libtest-") or artifact.basename.startswith("libstd-") or
1562            artifact.basename.startswith("test-") or artifact.basename.startswith("std-")
1563        ):
1564            return ["-lstatic=%s" % get_lib_name(artifact, for_windows)]
1565        return [
1566            "-lstatic=%s" % get_lib_name(artifact, for_windows),
1567            "-Clink-arg=-l%s" % (get_lib_name(artifact) if not for_windows else artifact.basename),
1568        ]
1569    elif _is_dylib(lib):
1570        return [
1571            "-ldylib=%s" % get_lib_name(artifact, for_windows),
1572        ]
1573
1574    return []
1575
1576def _make_link_flags_windows(linker_input_and_use_pic_and_ambiguous_libs):
1577    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1578    ret = []
1579    for lib in linker_input.libraries:
1580        if lib.alwayslink:
1581            ret.extend(["-C", "link-arg=/WHOLEARCHIVE:%s" % get_preferred_artifact(lib, use_pic).path])
1582        else:
1583            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs, for_windows = True))
1584    return ret
1585
1586def _make_link_flags_darwin(linker_input_and_use_pic_and_ambiguous_libs):
1587    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1588    ret = []
1589    for lib in linker_input.libraries:
1590        if lib.alwayslink:
1591            ret.extend([
1592                "-C",
1593                ("link-arg=-Wl,-force_load,%s" % get_preferred_artifact(lib, use_pic).path),
1594            ])
1595        else:
1596            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs))
1597    return ret
1598
1599def _make_link_flags_default(linker_input_and_use_pic_and_ambiguous_libs):
1600    linker_input, use_pic, ambiguous_libs = linker_input_and_use_pic_and_ambiguous_libs
1601    ret = []
1602    for lib in linker_input.libraries:
1603        if lib.alwayslink:
1604            ret.extend([
1605                "-C",
1606                "link-arg=-Wl,--whole-archive",
1607                "-C",
1608                ("link-arg=%s" % get_preferred_artifact(lib, use_pic).path),
1609                "-C",
1610                "link-arg=-Wl,--no-whole-archive",
1611            ])
1612        else:
1613            ret.extend(_portable_link_flags(lib, use_pic, ambiguous_libs))
1614    return ret
1615
1616def _libraries_dirnames(linker_input_and_use_pic_and_ambiguous_libs):
1617    link_input, use_pic, _ = linker_input_and_use_pic_and_ambiguous_libs
1618
1619    # De-duplicate names.
1620    return depset([get_preferred_artifact(lib, use_pic).dirname for lib in link_input.libraries]).to_list()
1621
1622def _add_native_link_flags(args, dep_info, linkstamp_outs, ambiguous_libs, crate_type, toolchain, cc_toolchain, feature_configuration):
1623    """Adds linker flags for all dependencies of the current target.
1624
1625    Args:
1626        args (Args): The Args struct for a ctx.action
1627        dep_info (DepInfo): Dependency Info provider
1628        linkstamp_outs (list): Linkstamp outputs of native dependencies
1629        ambiguous_libs (dict): Ambiguous libs, see `_disambiguate_libs`
1630        crate_type: Crate type of the current target
1631        toolchain (rust_toolchain): The current `rust_toolchain`
1632        cc_toolchain (CcToolchainInfo): The current `cc_toolchain`
1633        feature_configuration (FeatureConfiguration): feature configuration to use with cc_toolchain
1634    """
1635    if crate_type in ["lib", "rlib"]:
1636        return
1637
1638    use_pic = _should_use_pic(cc_toolchain, feature_configuration, crate_type)
1639
1640    if toolchain.os == "windows":
1641        make_link_flags = _make_link_flags_windows
1642    elif toolchain.os.startswith("mac") or toolchain.os.startswith("darwin"):
1643        make_link_flags = _make_link_flags_darwin
1644    else:
1645        make_link_flags = _make_link_flags_default
1646
1647    # TODO(hlopko): Remove depset flattening by using lambdas once we are on >=Bazel 5.0
1648    args_and_pic_and_ambiguous_libs = [(arg, use_pic, ambiguous_libs) for arg in dep_info.transitive_noncrates.to_list()]
1649    args.add_all(args_and_pic_and_ambiguous_libs, map_each = _libraries_dirnames, uniquify = True, format_each = "-Lnative=%s")
1650    if ambiguous_libs:
1651        # If there are ambiguous libs, the disambiguation symlinks to them are
1652        # all created in the same directory. Add it to the library search path.
1653        ambiguous_libs_dirname = ambiguous_libs.values()[0].dirname
1654        args.add("-Lnative={}".format(ambiguous_libs_dirname))
1655
1656    args.add_all(args_and_pic_and_ambiguous_libs, map_each = make_link_flags)
1657
1658    for linkstamp_out in linkstamp_outs:
1659        args.add_all(["-C", "link-arg=%s" % linkstamp_out.path])
1660
1661    if crate_type in ["dylib", "cdylib"]:
1662        # For shared libraries we want to link C++ runtime library dynamically
1663        # (for example libstdc++.so or libc++.so).
1664        args.add_all(
1665            cc_toolchain.dynamic_runtime_lib(feature_configuration = feature_configuration),
1666            map_each = _get_dirname,
1667            format_each = "-Lnative=%s",
1668        )
1669        args.add_all(
1670            cc_toolchain.dynamic_runtime_lib(feature_configuration = feature_configuration),
1671            map_each = get_lib_name,
1672            format_each = "-ldylib=%s",
1673        )
1674    else:
1675        # For all other crate types we want to link C++ runtime library statically
1676        # (for example libstdc++.a or libc++.a).
1677        args.add_all(
1678            cc_toolchain.static_runtime_lib(feature_configuration = feature_configuration),
1679            map_each = _get_dirname,
1680            format_each = "-Lnative=%s",
1681        )
1682        args.add_all(
1683            cc_toolchain.static_runtime_lib(feature_configuration = feature_configuration),
1684            map_each = get_lib_name,
1685            format_each = "-lstatic=%s",
1686        )
1687
1688def _get_dirname(file):
1689    """A helper function for `_add_native_link_flags`.
1690
1691    Args:
1692        file (File): The target file
1693
1694    Returns:
1695        str: Directory name of `file`
1696    """
1697    return file.dirname
1698
1699def _error_format_impl(ctx):
1700    """Implementation of the `error_format` rule
1701
1702    Args:
1703        ctx (ctx): The rule's context object
1704
1705    Returns:
1706        list: A list containing the ErrorFormatInfo provider
1707    """
1708    raw = ctx.build_setting_value
1709    if raw not in _error_format_values:
1710        fail("{} expected a value in `{}` but got `{}`".format(
1711            ctx.label,
1712            _error_format_values,
1713            raw,
1714        ))
1715    return [ErrorFormatInfo(error_format = raw)]
1716
1717error_format = rule(
1718    doc = (
1719        "Change the [--error-format](https://doc.rust-lang.org/rustc/command-line-arguments.html#option-error-format) " +
1720        "flag from the command line with `--@rules_rust//:error_format`. See rustc documentation for valid values."
1721    ),
1722    implementation = _error_format_impl,
1723    build_setting = config.string(flag = True),
1724)
1725
1726def _extra_rustc_flags_impl(ctx):
1727    return ExtraRustcFlagsInfo(extra_rustc_flags = ctx.build_setting_value)
1728
1729extra_rustc_flags = rule(
1730    doc = (
1731        "Add additional rustc_flags from the command line with `--@rules_rust//:extra_rustc_flags`. " +
1732        "This flag should only be used for flags that need to be applied across the entire build. For options that " +
1733        "apply to individual crates, use the rustc_flags attribute on the individual crate's rule instead. NOTE: " +
1734        "These flags not applied to the exec configuration (proc-macros, cargo_build_script, etc); " +
1735        "use `--@rules_rust//:extra_exec_rustc_flags` to apply flags to the exec configuration."
1736    ),
1737    implementation = _extra_rustc_flags_impl,
1738    build_setting = config.string_list(flag = True),
1739)
1740
1741def _extra_rustc_flag_impl(ctx):
1742    return ExtraRustcFlagsInfo(extra_rustc_flags = [f for f in ctx.build_setting_value if f != ""])
1743
1744extra_rustc_flag = rule(
1745    doc = (
1746        "Add additional rustc_flag from the command line with `--@rules_rust//:extra_rustc_flag`. " +
1747        "Multiple uses are accumulated and appended after the extra_rustc_flags."
1748    ),
1749    implementation = _extra_rustc_flag_impl,
1750    build_setting = config.string(flag = True, allow_multiple = True),
1751)
1752
1753def _extra_exec_rustc_flags_impl(ctx):
1754    return ExtraExecRustcFlagsInfo(extra_exec_rustc_flags = ctx.build_setting_value)
1755
1756extra_exec_rustc_flags = rule(
1757    doc = (
1758        "Add additional rustc_flags in the exec configuration from the command line with `--@rules_rust//:extra_exec_rustc_flags`. " +
1759        "This flag should only be used for flags that need to be applied across the entire build. " +
1760        "These flags only apply to the exec configuration (proc-macros, cargo_build_script, etc)."
1761    ),
1762    implementation = _extra_exec_rustc_flags_impl,
1763    build_setting = config.string_list(flag = True),
1764)
1765
1766def _extra_exec_rustc_flag_impl(ctx):
1767    return ExtraExecRustcFlagsInfo(extra_exec_rustc_flags = [f for f in ctx.build_setting_value if f != ""])
1768
1769extra_exec_rustc_flag = rule(
1770    doc = (
1771        "Add additional rustc_flags in the exec configuration from the command line with `--@rules_rust//:extra_exec_rustc_flag`. " +
1772        "Multiple uses are accumulated and appended after the extra_exec_rustc_flags."
1773    ),
1774    implementation = _extra_exec_rustc_flag_impl,
1775    build_setting = config.string(flag = True, allow_multiple = True),
1776)