fork/rules_rust

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

Erik GillingUse correct dynamic link args fro proc-macro crates (#1803)a5853fd3

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