fork/rules_rust

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

UebelAndreAdded comments to internal function (#1378)ec27dbe3

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