fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
74f164b9
cleanup
1# Copyright 2020 Google 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""" 16Rust Analyzer Bazel rules. 17 18rust_analyzer will generate a rust-project.json file for the 19given targets. This file can be consumed by rust-analyzer as an alternative 20to Cargo.toml files. 21""" 22 23load ( "//rust/platform:triple_mappings.bzl" , "system_to_dylib_ext" , "triple_to_system" ) 24load ( "//rust/private:common.bzl" , "rust_common" ) 25load ( "//rust/private:providers.bzl" , "RustAnalyzerGroupInfo" , "RustAnalyzerInfo" ) 26load ( "//rust/private:rustc.bzl" , "BuildInfo" ) 27load ( 28"//rust/private:utils.bzl" , 29"concat" , 30"dedent" , 31"dedup_expand_location" , 32"find_toolchain" , 33) 34 35def write_rust_analyzer_spec_file ( ctx , attrs , owner , base_info ): 36"""Write a rust-analyzer spec info file. 37 38Args: 39ctx (ctx): The current rule's context object. 40attrs (dict): A mapping of attributes. 41owner (Label): The label of the owner of the spec info. 42base_info (RustAnalyzerInfo): The data the resulting RustAnalyzerInfo is based on. 43 44Returns: 45RustAnalyzerInfo: Info with the embedded spec file. 46""" 47crate_spec = ctx . actions . declare_file ( "{}.rust_analyzer_crate_spec.json" . format ( owner . name )) 48 49# Recreate the provider with the spec file embedded in it. 50rust_analyzer_info = RustAnalyzerInfo ( 51aliases = base_info . aliases , 52crate = base_info . crate , 53cfgs = base_info . cfgs , 54env = base_info . env , 55deps = base_info . deps , 56crate_specs = depset ( direct = [ crate_spec ], transitive = [ base_info . crate_specs ]), 57proc_macro_dylib_path = base_info . proc_macro_dylib_path , 58build_info = base_info . build_info , 59) 60 61ctx . actions . write ( 62output = crate_spec , 63content = json . encode_indent ( 64_create_single_crate ( 65ctx , 66attrs , 67rust_analyzer_info , 68), 69indent = " " * 4 , 70), 71) 72 73return rust_analyzer_info 74 75def _accumulate_rust_analyzer_info ( dep_infos_to_accumulate , label_index_to_accumulate , dep ): 76if dep == None : 77return 78if RustAnalyzerInfo in dep : 79label_index_to_accumulate [ dep . label ] = dep [ RustAnalyzerInfo ] 80dep_infos_to_accumulate . append ( dep [ RustAnalyzerInfo ]) 81if RustAnalyzerGroupInfo in dep : 82for expanded_dep in dep [ RustAnalyzerGroupInfo ]. deps : 83label_index_to_accumulate [ expanded_dep . crate . owner ] = expanded_dep 84dep_infos_to_accumulate . append ( expanded_dep ) 85 86def _accumulate_rust_analyzer_infos ( dep_infos_to_accumulate , label_index_to_accumulate , deps_attr ): 87for dep in deps_attr : 88_accumulate_rust_analyzer_info ( dep_infos_to_accumulate , label_index_to_accumulate , dep ) 89 90def _rust_analyzer_aspect_impl ( target , ctx ): 91if ( rust_common . crate_info not in target and 92rust_common . test_crate_info not in target and 93rust_common . crate_group_info not in target ): 94return [] 95 96if RustAnalyzerInfo in target or RustAnalyzerGroupInfo in target : 97return [] 98 99toolchain = find_toolchain ( ctx ) 100 101# Always add `test` & `debug_assertions`. See rust-analyzer source code: 102# https://github.com/rust-analyzer/rust-analyzer/blob/2021-11-15/crates/project_model/src/workspace.rs#L529-L531 103cfgs = [ "test" , "debug_assertions" ] 104if hasattr ( ctx . rule . attr , "crate_features" ): 105cfgs += [ 'feature="{}"' . format ( f ) for f in ctx . rule . attr . crate_features ] 106if hasattr ( ctx . rule . attr , "rustc_flags" ): 107cfgs += [ f [ 6 :] for f in ctx . rule . attr . rustc_flags if f . startswith ( "--cfg " ) or f . startswith ( "--cfg=" )] 108 109build_info = None 110dep_infos = [] 111labels_to_rais = {} 112 113for dep in getattr ( ctx . rule . attr , "deps" , []): 114# Save BuildInfo if we find any (for build script output) 115if BuildInfo in dep : 116build_info = dep [ BuildInfo ] 117 118_accumulate_rust_analyzer_infos ( dep_infos , labels_to_rais , getattr ( ctx . rule . attr , "deps" , [])) 119_accumulate_rust_analyzer_infos ( dep_infos , labels_to_rais , getattr ( ctx . rule . attr , "proc_macro_deps" , [])) 120 121_accumulate_rust_analyzer_info ( dep_infos , labels_to_rais , getattr ( ctx . rule . attr , "crate" , None )) 122_accumulate_rust_analyzer_info ( dep_infos , labels_to_rais , getattr ( ctx . rule . attr , "actual" , None )) 123 124if rust_common . crate_group_info in target : 125return [ RustAnalyzerGroupInfo ( deps = dep_infos )] 126elif rust_common . crate_info in target : 127crate_info = target [ rust_common . crate_info ] 128elif rust_common . test_crate_info in target : 129crate_info = target [ rust_common . test_crate_info ]. crate 130else : 131fail ( "Unexpected target type: {}" . format ( target )) 132 133aliases = {} 134for aliased_target , aliased_name in getattr ( ctx . rule . attr , "aliases" , {}). items (): 135if aliased_target . label in labels_to_rais : 136aliases [ labels_to_rais [ aliased_target . label ]] = aliased_name 137 138rust_analyzer_info = write_rust_analyzer_spec_file ( ctx , ctx . rule . attr , ctx . label , RustAnalyzerInfo ( 139aliases = aliases , 140crate = crate_info , 141cfgs = cfgs , 142env = crate_info . rustc_env , 143deps = dep_infos , 144crate_specs = depset ( transitive = [ dep . crate_specs for dep in dep_infos ]), 145proc_macro_dylib_path = find_proc_macro_dylib_path ( toolchain , target ), 146build_info = build_info , 147)) 148 149return [ 150rust_analyzer_info , 151OutputGroupInfo ( rust_analyzer_crate_spec = rust_analyzer_info . crate_specs ), 152] 153 154def find_proc_macro_dylib_path ( toolchain , target ): 155"""Find the proc_macro_dylib_path of target. Returns None if target crate is not type proc-macro. 156 157Args: 158toolchain: The current rust toolchain. 159target: The current target. 160Returns: 161(path): The path to the proc macro dylib, or None if this crate is not a proc-macro. 162""" 163if rust_common . crate_info in target : 164crate_info = target [ rust_common . crate_info ] 165elif rust_common . test_crate_info in target : 166crate_info = target [ rust_common . test_crate_info ]. crate 167else : 168return None 169 170if crate_info . type != "proc-macro" : 171return None 172 173dylib_ext = system_to_dylib_ext ( triple_to_system ( toolchain . target_triple )) 174for action in target . actions : 175for output in action . outputs . to_list (): 176if output . extension == dylib_ext [ 1 :]: 177return output . path 178 179# Failed to find the dylib path inside a proc-macro crate. 180# TODO: Should this be an error? 181return None 182 183rust_analyzer_aspect = aspect ( 184attr_aspects = [ "deps" , "proc_macro_deps" , "crate" , "actual" , "proto" ], 185implementation = _rust_analyzer_aspect_impl , 186toolchains = [ str ( Label ( "//rust:toolchain_type" ))], 187doc = "Annotates rust rules with RustAnalyzerInfo later used to build a rust-project.json" , 188) 189 190# Paths in the generated JSON file begin with one of these placeholders. 191# The gen_rust_project driver will replace them with absolute paths. 192_WORKSPACE_TEMPLATE = "__WORKSPACE__/" 193_EXEC_ROOT_TEMPLATE = "__EXEC_ROOT__/" 194_OUTPUT_BASE_TEMPLATE = "__OUTPUT_BASE__/" 195 196def _crate_id ( crate_info ): 197"""Returns a unique stable identifier for a crate 198 199Returns: 200(string): This crate's unique stable id. 201""" 202return "ID-" + crate_info . root . path 203 204def _create_single_crate ( ctx , attrs , info ): 205"""Creates a crate in the rust-project.json format. 206 207Args: 208ctx (ctx): The rule context. 209attrs (dict): A mapping of attributes. 210info (RustAnalyzerInfo): RustAnalyzerInfo for the current crate. 211 212Returns: 213(dict) The crate rust-project.json representation 214""" 215crate_name = info . crate . name 216crate = dict () 217crate_id = _crate_id ( info . crate ) 218crate [ "crate_id" ] = crate_id 219crate [ "display_name" ] = crate_name 220crate [ "edition" ] = info . crate . edition 221crate [ "env" ] = {} 222crate [ "crate_type" ] = info . crate . type 223 224# Switch on external/ to determine if crates are in the workspace or remote. 225# TODO: Some folks may want to override this for vendored dependencies. 226is_external = info . crate . root . path . startswith ( "external/" ) 227is_generated = not info . crate . root . is_source 228path_prefix = _EXEC_ROOT_TEMPLATE if is_external or is_generated else _WORKSPACE_TEMPLATE 229crate [ "is_workspace_member" ] = not is_external 230crate [ "root_module" ] = path_prefix + info . crate . root . path 231crate [ "source" ] = { "exclude_dirs" : [], "include_dirs" : []} 232 233if is_generated : 234srcs = getattr ( ctx . rule . files , "srcs" , []) 235src_map = { src . short_path : src for src in srcs if src . is_source } 236if info . crate . root . short_path in src_map : 237crate [ "root_module" ] = _WORKSPACE_TEMPLATE + src_map [ info . crate . root . short_path ]. path 238crate [ "source" ][ "include_dirs" ]. append ( path_prefix + info . crate . root . dirname ) 239 240if info . build_info != None and info . build_info . out_dir != None : 241out_dir_path = info . build_info . out_dir . path 242crate [ "env" ]. update ({ "OUT_DIR" : _EXEC_ROOT_TEMPLATE + out_dir_path }) 243 244# We have to tell rust-analyzer about our out_dir since it's not under the crate root. 245crate [ "source" ][ "include_dirs" ]. extend ([ 246path_prefix + info . crate . root . dirname , 247_EXEC_ROOT_TEMPLATE + out_dir_path , 248]) 249 250# TODO: The only imagined use case is an env var holding a filename in the workspace passed to a 251# macro like include_bytes!. Other use cases might exist that require more complex logic. 252expand_targets = concat ([ getattr ( attrs , attr , []) for attr in [ "data" , "compile_data" ]]) 253 254crate [ "env" ]. update ({ k : dedup_expand_location ( ctx , v , expand_targets ) for k , v in info . env . items ()}) 255 256# Omit when a crate appears to depend on itself (e.g. foo_test crates). 257# It can happen a single source file is present in multiple crates - there can 258# be a `rust_library` with a `lib.rs` file, and a `rust_test` for the `test` 259# module in that file. Tests can declare more dependencies than what library 260# had. Therefore we had to collect all RustAnalyzerInfos for a given crate 261# and take deps from all of them. 262 263# There's one exception - if the dependency is the same crate name as the 264# the crate being processed, we don't add it as a dependency to itself. This is 265# common and expected - `rust_test.crate` pointing to the `rust_library`. 266crate [ "deps" ] = [ _crate_id ( dep . crate ) for dep in info . deps if _crate_id ( dep . crate ) != crate_id ] 267crate [ "aliases" ] = { _crate_id ( alias_target . crate ): alias_name for alias_target , alias_name in info . aliases . items ()} 268crate [ "cfg" ] = info . cfgs 269toolchain = find_toolchain ( ctx ) 270crate [ "target" ] = ( _EXEC_ROOT_TEMPLATE + toolchain . target_json . path ) if toolchain . target_json else toolchain . target_flag_value 271if info . proc_macro_dylib_path != None : 272crate [ "proc_macro_dylib_path" ] = _EXEC_ROOT_TEMPLATE + info . proc_macro_dylib_path 273return crate 274 275def _rust_analyzer_toolchain_impl ( ctx ): 276toolchain = platform_common . ToolchainInfo ( 277proc_macro_srv = ctx . executable . proc_macro_srv , 278rustc = ctx . executable . rustc , 279rustc_srcs = ctx . attr . rustc_srcs , 280) 281 282return [ toolchain ] 283 284rust_analyzer_toolchain = rule ( 285implementation = _rust_analyzer_toolchain_impl , 286doc = "A toolchain for [rust-analyzer](https://rust-analyzer.github.io/)." , 287attrs = { 288"proc_macro_srv" : attr . label ( 289doc = "The path to a `rust_analyzer_proc_macro_srv` binary." , 290cfg = "exec" , 291executable = True , 292allow_single_file = True , 293), 294"rustc" : attr . label ( 295doc = "The path to a `rustc` binary." , 296cfg = "exec" , 297executable = True , 298allow_single_file = True , 299mandatory = True , 300), 301"rustc_srcs" : attr . label ( 302doc = "The source code of rustc." , 303mandatory = True , 304), 305}, 306) 307 308def _rust_analyzer_detect_sysroot_impl ( ctx ): 309rust_analyzer_toolchain = ctx . toolchains [ Label ( "@rules_rust//rust/rust_analyzer:toolchain_type" )] 310 311if not rust_analyzer_toolchain . rustc_srcs : 312fail ( 313"Current Rust-Analyzer toolchain doesn't contain rustc sources in `rustc_srcs` attribute." , 314"These are needed by rust-analyzer. If you are using the default Rust toolchain, add `rust_repositories(include_rustc_srcs = True, ...).` to your WORKSPACE file." , 315) 316 317rustc_srcs = rust_analyzer_toolchain . rustc_srcs 318 319sysroot_src = rustc_srcs . label . package + "/library" 320if rustc_srcs . label . workspace_root : 321sysroot_src = _OUTPUT_BASE_TEMPLATE + rustc_srcs . label . workspace_root + "/" + sysroot_src 322else : 323sysroot_src = _WORKSPACE_TEMPLATE + sysroot_src 324 325rustc = rust_analyzer_toolchain . rustc 326sysroot_dir , _ , bin_dir = rustc . dirname . rpartition ( "/" ) 327if bin_dir != "bin" : 328fail ( "The rustc path is expected to be relative to the sysroot as `bin/rustc`. Instead got: {}" . format ( 329rustc . path , 330)) 331 332sysroot = _OUTPUT_BASE_TEMPLATE + sysroot_dir 333 334toolchain_info = { 335"sysroot" : sysroot , 336"sysroot_src" : sysroot_src , 337} 338 339output = ctx . actions . declare_file ( ctx . label . name + ".rust_analyzer_toolchain.json" ) 340ctx . actions . write ( 341output = output , 342content = json . encode_indent ( toolchain_info , indent = " " * 4 ), 343) 344 345return [ DefaultInfo ( files = depset ([ output ]))] 346 347rust_analyzer_detect_sysroot = rule ( 348implementation = _rust_analyzer_detect_sysroot_impl , 349toolchains = [ 350"@rules_rust//rust:toolchain_type" , 351"@rules_rust//rust/rust_analyzer:toolchain_type" , 352], 353doc = dedent ( """\ 354Detect the sysroot and store in a file for use by the gen_rust_project tool. 355""" ), 356)