fork/rules_rust

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

UebelAndreDeleted deprecated `rust_analyzer` rule. (#1405)3aa88ab0

0.6.0
9.3 KiB222 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("//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):
42    if rust_common.crate_info not in target:
43        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
55    build_info = None
56    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]
63
64    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])
68    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])
70
71    crate_spec = ctx.actions.declare_file(ctx.label.name + ".rust_analyzer_crate_spec")
72
73    crate_info = target[rust_common.crate_info]
74
75    rust_analyzer_info = RustAnalyzerInfo(
76        crate = crate_info,
77        cfgs = cfgs,
78        env = getattr(ctx.rule.attr, "rustc_env", {}),
79        deps = dep_infos,
80        crate_specs = depset(direct = [crate_spec], transitive = [dep.crate_specs for dep in dep_infos]),
81        proc_macro_dylib_path = find_proc_macro_dylib_path(toolchain, target),
82        build_info = build_info,
83    )
84
85    ctx.actions.write(
86        output = crate_spec,
87        content = json.encode(_create_single_crate(ctx, rust_analyzer_info)),
88    )
89
90    return [
91        rust_analyzer_info,
92        OutputGroupInfo(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
98    Args:
99        toolchain: The current rust toolchain.
100        target: The current target.
101    Returns:
102        (path): The path to the proc macro dylib, or None if this crate is not a proc-macro.
103    """
104    if target[rust_common.crate_info].type != "proc-macro":
105        return None
106
107    dylib_ext = system_to_dylib_ext(triple_to_system(toolchain.target_triple))
108    for action in target.actions:
109        for output in action.outputs.to_list():
110            if output.extension == dylib_ext[1:]:
111                return output.path
112
113    # Failed to find the dylib path inside a proc-macro crate.
114    # TODO: Should this be an error?
115    return None
116
117rust_analyzer_aspect = aspect(
118    attr_aspects = ["deps", "proc_macro_deps", "crate", "actual"],
119    implementation = _rust_analyzer_aspect_impl,
120    toolchains = [str(Label("//rust:toolchain"))],
121    incompatible_use_toolchain_transition = True,
122    doc = "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
130    Returns:
131        (string): This crate's unique stable id.
132    """
133    return "ID-" + crate_info.root.path
134
135def _create_single_crate(ctx, info):
136    """Creates a crate in the rust-project.json format.
137
138    Args:
139        ctx (ctx): The rule context
140        info (RustAnalyzerInfo): RustAnalyzerInfo for the current crate
141
142    Returns:
143        (dict) The crate rust-project.json representation
144    """
145    crate_name = info.crate.name
146    crate = dict()
147    crate_id = _crate_id(info.crate)
148    crate["crate_id"] = crate_id
149    crate["display_name"] = crate_name
150    crate["edition"] = info.crate.edition
151    crate["env"] = {}
152    crate["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.
156    is_external = info.crate.root.path.startswith("external/")
157    is_generated = not info.crate.root.is_source
158    path_prefix = _exec_root_tmpl if is_external or is_generated else ""
159    crate["is_workspace_member"] = not is_external
160    crate["root_module"] = path_prefix + info.crate.root.path
161    crate_root = path_prefix + info.crate.root.dirname
162
163    if info.build_info != None:
164        out_dir_path = info.build_info.out_dir.path
165        crate["env"].update({"OUT_DIR": _exec_root_tmpl + out_dir_path})
166        crate["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.
174    expand_targets = getattr(ctx.rule.attr, "data", []) + getattr(ctx.rule.attr, "compile_data", [])
175    crate["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`.
187    crate["deps"] = [_crate_id(dep.crate) for dep in info.deps if _crate_id(dep.crate) != crate_id]
188    crate["cfg"] = info.cfgs
189    crate["target"] = find_toolchain(ctx).target_triple
190    if info.proc_macro_dylib_path != None:
191        crate["proc_macro_dylib_path"] = _exec_root_tmpl + info.proc_macro_dylib_path
192    return crate
193
194def _rust_analyzer_detect_sysroot_impl(ctx):
195    rust_toolchain = find_toolchain(ctx)
196
197    if not rust_toolchain.rustc_srcs:
198        fail(
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        )
203    sysroot_src = rust_toolchain.rustc_srcs.label.package + "/library"
204    if rust_toolchain.rustc_srcs.label.workspace_root:
205        sysroot_src = _exec_root_tmpl + rust_toolchain.rustc_srcs.label.workspace_root + "/" + sysroot_src
206
207    sysroot_src_file = ctx.actions.declare_file(ctx.label.name + ".rust_analyzer_sysroot_src")
208    ctx.actions.write(
209        output = sysroot_src_file,
210        content = sysroot_src,
211    )
212
213    return [DefaultInfo(files = depset([sysroot_src_file]))]
214
215rust_analyzer_detect_sysroot = rule(
216    implementation = _rust_analyzer_detect_sysroot_impl,
217    toolchains = ["@rules_rust//rust:toolchain"],
218    incompatible_use_toolchain_transition = True,
219    doc = dedent("""\
220        Detect the sysroot and store in a file for use by the gen_rust_project tool.
221    """),
222)