fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
0e1297d3
patching
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 ): 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. 252 253Returns: 254string: The location-macro expanded version of the string. 255""" 256for directive in ( "$(execpath " , "$(location " ): 257if directive in env : 258# build script runner will expand pwd to execroot for us 259env = env . replace ( directive , "$${pwd}/" + directive ) 260return ctx . expand_make_variables ( 261env , 262dedup_expand_location ( ctx , env , data ), 263{}, 264) 265 266def expand_dict_value_locations ( ctx , env , data ): 267"""Performs location-macro expansion on string values. 268 269$(execroot ...) and $(location ...) are prefixed with ${pwd}, 270which process_wrapper and build_script_runner will expand at run time 271to the absolute path. This is necessary because include_str!() is relative 272to the currently compiled file, and build scripts run relative to the 273manifest dir, so we can not use execroot-relative paths. 274 275$(rootpath ...) is unmodified, and is useful for passing in paths via 276rustc_env that are encoded in the binary with env!(), but utilized at 277runtime, such as in tests. The absolute paths are not usable in this case, 278as compilation happens in a separate sandbox folder, so when it comes time 279to read the file at runtime, the path is no longer valid. 280 281For detailed documentation, see: 282- [`expand_location`](https://bazel.build/rules/lib/ctx#expand_location) 283- [`expand_make_variables`](https://bazel.build/rules/lib/ctx#expand_make_variables) 284 285Args: 286ctx (ctx): The rule's context object 287env (dict): A dict whose values we iterate over 288data (sequence of Targets): The targets which may be referenced by 289location macros. This is expected to be the `data` attribute of 290the target, though may have other targets or attributes mixed in. 291 292Returns: 293dict: A dict of environment variables with expanded location macros 294""" 295return dict ([( k , _expand_location_for_build_script_runner ( ctx , v , data )) for ( k , v ) in env . items ()]) 296 297def expand_list_element_locations ( ctx , args , data ): 298"""Performs location-macro expansion on a list of string values. 299 300$(execroot ...) and $(location ...) are prefixed with ${pwd}, 301which process_wrapper and build_script_runner will expand at run time 302to the absolute path. 303 304For detailed documentation, see: 305- [`expand_location`](https://bazel.build/rules/lib/ctx#expand_location) 306- [`expand_make_variables`](https://bazel.build/rules/lib/ctx#expand_make_variables) 307 308Args: 309ctx (ctx): The rule's context object 310args (list): A list we iterate over 311data (sequence of Targets): The targets which may be referenced by 312location macros. This is expected to be the `data` attribute of 313the target, though may have other targets or attributes mixed in. 314 315Returns: 316list: A list of arguments with expanded location macros 317""" 318return [ _expand_location_for_build_script_runner ( ctx , arg , data ) for arg in args ] 319 320def name_to_crate_name ( name ): 321"""Converts a build target's name into the name of its associated crate. 322 323Crate names cannot contain certain characters, such as -, which are allowed 324in build target names. All illegal characters will be converted to 325underscores. 326 327This is a similar conversion as that which cargo does, taking a 328`Cargo.toml`'s `package.name` and canonicalizing it 329 330Note that targets can specify the `crate_name` attribute to customize their 331crate name; in situations where this is important, use the 332compute_crate_name() function instead. 333 334Args: 335name (str): The name of the target. 336 337Returns: 338str: The name of the crate for this target. 339""" 340for illegal in ( "-" , "/" ): 341name = name . replace ( illegal , "_" ) 342return name 343 344def _invalid_chars_in_crate_name ( name ): 345"""Returns any invalid chars in the given crate name. 346 347Args: 348name (str): Name to test. 349 350Returns: 351list: List of invalid characters in the crate name. 352""" 353 354return dict ([( c , ( )) for c in name . elems () if not ( c . isalnum () or c == "_" )]). keys () 355 356def compute_crate_name ( workspace_name , label , toolchain , name_override = None ): 357"""Returns the crate name to use for the current target. 358 359Args: 360workspace_name (string): The current workspace name. 361label (struct): The label of the current target. 362toolchain (struct): The toolchain in use for the target. 363name_override (String): An optional name to use (as an override of label.name). 364 365Returns: 366str: The crate name to use for this target. 367""" 368if name_override : 369invalid_chars = _invalid_chars_in_crate_name ( name_override ) 370if invalid_chars : 371fail ( "Crate name '{}' contains invalid character(s): {}" . format ( 372name_override , 373" " . join ( invalid_chars ), 374)) 375return name_override 376 377if ( toolchain and label and toolchain . _rename_first_party_crates and 378should_encode_label_in_crate_name ( workspace_name , label , toolchain . _third_party_dir )): 379crate_name = encode_label_as_crate_name ( label . package , label . name ) 380else : 381crate_name = name_to_crate_name ( label . name ) 382 383invalid_chars = _invalid_chars_in_crate_name ( crate_name ) 384if invalid_chars : 385fail ( 386"Crate name '{}' " . format ( crate_name ) + 387"derived from Bazel target name '{}' " . format ( label . name ) + 388"contains invalid character(s): {}\n ".format(" " . join ( invalid_chars )) + 389"Consider adding a crate_name attribute to set a valid crate name" , 390) 391return crate_name 392 393def dedent ( doc_string ): 394"""Remove any common leading whitespace from every line in text. 395 396This functionality is similar to python's `textwrap.dedent` functionality 397https://docs.python.org/3/library/textwrap.html#textwrap.dedent 398 399Args: 400doc_string (str): A docstring style string 401 402Returns: 403str: A string optimized for stardoc rendering 404""" 405lines = doc_string . splitlines () 406if not lines : 407return doc_string 408 409# If the first line is empty, use the second line 410first_line = lines [ 0 ] 411if not first_line : 412first_line = lines [ 1 ] 413 414# Detect how much space prepends the first line and subtract that from all lines 415space_count = len ( first_line ) - len ( first_line . lstrip ()) 416 417# If there are no leading spaces, do not alter the docstring 418if space_count == 0 : 419return doc_string 420else : 421# Remove the leading block of spaces from the current line 422block = " " * space_count 423return "\n ".join([line.replace(block, " " , 1 ). rstrip () for line in lines ]) 424 425def make_static_lib_symlink ( ctx_package , actions , rlib_file ): 426"""Add a .a symlink to an .rlib file. 427 428The name of the symlink is derived from the <name> of the <name>.rlib file as follows: 429* `<name>.a`, if <name> starts with `lib` 430* `lib<name>.a`, otherwise. 431 432For example, the name of the symlink for 433* `libcratea.rlib` is `libcratea.a` 434* `crateb.rlib` is `libcrateb.a`. 435 436Args: 437ctx_package (string): The rule's context package name. 438actions (actions): The rule's context actions object. 439rlib_file (File): The file to symlink, which must end in .rlib. 440 441Returns: 442The symlink's File. 443""" 444 445if not rlib_file . basename . endswith ( ".rlib" ): 446fail ( "file is not an .rlib: " , rlib_file . basename ) 447basename = rlib_file . basename [: - 5 ] 448if not basename . startswith ( "lib" ): 449basename = "lib" + basename 450 451# The .a symlink below is created as a sibling to the .rlib file. 452# Bazel doesn't allow creating a symlink outside of the rule's package, 453# so if the .rlib file comes from a different package, first symlink it 454# to the rule's package. The name of the new .rlib symlink is derived 455# as the name of the original .rlib relative to its package. 456if rlib_file . owner . package != ctx_package : 457new_path = rlib_file . short_path . removeprefix ( rlib_file . owner . package ). removeprefix ( "/" ) 458new_rlib_file = actions . declare_file ( new_path ) 459actions . symlink ( output = new_rlib_file , target_file = rlib_file ) 460rlib_file = new_rlib_file 461 462dot_a = actions . declare_file ( basename + ".a" , sibling = rlib_file ) 463actions . symlink ( output = dot_a , target_file = rlib_file ) 464return dot_a 465 466def is_exec_configuration ( ctx ): 467"""Determine if a context is building for the exec configuration. 468 469This is helpful when processing command line flags that should apply 470to the target configuration but not the exec configuration. 471 472Args: 473ctx (ctx): The ctx object for the current target. 474 475Returns: 476True if the exec configuration is detected, False otherwise. 477""" 478 479# TODO(djmarcin): Is there any better way to determine cfg=exec? 480return ctx . genfiles_dir . path . find ( "-exec" ) != - 1 481 482def transform_deps ( deps ): 483"""Transforms a [Target] into [DepVariantInfo]. 484 485This helper function is used to transform ctx.attr.deps and ctx.attr.proc_macro_deps into 486[DepVariantInfo]. 487 488Args: 489deps (list of Targets): Dependencies coming from ctx.attr.deps or ctx.attr.proc_macro_deps 490 491Returns: 492list of DepVariantInfos. 493""" 494return [ DepVariantInfo ( 495crate_info = dep [ CrateInfo ] if CrateInfo in dep else None , 496dep_info = dep [ DepInfo ] if DepInfo in dep else None , 497build_info = dep [ BuildInfo ] if BuildInfo in dep else None , 498cc_info = dep [ CcInfo ] if CcInfo in dep else None , 499crate_group_info = dep [ CrateGroupInfo ] if CrateGroupInfo in dep else None , 500) for dep in deps ] 501 502def get_import_macro_deps ( ctx ): 503"""Returns a list of targets to be added to proc_macro_deps. 504 505Args: 506ctx (struct): the ctx of the current target. 507 508Returns: 509list of Targets. Either empty (if the fake import macro implementation 510is being used), or a singleton list with the real implementation. 511""" 512if not hasattr ( ctx . attr , "_import_macro_dep" ): 513return [] 514 515if ctx . attr . _import_macro_dep . label . name == "fake_import_macro_impl" : 516return [] 517 518return [ ctx . attr . _import_macro_dep ] 519 520def should_encode_label_in_crate_name ( workspace_name , label , third_party_dir ): 521"""Determines if the crate's name should include the Bazel label, encoded. 522 523Crate names may only encode the label if the target is in the current repo, 524the target is not in the third_party_dir, and the current repo is not 525rules_rust. 526 527Args: 528workspace_name (string): The name of the current workspace. 529label (Label): The package in question. 530third_party_dir (string): The directory in which third-party packages are kept. 531 532Returns: 533True if the crate name should encode the label, False otherwise. 534""" 535 536# TODO(hlopko): This code assumes a monorepo; make it work with external 537# repositories as well. 538return ( 539workspace_name != "rules_rust" and 540not label . workspace_root and 541not ( "//" + label . package + "/" ). startswith ( third_party_dir + "/" ) 542) 543 544# This is a list of pairs, where the first element of the pair is a character 545# that is allowed in Bazel package or target names but not in crate names; and 546# the second element is an encoding of that char suitable for use in a crate 547# name. 548_encodings = ( 549( ":" , "x" ), 550( "!" , "excl" ), 551( "%" , "prc" ), 552( "@" , "ao" ), 553( "^" , "caret" ), 554( "`" , "bt" ), 555( " " , "sp" ), 556( "\ "" , "dq" ), 557( " #", "octo"), 558(" $ ", " dllr " ), 559( "&" , "amp" ), 560( "'" , "sq" ), 561( "(" , "lp" ), 562( ")" , "rp" ), 563( "*" , "astr" ), 564( "-" , "d" ), 565( "+" , "pl" ), 566( "," , "cm" ), 567( ";" , "sm" ), 568( "<" , "la" ), 569( "=" , "eq" ), 570( ">" , "ra" ), 571( "?" , "qm" ), 572( "[" , "lbk" ), 573( "]" , "rbk" ), 574( "{" , "lbe" ), 575( "|" , "pp" ), 576( "}" , "rbe" ), 577( "~" , "td" ), 578( "/" , "y" ), 579( "." , "pd" ), 580) 581 582# For each of the above encodings, we generate two substitution rules: one that 583# ensures any occurrences of the encodings themselves in the package/target 584# aren't clobbered by this translation, and one that does the encoding itself. 585# We also include a rule that protects the clobbering-protection rules from 586# getting clobbered. 587_substitutions = [( "_z" , "_zz_" )] + [ 588subst 589for ( pattern , replacement ) in _encodings 590for subst in ( 591( "_{}_" . format ( replacement ), "_z{}_" . format ( replacement )), 592( pattern , "_{}_" . format ( replacement )), 593) 594] 595 596# Expose the substitutions for testing only. 597substitutions_for_testing = _substitutions 598 599def encode_label_as_crate_name ( package , name ): 600"""Encodes the package and target names in a format suitable for a crate name. 601 602Args: 603package (string): The package of the target in question. 604name (string): The name of the target in question. 605 606Returns: 607A string that encodes the package and target name, to be used as the crate's name. 608""" 609return _encode_raw_string ( package + ":" + name ) 610 611def _encode_raw_string ( str ): 612"""Encodes a string using the above encoding format. 613 614Args: 615str (string): The string to be encoded. 616 617Returns: 618An encoded version of the input string. 619""" 620return _replace_all ( str , _substitutions ) 621 622# Expose the underlying encoding function for testing only. 623encode_raw_string_for_testing = _encode_raw_string 624 625def decode_crate_name_as_label_for_testing ( crate_name ): 626"""Decodes a crate_name that was encoded by encode_label_as_crate_name. 627 628This is used to check that the encoding is bijective; it is expected to only 629be used in tests. 630 631Args: 632crate_name (string): The name of the crate. 633 634Returns: 635A string representing the Bazel label (package and target). 636""" 637return _replace_all ( crate_name , [( t [ 1 ], t [ 0 ]) for t in _substitutions ]) 638 639def _replace_all ( string , substitutions ): 640"""Replaces occurrences of the given patterns in `string`. 641 642There are a few reasons this looks complicated: 643* The substitutions are performed with some priority, i.e. patterns that are 644listed first in `substitutions` are higher priority than patterns that are 645listed later. 646* We also take pains to avoid doing replacements that overlap with each 647other, since overlaps invalidate pattern matches. 648* To avoid hairy offset invalidation, we apply the substitutions 649right-to-left. 650* To avoid the "_quote" -> "_quotequote_" rule introducing new pattern 651matches later in the string during decoding, we take the leftmost 652replacement, in cases of overlap. (Note that no rule can induce new 653pattern matches *earlier* in the string.) (E.g. "_quotedot_" encodes to 654"_quotequote_dot_". Note that "_quotequote_" and "_dot_" both occur in 655this string, and overlap.). 656 657Args: 658string (string): the string in which the replacements should be performed. 659substitutions: the list of patterns and replacements to apply. 660 661Returns: 662A string with the appropriate substitutions performed. 663""" 664 665# Find the highest-priority pattern matches for each string index, going 666# left-to-right and skipping indices that are already involved in a 667# pattern match. 668plan = {} 669matched_indices_set = {} 670for pattern_start in range ( len ( string )): 671if pattern_start in matched_indices_set : 672continue 673for ( pattern , replacement ) in substitutions : 674if not string . startswith ( pattern , pattern_start ): 675continue 676length = len ( pattern ) 677plan [ pattern_start ] = ( length , replacement ) 678matched_indices_set . update ([( pattern_start + i , True ) for i in range ( length )]) 679break 680 681# Execute the replacement plan, working from right to left. 682for pattern_start in sorted ( plan . keys (), reverse = True ): 683length , replacement = plan [ pattern_start ] 684after_pattern = pattern_start + length 685string = string [: pattern_start ] + replacement + string [ after_pattern :] 686 687return string 688 689def can_build_metadata ( toolchain , ctx , crate_type ): 690"""Can we build metadata for this rust_library? 691 692Args: 693toolchain (toolchain): The rust toolchain 694ctx (ctx): The rule's context object 695crate_type (String): one of lib|rlib|dylib|staticlib|cdylib|proc-macro 696 697Returns: 698bool: whether we can build metadata for this rule. 699""" 700 701# In order to enable pipelined compilation we require that: 702# 1) The _pipelined_compilation flag is enabled, 703# 2) the OS running the rule is something other than windows as we require sandboxing (for now), 704# 3) process_wrapper is enabled (this is disabled when compiling process_wrapper itself), 705# 4) the crate_type is rlib or lib. 706return toolchain . _pipelined_compilation and \ 707toolchain . exec_triple . system != "windows" and \ 708ctx . attr . _process_wrapper and \ 709crate_type in ( "rlib" , "lib" ) 710 711def crate_root_src ( name , srcs , crate_type ): 712"""Determines the source file for the crate root, should it not be specified in `attr.crate_root`. 713 714Args: 715name (str): The name of the target. 716srcs (list): A list of all sources for the target Crate. 717crate_type (str): The type of this crate ("bin", "lib", "rlib", "cdylib", etc). 718 719Returns: 720File: The root File object for a given crate. See the following links for more details: 721- https://doc.rust-lang.org/cargo/reference/cargo-targets.html#library 722- https://doc.rust-lang.org/cargo/reference/cargo-targets.html#binaries 723""" 724default_crate_root_filename = "main.rs" if crate_type == "bin" else "lib.rs" 725 726crate_root = ( 727( srcs [ 0 ] if len ( srcs ) == 1 else None ) or 728_shortest_src_with_basename ( srcs , default_crate_root_filename ) or 729_shortest_src_with_basename ( srcs , name + ".rs" ) 730) 731if not crate_root : 732file_names = [ default_crate_root_filename , name + ".rs" ] 733fail ( "Couldn't find {} among `srcs`, please use `crate_root` to specify the root file." . format ( " or " . join ( file_names ))) 734return crate_root 735 736def _shortest_src_with_basename ( srcs , basename ): 737"""Finds the shortest among the paths in srcs that match the desired basename. 738 739Args: 740srcs (list): A list of File objects 741basename (str): The target basename to match against. 742 743Returns: 744File: The File object with the shortest path that matches `basename` 745""" 746shortest = None 747for f in srcs : 748if f . basename == basename : 749if not shortest or len ( f . dirname ) < len ( shortest . dirname ): 750shortest = f 751return shortest 752 753def determine_lib_name ( name , crate_type , toolchain , lib_hash = None ): 754"""See https://github.com/bazelbuild/rules_rust/issues/405 755 756Args: 757name (str): The name of the current target 758crate_type (str): The `crate_type` 759toolchain (rust_toolchain): The current `rust_toolchain` 760lib_hash (str, optional): The hashed crate root path 761 762Returns: 763str: A unique library name 764""" 765extension = None 766prefix = "" 767if crate_type in ( "dylib" , "cdylib" , "proc-macro" ): 768extension = toolchain . dylib_ext 769elif crate_type == "staticlib" : 770extension = toolchain . staticlib_ext 771elif crate_type in ( "lib" , "rlib" ): 772# All platforms produce 'rlib' here 773extension = ".rlib" 774prefix = "lib" 775elif crate_type == "bin" : 776fail ( "crate_type of 'bin' was detected in a rust_library. Please compile " + 777"this crate as a rust_binary instead." ) 778 779if not extension : 780fail (( "Unknown crate_type: {}. If this is a cargo-supported crate type, " + 781"please file an issue!" ). format ( crate_type )) 782 783prefix = "lib" 784if toolchain . target_triple and toolchain . target_os == "windows" and crate_type not in ( "lib" , "rlib" ): 785prefix = "" 786if toolchain . target_arch == "wasm32" and crate_type == "cdylib" : 787prefix = "" 788 789return "{prefix}{name}{lib_hash}{extension}" . format ( 790prefix = prefix , 791name = name , 792lib_hash = "-" + lib_hash if lib_hash else "" , 793extension = extension , 794) 795 796def transform_sources ( ctx , srcs , crate_root ): 797"""Creates symlinks of the source files if needed. 798 799Rustc assumes that the source files are located next to the crate root. 800In case of a mix between generated and non-generated source files, this 801we violate this assumption, as part of the sources will be located under 802bazel-out/... . In order to allow for targets that contain both generated 803and non-generated source files, we generate symlinks for all non-generated 804files. 805 806Args: 807ctx (struct): The current rule's context. 808srcs (List[File]): The sources listed in the `srcs` attribute 809crate_root (File): The file specified in the `crate_root` attribute, 810if it exists, otherwise None 811 812Returns: 813Tuple(List[File], File): The transformed srcs and crate_root 814""" 815has_generated_sources = len ([ src for src in srcs if not src . is_source ]) > 0 816 817if not has_generated_sources : 818return srcs , crate_root 819 820package_root = paths . join ( ctx . label . workspace_root , ctx . label . package ) 821generated_sources = [ _symlink_for_non_generated_source ( ctx , src , package_root ) for src in srcs if src != crate_root ] 822generated_root = crate_root 823if crate_root : 824generated_root = _symlink_for_non_generated_source ( ctx , crate_root , package_root ) 825generated_sources . append ( generated_root ) 826 827return generated_sources , generated_root 828 829def get_edition ( attr , toolchain , label ): 830"""Returns the Rust edition from either the current rule's attributes or the current `rust_toolchain` 831 832Args: 833attr (struct): The current rule's attributes 834toolchain (rust_toolchain): The `rust_toolchain` for the current target 835label (Label): The label of the target being built 836 837Returns: 838str: The target Rust edition 839""" 840if getattr ( attr , "edition" ): 841return attr . edition 842elif not toolchain . default_edition : 843fail ( "Attribute `edition` is required for {}." . format ( label )) 844else : 845return toolchain . default_edition 846 847def _symlink_for_non_generated_source ( ctx , src_file , package_root ): 848"""Creates and returns a symlink for non-generated source files. 849 850This rule uses the full path to the source files and the rule directory to compute 851the relative paths. This is needed, instead of using `short_path`, because of non-generated 852source files in external repositories possibly returning relative paths depending on the 853current version of Bazel. 854 855Args: 856ctx (struct): The current rule's context. 857src_file (File): The source file. 858package_root (File): The full path to the directory containing the current rule. 859 860Returns: 861File: The created symlink if a non-generated file, or the file itself. 862""" 863 864if src_file . is_source or src_file . root . path != ctx . bin_dir . path : 865src_short_path = paths . relativize ( src_file . path , src_file . root . path ) 866src_symlink = ctx . actions . declare_file ( paths . relativize ( src_short_path , package_root )) 867ctx . actions . symlink ( 868output = src_symlink , 869target_file = src_file , 870progress_message = "Creating symlink to source file: {}" . format ( src_file . path ), 871) 872return src_symlink 873else : 874return src_file 875 876def generate_output_diagnostics ( ctx , sibling , require_process_wrapper = True ): 877"""Generates a .rustc-output file if it's required. 878 879Args: 880ctx: (ctx): The current rule's context object 881sibling: (File): The file to generate the diagnostics for. 882require_process_wrapper: (bool): Whether to require the process wrapper 883in order to generate the .rustc-output file. 884Returns: 885Optional[File] The .rustc-object file, if generated. 886""" 887 888# Since this feature requires error_format=json, we usually need 889# process_wrapper, since it can write the json here, then convert it to the 890# regular error format so the user can see the error properly. 891if require_process_wrapper and not ctx . attr . _process_wrapper : 892return None 893provider = ctx . attr . _rustc_output_diagnostics [ RustcOutputDiagnosticsInfo ] 894if not provider . rustc_output_diagnostics : 895return None 896 897return ctx . actions . declare_file ( 898sibling . basename + ".rustc-output" , 899sibling = sibling , 900) 901 902def is_std_dylib ( file ): 903"""Whether the file is a dylib crate for std 904 905""" 906basename = file . basename 907return ( 908# for linux and darwin 909basename . startswith ( "libstd-" ) and ( basename . endswith ( ".so" ) or basename . endswith ( ".dylib" )) or 910# for windows 911basename . startswith ( "std-" ) and basename . endswith ( ".dll" ) 912)