fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
a066bfed
0.5.0
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_tools//tools/cpp:toolchain_utils.bzl" , find_rules_cc_toolchain = "find_cpp_toolchain" ) 18load ( ":providers.bzl" , "BuildInfo" , "CrateInfo" , "DepInfo" , "DepVariantInfo" ) 19 20UNSUPPORTED_FEATURES = [ 21"thin_lto" , 22"module_maps" , 23"use_header_modules" , 24"fdo_instrument" , 25"fdo_optimize" , 26] 27 28def find_toolchain ( ctx ): 29"""Finds the first rust toolchain that is configured. 30 31Args: 32ctx (ctx): The ctx object for the current target. 33 34Returns: 35rust_toolchain: A Rust toolchain context. 36""" 37return ctx . toolchains [ Label ( "//rust:toolchain" )] 38 39def find_cc_toolchain ( ctx ): 40"""Extracts a CcToolchain from the current target's context 41 42Args: 43ctx (ctx): The current target's rule context object 44 45Returns: 46tuple: A tuple of (CcToolchain, FeatureConfiguration) 47""" 48cc_toolchain = find_rules_cc_toolchain ( ctx ) 49 50feature_configuration = cc_common . configure_features ( 51ctx = ctx , 52cc_toolchain = cc_toolchain , 53requested_features = ctx . features , 54unsupported_features = UNSUPPORTED_FEATURES + ctx . disabled_features , 55) 56return cc_toolchain , feature_configuration 57 58# TODO: Replace with bazel-skylib's `path.dirname`. This requires addressing some 59# dependency issues or generating docs will break. 60def relativize ( path , start ): 61"""Returns the relative path from start to path. 62 63Args: 64path (str): The path to relativize. 65start (str): The ancestor path against which to relativize. 66 67Returns: 68str: The portion of `path` that is relative to `start`. 69""" 70src_parts = _path_parts ( start ) 71dest_parts = _path_parts ( path ) 72n = 0 73for src_part , dest_part in zip ( src_parts , dest_parts ): 74if src_part != dest_part : 75 break 76n += 1 77 78relative_path = "" 79for _ in range ( n , len ( src_parts )): 80relative_path += "../" 81relative_path += "/" . join ( dest_parts [ n :]) 82 83return relative_path 84 85def _path_parts ( path ): 86"""Takes a path and returns a list of its parts with all "." elements removed. 87 88The main use case of this function is if one of the inputs to relativize() 89is a relative path, such as "./foo". 90 91Args: 92path (str): A string representing a unix path 93 94Returns: 95list: A list containing the path parts with all "." elements removed. 96""" 97path_parts = path . split ( "/" ) 98return [ part for part in path_parts if part != "." ] 99 100def get_lib_name ( lib ): 101"""Returns the name of a library artifact, eg. libabc.a -> abc 102 103Args: 104lib (File): A library file 105 106Returns: 107str: The name of the library 108""" 109# On macos and windows, dynamic/static libraries always end with the 110# extension and potential versions will be before the extension, and should 111# be part of the library name. 112# On linux, the version usually comes after the extension. 113# So regardless of the platform we want to find the extension and make 114# everything left to it the library name. 115 116# Search for the extension - starting from the right - by removing any 117# trailing digit. 118comps = lib . basename . split ( "." ) 119for comp in reversed ( comps ): 120if comp . isdigit (): 121comps . pop () 122else : 123 break 124 125# The library name is now everything minus the extension. 126libname = "." . join ( comps [: - 1 ]) 127 128if libname . startswith ( "lib" ): 129return libname [ 3 :] 130else : 131return libname 132 133def abs ( value ): 134"""Returns the absolute value of a number. 135 136Args: 137value (int): A number. 138 139Returns: 140int: The absolute value of the number. 141""" 142if value < 0 : 143return - value 144return value 145 146def determine_output_hash ( crate_root , label ): 147"""Generates a hash of the crate root file's path. 148 149Args: 150crate_root (File): The crate's root file (typically `lib.rs`). 151label (Label): The label of the target. 152 153Returns: 154str: A string representation of the hash. 155""" 156 157# Take the absolute value of hash() since it could be negative. 158h = abs ( hash ( crate_root . path ) + hash ( repr ( label ))) 159return repr ( h ) 160 161def get_preferred_artifact ( library_to_link , use_pic ): 162"""Get the first available library to link from a LibraryToLink object. 163 164Args: 165library_to_link (LibraryToLink): See the followg links for additional details: 166https://docs.bazel.build/versions/master/skylark/lib/LibraryToLink.html 167use_pic: If set, prefers pic_static_library over static_library. 168 169Returns: 170File: Returns the first valid library type (only one is expected) 171""" 172if use_pic : 173# Order consistent with https://github.com/bazelbuild/bazel/blob/815dfdabb7df31d4e99b6fc7616ff8e2f9385d98/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkingContext.java#L437. 174return ( 175library_to_link . pic_static_library or 176library_to_link . static_library or 177library_to_link . interface_library or 178library_to_link . dynamic_library 179) 180else : 181return ( 182library_to_link . static_library or 183library_to_link . pic_static_library or 184library_to_link . interface_library or 185library_to_link . dynamic_library 186) 187 188def _expand_location ( ctx , env , data ): 189"""A trivial helper for `_expand_locations` 190 191Args: 192ctx (ctx): The rule's context object 193env (str): The value possibly containing location macros to expand. 194data (sequence of Targets): see `_expand_locations` 195 196Returns: 197string: The location-macro expanded version of the string. 198""" 199for directive in ( "$(execpath " , "$(location " ): 200if directive in env : 201# build script runner will expand pwd to execroot for us 202env = env . replace ( directive , "${pwd}/" + directive ) 203return ctx . expand_location ( env , data ) 204 205def expand_dict_value_locations ( ctx , env , data ): 206"""Performs location-macro expansion on string values. 207 208$(execroot ...) and $(location ...) are prefixed with ${pwd}, 209which process_wrapper and build_script_runner will expand at run time 210to the absolute path. This is necessary because include_str!() is relative 211to the currently compiled file, and build scripts run relative to the 212manifest dir, so we can not use execroot-relative paths. 213 214$(rootpath ...) is unmodified, and is useful for passing in paths via 215rustc_env that are encoded in the binary with env!(), but utilized at 216runtime, such as in tests. The absolute paths are not usable in this case, 217as compilation happens in a separate sandbox folder, so when it comes time 218to read the file at runtime, the path is no longer valid. 219 220See [`expand_location`](https://docs.bazel.build/versions/main/skylark/lib/ctx.html#expand_location) for detailed documentation. 221 222Args: 223ctx (ctx): The rule's context object 224env (dict): A dict whose values we iterate over 225data (sequence of Targets): The targets which may be referenced by 226location macros. This is expected to be the `data` attribute of 227the target, though may have other targets or attributes mixed in. 228 229Returns: 230dict: A dict of environment variables with expanded location macros 231""" 232return dict ([( k , _expand_location ( ctx , v , data )) for ( k , v ) in env . items ()]) 233 234def expand_list_element_locations ( ctx , args , data ): 235"""Performs location-macro expansion on a list of string values. 236 237$(execroot ...) and $(location ...) are prefixed with ${pwd}, 238which process_wrapper and build_script_runner will expand at run time 239to the absolute path. 240 241See [`expand_location`](https://docs.bazel.build/versions/main/skylark/lib/ctx.html#expand_location) for detailed documentation. 242 243Args: 244ctx (ctx): The rule's context object 245args (list): A list we iterate over 246data (sequence of Targets): The targets which may be referenced by 247location macros. This is expected to be the `data` attribute of 248the target, though may have other targets or attributes mixed in. 249 250Returns: 251list: A list of arguments with expanded location macros 252""" 253return [ _expand_location ( ctx , arg , data ) for arg in args ] 254 255def name_to_crate_name ( name ): 256"""Converts a build target's name into the name of its associated crate. 257 258Crate names cannot contain certain characters, such as -, which are allowed 259in build target names. All illegal characters will be converted to 260underscores. 261 262This is a similar conversion as that which cargo does, taking a 263`Cargo.toml`'s `package.name` and canonicalizing it 264 265Note that targets can specify the `crate_name` attribute to customize their 266crate name; in situations where this is important, use the 267compute_crate_name() function instead. 268 269Args: 270name (str): The name of the target. 271 272Returns: 273str: The name of the crate for this target. 274""" 275for illegal in ( "-" , "/" ): 276name = name . replace ( illegal , "_" ) 277return name 278 279def _invalid_chars_in_crate_name ( name ): 280"""Returns any invalid chars in the given crate name. 281 282Args: 283name (str): Name to test. 284 285Returns: 286list: List of invalid characters in the crate name. 287""" 288 289return dict ([( c , ( )) for c in name . elems () if not ( c . isalnum () or c == "_" )]). keys () 290 291def compute_crate_name ( workspace_name , label , toolchain , name_override = None ): 292"""Returns the crate name to use for the current target. 293 294Args: 295workspace_name (string): The current workspace name. 296label (struct): The label of the current target. 297toolchain (struct): The toolchain in use for the target. 298name_override (String): An optional name to use (as an override of label.name). 299 300Returns: 301str: The crate name to use for this target. 302""" 303if name_override : 304invalid_chars = _invalid_chars_in_crate_name ( name_override ) 305if invalid_chars : 306fail ( "Crate name '{}' contains invalid character(s): {}" . format ( 307name_override , 308" " . join ( invalid_chars ), 309)) 310return name_override 311 312if ( toolchain and label and toolchain . _rename_first_party_crates and 313should_encode_label_in_crate_name ( workspace_name , label , toolchain . _third_party_dir )): 314crate_name = encode_label_as_crate_name ( label . package , label . name ) 315else : 316crate_name = name_to_crate_name ( label . name ) 317 318invalid_chars = _invalid_chars_in_crate_name ( crate_name ) 319if invalid_chars : 320fail ( 321"Crate name '{}' " . format ( crate_name ) + 322"derived from Bazel target name '{}' " . format ( label . name ) + 323"contains invalid character(s): {}\n ".format(" " . join ( invalid_chars )) + 324"Consider adding a crate_name attribute to set a valid crate name" , 325) 326return crate_name 327 328def dedent ( doc_string ): 329"""Remove any common leading whitespace from every line in text. 330 331This functionality is similar to python's `textwrap.dedent` functionality 332https://docs.python.org/3/library/textwrap.html#textwrap.dedent 333 334Args: 335doc_string (str): A docstring style string 336 337Returns: 338str: A string optimized for stardoc rendering 339""" 340lines = doc_string . splitlines () 341if not lines : 342return doc_string 343 344# If the first line is empty, use the second line 345first_line = lines [ 0 ] 346if not first_line : 347first_line = lines [ 1 ] 348 349# Detect how much space prepends the first line and subtract that from all lines 350space_count = len ( first_line ) - len ( first_line . lstrip ()) 351 352# If there are no leading spaces, do not alter the docstring 353if space_count == 0 : 354return doc_string 355else : 356# Remove the leading block of spaces from the current line 357block = " " * space_count 358return "\n ".join([line.replace(block, " " , 1 ). rstrip () for line in lines ]) 359 360def make_static_lib_symlink ( actions , rlib_file ): 361"""Add a .a symlink to an .rlib file. 362 363The name of the symlink is derived from the <name> of the <name>.rlib file as follows: 364* `<name>.a`, if <name> starts with `lib` 365* `lib<name>.a`, otherwise. 366 367For example, the name of the symlink for 368* `libcratea.rlib` is `libcratea.a` 369* `crateb.rlib` is `libcrateb.a`. 370 371Args: 372actions (actions): The rule's context actions object. 373rlib_file (File): The file to symlink, which must end in .rlib. 374 375Returns: 376The symlink's File. 377""" 378if not rlib_file . basename . endswith ( ".rlib" ): 379fail ( "file is not an .rlib: " , rlib_file . basename ) 380basename = rlib_file . basename [: - 5 ] 381if not basename . startswith ( "lib" ): 382basename = "lib" + basename 383dot_a = actions . declare_file ( basename + ".a" , sibling = rlib_file ) 384actions . symlink ( output = dot_a , target_file = rlib_file ) 385return dot_a 386 387def is_exec_configuration ( ctx ): 388"""Determine if a context is building for the exec configuration. 389 390This is helpful when processing command line flags that should apply 391to the target configuration but not the exec configuration. 392 393Args: 394ctx (ctx): The ctx object for the current target. 395 396Returns: 397True if the exec configuration is detected, False otherwise. 398""" 399 400# TODO(djmarcin): Is there any better way to determine cfg=exec? 401return ctx . genfiles_dir . path . find ( "-exec-" ) != - 1 402 403def transform_deps ( deps ): 404"""Transforms a [Target] into [DepVariantInfo]. 405 406This helper function is used to transform ctx.attr.deps and ctx.attr.proc_macro_deps into 407[DepVariantInfo]. 408 409Args: 410deps (list of Targets): Dependencies coming from ctx.attr.deps or ctx.attr.proc_macro_deps 411 412Returns: 413list of DepVariantInfos. 414""" 415return [ DepVariantInfo ( 416crate_info = dep [ CrateInfo ] if CrateInfo in dep else None , 417dep_info = dep [ DepInfo ] if DepInfo in dep else None , 418build_info = dep [ BuildInfo ] if BuildInfo in dep else None , 419cc_info = dep [ CcInfo ] if CcInfo in dep else None , 420) for dep in deps ] 421 422def get_import_macro_deps ( ctx ): 423"""Returns a list of targets to be added to proc_macro_deps. 424 425Args: 426ctx (struct): the ctx of the current target. 427 428Returns: 429list of Targets. Either empty (if the fake import macro implementation 430is being used), or a singleton list with the real implementation. 431""" 432if ctx . attr . _import_macro_dep . label . name == "fake_import_macro_impl" : 433return [] 434 435return [ ctx . attr . _import_macro_dep ] 436 437def should_encode_label_in_crate_name ( workspace_name , label , third_party_dir ): 438"""Determines if the crate's name should include the Bazel label, encoded. 439 440Crate names may only encode the label if the target is in the current repo, 441the target is not in the third_party_dir, and the current repo is not 442rules_rust. 443 444Args: 445workspace_name (string): The name of the current workspace. 446label (Label): The package in question. 447third_party_dir (string): The directory in which third-party packages are kept. 448 449Returns: 450True if the crate name should encode the label, False otherwise. 451""" 452 453# TODO(hlopko): This code assumes a monorepo; make it work with external 454# repositories as well. 455return ( 456workspace_name != "rules_rust" and 457not label . workspace_root and 458not ( "//" + label . package + "/" ). startswith ( third_party_dir + "/" ) 459) 460 461# This is a list of pairs, where the first element of the pair is a character 462# that is allowed in Bazel package or target names but not in crate names; and 463# the second element is an encoding of that char suitable for use in a crate 464# name. 465_encodings = ( 466( ":" , "colon" ), 467( "!" , "bang" ), 468( "%" , "percent" ), 469( "@" , "at" ), 470( "^" , "caret" ), 471( "`" , "backtick" ), 472( " " , "space" ), 473( "\ "" , "quote" ), 474( " #", "hash"), 475(" $ ", " dollar " ), 476( "&" , "ampersand" ), 477( "'" , "backslash" ), 478( "(" , "lparen" ), 479( ")" , "rparen" ), 480( "*" , "star" ), 481( "-" , "dash" ), 482( "+" , "plus" ), 483( "," , "comma" ), 484( ";" , "semicolon" ), 485( "<" , "langle" ), 486( "=" , "equal" ), 487( ">" , "rangle" ), 488( "?" , "question" ), 489( "[" , "lbracket" ), 490( "]" , "rbracket" ), 491( "{" , "lbrace" ), 492( "|" , "pipe" ), 493( "}" , "rbrace" ), 494( "~" , "tilde" ), 495( "/" , "slash" ), 496( "." , "dot" ), 497) 498 499# For each of the above encodings, we generate two substitution rules: one that 500# ensures any occurrences of the encodings themselves in the package/target 501# aren't clobbered by this translation, and one that does the encoding itself. 502# We also include a rule that protects the clobbering-protection rules from 503# getting clobbered. 504_substitutions = [( "_quote" , "_quotequote_" )] + [ 505subst 506for ( pattern , replacement ) in _encodings 507for subst in ( 508( "_{}_" . format ( replacement ), "_quote{}_" . format ( replacement )), 509( pattern , "_{}_" . format ( replacement )), 510) 511] 512 513def encode_label_as_crate_name ( package , name ): 514"""Encodes the package and target names in a format suitable for a crate name. 515 516Args: 517package (string): The package of the target in question. 518name (string): The name of the target in question. 519 520Returns: 521A string that encodes the package and target name, to be used as the crate's name. 522""" 523full_name = package + ":" + name 524return _replace_all ( full_name , _substitutions ) 525 526def decode_crate_name_as_label_for_testing ( crate_name ): 527"""Decodes a crate_name that was encoded by encode_label_as_crate_name. 528 529This is used to check that the encoding is bijective; it is expected to only 530be used in tests. 531 532Args: 533crate_name (string): The name of the crate. 534 535Returns: 536A string representing the Bazel label (package and target). 537""" 538return _replace_all ( crate_name , [( t [ 1 ], t [ 0 ]) for t in _substitutions ]) 539 540def _replace_all ( string , substitutions ): 541"""Replaces occurrences of the given patterns in `string`. 542 543There are a few reasons this looks complicated: 544* The substitutions are performed with some priority, i.e. patterns that are 545listed first in `substitutions` are higher priority than patterns that are 546listed later. 547* We also take pains to avoid doing replacements that overlap with each 548other, since overlaps invalidate pattern matches. 549* To avoid hairy offset invalidation, we apply the substitutions 550right-to-left. 551* To avoid the "_quote" -> "_quotequote_" rule introducing new pattern 552matches later in the string during decoding, we take the leftmost 553replacement, in cases of overlap. (Note that no rule can induce new 554pattern matches *earlier* in the string.) (E.g. "_quotedot_" encodes to 555"_quotequote_dot_". Note that "_quotequote_" and "_dot_" both occur in 556this string, and overlap.). 557 558Args: 559string (string): the string in which the replacements should be performed. 560substitutions: the list of patterns and replacements to apply. 561 562Returns: 563A string with the appropriate substitutions performed. 564""" 565 566# Find the highest-priority pattern matches for each string index, going 567# left-to-right and skipping indices that are already involved in a 568# pattern match. 569plan = {} 570matched_indices_set = {} 571for pattern_start in range ( len ( string )): 572if pattern_start in matched_indices_set : 573continue 574for ( pattern , replacement ) in substitutions : 575if not string . startswith ( pattern , pattern_start ): 576continue 577length = len ( pattern ) 578plan [ pattern_start ] = ( length , replacement ) 579matched_indices_set . update ([( pattern_start + i , True ) for i in range ( length )]) 580break 581 582# Execute the replacement plan, working from right to left. 583for pattern_start in sorted ( plan . keys (), reverse = True ): 584length , replacement = plan [ pattern_start ] 585after_pattern = pattern_start + length 586string = string [: pattern_start ] + replacement + string [ after_pattern :] 587 588return string