fork/rules_rust

git clone https://git.julia.blue/fork/rules_rust

UebelAndreConvert `rust_toolchain` attrs `exec_triple` and `target_triple` to structs (#1808)804d5fc1

rust-analyzer
11.5 KiB298 linesraw
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(
35    doc = "RustAnalyzerInfo holds rust crate metadata for targets",
36    fields = {
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):
48    if rust_common.crate_info not in target and rust_common.test_crate_info not in target:
49        return []
50
51    toolchain = 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
55    cfgs = ["test", "debug_assertions"]
56    if hasattr(ctx.rule.attr, "crate_features"):
57        cfgs += ['feature="{}"'.format(f) for f in ctx.rule.attr.crate_features]
58    if hasattr(ctx.rule.attr, "rustc_flags"):
59        cfgs += [f[6:] for f in ctx.rule.attr.rustc_flags if f.startswith("--cfg ") or f.startswith("--cfg=")]
60
61    build_info = None
62    dep_infos = []
63    if hasattr(ctx.rule.attr, "deps"):
64        for dep in ctx.rule.attr.deps:
65            # Save BuildInfo if we find any (for build script output)
66            if BuildInfo in dep:
67                build_info = dep[BuildInfo]
68        dep_infos = [dep[RustAnalyzerInfo] for dep in ctx.rule.attr.deps if RustAnalyzerInfo in dep]
69
70    if hasattr(ctx.rule.attr, "proc_macro_deps"):
71        dep_infos += [dep[RustAnalyzerInfo] for dep in ctx.rule.attr.proc_macro_deps if RustAnalyzerInfo in dep]
72    if hasattr(ctx.rule.attr, "crate") and ctx.rule.attr.crate != None:
73        dep_infos.append(ctx.rule.attr.crate[RustAnalyzerInfo])
74    if hasattr(ctx.rule.attr, "actual") and ctx.rule.attr.actual != None and RustAnalyzerInfo in ctx.rule.attr.actual:
75        dep_infos.append(ctx.rule.attr.actual[RustAnalyzerInfo])
76
77    crate_spec = ctx.actions.declare_file(ctx.label.name + ".rust_analyzer_crate_spec")
78
79    if rust_common.crate_info in target:
80        crate_info = target[rust_common.crate_info]
81    elif rust_common.test_crate_info in target:
82        crate_info = target[rust_common.test_crate_info].crate
83    else:
84        fail("Unexpected target type: {}".format(target))
85
86    rust_analyzer_info = RustAnalyzerInfo(
87        crate = crate_info,
88        cfgs = cfgs,
89        env = getattr(ctx.rule.attr, "rustc_env", {}),
90        deps = dep_infos,
91        crate_specs = depset(direct = [crate_spec], transitive = [dep.crate_specs for dep in dep_infos]),
92        proc_macro_dylib_path = find_proc_macro_dylib_path(toolchain, target),
93        build_info = build_info,
94    )
95
96    ctx.actions.write(
97        output = crate_spec,
98        content = json.encode(_create_single_crate(ctx, rust_analyzer_info)),
99    )
100
101    return [
102        rust_analyzer_info,
103        OutputGroupInfo(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
109    Args:
110        toolchain: The current rust toolchain.
111        target: The current target.
112    Returns:
113        (path): The path to the proc macro dylib, or None if this crate is not a proc-macro.
114    """
115    if rust_common.crate_info in target:
116        crate_info = target[rust_common.crate_info]
117    elif rust_common.test_crate_info in target:
118        crate_info = target[rust_common.test_crate_info].crate
119    else:
120        return None
121
122    if crate_info.type != "proc-macro":
123        return None
124
125    dylib_ext = system_to_dylib_ext(triple_to_system(toolchain.target_triple))
126    for action in target.actions:
127        for output in action.outputs.to_list():
128            if output.extension == dylib_ext[1:]:
129                return output.path
130
131    # Failed to find the dylib path inside a proc-macro crate.
132    # TODO: Should this be an error?
133    return None
134
135rust_analyzer_aspect = aspect(
136    attr_aspects = ["deps", "proc_macro_deps", "crate", "actual"],
137    implementation = _rust_analyzer_aspect_impl,
138    toolchains = [str(Label("//rust:toolchain_type"))],
139    incompatible_use_toolchain_transition = True,
140    doc = "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
149    Returns:
150        (string): This crate's unique stable id.
151    """
152    return "ID-" + crate_info.root.path
153
154def _create_single_crate(ctx, info):
155    """Creates a crate in the rust-project.json format.
156
157    Args:
158        ctx (ctx): The rule context
159        info (RustAnalyzerInfo): RustAnalyzerInfo for the current crate
160
161    Returns:
162        (dict) The crate rust-project.json representation
163    """
164    crate_name = info.crate.name
165    crate = dict()
166    crate_id = _crate_id(info.crate)
167    crate["crate_id"] = crate_id
168    crate["display_name"] = crate_name
169    crate["edition"] = info.crate.edition
170    crate["env"] = {}
171    crate["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.
175    is_external = info.crate.root.path.startswith("external/")
176    is_generated = not info.crate.root.is_source
177    path_prefix = _EXEC_ROOT_TEMPLATE if is_external or is_generated else ""
178    crate["is_workspace_member"] = not is_external
179    crate["root_module"] = path_prefix + info.crate.root.path
180    crate_root = path_prefix + info.crate.root.dirname
181
182    if info.build_info != None:
183        out_dir_path = info.build_info.out_dir.path
184        crate["env"].update({"OUT_DIR": _EXEC_ROOT_TEMPLATE + out_dir_path})
185        crate["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.
193    expand_targets = concat([getattr(ctx.rule.attr, attr, []) for attr in ["data", "compile_data"]])
194
195    crate["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`.
207    crate["deps"] = [_crate_id(dep.crate) for dep in info.deps if _crate_id(dep.crate) != crate_id]
208    crate["cfg"] = info.cfgs
209    crate["target"] = find_toolchain(ctx).target_triple.str
210    if info.proc_macro_dylib_path != None:
211        crate["proc_macro_dylib_path"] = _EXEC_ROOT_TEMPLATE + info.proc_macro_dylib_path
212    return crate
213
214def _rust_analyzer_toolchain_impl(ctx):
215    toolchain = platform_common.ToolchainInfo(
216        proc_macro_srv = ctx.executable.proc_macro_srv,
217        rustc = ctx.executable.rustc,
218        rustc_srcs = ctx.attr.rustc_srcs,
219    )
220
221    return [toolchain]
222
223rust_analyzer_toolchain = rule(
224    implementation = _rust_analyzer_toolchain_impl,
225    doc = "A toolchain for [rust-analyzer](https://rust-analyzer.github.io/).",
226    attrs = {
227        "proc_macro_srv": attr.label(
228            doc = "The path to a `rust_analyzer_proc_macro_srv` binary.",
229            cfg = "exec",
230            executable = True,
231            allow_single_file = True,
232        ),
233        "rustc": attr.label(
234            doc = "The path to a `rustc` binary.",
235            cfg = "exec",
236            executable = True,
237            allow_single_file = True,
238            mandatory = True,
239        ),
240        "rustc_srcs": attr.label(
241            doc = "The source code of rustc.",
242            mandatory = True,
243        ),
244    },
245    incompatible_use_toolchain_transition = True,
246)
247
248def _rust_analyzer_detect_sysroot_impl(ctx):
249    rust_analyzer_toolchain = ctx.toolchains[Label("@rules_rust//rust/rust_analyzer:toolchain_type")]
250
251    if not rust_analyzer_toolchain.rustc_srcs:
252        fail(
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
257    rustc_srcs = rust_analyzer_toolchain.rustc_srcs
258
259    sysroot_src = rustc_srcs.label.package + "/library"
260    if rustc_srcs.label.workspace_root:
261        sysroot_src = _OUTPUT_BASE_TEMPLATE + rustc_srcs.label.workspace_root + "/" + sysroot_src
262
263    rustc = rust_analyzer_toolchain.rustc
264    sysroot_dir, _, bin_dir = rustc.dirname.rpartition("/")
265    if bin_dir != "bin":
266        fail("The rustc path is expected to be relative to the sysroot as `bin/rustc`. Instead got: {}".format(
267            rustc.path,
268        ))
269
270    sysroot = "{}/{}".format(
271        _OUTPUT_BASE_TEMPLATE,
272        sysroot_dir,
273    )
274
275    toolchain_info = {
276        "sysroot": sysroot,
277        "sysroot_src": sysroot_src,
278    }
279
280    output = ctx.actions.declare_file(ctx.label.name + ".rust_analyzer_toolchain.json")
281    ctx.actions.write(
282        output = output,
283        content = json.encode_indent(toolchain_info, indent = " " * 4),
284    )
285
286    return [DefaultInfo(files = depset([output]))]
287
288rust_analyzer_detect_sysroot = rule(
289    implementation = _rust_analyzer_detect_sysroot_impl,
290    toolchains = [
291        "@rules_rust//rust:toolchain_type",
292        "@rules_rust//rust/rust_analyzer:toolchain_type",
293    ],
294    incompatible_use_toolchain_transition = True,
295    doc = dedent("""\
296        Detect the sysroot and store in a file for use by the gen_rust_project tool.
297    """),
298)