fork/rules_rust

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

Daniel Wagner-HallMake toolchain vars available but don't automatically set them (#2969)4e593b6c

main
33.5 KiB920 linesraw
1# Copyright 2015 The Bazel Authors. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#    http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Utility functions not specific to the rust toolchain."""
16
17load("@bazel_skylib//lib:paths.bzl", "paths")
18load("@bazel_tools//tools/cpp:toolchain_utils.bzl", find_rules_cc_toolchain = "find_cpp_toolchain")
19load(":providers.bzl", "BuildInfo", "CrateGroupInfo", "CrateInfo", "DepInfo", "DepVariantInfo", "RustcOutputDiagnosticsInfo")
20
21UNSUPPORTED_FEATURES = [
22    "thin_lto",
23    "module_maps",
24    "use_header_modules",
25    "fdo_instrument",
26    "fdo_optimize",
27    # This feature is unsupported by definition. The authors of C++ toolchain
28    # configuration can place any linker flags that should not be applied when
29    # linking Rust targets in a feature with this name.
30    "rules_rust_unsupported_feature",
31]
32
33def find_toolchain(ctx):
34    """Finds the first rust toolchain that is configured.
35
36    Args:
37        ctx (ctx): The ctx object for the current target.
38
39    Returns:
40        rust_toolchain: A Rust toolchain context.
41    """
42    return ctx.toolchains[Label("//rust:toolchain_type")]
43
44def find_cc_toolchain(ctx, extra_unsupported_features = tuple()):
45    """Extracts a CcToolchain from the current target's context
46
47    Args:
48        ctx (ctx): The current target's rule context object
49        extra_unsupported_features (sequence of str): Extra featrures to disable
50
51    Returns:
52        tuple: A tuple of (CcToolchain, FeatureConfiguration)
53    """
54    cc_toolchain = find_rules_cc_toolchain(ctx)
55
56    feature_configuration = cc_common.configure_features(
57        ctx = ctx,
58        cc_toolchain = cc_toolchain,
59        requested_features = ctx.features,
60        unsupported_features = UNSUPPORTED_FEATURES + ctx.disabled_features +
61                               list(extra_unsupported_features),
62    )
63    return cc_toolchain, feature_configuration
64
65# TODO: Replace with bazel-skylib's `path.dirname`. This requires addressing some
66# dependency issues or generating docs will break.
67def relativize(path, start):
68    """Returns the relative path from start to path.
69
70    Args:
71        path (str): The path to relativize.
72        start (str): The ancestor path against which to relativize.
73
74    Returns:
75        str: The portion of `path` that is relative to `start`.
76    """
77    src_parts = _path_parts(start)
78    dest_parts = _path_parts(path)
79    n = 0
80    for src_part, dest_part in zip(src_parts, dest_parts):
81        if src_part != dest_part:
82            break
83        n += 1
84
85    relative_path = ""
86    for _ in range(n, len(src_parts)):
87        relative_path += "../"
88    relative_path += "/".join(dest_parts[n:])
89
90    return relative_path
91
92def _path_parts(path):
93    """Takes a path and returns a list of its parts with all "." elements removed.
94
95    The main use case of this function is if one of the inputs to relativize()
96    is a relative path, such as "./foo".
97
98    Args:
99      path (str): A string representing a unix path
100
101    Returns:
102      list: A list containing the path parts with all "." elements removed.
103    """
104    path_parts = path.split("/")
105    return [part for part in path_parts if part != "."]
106
107def get_lib_name_default(lib):
108    """Returns the name of a library artifact.
109
110    Args:
111        lib (File): A library file
112
113    Returns:
114        str: The name of the library
115    """
116    # On macos and windows, dynamic/static libraries always end with the
117    # extension and potential versions will be before the extension, and should
118    # be part of the library name.
119    # On linux, the version usually comes after the extension.
120    # So regardless of the platform we want to find the extension and make
121    # everything left to it the library name.
122
123    # Search for the extension - starting from the right - by removing any
124    # trailing digit.
125    comps = lib.basename.split(".")
126    for comp in reversed(comps):
127        if comp.isdigit():
128            comps.pop()
129        else:
130            break
131
132    # The library name is now everything minus the extension.
133    libname = ".".join(comps[:-1])
134
135    if libname.startswith("lib"):
136        return libname[3:]
137    else:
138        return libname
139
140# TODO: Could we remove this function in favor of a "windows" parameter in the
141# above function? It looks like currently lambdas cannot accept local parameters
142# so the following doesn't work:
143#     args.add_all(
144#         cc_toolchain.dynamic_runtime_lib(feature_configuration = feature_configuration),
145#         map_each = lambda x: get_lib_name(x, for_windows = toolchain.target_os.startswith("windows)),
146#         format_each = "-ldylib=%s",
147#     )
148def get_lib_name_for_windows(lib):
149    """Returns the name of a library artifact for Windows builds.
150
151    Args:
152        lib (File): A library file
153
154    Returns:
155        str: The name of the library
156    """
157    # On macos and windows, dynamic/static libraries always end with the
158    # extension and potential versions will be before the extension, and should
159    # be part of the library name.
160    # On linux, the version usually comes after the extension.
161    # So regardless of the platform we want to find the extension and make
162    # everything left to it the library name.
163
164    # Search for the extension - starting from the right - by removing any
165    # trailing digit.
166    comps = lib.basename.split(".")
167    for comp in reversed(comps):
168        if comp.isdigit():
169            comps.pop()
170        else:
171            break
172
173    # The library name is now everything minus the extension.
174    libname = ".".join(comps[:-1])
175
176    return libname
177
178def abs(value):
179    """Returns the absolute value of a number.
180
181    Args:
182      value (int): A number.
183
184    Returns:
185      int: The absolute value of the number.
186    """
187    if value < 0:
188        return -value
189    return value
190
191def determine_output_hash(crate_root, label):
192    """Generates a hash of the crate root file's path.
193
194    Args:
195        crate_root (File): The crate's root file (typically `lib.rs`).
196        label (Label): The label of the target.
197
198    Returns:
199        str: A string representation of the hash.
200    """
201
202    # Take the absolute value of hash() since it could be negative.
203    h = abs(hash(crate_root.path) + hash(repr(label)))
204    return repr(h)
205
206def get_preferred_artifact(library_to_link, use_pic):
207    """Get the first available library to link from a LibraryToLink object.
208
209    Args:
210        library_to_link (LibraryToLink): See the followg links for additional details:
211            https://docs.bazel.build/versions/master/skylark/lib/LibraryToLink.html
212        use_pic: If set, prefers pic_static_library over static_library.
213
214    Returns:
215        File: Returns the first valid library type (only one is expected)
216    """
217    if use_pic:
218        # Order consistent with https://github.com/bazelbuild/bazel/blob/815dfdabb7df31d4e99b6fc7616ff8e2f9385d98/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkingContext.java#L437.
219        return (
220            library_to_link.pic_static_library or
221            library_to_link.static_library or
222            library_to_link.interface_library or
223            library_to_link.dynamic_library
224        )
225    else:
226        return (
227            library_to_link.static_library or
228            library_to_link.pic_static_library or
229            library_to_link.interface_library or
230            library_to_link.dynamic_library
231        )
232
233# The normal ctx.expand_location, but with an additional deduplication step.
234# We do this to work around a potential crash, see
235# https://github.com/bazelbuild/bazel/issues/16664
236def dedup_expand_location(ctx, input, targets = []):
237    return ctx.expand_location(input, _deduplicate(targets))
238
239def _deduplicate(xs):
240    return {x: True for x in xs}.keys()
241
242def concat(xss):
243    return [x for xs in xss for x in xs]
244
245def _expand_location_for_build_script_runner(ctx, env, data, known_variables):
246    """A trivial helper for `expand_dict_value_locations` and `expand_list_element_locations`
247
248    Args:
249        ctx (ctx): The rule's context object
250        env (str): The value possibly containing location macros to expand.
251        data (sequence of Targets): See one of the parent functions.
252        known_variables (dict): Make variables (probably from toolchains) to substitute in when doing make variable expansion.
253
254    Returns:
255        string: The location-macro expanded version of the string.
256    """
257    for directive in ("$(execpath ", "$(location "):
258        if directive in env:
259            # build script runner will expand pwd to execroot for us
260            env = env.replace(directive, "$${pwd}/" + directive)
261    return ctx.expand_make_variables(
262        env,
263        dedup_expand_location(ctx, env, data),
264        known_variables,
265    )
266
267def expand_dict_value_locations(ctx, env, data, known_variables):
268    """Performs location-macro expansion on string values.
269
270    $(execroot ...) and $(location ...) are prefixed with ${pwd},
271    which process_wrapper and build_script_runner will expand at run time
272    to the absolute path. This is necessary because include_str!() is relative
273    to the currently compiled file, and build scripts run relative to the
274    manifest dir, so we can not use execroot-relative paths.
275
276    $(rootpath ...) is unmodified, and is useful for passing in paths via
277    rustc_env that are encoded in the binary with env!(), but utilized at
278    runtime, such as in tests. The absolute paths are not usable in this case,
279    as compilation happens in a separate sandbox folder, so when it comes time
280    to read the file at runtime, the path is no longer valid.
281
282    For detailed documentation, see:
283    - [`expand_location`](https://bazel.build/rules/lib/ctx#expand_location)
284    - [`expand_make_variables`](https://bazel.build/rules/lib/ctx#expand_make_variables)
285
286    Args:
287        ctx (ctx): The rule's context object
288        env (dict): A dict whose values we iterate over
289        data (sequence of Targets): The targets which may be referenced by
290            location macros. This is expected to be the `data` attribute of
291            the target, though may have other targets or attributes mixed in.
292        known_variables (dict): Make variables (probably from toolchains) to substitute in when doing make variable expansion.
293
294    Returns:
295        dict: A dict of environment variables with expanded location macros
296    """
297    return dict([(k, _expand_location_for_build_script_runner(ctx, v, data, known_variables)) for (k, v) in env.items()])
298
299def expand_list_element_locations(ctx, args, data, known_variables):
300    """Performs location-macro expansion on a list of string values.
301
302    $(execroot ...) and $(location ...) are prefixed with ${pwd},
303    which process_wrapper and build_script_runner will expand at run time
304    to the absolute path.
305
306    For detailed documentation, see:
307    - [`expand_location`](https://bazel.build/rules/lib/ctx#expand_location)
308    - [`expand_make_variables`](https://bazel.build/rules/lib/ctx#expand_make_variables)
309
310    Args:
311        ctx (ctx): The rule's context object
312        args (list): A list we iterate over
313        data (sequence of Targets): The targets which may be referenced by
314            location macros. This is expected to be the `data` attribute of
315            the target, though may have other targets or attributes mixed in.
316        known_variables (dict): Make variables (probably from toolchains) to substitute in when doing make variable expansion.
317
318    Returns:
319        list: A list of arguments with expanded location macros
320    """
321    return [_expand_location_for_build_script_runner(ctx, arg, data, known_variables) for arg in args]
322
323def name_to_crate_name(name):
324    """Converts a build target's name into the name of its associated crate.
325
326    Crate names cannot contain certain characters, such as -, which are allowed
327    in build target names. All illegal characters will be converted to
328    underscores.
329
330    This is a similar conversion as that which cargo does, taking a
331    `Cargo.toml`'s `package.name` and canonicalizing it
332
333    Note that targets can specify the `crate_name` attribute to customize their
334    crate name; in situations where this is important, use the
335    compute_crate_name() function instead.
336
337    Args:
338        name (str): The name of the target.
339
340    Returns:
341        str: The name of the crate for this target.
342    """
343    for illegal in ("-", "/"):
344        name = name.replace(illegal, "_")
345    return name
346
347def _invalid_chars_in_crate_name(name):
348    """Returns any invalid chars in the given crate name.
349
350    Args:
351        name (str): Name to test.
352
353    Returns:
354        list: List of invalid characters in the crate name.
355    """
356
357    return dict([(c, ()) for c in name.elems() if not (c.isalnum() or c == "_")]).keys()
358
359def compute_crate_name(workspace_name, label, toolchain, name_override = None):
360    """Returns the crate name to use for the current target.
361
362    Args:
363        workspace_name (string): The current workspace name.
364        label (struct): The label of the current target.
365        toolchain (struct): The toolchain in use for the target.
366        name_override (String): An optional name to use (as an override of label.name).
367
368    Returns:
369        str: The crate name to use for this target.
370    """
371    if name_override:
372        invalid_chars = _invalid_chars_in_crate_name(name_override)
373        if invalid_chars:
374            fail("Crate name '{}' contains invalid character(s): {}".format(
375                name_override,
376                " ".join(invalid_chars),
377            ))
378        return name_override
379
380    if (toolchain and label and toolchain._rename_first_party_crates and
381        should_encode_label_in_crate_name(workspace_name, label, toolchain._third_party_dir)):
382        crate_name = encode_label_as_crate_name(label.package, label.name)
383    else:
384        crate_name = name_to_crate_name(label.name)
385
386    invalid_chars = _invalid_chars_in_crate_name(crate_name)
387    if invalid_chars:
388        fail(
389            "Crate name '{}' ".format(crate_name) +
390            "derived from Bazel target name '{}' ".format(label.name) +
391            "contains invalid character(s): {}\n".format(" ".join(invalid_chars)) +
392            "Consider adding a crate_name attribute to set a valid crate name",
393        )
394    return crate_name
395
396def dedent(doc_string):
397    """Remove any common leading whitespace from every line in text.
398
399    This functionality is similar to python's `textwrap.dedent` functionality
400    https://docs.python.org/3/library/textwrap.html#textwrap.dedent
401
402    Args:
403        doc_string (str): A docstring style string
404
405    Returns:
406        str: A string optimized for stardoc rendering
407    """
408    lines = doc_string.splitlines()
409    if not lines:
410        return doc_string
411
412    # If the first line is empty, use the second line
413    first_line = lines[0]
414    if not first_line:
415        first_line = lines[1]
416
417    # Detect how much space prepends the first line and subtract that from all lines
418    space_count = len(first_line) - len(first_line.lstrip())
419
420    # If there are no leading spaces, do not alter the docstring
421    if space_count == 0:
422        return doc_string
423    else:
424        # Remove the leading block of spaces from the current line
425        block = " " * space_count
426        return "\n".join([line.replace(block, "", 1).rstrip() for line in lines])
427
428def make_static_lib_symlink(ctx_package, actions, rlib_file):
429    """Add a .a symlink to an .rlib file.
430
431    The name of the symlink is derived from the <name> of the <name>.rlib file as follows:
432    * `<name>.a`, if <name> starts with `lib`
433    * `lib<name>.a`, otherwise.
434
435    For example, the name of the symlink for
436    * `libcratea.rlib` is `libcratea.a`
437    * `crateb.rlib` is `libcrateb.a`.
438
439    Args:
440        ctx_package (string): The rule's context package name.
441        actions (actions): The rule's context actions object.
442        rlib_file (File): The file to symlink, which must end in .rlib.
443
444    Returns:
445        The symlink's File.
446    """
447
448    if not rlib_file.basename.endswith(".rlib"):
449        fail("file is not an .rlib: ", rlib_file.basename)
450    basename = rlib_file.basename[:-5]
451    if not basename.startswith("lib"):
452        basename = "lib" + basename
453
454    # The .a symlink below is created as a sibling to the .rlib file.
455    # Bazel doesn't allow creating a symlink outside of the rule's package,
456    # so if the .rlib file comes from a different package, first symlink it
457    # to the rule's package. The name of the new .rlib symlink is derived
458    # as the name of the original .rlib relative to its package.
459    if rlib_file.owner.package != ctx_package:
460        new_path = rlib_file.short_path.removeprefix(rlib_file.owner.package).removeprefix("/")
461        new_rlib_file = actions.declare_file(new_path)
462        actions.symlink(output = new_rlib_file, target_file = rlib_file)
463        rlib_file = new_rlib_file
464
465    dot_a = actions.declare_file(basename + ".a", sibling = rlib_file)
466    actions.symlink(output = dot_a, target_file = rlib_file)
467    return dot_a
468
469def is_exec_configuration(ctx):
470    """Determine if a context is building for the exec configuration.
471
472    This is helpful when processing command line flags that should apply
473    to the target configuration but not the exec configuration.
474
475    Args:
476        ctx (ctx): The ctx object for the current target.
477
478    Returns:
479        True if the exec configuration is detected, False otherwise.
480    """
481
482    # TODO(djmarcin): Is there any better way to determine cfg=exec?
483    return ctx.genfiles_dir.path.find("-exec") != -1
484
485def transform_deps(deps):
486    """Transforms a [Target] into [DepVariantInfo].
487
488    This helper function is used to transform ctx.attr.deps and ctx.attr.proc_macro_deps into
489    [DepVariantInfo].
490
491    Args:
492        deps (list of Targets): Dependencies coming from ctx.attr.deps or ctx.attr.proc_macro_deps
493
494    Returns:
495        list of DepVariantInfos.
496    """
497    return [DepVariantInfo(
498        crate_info = dep[CrateInfo] if CrateInfo in dep else None,
499        dep_info = dep[DepInfo] if DepInfo in dep else None,
500        build_info = dep[BuildInfo] if BuildInfo in dep else None,
501        cc_info = dep[CcInfo] if CcInfo in dep else None,
502        crate_group_info = dep[CrateGroupInfo] if CrateGroupInfo in dep else None,
503    ) for dep in deps]
504
505def get_import_macro_deps(ctx):
506    """Returns a list of targets to be added to proc_macro_deps.
507
508    Args:
509        ctx (struct): the ctx of the current target.
510
511    Returns:
512        list of Targets. Either empty (if the fake import macro implementation
513        is being used), or a singleton list with the real implementation.
514    """
515    if not hasattr(ctx.attr, "_import_macro_dep"):
516        return []
517
518    if ctx.attr._import_macro_dep.label.name == "fake_import_macro_impl":
519        return []
520
521    return [ctx.attr._import_macro_dep]
522
523def should_encode_label_in_crate_name(workspace_name, label, third_party_dir):
524    """Determines if the crate's name should include the Bazel label, encoded.
525
526    Crate names may only encode the label if the target is in the current repo,
527    the target is not in the third_party_dir, and the current repo is not
528    rules_rust.
529
530    Args:
531        workspace_name (string): The name of the current workspace.
532        label (Label): The package in question.
533        third_party_dir (string): The directory in which third-party packages are kept.
534
535    Returns:
536        True if the crate name should encode the label, False otherwise.
537    """
538
539    # TODO(hlopko): This code assumes a monorepo; make it work with external
540    # repositories as well.
541    return (
542        workspace_name != "rules_rust" and
543        not label.workspace_root and
544        not ("//" + label.package + "/").startswith(third_party_dir + "/")
545    )
546
547# This is a list of pairs, where the first element of the pair is a character
548# that is allowed in Bazel package or target names but not in crate names; and
549# the second element is an encoding of that char suitable for use in a crate
550# name.
551_encodings = (
552    (":", "x"),
553    ("!", "excl"),
554    ("%", "prc"),
555    ("@", "ao"),
556    ("^", "caret"),
557    ("`", "bt"),
558    (" ", "sp"),
559    ("\"", "dq"),
560    ("#", "octo"),
561    ("$", "dllr"),
562    ("&", "amp"),
563    ("'", "sq"),
564    ("(", "lp"),
565    (")", "rp"),
566    ("*", "astr"),
567    ("-", "d"),
568    ("+", "pl"),
569    (",", "cm"),
570    (";", "sm"),
571    ("<", "la"),
572    ("=", "eq"),
573    (">", "ra"),
574    ("?", "qm"),
575    ("[", "lbk"),
576    ("]", "rbk"),
577    ("{", "lbe"),
578    ("|", "pp"),
579    ("}", "rbe"),
580    ("~", "td"),
581    ("/", "y"),
582    (".", "pd"),
583)
584
585# For each of the above encodings, we generate two substitution rules: one that
586# ensures any occurrences of the encodings themselves in the package/target
587# aren't clobbered by this translation, and one that does the encoding itself.
588# We also include a rule that protects the clobbering-protection rules from
589# getting clobbered.
590_substitutions = [("_z", "_zz_")] + [
591    subst
592    for (pattern, replacement) in _encodings
593    for subst in (
594        ("_{}_".format(replacement), "_z{}_".format(replacement)),
595        (pattern, "_{}_".format(replacement)),
596    )
597]
598
599# Expose the substitutions for testing only.
600substitutions_for_testing = _substitutions
601
602def encode_label_as_crate_name(package, name):
603    """Encodes the package and target names in a format suitable for a crate name.
604
605    Args:
606        package (string): The package of the target in question.
607        name (string): The name of the target in question.
608
609    Returns:
610        A string that encodes the package and target name, to be used as the crate's name.
611    """
612    return _encode_raw_string(package + ":" + name)
613
614def _encode_raw_string(str):
615    """Encodes a string using the above encoding format.
616
617    Args:
618        str (string): The string to be encoded.
619
620    Returns:
621        An encoded version of the input string.
622    """
623    return _replace_all(str, _substitutions)
624
625# Expose the underlying encoding function for testing only.
626encode_raw_string_for_testing = _encode_raw_string
627
628def decode_crate_name_as_label_for_testing(crate_name):
629    """Decodes a crate_name that was encoded by encode_label_as_crate_name.
630
631    This is used to check that the encoding is bijective; it is expected to only
632    be used in tests.
633
634    Args:
635        crate_name (string): The name of the crate.
636
637    Returns:
638        A string representing the Bazel label (package and target).
639    """
640    return _replace_all(crate_name, [(t[1], t[0]) for t in _substitutions])
641
642def _replace_all(string, substitutions):
643    """Replaces occurrences of the given patterns in `string`.
644
645    There are a few reasons this looks complicated:
646    * The substitutions are performed with some priority, i.e. patterns that are
647      listed first in `substitutions` are higher priority than patterns that are
648      listed later.
649    * We also take pains to avoid doing replacements that overlap with each
650      other, since overlaps invalidate pattern matches.
651    * To avoid hairy offset invalidation, we apply the substitutions
652      right-to-left.
653    * To avoid the "_quote" -> "_quotequote_" rule introducing new pattern
654      matches later in the string during decoding, we take the leftmost
655      replacement, in cases of overlap.  (Note that no rule can induce new
656      pattern matches *earlier* in the string.) (E.g. "_quotedot_" encodes to
657      "_quotequote_dot_". Note that "_quotequote_" and "_dot_" both occur in
658      this string, and overlap.).
659
660    Args:
661        string (string): the string in which the replacements should be performed.
662        substitutions: the list of patterns and replacements to apply.
663
664    Returns:
665        A string with the appropriate substitutions performed.
666    """
667
668    # Find the highest-priority pattern matches for each string index, going
669    # left-to-right and skipping indices that are already involved in a
670    # pattern match.
671    plan = {}
672    matched_indices_set = {}
673    for pattern_start in range(len(string)):
674        if pattern_start in matched_indices_set:
675            continue
676        for (pattern, replacement) in substitutions:
677            if not string.startswith(pattern, pattern_start):
678                continue
679            length = len(pattern)
680            plan[pattern_start] = (length, replacement)
681            matched_indices_set.update([(pattern_start + i, True) for i in range(length)])
682            break
683
684    # Execute the replacement plan, working from right to left.
685    for pattern_start in sorted(plan.keys(), reverse = True):
686        length, replacement = plan[pattern_start]
687        after_pattern = pattern_start + length
688        string = string[:pattern_start] + replacement + string[after_pattern:]
689
690    return string
691
692def can_build_metadata(toolchain, ctx, crate_type):
693    """Can we build metadata for this rust_library?
694
695    Args:
696        toolchain (toolchain): The rust toolchain
697        ctx (ctx): The rule's context object
698        crate_type (String): one of lib|rlib|dylib|staticlib|cdylib|proc-macro
699
700    Returns:
701        bool: whether we can build metadata for this rule.
702    """
703
704    # In order to enable pipelined compilation we require that:
705    # 1) The _pipelined_compilation flag is enabled,
706    # 2) the OS running the rule is something other than windows as we require sandboxing (for now),
707    # 3) process_wrapper is enabled (this is disabled when compiling process_wrapper itself),
708    # 4) the crate_type is rlib or lib.
709    return toolchain._pipelined_compilation and \
710           toolchain.exec_triple.system != "windows" and \
711           ctx.attr._process_wrapper and \
712           crate_type in ("rlib", "lib")
713
714def crate_root_src(name, crate_name, srcs, crate_type):
715    """Determines the source file for the crate root, should it not be specified in `attr.crate_root`.
716
717    Args:
718        name (str): The name of the target.
719        crate_name (str): The target's `crate_name` attribute.
720        srcs (list): A list of all sources for the target Crate.
721        crate_type (str): The type of this crate ("bin", "lib", "rlib", "cdylib", etc).
722
723    Returns:
724        File: The root File object for a given crate. See the following links for more details:
725            - https://doc.rust-lang.org/cargo/reference/cargo-targets.html#library
726            - https://doc.rust-lang.org/cargo/reference/cargo-targets.html#binaries
727    """
728    default_crate_root_filename = "main.rs" if crate_type == "bin" else "lib.rs"
729
730    if not crate_name:
731        crate_name = name
732
733    crate_root = (
734        (srcs[0] if len(srcs) == 1 else None) or
735        _shortest_src_with_basename(srcs, default_crate_root_filename) or
736        _shortest_src_with_basename(srcs, name + ".rs") or
737        _shortest_src_with_basename(srcs, crate_name + ".rs")
738    )
739    if not crate_root:
740        file_names = [default_crate_root_filename, name + ".rs"]
741        fail("Couldn't find {} among `srcs`, please use `crate_root` to specify the root file.".format(" or ".join(file_names)))
742    return crate_root
743
744def _shortest_src_with_basename(srcs, basename):
745    """Finds the shortest among the paths in srcs that match the desired basename.
746
747    Args:
748        srcs (list): A list of File objects
749        basename (str): The target basename to match against.
750
751    Returns:
752        File: The File object with the shortest path that matches `basename`
753    """
754    shortest = None
755    for f in srcs:
756        if f.basename == basename:
757            if not shortest or len(f.dirname) < len(shortest.dirname):
758                shortest = f
759    return shortest
760
761def determine_lib_name(name, crate_type, toolchain, lib_hash = None):
762    """See https://github.com/bazelbuild/rules_rust/issues/405
763
764    Args:
765        name (str): The name of the current target
766        crate_type (str): The `crate_type`
767        toolchain (rust_toolchain): The current `rust_toolchain`
768        lib_hash (str, optional): The hashed crate root path
769
770    Returns:
771        str: A unique library name
772    """
773    extension = None
774    prefix = ""
775    if crate_type in ("dylib", "cdylib", "proc-macro"):
776        extension = toolchain.dylib_ext
777    elif crate_type == "staticlib":
778        extension = toolchain.staticlib_ext
779    elif crate_type in ("lib", "rlib"):
780        # All platforms produce 'rlib' here
781        extension = ".rlib"
782        prefix = "lib"
783    elif crate_type == "bin":
784        fail("crate_type of 'bin' was detected in a rust_library. Please compile " +
785             "this crate as a rust_binary instead.")
786
787    if not extension:
788        fail(("Unknown crate_type: {}. If this is a cargo-supported crate type, " +
789              "please file an issue!").format(crate_type))
790
791    prefix = "lib"
792    if toolchain.target_triple and toolchain.target_os == "windows" and crate_type not in ("lib", "rlib"):
793        prefix = ""
794    if toolchain.target_arch in ("wasm32", "wasm64") and crate_type == "cdylib":
795        prefix = ""
796
797    return "{prefix}{name}{lib_hash}{extension}".format(
798        prefix = prefix,
799        name = name,
800        lib_hash = "-" + lib_hash if lib_hash else "",
801        extension = extension,
802    )
803
804def transform_sources(ctx, srcs, crate_root):
805    """Creates symlinks of the source files if needed.
806
807    Rustc assumes that the source files are located next to the crate root.
808    In case of a mix between generated and non-generated source files, this
809    we violate this assumption, as part of the sources will be located under
810    bazel-out/... . In order to allow for targets that contain both generated
811    and non-generated source files, we generate symlinks for all non-generated
812    files.
813
814    Args:
815        ctx (struct): The current rule's context.
816        srcs (List[File]): The sources listed in the `srcs` attribute
817        crate_root (File): The file specified in the `crate_root` attribute,
818                           if it exists, otherwise None
819
820    Returns:
821        Tuple(List[File], File): The transformed srcs and crate_root
822    """
823    has_generated_sources = len([src for src in srcs if not src.is_source]) > 0
824
825    if not has_generated_sources:
826        return srcs, crate_root
827
828    package_root = paths.join(ctx.label.workspace_root, ctx.label.package)
829    generated_sources = [_symlink_for_non_generated_source(ctx, src, package_root) for src in srcs if src != crate_root]
830    generated_root = crate_root
831    if crate_root:
832        generated_root = _symlink_for_non_generated_source(ctx, crate_root, package_root)
833        generated_sources.append(generated_root)
834
835    return generated_sources, generated_root
836
837def get_edition(attr, toolchain, label):
838    """Returns the Rust edition from either the current rule's attributes or the current `rust_toolchain`
839
840    Args:
841        attr (struct): The current rule's attributes
842        toolchain (rust_toolchain): The `rust_toolchain` for the current target
843        label (Label): The label of the target being built
844
845    Returns:
846        str: The target Rust edition
847    """
848    if getattr(attr, "edition"):
849        return attr.edition
850    elif not toolchain.default_edition:
851        fail("Attribute `edition` is required for {}.".format(label))
852    else:
853        return toolchain.default_edition
854
855def _symlink_for_non_generated_source(ctx, src_file, package_root):
856    """Creates and returns a symlink for non-generated source files.
857
858    This rule uses the full path to the source files and the rule directory to compute
859    the relative paths. This is needed, instead of using `short_path`, because of non-generated
860    source files in external repositories possibly returning relative paths depending on the
861    current version of Bazel.
862
863    Args:
864        ctx (struct): The current rule's context.
865        src_file (File): The source file.
866        package_root (File): The full path to the directory containing the current rule.
867
868    Returns:
869        File: The created symlink if a non-generated file, or the file itself.
870    """
871
872    if src_file.is_source or src_file.root.path != ctx.bin_dir.path:
873        src_short_path = paths.relativize(src_file.path, src_file.root.path)
874        src_symlink = ctx.actions.declare_file(paths.relativize(src_short_path, package_root))
875        ctx.actions.symlink(
876            output = src_symlink,
877            target_file = src_file,
878            progress_message = "Creating symlink to source file: {}".format(src_file.path),
879        )
880        return src_symlink
881    else:
882        return src_file
883
884def generate_output_diagnostics(ctx, sibling, require_process_wrapper = True):
885    """Generates a .rustc-output file if it's required.
886
887    Args:
888        ctx: (ctx): The current rule's context object
889        sibling: (File): The file to generate the diagnostics for.
890        require_process_wrapper: (bool): Whether to require the process wrapper
891          in order to generate the .rustc-output file.
892    Returns:
893        Optional[File] The .rustc-object file, if generated.
894    """
895
896    # Since this feature requires error_format=json, we usually need
897    # process_wrapper, since it can write the json here, then convert it to the
898    # regular error format so the user can see the error properly.
899    if require_process_wrapper and not ctx.attr._process_wrapper:
900        return None
901    provider = ctx.attr._rustc_output_diagnostics[RustcOutputDiagnosticsInfo]
902    if not provider.rustc_output_diagnostics:
903        return None
904
905    return ctx.actions.declare_file(
906        sibling.basename + ".rustc-output",
907        sibling = sibling,
908    )
909
910def is_std_dylib(file):
911    """Whether the file is a dylib crate for std
912
913    """
914    basename = file.basename
915    return (
916        # for linux and darwin
917        basename.startswith("libstd-") and (basename.endswith(".so") or basename.endswith(".dylib")) or
918        # for windows
919        basename.startswith("std-") and basename.endswith(".dll")
920    )