fork/rules_rust
git clone https://git.julia.blue/fork/rules_rust
3aa88ab0
0.6.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 : 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 73crate_info = target [ rust_common . crate_info ] 74 75rust_analyzer_info = RustAnalyzerInfo ( 76crate = crate_info , 77cfgs = cfgs , 78env = getattr ( ctx . rule . attr , "rustc_env" , {}), 79deps = dep_infos , 80crate_specs = depset ( direct = [ crate_spec ], transitive = [ dep . crate_specs for dep in dep_infos ]), 81proc_macro_dylib_path = find_proc_macro_dylib_path ( toolchain , target ), 82build_info = build_info , 83) 84 85ctx . actions . write ( 86output = crate_spec , 87content = json . encode ( _create_single_crate ( ctx , rust_analyzer_info )), 88) 89 90return [ 91rust_analyzer_info , 92OutputGroupInfo ( rust_analyzer_crate_spec = rust_analyzer_info . crate_specs ), 93] 94 95def find_proc_macro_dylib_path ( toolchain , target ): 96"""Find the proc_macro_dylib_path of target. Returns None if target crate is not type proc-macro. 97 98Args: 99toolchain: The current rust toolchain. 100target: The current target. 101Returns: 102(path): The path to the proc macro dylib, or None if this crate is not a proc-macro. 103""" 104if target [ rust_common . crate_info ]. type != "proc-macro" : 105return None 106 107dylib_ext = system_to_dylib_ext ( triple_to_system ( toolchain . target_triple )) 108for action in target . actions : 109for output in action . outputs . to_list (): 110if output . extension == dylib_ext [ 1 :]: 111return output . path 112 113# Failed to find the dylib path inside a proc-macro crate. 114# TODO: Should this be an error? 115return None 116 117rust_analyzer_aspect = aspect ( 118attr_aspects = [ "deps" , "proc_macro_deps" , "crate" , "actual" ], 119implementation = _rust_analyzer_aspect_impl , 120toolchains = [ str ( Label ( "//rust:toolchain" ))], 121incompatible_use_toolchain_transition = True , 122doc = "Annotates rust rules with RustAnalyzerInfo later used to build a rust-project.json" , 123) 124 125_exec_root_tmpl = "__EXEC_ROOT__/" 126 127def _crate_id ( crate_info ): 128"""Returns a unique stable identifier for a crate 129 130Returns: 131(string): This crate's unique stable id. 132""" 133return "ID-" + crate_info . root . path 134 135def _create_single_crate ( ctx , info ): 136"""Creates a crate in the rust-project.json format. 137 138Args: 139ctx (ctx): The rule context 140info (RustAnalyzerInfo): RustAnalyzerInfo for the current crate 141 142Returns: 143(dict) The crate rust-project.json representation 144""" 145crate_name = info . crate . name 146crate = dict () 147crate_id = _crate_id ( info . crate ) 148crate [ "crate_id" ] = crate_id 149crate [ "display_name" ] = crate_name 150crate [ "edition" ] = info . crate . edition 151crate [ "env" ] = {} 152crate [ "crate_type" ] = info . crate . type 153 154# Switch on external/ to determine if crates are in the workspace or remote. 155# TODO: Some folks may want to override this for vendored dependencies. 156is_external = info . crate . root . path . startswith ( "external/" ) 157is_generated = not info . crate . root . is_source 158path_prefix = _exec_root_tmpl if is_external or is_generated else "" 159crate [ "is_workspace_member" ] = not is_external 160crate [ "root_module" ] = path_prefix + info . crate . root . path 161crate_root = path_prefix + info . crate . root . dirname 162 163if info . build_info != None : 164out_dir_path = info . build_info . out_dir . path 165crate [ "env" ]. update ({ "OUT_DIR" : _exec_root_tmpl + out_dir_path }) 166crate [ "source" ] = { 167# We have to tell rust-analyzer about our out_dir since it's not under the crate root. 168"exclude_dirs" : [], 169"include_dirs" : [ crate_root , _exec_root_tmpl + out_dir_path ], 170} 171 172# TODO: The only imagined use case is an env var holding a filename in the workspace passed to a 173# macro like include_bytes!. Other use cases might exist that require more complex logic. 174expand_targets = getattr ( ctx . rule . attr , "data" , []) + getattr ( ctx . rule . attr , "compile_data" , []) 175crate [ "env" ]. update ({ k : ctx . expand_location ( v , expand_targets ) for k , v in info . env . items ()}) 176 177# Omit when a crate appears to depend on itself (e.g. foo_test crates). 178# It can happen a single source file is present in multiple crates - there can 179# be a `rust_library` with a `lib.rs` file, and a `rust_test` for the `test` 180# module in that file. Tests can declare more dependencies than what library 181# had. Therefore we had to collect all RustAnalyzerInfos for a given crate 182# and take deps from all of them. 183 184# There's one exception - if the dependency is the same crate name as the 185# the crate being processed, we don't add it as a dependency to itself. This is 186# common and expected - `rust_test.crate` pointing to the `rust_library`. 187crate [ "deps" ] = [ _crate_id ( dep . crate ) for dep in info . deps if _crate_id ( dep . crate ) != crate_id ] 188crate [ "cfg" ] = info . cfgs 189crate [ "target" ] = find_toolchain ( ctx ). target_triple 190if info . proc_macro_dylib_path != None : 191crate [ "proc_macro_dylib_path" ] = _exec_root_tmpl + info . proc_macro_dylib_path 192return crate 193 194def _rust_analyzer_detect_sysroot_impl ( ctx ): 195rust_toolchain = find_toolchain ( ctx ) 196 197if not rust_toolchain . rustc_srcs : 198fail ( 199"Current Rust toolchain doesn't contain rustc sources in `rustc_srcs` attribute." , 200"These are needed by rust analyzer." , 201"If you are using the default Rust toolchain, add `rust_repositories(include_rustc_srcs = True, ...).` to your WORKSPACE file." , 202) 203sysroot_src = rust_toolchain . rustc_srcs . label . package + "/library" 204if rust_toolchain . rustc_srcs . label . workspace_root : 205sysroot_src = _exec_root_tmpl + rust_toolchain . rustc_srcs . label . workspace_root + "/" + sysroot_src 206 207sysroot_src_file = ctx . actions . declare_file ( ctx . label . name + ".rust_analyzer_sysroot_src" ) 208ctx . actions . write ( 209output = sysroot_src_file , 210content = sysroot_src , 211) 212 213return [ DefaultInfo ( files = depset ([ sysroot_src_file ]))] 214 215rust_analyzer_detect_sysroot = rule ( 216implementation = _rust_analyzer_detect_sysroot_impl , 217toolchains = [ "@rules_rust//rust:toolchain" ], 218incompatible_use_toolchain_transition = True , 219doc = dedent ( """\ 220Detect the sysroot and store in a file for use by the gen_rust_project tool. 221""" ), 222)