Skip to content

Commit

Permalink
Auto merge of #16586 - Veykril:crate-graph-side-table, r=Veykril
Browse files Browse the repository at this point in the history
fix: Remove cargo knowledge from `CrateData`

Fixes #16170, Fixes #15656
  • Loading branch information
bors committed Feb 16, 2024
2 parents bb0f93a + ead3691 commit 25d1267
Show file tree
Hide file tree
Showing 34 changed files with 462 additions and 739 deletions.
229 changes: 38 additions & 191 deletions crates/base-db/src/input.rs

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions crates/base-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ pub trait SourceDatabase: FileLoader + std::fmt::Debug {
/// The crate graph.
#[salsa::input]
fn crate_graph(&self) -> Arc<CrateGraph>;

// FIXME: Consider removing this, making HirDatabase::target_data_layout an input query
#[salsa::input]
fn data_layout(&self, krate: CrateId) -> TargetLayoutLoadResult;

#[salsa::input]
fn toolchain(&self, krate: CrateId) -> Option<Version>;

#[salsa::transparent]
fn toolchain_channel(&self, krate: CrateId) -> Option<ReleaseChannel>;
}

fn toolchain_channel(db: &dyn SourceDatabase, krate: CrateId) -> Option<ReleaseChannel> {
db.toolchain(krate).as_ref().and_then(|v| ReleaseChannel::from_str(&v.pre))
}

