fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
0fc834bd
0.9.0
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:rustc.bzl" , "BuildInfo" ) 26load ( "//rust/private:utils.bzl" , "dedent" , "find_toolchain" ) 27 28RustAnalyzerInfo = provider ( 29doc = "RustAnalyzerInfo holds rust crate metadata for targets" , 30fields = { 31"build_info" : "BuildInfo: build info for this crate if present" , 32"cfgs" : "List[String]: features or other compilation --cfg settings" , 33"crate" : "rust_common.crate_info" , 34"crate_specs" : "Depset[File]: transitive closure of OutputGroupInfo files" , 35"deps" : "List[RustAnalyzerInfo]: direct dependencies" , 36"env" : "Dict{String: String}: Environment variables, used for the `env!` macro" , 37"proc_macro_dylib_path" : "File: compiled shared library output of proc-macro rule" , 38}, 39) 40 41def _rust_analyzer_aspect_impl ( target , ctx ): 42if rust_common . crate_info not in target and rust_common . test_crate_info not in target : 43return [] 44 45toolchain = find_toolchain ( ctx ) 46 47# Always add `test` & `debug_assertions`. See rust-analyzer source code: 48# https://github.com/rust-analyzer/rust-analyzer/blob/2021-11-15/crates/project_model/src/workspace.rs#L529-L531 49cfgs = [ "test" , "debug_assertions" ] 50if hasattr ( ctx . rule . attr , "crate_features" ): 51cfgs += [ 'feature="{}"' . format ( f ) for f in ctx . rule . attr . crate_features ] 52if hasattr ( ctx . rule . attr , "rustc_flags" ): 53cfgs += [ f [ 6 :] for f in ctx . rule . attr . rustc_flags if f . startswith ( "--cfg " ) or f . startswith ( "--cfg=" )] 54 55build_info = None 56dep_infos = [] 57if hasattr ( ctx . rule . attr , "deps" ): 58for dep in ctx . rule . attr . deps : 59# Save BuildInfo if we find any (for build script output) 60if BuildInfo in dep : 61build_info = dep [ BuildInfo ] 62dep_infos = [ dep [ RustAnalyzerInfo ] for dep in ctx . rule . attr . deps if RustAnalyzerInfo in dep ] 63 64if hasattr ( ctx . rule . attr , "proc_macro_deps" ): 65dep_infos += [ dep [ RustAnalyzerInfo ] for dep in ctx . rule . attr . proc_macro_deps if RustAnalyzerInfo in dep ] 66if hasattr ( ctx . rule . attr , "crate" ) and ctx . rule . attr . crate != None : 67dep_infos . append ( ctx . rule . attr . crate [ RustAnalyzerInfo ]) 68if hasattr ( ctx . rule . attr , "actual" ) and ctx . rule . attr . actual != None and RustAnalyzerInfo in ctx . rule . attr . actual : 69dep_infos . append ( ctx . rule . attr . actual [ RustAnalyzerInfo ]) 70 71crate_spec = ctx . actions . declare_file ( ctx . label . name + ".rust_analyzer_crate_spec" ) 72 73if rust_common . crate_info in target : 74crate_info = target [ rust_common . crate_info ] 75elif rust_common . test_crate_info in target : 76crate_info = target [ rust_common . test_crate_info ]. crate 77else : 78fail ( "Unexpected target type: {}" . format ( target )) 79 80rust_analyzer_info = RustAnalyzerInfo ( 81crate = crate_info , 82cfgs = cfgs , 83env = getattr ( ctx . rule . attr , "rustc_env" , {}), 84deps = dep_infos , 85crate_specs = depset ( direct = [ crate_spec ], transitive = [ dep . crate_specs for dep in dep_infos ]), 86proc_macro_dylib_path = find_proc_macro_dylib_path ( toolchain , target ), 87build_info = build_info , 88) 89 90ctx . actions . write ( 91output = crate_spec , 92content = json . encode ( _create_single_crate ( ctx , rust_analyzer_info )), 93) 94 95return [ 96rust_analyzer_info , 97OutputGroupInfo ( rust_analyzer_crate_spec = rust_analyzer_info . crate_specs ), 98] 99 100def find_proc_macro_dylib_path ( toolchain , target ): 101"""Find the proc_macro_dylib_path of target. Returns None if target crate is not type proc-macro. 102 103Args: 104toolchain: The current rust toolchain. 105target: The current target. 106Returns: 107(path): The path to the proc macro dylib, or None if this crate is not a proc-macro. 108""" 109if rust_common . crate_info in target : 110crate_info = target [ rust_common . crate_info ] 111elif rust_common . test_crate_info in target : 112crate_info = target [ rust_common . test_crate_info ]. crate 113else : 114return None 115 116if crate_info . type != "proc-macro" : 117return None 118 119dylib_ext = system_to_dylib_ext ( triple_to_system ( toolchain . target_triple )) 120for action in target . actions : 121for output in action . outputs . to_list (): 122if output . extension == dylib_ext [ 1 :]: 123return output . path 124 125# Failed to find the dylib path inside a proc-macro crate. 126# TODO: Should this be an error? 127return None 128 129rust_analyzer_aspect = aspect ( 130attr_aspects = [ "deps" , "proc_macro_deps" , "crate" , "actual" ], 131implementation = _rust_analyzer_aspect_impl , 132toolchains = [ str ( Label ( "//rust:toolchain_type" ))], 133incompatible_use_toolchain_transition = True , 134doc = "Annotates rust rules with RustAnalyzerInfo later used to build a rust-project.json" , 135) 136 137_EXEC_ROOT_TEMPLATE = "__EXEC_ROOT__/" 138_OUTPUT_BASE_TEMPLATE = "__OUTPUT_BASE__/" 139 140def _crate_id ( crate_info ): 141"""Returns a unique stable identifier for a crate 142 143Returns: 144(string): This crate's unique stable id. 145""" 146return "ID-" + crate_info . root . path 147 148def _create_single_crate ( ctx , info ): 149"""Creates a crate in the rust-project.json format. 150 151Args: 152ctx (ctx): The rule context 153info (RustAnalyzerInfo): RustAnalyzerInfo for the current crate 154 155Returns: 156(dict) The crate rust-project.json representation 157""" 158crate_name = info . crate . name 159crate = dict () 160crate_id = _crate_id ( info . crate ) 161crate [ "crate_id" ] = crate_id 162crate [ "display_name" ] = crate_name 163crate [ "edition" ] = info . crate . edition 164crate [ "env" ] = {} 165crate [ "crate_type" ] = info . crate . type 166 167# Switch on external/ to determine if crates are in the workspace or remote. 168# TODO: Some folks may want to override this for vendored dependencies. 169is_external = info . crate . root . path . startswith ( "external/" ) 170is_generated = not info . crate . root . is_source 171path_prefix = _EXEC_ROOT_TEMPLATE if is_external or is_generated else "" 172crate [ "is_workspace_member" ] = not is_external 173crate [ "root_module" ] = path_prefix + info . crate . root . path 174crate_root = path_prefix + info . crate . root . dirname 175 176if info . build_info != None : 177out_dir_path = info . build_info . out_dir . path 178crate [ "env" ]. update ({ "OUT_DIR" : _EXEC_ROOT_TEMPLATE + out_dir_path }) 179crate [ "source" ] = { 180# We have to tell rust-analyzer about our out_dir since it's not under the crate root. 181"exclude_dirs" : [], 182"include_dirs" : [ crate_root , _EXEC_ROOT_TEMPLATE + out_dir_path ], 183} 184 185# TODO: The only imagined use case is an env var holding a filename in the workspace passed to a 186# macro like include_bytes!. Other use cases might exist that require more complex logic. 187expand_targets = getattr ( ctx . rule . attr , "data" , []) + getattr ( ctx . rule . attr , "compile_data" , []) 188crate [ "env" ]. update ({ k : ctx . expand_location ( v , expand_targets ) for k , v in info . env . items ()}) 189 190# Omit when a crate appears to depend on itself (e.g. foo_test crates). 191# It can happen a single source file is present in multiple crates - there can 192# be a `rust_library` with a `lib.rs` file, and a `rust_test` for the `test` 193# module in that file. Tests can declare more dependencies than what library 194# had. Therefore we had to collect all RustAnalyzerInfos for a given crate 195# and take deps from all of them. 196 197# There's one exception - if the dependency is the same crate name as the 198# the crate being processed, we don't add it as a dependency to itself. This is 199# common and expected - `rust_test.crate` pointing to the `rust_library`. 200crate [ "deps" ] = [ _crate_id ( dep . crate ) for dep in info . deps if _crate_id ( dep . crate ) != crate_id ] 201crate [ "cfg" ] = info . cfgs 202crate [ "target" ] = find_toolchain ( ctx ). target_triple 203if info . proc_macro_dylib_path != None : 204crate [ "proc_macro_dylib_path" ] = _EXEC_ROOT_TEMPLATE + info . proc_macro_dylib_path 205return crate 206 207def _rust_analyzer_toolchain_impl ( ctx ): 208toolchain = platform_common . ToolchainInfo ( 209rustc_srcs = ctx . attr . rustc_srcs , 210) 211 212return [ toolchain ] 213 214rust_analyzer_toolchain = rule ( 215implementation = _rust_analyzer_toolchain_impl , 216doc = "A toolchain for [rust-analyzer](https://rust-analyzer.github.io/)." , 217attrs = { 218"rustc_srcs" : attr . label ( 219doc = "The source code of rustc." , 220mandatory = True , 221), 222}, 223incompatible_use_toolchain_transition = True , 224) 225 226def _rust_analyzer_detect_sysroot_impl ( ctx ): 227rust_analyzer_toolchain = ctx . toolchains [ Label ( "@rules_rust//rust/rust_analyzer:toolchain_type" )] 228 229if not rust_analyzer_toolchain . rustc_srcs : 230fail ( 231"Current Rust-Analyzer toolchain doesn't contain rustc sources in `rustc_srcs` attribute." , 232"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." , 233) 234 235rustc_srcs = rust_analyzer_toolchain . rustc_srcs 236 237sysroot_src = rustc_srcs . label . package + "/library" 238if rustc_srcs . label . workspace_root : 239sysroot_src = _OUTPUT_BASE_TEMPLATE + rustc_srcs . label . workspace_root + "/" + sysroot_src 240 241sysroot_src_file = ctx . actions . declare_file ( ctx . label . name + ".rust_analyzer_sysroot_src" ) 242ctx . actions . write ( 243output = sysroot_src_file , 244content = sysroot_src , 245) 246 247return [ DefaultInfo ( files = depset ([ sysroot_src_file ]))] 248 249rust_analyzer_detect_sysroot = rule ( 250implementation = _rust_analyzer_detect_sysroot_impl , 251toolchains = [ 252"@rules_rust//rust:toolchain_type" , 253"@rules_rust//rust/rust_analyzer:toolchain_type" , 254], 255incompatible_use_toolchain_transition = True , 256doc = dedent ( """\ 257Detect the sysroot and store in a file for use by the gen_rust_project tool. 258""" ), 259)