Skip to content

Commit 0ccb3b8

Browse files
committed
Move dedup-dev-deps tests into rust-analyzer crate
1 parent b1404d3 commit 0ccb3b8

File tree

8 files changed

+234
-153
lines changed

8 files changed

+234
-153
lines changed

crates/base-db/src/input.rs

+11-44
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ pub struct CrateData {
295295

296296
impl CrateData {
297297
/// Check if [`other`] is almost equal to [`self`] ignoring `CrateOrigin` value.
298-
fn eq_ignoring_origin_and_deps(&self, other: &CrateData, ignore_dev_deps: bool) -> bool {
298+
pub fn eq_ignoring_origin_and_deps(&self, other: &CrateData, ignore_dev_deps: bool) -> bool {
299299
// This method has some obscure bits. These are mostly there to be compliant with
300300
// some patches. References to the patches are given.
301301
if self.root_file_id != other.root_file_id {
@@ -622,57 +622,24 @@ impl CrateGraph {
622622
&mut self,
623623
mut other: CrateGraph,
624624
proc_macros: &mut ProcMacroPaths,
625-
may_merge: impl Fn((CrateId, &CrateData), (CrateId, &CrateData)) -> bool,
625+
merge: impl Fn((CrateId, &mut CrateData), (CrateId, &CrateData)) -> bool,
626626
) -> FxHashMap<CrateId, CrateId> {
627+
let m = self.len();
627628
let topo = other.crates_in_topological_order();
628629
let mut id_map: FxHashMap<CrateId, CrateId> = FxHashMap::default();
629630
for topo in topo {
630631
let crate_data = &mut other.arena[topo];
631632

632633
crate_data.dependencies.iter_mut().for_each(|dep| dep.crate_id = id_map[&dep.crate_id]);
633634
crate_data.dependencies.sort_by_key(|dep| dep.crate_id);
634-
let res = self.arena.iter().find_map(|(id, data)| {
635-
if !may_merge((id, &data), (topo, &crate_data)) {
636-
return None;
637-
}
638-
639-
match (&data.origin, &crate_data.origin) {
640-
(a, b) if a == b => {
641-
if data.eq_ignoring_origin_and_deps(crate_data, false) {
642-
return Some((id, false));
643-
}
644-
}
645-
(a @ CrateOrigin::Local { .. }, CrateOrigin::Library { .. })
646-
| (a @ CrateOrigin::Library { .. }, CrateOrigin::Local { .. }) => {
647-
// If the origins differ, check if the two crates are equal without
648-
// considering the dev dependencies, if they are, they most likely are in
649-
// different loaded workspaces which may cause issues. We keep the local
650-
// version and discard the library one as the local version may have
651-
// dev-dependencies that we want to keep resolving. See #15656 for more
652-
// information.
653-
if data.eq_ignoring_origin_and_deps(crate_data, true) {
654-
return Some((id, !a.is_local()));
655-
}
656-
}
657-
(_, _) => return None,
658-
}
659-
660-
None
661-
});
662-
663-
let new_id = if let Some((res, should_update_lib_to_local)) = res {
664-
if should_update_lib_to_local {
665-
assert!(self.arena[res].origin.is_lib());
666-
assert!(crate_data.origin.is_local());
667-
self.arena[res].origin = crate_data.origin.clone();
668-
669-
// Move local's dev dependencies into the newly-local-formerly-lib crate.
670-
self.arena[res].dependencies = crate_data.dependencies.clone();
671-
}
672-
res
673-
} else {
674-
self.arena.alloc(crate_data.clone())
675-
};
635+
let res = self
636+
.arena
637+
.iter_mut()
638+
.take(m)
639+
.find_map(|(id, data)| merge((id, data), (topo, &crate_data)).then_some(id));
640+
641+
let new_id =
642+
if let Some(res) = res { res } else { self.arena.alloc(crate_data.clone()) };
676643
id_map.insert(topo, new_id);
677644
}
678645

crates/project-model/src/tests.rs

+2-54
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ fn crate_graph_dedup_identical() {
238238

239239
let (d_crate_graph, mut d_proc_macros) = (crate_graph.clone(), proc_macros.clone());
240240

241-
crate_graph.extend(d_crate_graph.clone(), &mut d_proc_macros, |_, _| true);
241+
crate_graph.extend(d_crate_graph.clone(), &mut d_proc_macros, |(_, a), (_, b)| a == b);
242242
assert!(crate_graph.iter().eq(d_crate_graph.iter()));
243243
assert_eq!(proc_macros, d_proc_macros);
244244
}
@@ -254,62 +254,10 @@ fn crate_graph_dedup() {
254254
load_cargo_with_fake_sysroot(path_map, "regex-metadata.json");
255255
assert_eq!(regex_crate_graph.iter().count(), 60);
256256

257-
crate_graph.extend(regex_crate_graph, &mut regex_proc_macros, |_, _| true);
257+
crate_graph.extend(regex_crate_graph, &mut regex_proc_macros, |(_, a), (_, b)| a == b);
258258
assert_eq!(crate_graph.iter().count(), 118);
259259
}
260260

261-
#[test]
262-
fn test_deduplicate_origin_dev() {
263-
let path_map = &mut Default::default();
264-
let (mut crate_graph, _proc_macros) =
265-
load_cargo_with_fake_sysroot(path_map, "deduplication_crate_graph_A.json");
266-
crate_graph.sort_deps();
267-
let (crate_graph_1, mut _proc_macros_2) =
268-
load_cargo_with_fake_sysroot(path_map, "deduplication_crate_graph_B.json");
269-
270-
crate_graph.extend(crate_graph_1, &mut _proc_macros_2, |_, _| true);
271-
272-
let mut crates_named_p2 = vec![];
273-
for id in crate_graph.iter() {
274-
let krate = &crate_graph[id];
275-
if let Some(name) = krate.display_name.as_ref() {
276-
if name.to_string() == "p2" {
277-
crates_named_p2.push(krate);
278-
}
279-
}
280-
}
281-
282-
assert!(crates_named_p2.len() == 1);
283-
let p2 = crates_named_p2[0];
284-
assert!(p2.origin.is_local());
285-
}
286-
287-
#[test]
288-
fn test_deduplicate_origin_dev_rev() {
289-
let path_map = &mut Default::default();
290-
let (mut crate_graph, _proc_macros) =
291-
load_cargo_with_fake_sysroot(path_map, "deduplication_crate_graph_B.json");
292-
crate_graph.sort_deps();
293-
let (crate_graph_1, mut _proc_macros_2) =
294-
load_cargo_with_fake_sysroot(path_map, "deduplication_crate_graph_A.json");
295-
296-
crate_graph.extend(crate_graph_1, &mut _proc_macros_2, |_, _| true);
297-
298-
let mut crates_named_p2 = vec![];
299-
for id in crate_graph.iter() {
300-
let krate = &crate_graph[id];
301-
if let Some(name) = krate.display_name.as_ref() {
302-
if name.to_string() == "p2" {
303-
crates_named_p2.push(krate);
304-
}
305-
}
306-
}
307-
308-
assert!(crates_named_p2.len() == 1);
309-
let p2 = crates_named_p2[0];
310-
assert!(p2.origin.is_local());
311-
}
312-
313261
#[test]
314262
fn smoke_test_real_sysroot_cargo() {
315263
if std::env::var("SYSROOT_CARGO_METADATA").is_err() {

crates/project-model/src/workspace.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1411,7 +1411,7 @@ fn sysroot_to_crate_graph(
14111411

14121412
// Remove all crates except the ones we are interested in to keep the sysroot graph small.
14131413
let removed_mapping = cg.remove_crates_except(&marker_set);
1414-
let mapping = crate_graph.extend(cg, &mut pm, |_, _| true);
1414+
let mapping = crate_graph.extend(cg, &mut pm, |(_, a), (_, b)| a == b);
14151415

14161416
// Map the id through the removal mapping first, then through the crate graph extension mapping.
14171417
pub_deps.iter_mut().for_each(|(_, cid, _)| {

crates/rust-analyzer/src/lib.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,9 @@ mod integrated_benchmarks;
4747

4848
use serde::de::DeserializeOwned;
4949

50-
pub use crate::{caps::server_capabilities, main_loop::main_loop, version::version};
50+
pub use crate::{
51+
caps::server_capabilities, main_loop::main_loop, reload::ws_to_crate_graph, version::version,
52+
};
5153

5254
pub fn from_json<T: DeserializeOwned>(
5355
what: &'static str,

crates/rust-analyzer/src/reload.rs

+99-53
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ use std::{iter, mem};
1717

1818
use flycheck::{FlycheckConfig, FlycheckHandle};
1919
use hir::{db::DefDatabase, Change, ProcMacros};
20+
use ide::CrateId;
2021
use ide_db::{
21-
base_db::{salsa::Durability, CrateGraph, ProcMacroPaths},
22+
base_db::{salsa::Durability, CrateGraph, CrateOrigin, ProcMacroPaths, Version},
2223
FxHashMap,
2324
};
2425
use itertools::Itertools;
@@ -28,7 +29,7 @@ use project_model::{ProjectWorkspace, WorkspaceBuildScripts};
2829
use rustc_hash::FxHashSet;
2930
use stdx::{format_to, thread::ThreadIntent};
3031
use triomphe::Arc;
31-
use vfs::{AbsPath, ChangeKind};
32+
use vfs::{AbsPath, AbsPathBuf, ChangeKind};
3233

3334
use crate::{
3435
config::{Config, FilesWatcher, LinkedProject},
@@ -532,7 +533,7 @@ impl GlobalState {
532533
// deleted or created we trigger a reconstruction of the crate graph
533534
let mut crate_graph_file_dependencies = FxHashSet::default();
534535

535-
let mut load = |path: &AbsPath| {
536+
let load = |path: &AbsPath| {
536537
let _p = tracing::span!(tracing::Level::DEBUG, "switch_workspaces::load").entered();
537538
let vfs_path = vfs::VfsPath::from(path.to_path_buf());
538539
crate_graph_file_dependencies.insert(vfs_path.clone());
@@ -547,56 +548,8 @@ impl GlobalState {
547548
}
548549
};
549550

550-
let mut crate_graph = CrateGraph::default();
551-
let mut proc_macro_paths = Vec::default();
552-
let mut layouts = Vec::default();
553-
let mut toolchains = Vec::default();
554-
let e = Err(Arc::from("missing layout"));
555-
for ws in &**self.workspaces {
556-
let (other, mut crate_proc_macros) =
557-
ws.to_crate_graph(&mut load, self.config.extra_env());
558-
let num_layouts = layouts.len();
559-
let num_toolchains = toolchains.len();
560-
let (toolchain, layout) = match ws {
561-
ProjectWorkspace::Cargo { toolchain, target_layout, .. }
562-
| ProjectWorkspace::Json { toolchain, target_layout, .. } => {
563-
(toolchain.clone(), target_layout.clone())
564-
}
565-
ProjectWorkspace::DetachedFiles { .. } => {
566-
(None, Err("detached files have no layout".into()))
567-
}
568-
};
569-
570-
let mapping = crate_graph.extend(
571-
other,
572-
&mut crate_proc_macros,
573-
|(cg_id, _cg_data), (_o_id, _o_data)| {
574-
// if the newly created crate graph's layout is equal to the crate of the merged graph, then
575-
// we can merge the crates.
576-
layouts[cg_id.into_raw().into_u32() as usize] == layout
577-
&& toolchains[cg_id.into_raw().into_u32() as usize] == toolchain
578-
},
579-
);
580-
// Populate the side tables for the newly merged crates
581-
mapping.values().for_each(|val| {
582-
let idx = val.into_raw().into_u32() as usize;
583-
// we only need to consider crates that were not merged and remapped, as the
584-
// ones that were remapped already have the correct layout and toolchain
585-
if idx >= num_layouts {
586-
if layouts.len() <= idx {
587-
layouts.resize(idx + 1, e.clone());
588-
}
589-
layouts[idx] = layout.clone();
590-
}
591-
if idx >= num_toolchains {
592-
if toolchains.len() <= idx {
593-
toolchains.resize(idx + 1, None);
594-
}
595-
toolchains[idx] = toolchain.clone();
596-
}
597-
});
598-
proc_macro_paths.push(crate_proc_macros);
599-
}
551+
let (crate_graph, proc_macro_paths, layouts, toolchains) =
552+
ws_to_crate_graph(&self.workspaces, self.config.extra_env(), load);
600553

601554
let mut change = Change::new();
602555
if self.config.expand_proc_macros() {
@@ -609,6 +562,8 @@ impl GlobalState {
609562
self.fetch_proc_macros_queue.request_op(cause, proc_macro_paths);
610563
}
611564
change.set_crate_graph(crate_graph);
565+
change.set_target_data_layouts(layouts);
566+
change.set_toolchains(toolchains);
612567
self.analysis_host.apply_change(change);
613568
self.crate_graph_file_dependencies = crate_graph_file_dependencies;
614569
}
@@ -719,6 +674,97 @@ impl GlobalState {
719674
}
720675
}
721676

677+
// FIXME: Move this into load-cargo?
678+
pub fn ws_to_crate_graph(
679+
workspaces: &[ProjectWorkspace],
680+
extra_env: &FxHashMap<String, String>,
681+
mut load: impl FnMut(&AbsPath) -> Option<vfs::FileId>,
682+
) -> (
683+
CrateGraph,
684+
Vec<FxHashMap<CrateId, Result<(Option<String>, AbsPathBuf), String>>>,
685+
Vec<Result<Arc<str>, Arc<str>>>,
686+
Vec<Option<Version>>,
687+
) {
688+
let mut crate_graph = CrateGraph::default();
689+
let mut proc_macro_paths = Vec::default();
690+
let mut layouts = Vec::default();
691+
let mut toolchains = Vec::default();
692+
let e = Err(Arc::from("missing layout"));
693+
for ws in workspaces {
694+
let (other, mut crate_proc_macros) = ws.to_crate_graph(&mut load, extra_env);
695+
let num_layouts = layouts.len();
696+
let num_toolchains = toolchains.len();
697+
let (toolchain, layout) = match ws {
698+
ProjectWorkspace::Cargo { toolchain, target_layout, .. }
699+
| ProjectWorkspace::Json { toolchain, target_layout, .. } => {
700+
(toolchain.clone(), target_layout.clone())
701+
}
702+
ProjectWorkspace::DetachedFiles { .. } => {
703+
(None, Err("detached files have no layout".into()))
704+
}
705+
};
706+
707+
let mapping = crate_graph.extend(
708+
other,
709+
&mut crate_proc_macros,
710+
|(cg_id, _cg_data), (_o_id, _o_data)| {
711+
// if the newly created crate graph's layout is equal to the crate of the merged graph, then
712+
// we can merge the crates.
713+
let id = cg_id.into_raw().into_u32() as usize;
714+
if layouts[id] == layout && toolchains[id] == toolchain {
715+
let (res, update) = match (&_cg_data.origin, &_o_data.origin) {
716+
(a, b)
717+
if a == b && _cg_data.eq_ignoring_origin_and_deps(_o_data, false) =>
718+
{
719+
(true, false)
720+
}
721+
(a @ CrateOrigin::Local { .. }, CrateOrigin::Library { .. })
722+
| (a @ CrateOrigin::Library { .. }, CrateOrigin::Local { .. })
723+
if _cg_data.eq_ignoring_origin_and_deps(_o_data, true) =>
724+
{
725+
// If the origins differ, check if the two crates are equal without
726+
// considering the dev dependencies, if they are, they most likely are in
727+
// different loaded workspaces which may cause issues. We keep the local
728+
// version and discard the library one as the local version may have
729+
// dev-dependencies that we want to keep resolving. See #15656 for more
730+
// information.
731+
(true, !a.is_local())
732+
}
733+
(_, _) => (false, false),
734+
};
735+
if res && update {
736+
_cg_data.origin = _o_data.origin.clone();
737+
_cg_data.dependencies = _o_data.dependencies.clone();
738+
}
739+
res
740+
} else {
741+
false
742+
}
743+
},
744+
);
745+
// Populate the side tables for the newly merged crates
746+
mapping.values().for_each(|val| {
747+
let idx = val.into_raw().into_u32() as usize;
748+
// we only need to consider crates that were not merged and remapped, as the
749+
// ones that were remapped already have the correct layout and toolchain
750+
if idx >= num_layouts {
751+
if layouts.len() <= idx {
752+
layouts.resize(idx + 1, e.clone());
753+
}
754+
layouts[idx] = layout.clone();
755+
}
756+
if idx >= num_toolchains {
757+
if toolchains.len() <= idx {
758+
toolchains.resize(idx + 1, None);
759+
}
760+
toolchains[idx] = toolchain.clone();
761+
}
762+
});
763+
proc_macro_paths.push(crate_proc_macros);
764+
}
765+
(crate_graph, proc_macro_paths, layouts, toolchains)
766+
}
767+
722768
pub(crate) fn should_refresh_for_change(path: &AbsPath, change_kind: ChangeKind) -> bool {
723769
const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
724770
const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];

0 commit comments

Comments
 (0)