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