Skip to content

Commit d57c9f7

Browse files
bors[bot]DJMcNab
andauthored
Merge #7891
7891: Improve handling of rustc_private r=matklad a=DJMcNab This PR changes how `rust-analyzer` handles `rustc_private`. In particular, packages now must opt-in to using `rustc_private` in `Cargo.toml`, by adding: ```toml [package.metadata.rust-analyzer] rustc_private=true ``` This means that depending on crates which also use `rustc_private` will be significantly improved, since their dependencies on the `rustc_private` crates will be resolved properly. A similar approach could be used in #6714 to allow annotating that your package uses the `test` crate, although I have not yet handled that in this PR. Additionally, we now only index the crates which are transitive dependencies of `rustc_driver` in the `rustcSource` directory. This should not cause any change in behaviour when using `rustcSource: "discover"`, as the source used then will only be a partial clone. However, if `rustcSource` pointing at a local checkout of rustc, this should significantly improve the memory usage and lower indexing time. This is because we avoids indexing all crates in `src/tools/`, which includes `rust-analyzer` itself. Furthermore, we also prefer named dependencies over dependencies from `rustcSource`. This ensures that feature resolution for crates which are depended on by both `rustc` and your crate uses the correct set for analysing your crate. See also [introductory zulip stream](https://rust-lang.zulipchat.com/#narrow/stream/185405-t-compiler.2Fwg-rls-2.2E0/topic/Fixed.20crate.20graphs.20and.20optional.20builtin.20crates/near/229086673) I have tested this in [priroda](https://github.com/oli-obk/priroda/), and it provides a significant improvement to the development experience (once I give `miri` the required data in `Cargo.toml`) Todo: - [ ] Documentation This is ready to review, and I will add documentation if this would be accepted (or if I get time to do so anyway) Co-authored-by: Daniel McNab <[email protected]>
2 parents f2b8df1 + 20007fd commit d57c9f7

File tree

5 files changed

+114
-54
lines changed

5 files changed

+114
-54
lines changed

crates/project_model/src/cargo_workspace.rs

+21-2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ use cargo_metadata::{CargoOpt, MetadataCommand};
99
use la_arena::{Arena, Idx};
1010
use paths::{AbsPath, AbsPathBuf};
1111
use rustc_hash::FxHashMap;
12+
use serde::Deserialize;
13+
use serde_json::from_value;
1214

1315
use crate::build_data::BuildDataConfig;
1416
use crate::utf8_stdout;
@@ -104,6 +106,13 @@ pub struct PackageData {
104106
pub active_features: Vec<String>,
105107
// String representation of package id
106108
pub id: String,
109+
// The contents of [package.metadata.rust-analyzer]
110+
pub metadata: RustAnalyzerPackageMetaData,
111+
}
112+
113+
#[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
114+
pub struct RustAnalyzerPackageMetaData {
115+
pub rustc_private: bool,
107116
}
108117

109118
#[derive(Debug, Clone, Eq, PartialEq)]
@@ -161,6 +170,13 @@ impl PackageData {
161170
}
162171
}
163172