fn parse(db: &dyn SourceDatabase, file_id: FileId) -> Parse<ast::SourceFile> {
Expand Down
34 changes: 33 additions & 1 deletion crates/hir-expand/src/change.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//! Defines a unit of change that can applied to the database to get the next
//! state. Changes are transactional.
use base_db::{salsa::Durability, CrateGraph, FileChange, SourceDatabaseExt, SourceRoot};
use base_db::{
salsa::Durability, CrateGraph, CrateId, FileChange, SourceDatabaseExt, SourceRoot,
TargetLayoutLoadResult, Version,
};
use la_arena::RawIdx;
use span::FileId;
use triomphe::Arc;

Expand All @@ -10,6 +14,8 @@ use crate::{db::ExpandDatabase, proc_macro::ProcMacros};
pub struct Change {
pub source_change: FileChange,
pub proc_macros: Option<ProcMacros>,
pub toolchains: Option<Vec<Option<Version>>>,
pub target_data_layouts: Option<Vec<TargetLayoutLoadResult>>,
}

impl Change {
Expand All @@ -22,6 +28,24 @@ impl Change {
if let Some(proc_macros) = self.proc_macros {
db.set_proc_macros_with_durability(Arc::new(proc_macros), Durability::HIGH);
}
if let Some(target_data_layouts) = self.target_data_layouts {
for (id, val) in target_data_layouts.into_iter().enumerate() {
db.set_data_layout_with_durability(
CrateId::from_raw(RawIdx::from(id as u32)),
val,
Durability::HIGH,
);
}
}
if let Some(toolchains) = self.toolchains {
for (id, val) in toolchains.into_iter().enumerate() {
db.set_toolchain_with_durability(
CrateId::from_raw(RawIdx::from(id as u32)),
val,
Durability::HIGH,
);
}
}
}

pub fn change_file(&mut self, file_id: FileId, new_text: Option<Arc<str>>) {
Expand All @@ -36,6 +60,14 @@ impl Change {
self.proc_macros = Some(proc_macros);
}

pub fn set_toolchains(&mut self, toolchains: Vec<Option<Version>>) {
self.toolchains = Some(toolchains);
}

pub fn set_target_data_layouts(&mut self, target_data_layouts: Vec<TargetLayoutLoadResult>) {
self.target_data_layouts = Some(target_data_layouts);
}

pub fn set_roots(&mut self, roots: Vec<SourceRoot>) {
self.source_change.set_roots(roots)
}
Expand Down
6 changes: 3 additions & 3 deletions crates/hir-expand/src/declarative.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl DeclarativeMacroExpander {
call_id: MacroCallId,
) -> ExpandResult<tt::Subtree> {
let loc = db.lookup_intern_macro_call(call_id);
let toolchain = &db.crate_graph()[loc.def.krate].toolchain;
let toolchain = db.toolchain(loc.def.krate);
let new_meta_vars = toolchain.as_ref().map_or(false, |version| {
REQUIREMENT.get_or_init(|| VersionReq::parse(">=1.76").unwrap()).matches(
&base_db::Version {
Expand Down Expand Up @@ -67,7 +67,7 @@ impl DeclarativeMacroExpander {
krate: CrateId,
call_site: Span,
) -> ExpandResult<tt::Subtree> {
let toolchain = &db.crate_graph()[krate].toolchain;
let toolchain = db.toolchain(krate);
let new_meta_vars = toolchain.as_ref().map_or(false, |version| {
REQUIREMENT.get_or_init(|| VersionReq::parse(">=1.76").unwrap()).matches(
&base_db::Version {
Expand Down Expand Up @@ -119,7 +119,7 @@ impl DeclarativeMacroExpander {
_ => None,
}
};
let toolchain = crate_data.toolchain.as_ref();
let toolchain = db.toolchain(def_crate);
let new_meta_vars = toolchain.as_ref().map_or(false, |version| {
REQUIREMENT.get_or_init(|| VersionReq::parse(">=1.76").unwrap()).matches(
&base_db::Version {
Expand Down
8 changes: 3 additions & 5 deletions crates/hir-ty/src/layout/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ pub fn target_data_layout_query(
db: &dyn HirDatabase,
krate: CrateId,
) -> Result<Arc<TargetDataLayout>, Arc<str>> {
let crate_graph = db.crate_graph();
let res = crate_graph[krate].target_layout.as_deref();
match res {
Ok(it) => match TargetDataLayout::parse_from_llvm_datalayout_string(it) {
match db.data_layout(krate) {
Ok(it) => match TargetDataLayout::parse_from_llvm_datalayout_string(&it) {
Ok(it) => Ok(Arc::new(it)),
Err(e) => {
Err(match e {
Expand Down Expand Up @@ -44,6 +42,6 @@ pub fn target_data_layout_query(
}.into())
}
},
Err(e) => Err(Arc::from(&**e)),
Err(e) => Err(e),
}
}
4 changes: 2 additions & 2 deletions crates/hir-ty/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn current_machine_data_layout() -> String {
fn eval_goal(ra_fixture: &str, minicore: &str) -> Result<Arc<Layout>, LayoutError> {
let target_data_layout = current_machine_data_layout();
let ra_fixture = format!(
"{minicore}//- /main.rs crate:test target_data_layout:{target_data_layout}\n{ra_fixture}",
"//- target_data_layout: {target_data_layout}\n{minicore}//- /main.rs crate:test\n{ra_fixture}",
);

let (db, file_ids) = TestDB::with_many_files(&ra_fixture);
Expand Down Expand Up @@ -76,7 +76,7 @@ fn eval_goal(ra_fixture: &str, minicore: &str) -> Result<Arc<Layout>, LayoutErro
fn eval_expr(ra_fixture: &str, minicore: &str) -> Result<Arc<Layout>, LayoutError> {
let target_data_layout = current_machine_data_layout();
let ra_fixture = format!(
"{minicore}//- /main.rs crate:test target_data_layout:{target_data_layout}\nfn main(){{let goal = {{{ra_fixture}}};}}",
"//- target_data_layout: {target_data_layout}\n{minicore}//- /main.rs crate:test\nfn main(){{let goal = {{{ra_fixture}}};}}",
);

let (db, file_id) = TestDB::with_single_file(&ra_fixture);
Expand Down
2 changes: 1 addition & 1 deletion crates/ide-completion/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@ impl<'a> CompletionContext<'a> {
let krate = scope.krate();
let module = scope.module();

let toolchain = db.crate_graph()[krate.into()].channel();
let toolchain = db.toolchain_channel(krate.into());
// `toolchain == None` means we're in some detached files. Since we have no information on
// the toolchain being used, let's just allow unstable items to be listed.
let is_nightly = matches!(toolchain, Some(base_db::ReleaseChannel::Nightly) | None);
Expand Down
5 changes: 2 additions & 3 deletions crates/ide-db/src/rename.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ impl Definition {
&self,
sema: &Semantics<'_, RootDatabase>,
new_name: &str,
rename_external: bool,
) -> Result<SourceChange> {
// self.krate() returns None if
// self is a built-in attr, built-in type or tool module.
Expand All @@ -80,8 +79,8 @@ impl Definition {
if let Some(krate) = self.krate(sema.db) {
// Can we not rename non-local items?
// Then bail if non-local
if !rename_external && !krate.origin(sema.db).is_local() {
bail!("Cannot rename a non-local definition as the config for it is disabled")
if !krate.origin(sema.db).is_local() {
bail!("Cannot rename a non-local definition")
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ide-diagnostics/src/handlers/incorrect_case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::IncorrectCase) -> Option<Vec<Ass
let label = format!("Rename to {}", d.suggested_text);
let mut res = unresolved_fix("change_case", &label, frange.range);
if ctx.resolve.should_resolve(&res.id) {
let source_change = def.rename(&ctx.sema, &d.suggested_text, true);
let source_change = def.rename(&ctx.sema, &d.suggested_text);
res.source_change = Some(source_change.ok().unwrap_or_default());
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ide/src/doc_links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ fn get_doc_base_urls(
let Some(krate) = def.krate(db) else { return Default::default() };
let Some(display_name) = krate.display_name(db) else { return Default::default() };
let crate_data = &db.crate_graph()[krate.into()];
let channel = crate_data.channel().unwrap_or(ReleaseChannel::Nightly).as_str();
let channel = db.toolchain_channel(krate.into()).unwrap_or(ReleaseChannel::Nightly).as_str();

let (web_base, local_base) = match &crate_data.origin {
// std and co do not specify `html_root_url` any longer so we gotta handwrite this ourself.
Expand Down
7 changes: 3 additions & 4 deletions crates/ide/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,11 @@ impl Analysis {
Env::default(),
false,
CrateOrigin::Local { repo: None, name: None },
Err("Analysis::from_single_file has no target layout".into()),
None,
);
change.change_file(file_id, Some(Arc::from(text)));
change.set_crate_graph(crate_graph);
change.set_target_data_layouts(vec![Err("fixture has no layout".into())]);
change.set_toolchains(vec![None]);
host.apply_change(change);
(host.analysis(), file_id)
}
Expand Down Expand Up @@ -675,9 +675,8 @@ impl Analysis {
&self,
position: FilePosition,
new_name: &str,
rename_external: bool,
) -> Cancellable<Result<SourceChange, RenameError>> {
self.with_db(|db| rename::rename(db, position, new_name, rename_external))
self.with_db(|db| rename::rename(db, position, new_name))
}

pub fn prepare_rename(
Expand Down
41 changes: 10 additions & 31 deletions crates/ide/src/rename.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ pub(crate) fn rename(
db: &RootDatabase,
position: FilePosition,
new_name: &str,
rename_external: bool,
) -> RenameResult<SourceChange> {
let sema = Semantics::new(db);
let source_file = sema.parse(position.file_id);
Expand All @@ -104,7 +103,7 @@ pub(crate) fn rename(
return rename_to_self(&sema, local);
}
}
def.rename(&sema, new_name, rename_external)
def.rename(&sema, new_name)
})
.collect();

Expand All @@ -123,9 +122,9 @@ pub(crate) fn will_rename_file(
let module = sema.to_module_def(file_id)?;
let def = Definition::Module(module);
let mut change = if is_raw_identifier(new_name_stem) {
def.rename(&sema, &SmolStr::from_iter(["r#", new_name_stem]), true).ok()?
def.rename(&sema, &SmolStr::from_iter(["r#", new_name_stem])).ok()?
} else {
def.rename(&sema, new_name_stem, true).ok()?
def.rename(&sema, new_name_stem).ok()?
};
change.file_system_edits.clear();
Some(change)
Expand Down Expand Up @@ -377,16 +376,11 @@ mod tests {
use super::{RangeInfo, RenameError};

fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
check_with_rename_config(new_name, ra_fixture_before, ra_fixture_after, true);
check_with_rename_config(new_name, ra_fixture_before, ra_fixture_after);
}

#[track_caller]
fn check_with_rename_config(
new_name: &str,
ra_fixture_before: &str,
ra_fixture_after: &str,
rename_external: bool,
) {
fn check_with_rename_config(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
let ra_fixture_after = &trim_indent(ra_fixture_after);
let (analysis, position) = fixture::position(ra_fixture_before);
if !ra_fixture_after.starts_with("error: ") {
Expand All @@ -395,7 +389,7 @@ mod tests {
}
}
let rename_result = analysis
.rename(position, new_name, rename_external)
.rename(position, new_name)
.unwrap_or_else(|err| panic!("Rename to '{new_name}' was cancelled: {err}"));
match rename_result {
Ok(source_change) => {
Expand Down Expand Up @@ -426,10 +420,8 @@ mod tests {

fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
let (analysis, position) = fixture::position(ra_fixture);
let source_change = analysis
.rename(position, new_name, true)
.unwrap()
.expect("Expect returned a RenameError");
let source_change =
analysis.rename(position, new_name).unwrap().expect("Expect returned a RenameError");
expect.assert_eq(&filter_expect(source_change))
}

Expand Down Expand Up @@ -2636,19 +2628,7 @@ pub struct S;
//- /main.rs crate:main deps:lib new_source_root:local
use lib::S$0;
"#,
"error: Cannot rename a non-local definition as the config for it is disabled",
false,
);

check(
"Baz",
r#"
//- /lib.rs crate:lib new_source_root:library
pub struct S;
//- /main.rs crate:main deps:lib new_source_root:local
use lib::S$0;
"#,
"use lib::Baz;\n",
"error: Cannot rename a non-local definition",
);
}

Expand All @@ -2663,8 +2643,7 @@ use core::hash::Hash;
#[derive(H$0ash)]
struct A;
"#,
"error: Cannot rename a non-local definition as the config for it is disabled",
false,
"error: Cannot rename a non-local definition",
);
}

Expand Down
2 changes: 0 additions & 2 deletions crates/ide/src/shuffle_crate_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@ pub(crate) fn shuffle_crate_graph(db: &mut RootDatabase) {
data.env.clone(),
data.is_proc_macro,
data.origin.clone(),
data.target_layout.clone(),
data.toolchain.clone(),
);
new_proc_macros.insert(new_id, proc_macros[&old_id].clone());
map.insert(old_id, new_id);
Expand Down
8 changes: 0 additions & 8 deletions crates/ide/src/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@ pub(crate) fn status(db: &RootDatabase, file_id: Option<FileId>) -> String {
dependencies,
origin,
is_proc_macro,
target_layout,
toolchain,
} = &crate_graph[crate_id];
format_to!(
buf,
Expand All @@ -91,12 +89,6 @@ pub(crate) fn status(db: &RootDatabase, file_id: Option<FileId>) -> String {
format_to!(buf, " Env: {:?}\n", env);
format_to!(buf, " Origin: {:?}\n", origin);
format_to!(buf, " Is a proc macro crate: {}\n", is_proc_macro);
format_to!(buf, " Workspace Target Layout: {:?}\n", target_layout);
format_to!(
buf,
" Workspace Toolchain: {}\n",
toolchain.as_ref().map_or_else(|| "n/a".into(), |v| v.to_string())
);
let deps = dependencies
.iter()
.map(|dep| format!("{}={}", dep.name, dep.crate_id.into_raw()))
Expand Down
Loading

0 comments on commit 25d1267

Please sign in to comment.