Skip to content

Commit 8c09608

Browse files
committed
Detect sysroot dependencies
1 parent 9b54e39 commit 8c09608

File tree

3 files changed

+156
-57
lines changed

3 files changed

+156
-57
lines changed

crates/base-db/src/input.rs

+39-7
Original file line numberDiff line numberDiff line change
@@ -386,24 +386,56 @@ impl CrateGraph {
386386
self.arena.alloc(data)
387387
}
388388

389+
/// Remove the crate from crate graph. If any crates depend on this crate, the dependency would be replaced
390+
/// with the second input.
391+
pub fn remove_and_replace(&mut self, id: CrateId, replace_with: CrateId) -> Result<(), CyclicDependenciesError> {
392+
for (x, data) in self.arena.iter() {
393+
if x == id {
394+
continue;
395+
}
396+
for edge in &data.dependencies {
397+
if edge.crate_id == id {
398+
self.check_cycle_after_dependency(edge.crate_id, replace_with)?;
399+
}
400+
}
401+
}
402+
// if everything was ok, start to replace
403+
for (x, data) in self.arena.iter_mut() {
404+
if x == id {
405+
continue;
406+
}
407+
for edge in &mut data.dependencies {
408+
if edge.crate_id == id {
409+
edge.crate_id = replace_with;
410+
}
411+
}
412+
}
413+
Ok(())
414+
}
415+
389416
pub fn add_dep(
390417
&mut self,
391418
from: CrateId,
392419
dep: Dependency,
393420
) -> Result<(), CyclicDependenciesError> {
394421
let _p = profile::span("add_dep");
395422

396-
// Check if adding a dep from `from` to `to` creates a cycle. To figure
397-
// that out, look for a path in the *opposite* direction, from `to` to
398-
// `from`.
399-
if let Some(path) = self.find_path(&mut FxHashSet::default(), dep.crate_id, from) {
423+
self.check_cycle_after_dependency(from, dep.crate_id)?;
424+
425+
self.arena[from].add_dep(dep);
426+
Ok(())
427+
}
428+
429+
/// Check if adding a dep from `from` to `to` creates a cycle. To figure
430+
/// that out, look for a path in the *opposite* direction, from `to` to
431+
/// `from`.
432+
fn check_cycle_after_dependency(&self, from: CrateId, to: CrateId) -> Result<(), CyclicDependenciesError> {
433+
if let Some(path) = self.find_path(&mut FxHashSet::default(), to, from) {
400434
let path = path.into_iter().map(|it| (it, self[it].display_name.clone())).collect();
401435
let err = CyclicDependenciesError { path };
402-
assert!(err.from().0 == from && err.to().0 == dep.crate_id);
436+
assert!(err.from().0 == from && err.to().0 == to);
403437
return Err(err);
404438
}
405-
406-
self.arena[from].add_dep(dep);
407439
Ok(())
408440
}
409441

crates/project-model/src/sysroot.rs

+21-4
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@ use la_arena::{Arena, Idx};
1212
use paths::{AbsPath, AbsPathBuf};
1313
use rustc_hash::FxHashMap;
1414

15-
use crate::{utf8_stdout, ManifestPath};
15+
use crate::{utf8_stdout, CargoConfig, CargoWorkspace, ManifestPath};
1616

1717
#[derive(Debug, Clone, Eq, PartialEq)]
1818
pub struct Sysroot {
1919
root: AbsPathBuf,
2020
src_root: AbsPathBuf,
2121
crates: Arena<SysrootCrateData>,
22+
pub cargo_workspace: Option<CargoWorkspace>,
2223
}
2324

2425
pub(crate) type SysrootCrate = Idx<SysrootCrateData>;
@@ -125,9 +126,25 @@ impl Sysroot {
125126
Ok(Sysroot::load(sysroot_dir, sysroot_src_dir))
126127
}
127128

128-
pub fn load(sysroot_dir: AbsPathBuf, sysroot_src_dir: AbsPathBuf) -> Sysroot {
129-
let mut sysroot =
130-
Sysroot { root: sysroot_dir, src_root: sysroot_src_dir, crates: Arena::default() };
129+
pub fn load(sysroot_dir: AbsPathBuf, _sysroot_src_dir: AbsPathBuf) -> Sysroot {
130+
// FIXME: generate /tmp/ra-sysroot-hack from sysroot_src_dir
131+
let path = "/tmp/ra-sysroot-hack";
132+
let cargo_toml =
133+
ManifestPath::try_from(AbsPathBuf::try_from(&*format!("{path}/Cargo.toml")).unwrap())
134+
.unwrap();
135+
let mut sysroot = Sysroot {
136+
root: sysroot_dir,
137+
src_root: AbsPathBuf::try_from(path).unwrap().join("library"),
138+
crates: Arena::default(),
139+
cargo_workspace: CargoWorkspace::fetch_metadata(
140+
&cargo_toml,
141+
&AbsPathBuf::try_from("/home/hamid/oss/rust-analyzer").unwrap(),
142+
&CargoConfig::default(),
143+
&|_| (),
144+
)
145+
.map(CargoWorkspace::new)
146+
.ok(),
147+
};
131148

132149
for path in SYSROOT_CRATES.trim().lines() {
133150
let name = path.split('/').last().unwrap();

crates/project-model/src/workspace.rs

+96-46
Original file line numberDiff line numberDiff line change
@@ -615,20 +615,27 @@ impl ProjectWorkspace {
615615
build_scripts,
616616
toolchain,
617617
target_layout,
618-
} => cargo_to_crate_graph(
619-
load,
620-
rustc.as_ref().ok(),
621-
cargo,
622-
sysroot.as_ref().ok(),
623-
rustc_cfg.clone(),
624-
cfg_overrides,
625-
build_scripts,
626-
match target_layout.as_ref() {
627-
Ok(it) => Ok(Arc::from(it.as_str())),
628-
Err(it) => Err(Arc::from(it.as_str())),
629-
},
630-
toolchain.as_ref().and_then(|it| ReleaseChannel::from_str(it.pre.as_str())),
631-
),
618+
} => {
619+
let mut res = (CrateGraph::default(), ProcMacroPaths::default());
620+
cargo_to_crate_graph(
621+
&mut res.0,
622+
&mut res.1,
623+
load,
624+
rustc.as_ref().ok(),
625+
cargo,
626+
sysroot.as_ref().ok(),
627+
rustc_cfg.clone(),
628+
cfg_overrides,
629+
None,
630+
build_scripts,
631+
match target_layout.as_ref() {
632+
Ok(it) => Ok(Arc::from(it.as_str())),
633+
Err(it) => Err(Arc::from(it.as_str())),
634+
},
635+
toolchain.as_ref().and_then(|it| ReleaseChannel::from_str(it.pre.as_str())),
636+
);
637+
res
638+
}
632639
ProjectWorkspace::DetachedFiles { files, sysroot, rustc_cfg } => {
633640
detached_files_to_crate_graph(
634641
rustc_cfg.clone(),
@@ -815,20 +822,21 @@ fn project_json_to_crate_graph(
815822
}
816823

817824
fn cargo_to_crate_graph(
825+
crate_graph: &mut CrateGraph,
826+
proc_macros: &mut ProcMacroPaths,
818827
load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
819828
rustc: Option<&(CargoWorkspace, WorkspaceBuildScripts)>,
820829
cargo: &CargoWorkspace,
821830
sysroot: Option<&Sysroot>,
822831
rustc_cfg: Vec<CfgFlag>,
823832
override_cfg: &CfgOverrides,
833+
// Don't compute cfg and use this if present
834+
forced_cfg: Option<CfgOptions>,
824835
build_scripts: &WorkspaceBuildScripts,
825836
target_layout: TargetLayoutLoadResult,
826837
channel: Option<ReleaseChannel>,
827-
) -> (CrateGraph, ProcMacroPaths) {
838+
) {
828839
let _p = profile::span("cargo_to_crate_graph");
829-
let mut res = (CrateGraph::default(), ProcMacroPaths::default());
830-
let crate_graph = &mut res.0;
831-
let proc_macros = &mut res.1;
832840
let (public_deps, libproc_macro) = match sysroot {
833841
Some(sysroot) => sysroot_to_crate_graph(
834842
crate_graph,
@@ -858,7 +866,7 @@ fn cargo_to_crate_graph(
858866
for pkg in cargo.packages() {
859867
has_private |= cargo[pkg].metadata.rustc_private;
860868

861-
let cfg_options = {
869+
let cfg_options = forced_cfg.clone().unwrap_or_else(|| {
862870
let mut cfg_options = cfg_options.clone();
863871

864872
// Add test cfg for local crates
@@ -882,7 +890,7 @@ fn cargo_to_crate_graph(
882890
cfg_options.apply_diff(overrides.clone());
883891
};
884892
cfg_options
885-
};
893+
});
886894

887895
let mut lib_tgt = None;
888896
for &tgt in cargo[pkg].targets.iter() {
@@ -989,7 +997,6 @@ fn cargo_to_crate_graph(
989997
);
990998
}
991999
}
992-
res
9931000
}
9941001

9951002
fn detached_files_to_crate_graph(
@@ -1280,31 +1287,74 @@ fn sysroot_to_crate_graph(
12801287
) -> (SysrootPublicDeps, Option<CrateId>) {
12811288
let _p = profile::span("sysroot_to_crate_graph");
12821289
let mut cfg_options = CfgOptions::default();
1283-
cfg_options.extend(rustc_cfg);
1284-
let sysroot_crates: FxHashMap<SysrootCrate, CrateId> = sysroot
1285-
.crates()
1286-
.filter_map(|krate| {
1287-
let file_id = load(&sysroot[krate].root)?;
1288-
1289-
let env = Env::default();
1290-
let display_name = CrateDisplayName::from_canonical_name(sysroot[krate].name.clone());
1291-
let crate_id = crate_graph.add_crate_root(
1292-
file_id,
1293-
Edition::CURRENT,
1294-
Some(display_name),
1295-
None,
1296-
cfg_options.clone(),
1297-
None,
1298-
env,
1299-
false,
1300-
CrateOrigin::Lang(LangCrateOrigin::from(&*sysroot[krate].name)),
1301-
target_layout.clone(),
1302-
channel,
1303-
);
1304-
Some((krate, crate_id))
1305-
})
1306-
.collect();
1307-
1290+
cfg_options.extend(rustc_cfg.clone());
1291+
let sysroot_crates: FxHashMap<SysrootCrate, CrateId> = if let Some(cargo) =
1292+
&sysroot.cargo_workspace
1293+
{
1294+
cargo_to_crate_graph(
1295+
crate_graph,
1296+
&mut Default::default(),
1297+
load,
1298+
None,
1299+
cargo,
1300+
None,
1301+
rustc_cfg,
1302+
&CfgOverrides::default(),
1303+
Some(cfg_options),
1304+
&WorkspaceBuildScripts::default(),
1305+
target_layout,
1306+
channel,
1307+
);
1308+
for crate_name in ["std", "alloc", "core"] {
1309+
let original = crate_graph
1310+
.iter()
1311+
.find(|x| {
1312+
crate_graph[*x].display_name.as_ref().map(|x| x.canonical_name() == crate_name).unwrap_or(false)
1313+
})
1314+
.unwrap();
1315+
let fake_crate_name = format!("rustc-std-workspace-{}", crate_name);
1316+
let fake = crate_graph
1317+
.iter()
1318+
.find(|x| {
1319+
crate_graph[*x].display_name.as_ref().map(|x| x.canonical_name() == fake_crate_name).unwrap_or(false)
1320+
})
1321+
.unwrap();
1322+
crate_graph.remove_and_replace(fake, original).unwrap();
1323+
}
1324+
sysroot
1325+
.crates()
1326+
.filter_map(|krate| {
1327+
let file_id = load(&sysroot[krate].root)?;
1328+
let crate_id = crate_graph.crate_id_for_crate_root(file_id)?;
1329+
Some((krate, crate_id))
1330+
})
1331+
.collect()
1332+
} else {
1333+
sysroot
1334+
.crates()
1335+
.filter_map(|krate| {
1336+
let file_id = load(&sysroot[krate].root)?;
1337+
1338+
let env = Env::default();
1339+
let display_name =
1340+
CrateDisplayName::from_canonical_name(sysroot[krate].name.clone());
1341+
let crate_id = crate_graph.add_crate_root(
1342+
file_id,
1343+
Edition::CURRENT,
1344+
Some(display_name),
1345+
None,
1346+
cfg_options.clone(),
1347+
None,
1348+
env,
1349+
false,
1350+
CrateOrigin::Lang(LangCrateOrigin::from(&*sysroot[krate].name)),
1351+
target_layout.clone(),
1352+
channel,
1353+
);
1354+
Some((krate, crate_id))
1355+
})
1356+
.collect()
1357+
};
13081358
for from in sysroot.crates() {
13091359
for &to in sysroot[from].deps.iter() {
13101360
let name = CrateName::new(&sysroot[to].name).unwrap();

0 commit comments

Comments
 (0)