fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
4e593b6c
cleanup
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 36Args: 37ctx (ctx): The ctx object for the current target. 38 39Returns: 40rust_toolchain: A Rust toolchain context. 41""" 42return 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 47Args: 48ctx (ctx): The current target's rule context object 49extra_unsupported_features (sequence of str): Extra featrures to disable 50 51Returns: 52tuple: A tuple of (CcToolchain, FeatureConfiguration) 53""" 54cc_toolchain = find_rules_cc_toolchain ( ctx ) 55 56feature_configuration = cc_common . configure_features ( 57ctx = ctx , 58cc_toolchain = cc_toolchain , 59requested_features = ctx . features , 60unsupported_features = UNSUPPORTED_FEATURES + ctx . disabled_features + 61list ( extra_unsupported_features ), 62) 63return 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 70Args: 71path (str): The path to relativize. 72start (str): The ancestor path against which to relativize. 73 74Returns: 75str: The portion of `path` that is relative to `start`. 76""" 77src_parts = _path_parts ( start ) 78dest_parts = _path_parts ( path ) 79n = 0 80for src_part , dest_part in zip ( src_parts , dest_parts ): 81if src_part != dest_part : 82 break 83n += 1 84 85relative_path = "" 86for _ in range ( n , len ( src_parts )): 87relative_path += "../" 88relative_path += "/" . join ( dest_parts [ n :]) 89 90return relative_path 91 92def _path_parts ( path ): 93"""Takes a path and returns a list of its parts with all "." elements removed. 94 95The main use case of this function is if one of the inputs to relativize() 96is a relative path, such as "./foo". 97 98Args: 99path (str): A string representing a unix path 100 101Returns: 102list: A list containing the path parts with all "." elements removed. 103""" 104path_parts = path . split ( "/" ) 105return [ part for part in path_parts if part != "." ] 106 107def get_lib_name_default ( lib ): 108"""Returns the name of a library artifact. 109 110Args: 111lib (File): A library file 112 113Returns: 114str: 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. 125comps = lib . basename . split ( "." ) 126for comp in reversed ( comps ): 127if comp . isdigit (): 128comps . pop () 129else : 130 break 131 132# The library name is now everything minus the extension. 133libname = "." . join ( comps [: - 1 ]) 134 135if libname . startswith ( "lib" ): 136return libname [ 3 :] 137else : 138return 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 151Args: 152lib (File): A library file 153 154Returns: 155str: 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. 166comps = lib . basename . split ( "." ) 167for comp in reversed ( comps ): 168if comp . isdigit (): 169comps . pop () 170else : 171 break 172 173# The library name is now everything minus the extension. 174libname = "." . join ( comps [: - 1 ]) 175 176return libname 177 178def abs ( value ): 179"""Returns the absolute value of a number. 180 181Args: 182value (int): A number. 183 184Returns: 185int: The absolute value of the number. 186""" 187if value < 0 : 188return - value 189return value 190 191def determine_output_hash ( crate_root , label ): 192"""Generates a hash of the crate root file's path. 193 194Args: 195crate_root (File): The crate's root file (typically `lib.rs`). 196label (Label): The label of the target. 197 198Returns: 199str: A string representation of the hash. 200""" 201 202# Take the absolute value of hash() since it could be negative. 203h = abs ( hash ( crate_root . path ) + hash ( repr ( label ))) 204return 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 209Args: 210library_to_link (LibraryToLink): See the followg links for additional details: 211https://docs.bazel.build/versions/master/skylark/lib/LibraryToLink.html 212use_pic: If set, prefers pic_static_library over static_library. 213 214Returns: 215File: Returns the first valid library type (only one is expected) 216""" 217if 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. 219return ( 220library_to_link . pic_static_library or 221library_to_link . static_library or 222library_to_link . interface_library or 223library_to_link . dynamic_library 224) 225else : 226return ( 227library_to_link . static_library or 228library_to_link . pic_static_library or 229library_to_link . interface_library or 230library_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 = []): 237return ctx . expand_location ( input , _deduplicate ( targets )) 238 239def _deduplicate ( xs ): 240return { x : True for x in xs }. keys () 241 242def concat ( xss ): 243return [ 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 248Args: 249ctx (ctx): The rule's context object 250env (str): The value possibly containing location macros to expand. 251data (sequence of Targets): See one of the parent functions. 252known_variables (dict): Make variables (probably from toolchains) to substitute in when doing make variable expansion. 253 254Returns: 255string: The location-macro expanded version of the string. 256""" 257for directive in ( "$(execpath " , "$(location " ): 258if directive in env : 259# build script runner will expand pwd to execroot for us 260env = env . replace ( directive , "$${pwd}/" + directive ) 261return ctx . expand_make_variables ( 262env , 263dedup_expand_location ( ctx , env , data ), 264known_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}, 271which process_wrapper and build_script_runner will expand at run time 272to the absolute path. This is necessary because include_str!() is relative 273to the currently compiled file, and build scripts run relative to the 274manifest dir, so we can not use execroot-relative paths. 275 276$(rootpath ...) is unmodified, and is useful for passing in paths via 277rustc_env that are encoded in the binary with env!(), but utilized at 278runtime, such as in tests. The absolute paths are not usable in this case, 279as compilation happens in a separate sandbox folder, so when it comes time 280to read the file at runtime, the path is no longer valid. 281 282For 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 286Args: 287ctx (ctx): The rule's context object 288env (dict): A dict whose values we iterate over 289data (sequence of Targets): The targets which may be referenced by 290location macros. This is expected to be the `data` attribute of 291the target, though may have other targets or attributes mixed in. 292known_variables (dict): Make variables (probably from toolchains) to substitute in when doing make variable expansion. 293 294Returns: 295dict: A dict of environment variables with expanded location macros 296""" 297return 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}, 303which process_wrapper and build_script_runner will expand at run time 304to the absolute path. 305 306For 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 310Args: 311ctx (ctx): The rule's context object 312args (list): A list we iterate over 313data (sequence of Targets): The targets which may be referenced by 314location macros. This is expected to be the `data` attribute of 315the target, though may have other targets or attributes mixed in. 316known_variables (dict): Make variables (probably from toolchains) to substitute in when doing make variable expansion. 317 318Returns: 319list: A list of arguments with expanded location macros 320""" 321return [ _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 326Crate names cannot contain certain characters, such as -, which are allowed 327in build target names. All illegal characters will be converted to 328underscores. 329 330This is a similar conversion as that which cargo does, taking a 331`Cargo.toml`'s `package.name` and canonicalizing it 332 333Note that targets can specify the `crate_name` attribute to customize their 334crate name; in situations where this is important, use the 335compute_crate_name() function instead. 336 337Args: 338name (str): The name of the target. 339 340Returns: 341str: The name of the crate for this target. 342""" 343for illegal in ( "-" , "/" ): 344name = name . replace ( illegal , "_" ) 345return name 346 347def _invalid_chars_in_crate_name ( name ): 348"""Returns any invalid chars in the given crate name. 349 350Args: 351name (str): Name to test. 352 353Returns: 354list: List of invalid characters in the crate name. 355""" 356 357return 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 362Args: 363workspace_name (string): The current workspace name. 364label (struct): The label of the current target. 365toolchain (struct): The toolchain in use for the target. 366name_override (String): An optional name to use (as an override of label.name). 367 368Returns: 369str: The crate name to use for this target. 370""" 371if name_override : 372invalid_chars = _invalid_chars_in_crate_name ( name_override ) 373if invalid_chars : 374fail ( "Crate name '{}' contains invalid character(s): {}" . format ( 375name_override , 376" " . join ( invalid_chars ), 377)) 378return name_override 379 380if ( toolchain and label and toolchain . _rename_first_party_crates and 381should_encode_label_in_crate_name ( workspace_name , label , toolchain . _third_party_dir )): 382crate_name = encode_label_as_crate_name ( label . package , label . name ) 383else : 384crate_name = name_to_crate_name ( label . name ) 385 386invalid_chars = _invalid_chars_in_crate_name ( crate_name ) 387if invalid_chars : 388fail ( 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) 394return crate_name 395 396def dedent ( doc_string ): 397"""Remove any common leading whitespace from every line in text. 398 399This functionality is similar to python's `textwrap.dedent` functionality 400https://docs.python.org/3/library/textwrap.html#textwrap.dedent 401 402Args: 403doc_string (str): A docstring style string 404 405Returns: 406str: A string optimized for stardoc rendering 407""" 408lines = doc_string . splitlines () 409if not lines : 410return doc_string 411 412# If the first line is empty, use the second line 413first_line = lines [ 0 ] 414if not first_line : 415first_line = lines [ 1 ] 416 417# Detect how much space prepends the first line and subtract that from all lines 418space_count = len ( first_line ) - len ( first_line . lstrip ()) 419 420# If there are no leading spaces, do not alter the docstring 421if space_count == 0 : 422return doc_string 423else : 424# Remove the leading block of spaces from the current line 425block = " " * space_count 426return "\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 431The 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 435For example, the name of the symlink for 436* `libcratea.rlib` is `libcratea.a` 437* `crateb.rlib` is `libcrateb.a`. 438 439Args: 440ctx_package (string): The rule's context package name. 441actions (actions): The rule's context actions object. 442rlib_file (File): The file to symlink, which must end in .rlib. 443 444Returns: 445The symlink's File. 446""" 447 448if not rlib_file . basename . endswith ( ".rlib" ): 449fail ( "file is not an .rlib: " , rlib_file . basename ) 450basename = rlib_file . basename [: - 5 ] 451if not basename . startswith ( "lib" ): 452basename = "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. 459if rlib_file . owner . package != ctx_package : 460new_path = rlib_file . short_path . removeprefix ( rlib_file . owner . package ). removeprefix ( "/" ) 461new_rlib_file = actions . declare_file ( new_path ) 462actions . symlink ( output = new_rlib_file , target_file = rlib_file ) 463rlib_file = new_rlib_file 464 465dot_a = actions . declare_file ( basename + ".a" , sibling = rlib_file ) 466actions . symlink ( output = dot_a , target_file = rlib_file ) 467return dot_a 468 469def is_exec_configuration ( ctx ): 470"""Determine if a context is building for the exec configuration. 471 472This is helpful when processing command line flags that should apply 473to the target configuration but not the exec configuration. 474 475Args: 476ctx (ctx): The ctx object for the current target. 477 478Returns: 479True if the exec configuration is detected, False otherwise. 480""" 481 482# TODO(djmarcin): Is there any better way to determine cfg=exec? 483return ctx . genfiles_dir . path . find ( "-exec" ) != - 1 484 485def transform_deps ( deps ): 486"""Transforms a [Target] into [DepVariantInfo]. 487 488This helper function is used to transform ctx.attr.deps and ctx.attr.proc_macro_deps into 489[DepVariantInfo]. 490 491Args: 492deps (list of Targets): Dependencies coming from ctx.attr.deps or ctx.attr.proc_macro_deps 493 494Returns: 495list of DepVariantInfos. 496""" 497return [ DepVariantInfo ( 498crate_info = dep [ CrateInfo ] if CrateInfo in dep else None , 499dep_info = dep [ DepInfo ] if DepInfo in dep else None , 500build_info = dep [ BuildInfo ] if BuildInfo in dep else None , 501cc_info = dep [ CcInfo ] if CcInfo in dep else None , 502crate_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 508Args: 509ctx (struct): the ctx of the current target. 510 511Returns: 512list of Targets. Either empty (if the fake import macro implementation 513is being used), or a singleton list with the real implementation. 514""" 515if not hasattr ( ctx . attr , "_import_macro_dep" ): 516return [] 517 518if ctx . attr . _import_macro_dep . label . name == "fake_import_macro_impl" : 519return [] 520 521return [ 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 526Crate names may only encode the label if the target is in the current repo, 527the target is not in the third_party_dir, and the current repo is not 528rules_rust. 529 530Args: 531workspace_name (string): The name of the current workspace. 532label (Label): The package in question. 533third_party_dir (string): The directory in which third-party packages are kept. 534 535Returns: 536True 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. 541return ( 542workspace_name != "rules_rust" and 543not label . workspace_root and 544not ( "//" + 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_" )] + [ 591subst 592for ( pattern , replacement ) in _encodings 593for 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 605Args: 606package (string): The package of the target in question. 607name (string): The name of the target in question. 608 609Returns: 610A string that encodes the package and target name, to be used as the crate's name. 611""" 612return _encode_raw_string ( package + ":" + name ) 613 614def _encode_raw_string ( str ): 615"""Encodes a string using the above encoding format. 616 617Args: 618str (string): The string to be encoded. 619 620Returns: 621An encoded version of the input string. 622""" 623return _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 631This is used to check that the encoding is bijective; it is expected to only 632be used in tests. 633 634Args: 635crate_name (string): The name of the crate. 636 637Returns: 638A string representing the Bazel label (package and target). 639""" 640return _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 645There are a few reasons this looks complicated: 646* The substitutions are performed with some priority, i.e. patterns that are 647listed first in `substitutions` are higher priority than patterns that are 648listed later. 649* We also take pains to avoid doing replacements that overlap with each 650other, since overlaps invalidate pattern matches. 651* To avoid hairy offset invalidation, we apply the substitutions 652right-to-left. 653* To avoid the "_quote" -> "_quotequote_" rule introducing new pattern 654matches later in the string during decoding, we take the leftmost 655replacement, in cases of overlap. (Note that no rule can induce new 656pattern matches *earlier* in the string.) (E.g. "_quotedot_" encodes to 657"_quotequote_dot_". Note that "_quotequote_" and "_dot_" both occur in 658this string, and overlap.). 659 660Args: 661string (string): the string in which the replacements should be performed. 662substitutions: the list of patterns and replacements to apply. 663 664Returns: 665A 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. 671plan = {} 672matched_indices_set = {} 673for pattern_start in range ( len ( string )): 674if pattern_start in matched_indices_set : 675continue 676for ( pattern , replacement ) in substitutions : 677if not string . startswith ( pattern , pattern_start ): 678continue 679length = len ( pattern ) 680plan [ pattern_start ] = ( length , replacement ) 681matched_indices_set . update ([( pattern_start + i , True ) for i in range ( length )]) 682break 683 684# Execute the replacement plan, working from right to left. 685for pattern_start in sorted ( plan . keys (), reverse = True ): 686length , replacement = plan [ pattern_start ] 687after_pattern = pattern_start + length 688string = string [: pattern_start ] + replacement + string [ after_pattern :] 689 690return string 691 692def can_build_metadata ( toolchain , ctx , crate_type ): 693"""Can we build metadata for this rust_library? 694 695Args: 696toolchain (toolchain): The rust toolchain 697ctx (ctx): The rule's context object 698crate_type (String): one of lib|rlib|dylib|staticlib|cdylib|proc-macro 699 700Returns: 701bool: 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. 709return toolchain . _pipelined_compilation and \ 710toolchain . exec_triple . system != "windows" and \ 711ctx . attr . _process_wrapper and \ 712crate_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 717Args: 718name (str): The name of the target. 719crate_name (str): The target's `crate_name` attribute. 720srcs (list): A list of all sources for the target Crate. 721crate_type (str): The type of this crate ("bin", "lib", "rlib", "cdylib", etc). 722 723Returns: 724File: 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""" 728default_crate_root_filename = "main.rs" if crate_type == "bin" else "lib.rs" 729 730if not crate_name : 731crate_name = name 732 733crate_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) 739if not crate_root : 740file_names = [ default_crate_root_filename , name + ".rs" ] 741fail ( "Couldn't find {} among `srcs`, please use `crate_root` to specify the root file." . format ( " or " . join ( file_names ))) 742return 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 747Args: 748srcs (list): A list of File objects 749basename (str): The target basename to match against. 750 751Returns: 752File: The File object with the shortest path that matches `basename` 753""" 754shortest = None 755for f in srcs : 756if f . basename == basename : 757if not shortest or len ( f . dirname ) < len ( shortest . dirname ): 758shortest = f 759return shortest 760 761def determine_lib_name ( name , crate_type , toolchain , lib_hash = None ): 762"""See https://github.com/bazelbuild/rules_rust/issues/405 763 764Args: 765name (str): The name of the current target 766crate_type (str): The `crate_type` 767toolchain (rust_toolchain): The current `rust_toolchain` 768lib_hash (str, optional): The hashed crate root path 769 770Returns: 771str: A unique library name 772""" 773extension = None 774prefix = "" 775if crate_type in ( "dylib" , "cdylib" , "proc-macro" ): 776extension = toolchain . dylib_ext 777elif crate_type == "staticlib" : 778extension = toolchain . staticlib_ext 779elif crate_type in ( "lib" , "rlib" ): 780# All platforms produce 'rlib' here 781extension = ".rlib" 782prefix = "lib" 783elif crate_type == "bin" : 784fail ( "crate_type of 'bin' was detected in a rust_library. Please compile " + 785"this crate as a rust_binary instead." ) 786 787if not extension : 788fail (( "Unknown crate_type: {}. If this is a cargo-supported crate type, " + 789"please file an issue!" ). format ( crate_type )) 790 791prefix = "lib" 792if toolchain . target_triple and toolchain . target_os == "windows" and crate_type not in ( "lib" , "rlib" ): 793prefix = "" 794if toolchain . target_arch in ( "wasm32" , "wasm64" ) and crate_type == "cdylib" : 795prefix = "" 796 797return "{prefix}{name}{lib_hash}{extension}" . format ( 798prefix = prefix , 799name = name , 800lib_hash = "-" + lib_hash if lib_hash else "" , 801extension = extension , 802) 803 804def transform_sources ( ctx , srcs , crate_root ): 805"""Creates symlinks of the source files if needed. 806 807Rustc assumes that the source files are located next to the crate root. 808In case of a mix between generated and non-generated source files, this 809we violate this assumption, as part of the sources will be located under 810bazel-out/... . In order to allow for targets that contain both generated 811and non-generated source files, we generate symlinks for all non-generated 812files. 813 814Args: 815ctx (struct): The current rule's context. 816srcs (List[File]): The sources listed in the `srcs` attribute 817crate_root (File): The file specified in the `crate_root` attribute, 818if it exists, otherwise None 819 820Returns: 821Tuple(List[File], File): The transformed srcs and crate_root 822""" 823has_generated_sources = len ([ src for src in srcs if not src . is_source ]) > 0 824 825if not has_generated_sources : 826return srcs , crate_root 827 828package_root = paths . join ( ctx . label . workspace_root , ctx . label . package ) 829generated_sources = [ _symlink_for_non_generated_source ( ctx , src , package_root ) for src in srcs if src != crate_root ] 830generated_root = crate_root 831if crate_root : 832generated_root = _symlink_for_non_generated_source ( ctx , crate_root , package_root ) 833generated_sources . append ( generated_root ) 834 835return 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 840Args: 841attr (struct): The current rule's attributes 842toolchain (rust_toolchain): The `rust_toolchain` for the current target 843label (Label): The label of the target being built 844 845Returns: 846str: The target Rust edition 847""" 848if getattr ( attr , "edition" ): 849return attr . edition 850elif not toolchain . default_edition : 851fail ( "Attribute `edition` is required for {}." . format ( label )) 852else : 853return 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 858This rule uses the full path to the source files and the rule directory to compute 859the relative paths. This is needed, instead of using `short_path`, because of non-generated 860source files in external repositories possibly returning relative paths depending on the 861current version of Bazel. 862 863Args: 864ctx (struct): The current rule's context. 865src_file (File): The source file. 866package_root (File): The full path to the directory containing the current rule. 867 868Returns: 869File: The created symlink if a non-generated file, or the file itself. 870""" 871 872if src_file . is_source or src_file . root . path != ctx . bin_dir . path : 873src_short_path = paths . relativize ( src_file . path , src_file . root . path ) 874src_symlink = ctx . actions . declare_file ( paths . relativize ( src_short_path , package_root )) 875ctx . actions . symlink ( 876output = src_symlink , 877target_file = src_file , 878progress_message = "Creating symlink to source file: {}" . format ( src_file . path ), 879) 880return src_symlink 881else : 882return src_file 883 884def generate_output_diagnostics ( ctx , sibling , require_process_wrapper = True ): 885"""Generates a .rustc-output file if it's required. 886 887Args: 888ctx: (ctx): The current rule's context object 889sibling: (File): The file to generate the diagnostics for. 890require_process_wrapper: (bool): Whether to require the process wrapper 891in order to generate the .rustc-output file. 892Returns: 893Optional[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. 899if require_process_wrapper and not ctx . attr . _process_wrapper : 900return None 901provider = ctx . attr . _rustc_output_diagnostics [ RustcOutputDiagnosticsInfo ] 902if not provider . rustc_output_diagnostics : 903return None 904 905return ctx . actions . declare_file ( 906sibling . basename + ".rustc-output" , 907sibling = sibling , 908) 909 910def is_std_dylib ( file ): 911"""Whether the file is a dylib crate for std 912 913""" 914basename = file . basename 915return ( 916# for linux and darwin 917basename . startswith ( "libstd-" ) and ( basename . endswith ( ".so" ) or basename . endswith ( ".dylib" )) or 918# for windows 919basename . startswith ( "std-" ) and basename . endswith ( ".dll" ) 920)