173+
#[derive(Deserialize, Default)]
174+
// Deserialise helper for the cargo metadata
175+
struct PackageMetadata {
176+
#[serde(rename = "rust-analyzer")]
177+
rust_analyzer: Option<RustAnalyzerPackageMetaData>,
178+
}
179+
164180
impl CargoWorkspace {
165181
pub fn from_cargo_metadata(
166182
cargo_toml: &AbsPath,
@@ -244,8 +260,10 @@ impl CargoWorkspace {
244260

245261
meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
246262
for meta_pkg in &meta.packages {
247-
let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
248-
meta_pkg;
263+
let cargo_metadata::Package {
264+
id, edition, name, manifest_path, version, metadata, ..
265+
} = meta_pkg;
266+
let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
249267
let is_member = ws_members.contains(&id);
250268
let edition = edition
251269
.parse::<Edition>()
@@ -262,6 +280,7 @@ impl CargoWorkspace {
262280
dependencies: Vec::new(),
263281
features: meta_pkg.features.clone().into_iter().collect(),
264282
active_features: Vec::new(),
283+
metadata: meta.rust_analyzer.unwrap_or_default(),
265284
});
266285
let pkg_data = &mut packages[pkg];
267286
pkg_by_id.insert(id, pkg);

crates/project_model/src/workspace.rs

+89-49
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,7 @@
22
//! metadata` or `rust-project.json`) into representation stored in the salsa
33
//! database -- `CrateGraph`.
44
5-
use std::{
6-
fmt, fs,
7-
path::{Component, Path},
8-
process::Command,
9-
};
5+
use std::{collections::VecDeque, fmt, fs, path::Path, process::Command};
106

117
use anyhow::{Context, Result};
128
use base_db::{CrateDisplayName, CrateGraph, CrateId, CrateName, Edition, Env, FileId, ProcMacro};
@@ -60,6 +56,7 @@ impl fmt::Debug for ProjectWorkspace {
6056
match self {
6157
ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg } => f
6258
.debug_struct("Cargo")
59+
.field("root", &cargo.workspace_root().file_name())
6360
.field("n_packages", &cargo.packages().len())
6461
.field("n_sysroot_crates", &sysroot.crates().len())
6562
.field(
@@ -279,11 +276,8 @@ impl ProjectWorkspace {
279276

280277
pub fn collect_build_data_configs(&self, collector: &mut BuildDataCollector) {
281278
match self {
282-
ProjectWorkspace::Cargo { cargo, rustc, .. } => {
279+
ProjectWorkspace::Cargo { cargo, .. } => {
283280
collector.add_config(&cargo.workspace_root(), cargo.build_data_config().clone());
284-
if let Some(rustc) = rustc {
285-
collector.add_config(rustc.workspace_root(), rustc.build_data_config().clone());
286-
}
287281
}
288282
_ => {}
289283
}
@@ -380,9 +374,11 @@ fn cargo_to_crate_graph(
380374
cfg_options.insert_atom("debug_assertions".into());
381375

382376
let mut pkg_crates = FxHashMap::default();
383-
377+
// Does any crate signal to rust-analyzer that they need the rustc_private crates?
378+
let mut has_private = false;
384379
// Next, create crates for each package, target pair
385380
for pkg in cargo.packages() {
381+
has_private |= cargo[pkg].metadata.rustc_private;
386382
let mut lib_tgt = None;
387383
for &tgt in cargo[pkg].targets.iter() {
388384
if let Some(file_id) = load(&cargo[tgt].root) {
@@ -443,73 +439,117 @@ fn cargo_to_crate_graph(
443439
}
444440
}
445441

446-
let mut rustc_pkg_crates = FxHashMap::default();
442+
if has_private {
443+
// If the user provided a path to rustc sources, we add all the rustc_private crates
444+
// and create dependencies on them for the crates which opt-in to that
445+
if let Some(rustc_workspace) = rustc {
446+
handle_rustc_crates(
447+
rustc_workspace,
448+
load,
449+
&mut crate_graph,
450+
rustc_build_data_map,
451+
&cfg_options,
452+
proc_macro_loader,
453+
&mut pkg_to_lib_crate,
454+
&public_deps,
455+
cargo,
456+
&pkg_crates,
457+
);
458+
}
459+
}
460+
crate_graph
461+
}
447462

448-
// If the user provided a path to rustc sources, we add all the rustc_private crates
449-
// and create dependencies on them for the crates in the current workspace
450-
if let Some(rustc_workspace) = rustc {
451-
for pkg in rustc_workspace.packages() {
463+
fn handle_rustc_crates(
464+
rustc_workspace: &CargoWorkspace,
465+
load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
466+
crate_graph: &mut CrateGraph,
467+
rustc_build_data_map: Option<&FxHashMap<String, BuildData>>,
468+
cfg_options: &CfgOptions,
469+
proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
470+
pkg_to_lib_crate: &mut FxHashMap<la_arena::Idx<crate::PackageData>, CrateId>,
471+
public_deps: &[(CrateName, CrateId)],
472+
cargo: &CargoWorkspace,
473+
pkg_crates: &FxHashMap<la_arena::Idx<crate::PackageData>, Vec<CrateId>>,
474+
) {
475+
let mut rustc_pkg_crates = FxHashMap::default();
476+
// The root package of the rustc-dev component is rustc_driver, so we match that
477+
let root_pkg =
478+
rustc_workspace.packages().find(|package| rustc_workspace[*package].name == "rustc_driver");
479+
// The rustc workspace might be incomplete (such as if rustc-dev is not
480+
// installed for the current toolchain) and `rustcSource` is set to discover.
481+
if let Some(root_pkg) = root_pkg {
482+
// Iterate through every crate in the dependency subtree of rustc_driver using BFS
483+
let mut queue = VecDeque::new();
484+
queue.push_back(root_pkg);
485+
while let Some(pkg) = queue.pop_front() {
486+
// Don't duplicate packages if they are dependended on a diamond pattern
487+
// N.B. if this line is ommitted, we try to analyse over 4_800_000 crates
488+
// which is not ideal
489+
if rustc_pkg_crates.contains_key(&pkg) {
490+
continue;
491+
}
492+
for dep in &rustc_workspace[pkg].dependencies {
493+
queue.push_back(dep.pkg);
494+
}
452495
for &tgt in rustc_workspace[pkg].targets.iter() {
453496
if rustc_workspace[tgt].kind != TargetKind::Lib {
454497
continue;
455498
}
456-
// Exclude alloc / core / std
457-
if rustc_workspace[tgt]
458-
.root
459-
.components()
460-
.any(|c| c == Component::Normal("library".as_ref()))
461-
{
462-
continue;
463-
}
464-
465499
if let Some(file_id) = load(&rustc_workspace[tgt].root) {
466500
let crate_id = add_target_crate_root(
467-
&mut crate_graph,
501+
crate_graph,
468502
&rustc_workspace[pkg],
469503
rustc_build_data_map.and_then(|it| it.get(&rustc_workspace[pkg].id)),
470504
&cfg_options,
471505
proc_macro_loader,
472506
file_id,
473507
);
474508
pkg_to_lib_crate.insert(pkg, crate_id);
475-
// Add dependencies on the core / std / alloc for rustc
509+
// Add dependencies on core / std / alloc for this crate
476510
for (name, krate) in public_deps.iter() {
477-
add_dep(&mut crate_graph, crate_id, name.clone(), *krate);
511+
add_dep(crate_graph, crate_id, name.clone(), *krate);
478512
}
479513
rustc_pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
480514
}
481515
}
482516
}
483-
// Now add a dep edge from all targets of upstream to the lib
484-
// target of downstream.
485-
for pkg in rustc_workspace.packages() {
486-
for dep in rustc_workspace[pkg].dependencies.iter() {
487-
let name = CrateName::new(&dep.name).unwrap();
488-
if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
489-
for &from in rustc_pkg_crates.get(&pkg).into_iter().flatten() {
490-
add_dep(&mut crate_graph, from, name.clone(), to);
491-
}
517+
}
518+
// Now add a dep edge from all targets of upstream to the lib
519+
// target of downstream.
520+
for pkg in rustc_pkg_crates.keys().copied() {
521+
for dep in rustc_workspace[pkg].dependencies.iter() {
522+
let name = CrateName::new(&dep.name).unwrap();
523+
if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
524+
for &from in rustc_pkg_crates.get(&pkg).into_iter().flatten() {
525+
add_dep(crate_graph, from, name.clone(), to);
492526
}
493527
}
494528
}
495-
496-
// Add dependencies for all the crates of the current workspace to rustc_private libraries
497-
for dep in rustc_workspace.packages() {
498-
let name = CrateName::normalize_dashes(&rustc_workspace[dep].name);
499-
500-
if let Some(&to) = pkg_to_lib_crate.get(&dep) {
501-
for pkg in cargo.packages() {
502-
if !cargo[pkg].is_member {
503-
continue;
504-
}
505-
for &from in pkg_crates.get(&pkg).into_iter().flatten() {
506-
add_dep(&mut crate_graph, from, name.clone(), to);
529+
}
530+
// Add a dependency on the rustc_private crates for all targets of each package
531+
// which opts in
532+
for dep in rustc_workspace.packages() {
533+
let name = CrateName::normalize_dashes(&rustc_workspace[dep].name);
534+
535+
if let Some(&to) = pkg_to_lib_crate.get(&dep) {
536+
for pkg in cargo.packages() {
537+
let package = &cargo[pkg];
538+
if !package.metadata.rustc_private {
539+
continue;
540+
}
541+
for &from in pkg_crates.get(&pkg).into_iter().flatten() {
542+
// Avoid creating duplicate dependencies
543+
// This avoids the situation where `from` depends on e.g. `arrayvec`, but
544+
// `rust_analyzer` thinks that it should use the one from the `rustcSource`
545+
// instead of the one from `crates.io`
546+
if !crate_graph[from].dependencies.iter().any(|d| d.name == name) {
547+
add_dep(crate_graph, from, name.clone(), to);
507548
}
508549
}
509550
}
510551
}
511552
}
512-
crate_graph
513553
}
514554

515555
fn add_target_crate_root(

crates/rust-analyzer/src/config.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,8 @@ config_data! {
181181
runnables_cargoExtraArgs: Vec<String> = "[]",
182182

183183
/// Path to the rust compiler sources, for usage in rustc_private projects, or "discover"
184-
/// to try to automatically find it.
184+
/// to try to automatically find it. Any project which uses rust-analyzer with the rustcPrivate
185+
/// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
185186
rustcSource : Option<String> = "null",
186187

187188
/// Additional arguments to `rustfmt`.

docs/user/generated_config.adoc

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@
107107
[[rust-analyzer.runnables.cargoExtraArgs]]rust-analyzer.runnables.cargoExtraArgs (default: `[]`)::
108108
Additional arguments to be passed to cargo for runnables such as tests or binaries.\nFor example, it may be `--release`.
109109
[[rust-analyzer.rustcSource]]rust-analyzer.rustcSource (default: `null`)::
110-
Path to the rust compiler sources, for usage in rustc_private projects, or "discover" to try to automatically find it.
110+
Path to the rust compiler sources, for usage in rustc_private projects, or "discover" to try to automatically find it. Any project which uses rust-analyzer with the rustcPrivate crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
111111
[[rust-analyzer.rustfmt.extraArgs]]rust-analyzer.rustfmt.extraArgs (default: `[]`)::
112112
Additional arguments to `rustfmt`.
113113
[[rust-analyzer.rustfmt.overrideCommand]]rust-analyzer.rustfmt.overrideCommand (default: `null`)::

editors/code/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -713,7 +713,7 @@
713713
}
714714
},
715715
"rust-analyzer.rustcSource": {
716-
"markdownDescription": "Path to the rust compiler sources, for usage in rustc_private projects, or \"discover\" to try to automatically find it.",
716+
"markdownDescription": "Path to the rust compiler sources, for usage in rustc_private projects, or \"discover\" to try to automatically find it. Any project which uses rust-analyzer with the rustcPrivate crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.",
717717
"default": null,
718718
"type": [
719719
"null",

0 commit comments

Comments
 (0)