blob: 7515fd7c33b003212367cb2cece270a0789d74c7 [file] [log] [blame]
Brian Silvermancc09f182022-03-09 15:40:20 -08001# 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(
29 doc = "RustAnalyzerInfo holds rust crate metadata for targets",
30 fields = {
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):
Brian Silverman5f6f2762022-08-13 19:30:05 -070042 if rust_common.crate_info not in target and rust_common.test_crate_info not in target:
Brian Silvermancc09f182022-03-09 15:40:20 -080043 return []
44
45 toolchain = 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
49 cfgs = ["test", "debug_assertions"]
50 if hasattr(ctx.rule.attr, "crate_features"):
51 cfgs += ['feature="{}"'.format(f) for f in ctx.rule.attr.crate_features]
52 if hasattr(ctx.rule.attr, "rustc_flags"):
53 cfgs += [f[6:] for f in ctx.rule.attr.rustc_flags if f.startswith("--cfg ") or f.startswith("--cfg=")]
54
Brian Silvermancc09f182022-03-09 15:40:20 -080055 build_info = None
Brian Silverman5f6f2762022-08-13 19:30:05 -070056 dep_infos = []
57 if hasattr(ctx.rule.attr, "deps"):
58 for dep in ctx.rule.attr.deps:
59 # Save BuildInfo if we find any (for build script output)
60 if BuildInfo in dep:
61 build_info = dep[BuildInfo]
62 dep_infos = [dep[RustAnalyzerInfo] for dep in ctx.rule.attr.deps if RustAnalyzerInfo in dep]
Brian Silvermancc09f182022-03-09 15:40:20 -080063
Brian Silvermancc09f182022-03-09 15:40:20 -080064 if hasattr(ctx.rule.attr, "proc_macro_deps"):
65 dep_infos += [dep[RustAnalyzerInfo] for dep in ctx.rule.attr.proc_macro_deps if RustAnalyzerInfo in dep]
66 if hasattr(ctx.rule.attr, "crate") and ctx.rule.attr.crate != None:
67 dep_infos.append(ctx.rule.attr.crate[RustAnalyzerInfo])
Brian Silverman5f6f2762022-08-13 19:30:05 -070068 if hasattr(ctx.rule.attr, "actual") and ctx.rule.attr.actual != None and RustAnalyzerInfo in ctx.rule.attr.actual:
69 dep_infos.append(ctx.rule.attr.actual[RustAnalyzerInfo])
Brian Silvermancc09f182022-03-09 15:40:20 -080070
71 crate_spec = ctx.actions.declare_file(ctx.label.name + ".rust_analyzer_crate_spec")
72
Brian Silverman5f6f2762022-08-13 19:30:05 -070073 if rust_common.crate_info in target:
74 crate_info = target[rust_common.crate_info]
75 elif rust_common.test_crate_info in target:
76 crate_info = target[rust_common.test_crate_info].crate
77 else:
78 fail("Unexpected target type: {}".format(target))
Brian Silvermancc09f182022-03-09 15:40:20 -080079
80 rust_analyzer_info = RustAnalyzerInfo(
81 crate = crate_info,
82 cfgs = cfgs,
83 env = getattr(ctx.rule.attr, "rustc_env", {}),
84 deps = dep_infos,
85 crate_specs = depset(direct = [crate_spec], transitive = [dep.crate_specs for dep in dep_infos]),
86 proc_macro_dylib_path = find_proc_macro_dylib_path(toolchain, target),
87 build_info = build_info,
88 )
89
90 ctx.actions.write(
91 output = crate_spec,
92 content = json.encode(_create_single_crate(ctx, rust_analyzer_info)),
93 )
94
95 return [
96 rust_analyzer_info,
97 OutputGroupInfo(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
103 Args:
104 toolchain: The current rust toolchain.
105 target: The current target.
106 Returns:
107 (path): The path to the proc macro dylib, or None if this crate is not a proc-macro.
108 """
Brian Silverman5f6f2762022-08-13 19:30:05 -0700109 if rust_common.crate_info in target:
110 crate_info = target[rust_common.crate_info]
111 elif rust_common.test_crate_info in target:
112 crate_info = target[rust_common.test_crate_info].crate
113 else:
114 return None
115
116 if crate_info.type != "proc-macro":
Brian Silvermancc09f182022-03-09 15:40:20 -0800117 return None
118
119 dylib_ext = system_to_dylib_ext(triple_to_system(toolchain.target_triple))
120 for action in target.actions:
121 for output in action.outputs.to_list():
122 if output.extension == dylib_ext[1:]:
123 return output.path
124
125 # Failed to find the dylib path inside a proc-macro crate.
126 # TODO: Should this be an error?
127 return None
128
129rust_analyzer_aspect = aspect(
Brian Silverman5f6f2762022-08-13 19:30:05 -0700130 attr_aspects = ["deps", "proc_macro_deps", "crate", "actual"],
Brian Silvermancc09f182022-03-09 15:40:20 -0800131 implementation = _rust_analyzer_aspect_impl,
Brian Silverman5f6f2762022-08-13 19:30:05 -0700132 toolchains = [str(Label("//rust:toolchain_type"))],
Brian Silvermancc09f182022-03-09 15:40:20 -0800133 incompatible_use_toolchain_transition = True,
134 doc = "Annotates rust rules with RustAnalyzerInfo later used to build a rust-project.json",
135)
136
Brian Silverman5f6f2762022-08-13 19:30:05 -0700137_EXEC_ROOT_TEMPLATE = "__EXEC_ROOT__/"
138_OUTPUT_BASE_TEMPLATE = "__OUTPUT_BASE__/"
Brian Silvermancc09f182022-03-09 15:40:20 -0800139
140def _crate_id(crate_info):
141 """Returns a unique stable identifier for a crate
142
143 Returns:
144 (string): This crate's unique stable id.
145 """
146 return "ID-" + crate_info.root.path
147
148def _create_single_crate(ctx, info):
149 """Creates a crate in the rust-project.json format.
150
151 Args:
152 ctx (ctx): The rule context
153 info (RustAnalyzerInfo): RustAnalyzerInfo for the current crate
154
155 Returns:
156 (dict) The crate rust-project.json representation
157 """
158 crate_name = info.crate.name
159 crate = dict()
160 crate_id = _crate_id(info.crate)
161 crate["crate_id"] = crate_id
162 crate["display_name"] = crate_name
163 crate["edition"] = info.crate.edition
164 crate["env"] = {}
165 crate["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.
Brian Silverman5f6f2762022-08-13 19:30:05 -0700169 is_external = info.crate.root.path.startswith("external/")
170 is_generated = not info.crate.root.is_source
171 path_prefix = _EXEC_ROOT_TEMPLATE if is_external or is_generated else ""
172 crate["is_workspace_member"] = not is_external
173 crate["root_module"] = path_prefix + info.crate.root.path
174 crate_root = path_prefix + info.crate.root.dirname
Brian Silvermancc09f182022-03-09 15:40:20 -0800175
176 if info.build_info != None:
177 out_dir_path = info.build_info.out_dir.path
Brian Silverman5f6f2762022-08-13 19:30:05 -0700178 crate["env"].update({"OUT_DIR": _EXEC_ROOT_TEMPLATE + out_dir_path})
Brian Silvermancc09f182022-03-09 15:40:20 -0800179 crate["source"] = {
180 # We have to tell rust-analyzer about our out_dir since it's not under the crate root.
181 "exclude_dirs": [],
Brian Silverman5f6f2762022-08-13 19:30:05 -0700182 "include_dirs": [crate_root, _EXEC_ROOT_TEMPLATE + out_dir_path],
Brian Silvermancc09f182022-03-09 15:40:20 -0800183 }
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.
187 expand_targets = getattr(ctx.rule.attr, "data", []) + getattr(ctx.rule.attr, "compile_data", [])
188 crate["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`.
200 crate["deps"] = [_crate_id(dep.crate) for dep in info.deps if _crate_id(dep.crate) != crate_id]
201 crate["cfg"] = info.cfgs
202 crate["target"] = find_toolchain(ctx).target_triple
203 if info.proc_macro_dylib_path != None:
Brian Silverman5f6f2762022-08-13 19:30:05 -0700204 crate["proc_macro_dylib_path"] = _EXEC_ROOT_TEMPLATE + info.proc_macro_dylib_path
Brian Silvermancc09f182022-03-09 15:40:20 -0800205 return crate
206
Brian Silverman5f6f2762022-08-13 19:30:05 -0700207def _rust_analyzer_toolchain_impl(ctx):
208 toolchain = platform_common.ToolchainInfo(
209 rustc_srcs = ctx.attr.rustc_srcs,
210 )
Brian Silvermancc09f182022-03-09 15:40:20 -0800211
Brian Silverman5f6f2762022-08-13 19:30:05 -0700212 return [toolchain]
213
214rust_analyzer_toolchain = rule(
215 implementation = _rust_analyzer_toolchain_impl,
216 doc = "A toolchain for [rust-analyzer](https://rust-analyzer.github.io/).",
217 attrs = {
218 "rustc_srcs": attr.label(
219 doc = "The source code of rustc.",
220 mandatory = True,
221 ),
222 },
223 incompatible_use_toolchain_transition = True,
224)
225
226def _rust_analyzer_detect_sysroot_impl(ctx):
227 rust_analyzer_toolchain = ctx.toolchains[Label("@rules_rust//rust/rust_analyzer:toolchain_type")]
228
229 if not rust_analyzer_toolchain.rustc_srcs:
Brian Silvermancc09f182022-03-09 15:40:20 -0800230 fail(
Brian Silverman5f6f2762022-08-13 19:30:05 -0700231 "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.",
Brian Silvermancc09f182022-03-09 15:40:20 -0800233 )
Brian Silverman5f6f2762022-08-13 19:30:05 -0700234
235 rustc_srcs = rust_analyzer_toolchain.rustc_srcs
236
237 sysroot_src = rustc_srcs.label.package + "/library"
238 if rustc_srcs.label.workspace_root:
239 sysroot_src = _OUTPUT_BASE_TEMPLATE + rustc_srcs.label.workspace_root + "/" + sysroot_src
Brian Silvermancc09f182022-03-09 15:40:20 -0800240
241 sysroot_src_file = ctx.actions.declare_file(ctx.label.name + ".rust_analyzer_sysroot_src")
242 ctx.actions.write(
243 output = sysroot_src_file,
244 content = sysroot_src,
245 )
246
247 return [DefaultInfo(files = depset([sysroot_src_file]))]
248
249rust_analyzer_detect_sysroot = rule(
250 implementation = _rust_analyzer_detect_sysroot_impl,
Brian Silverman5f6f2762022-08-13 19:30:05 -0700251 toolchains = [
252 "@rules_rust//rust:toolchain_type",
253 "@rules_rust//rust/rust_analyzer:toolchain_type",
254 ],
Brian Silvermancc09f182022-03-09 15:40:20 -0800255 incompatible_use_toolchain_transition = True,
256 doc = dedent("""\
257 Detect the sysroot and store in a file for use by the gen_rust_project tool.
258 """),
259)