Skip to content

Commit 003620f

Browse files
committed
Use downcasting for CargoTomlNotFoundError
1 parent e7bb82c commit 003620f

File tree

6 files changed

+48
-97
lines changed

6 files changed

+48
-97
lines changed

crates/ra_db/src/lib.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,7 @@ use ra_syntax::{ast, Parse, SourceFile, TextRange, TextUnit};
1010

1111
pub use crate::{
1212
cancellation::Canceled,
13-
input::{
14-
CrateGraph, CrateId, Dependency, Edition, Env, FileId, ParseEditionError, SourceRoot,
15-
SourceRootId,
16-
},
13+
input::{CrateGraph, CrateId, Dependency, Edition, Env, FileId, SourceRoot, SourceRootId},
1714
};
1815
pub use relative_path::{RelativePath, RelativePathBuf};
1916
pub use salsa;

crates/ra_lsp_server/src/main_loop.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ use lsp_types::{ClientCapabilities, NumberOrString};
1313
use ra_cargo_watch::{CheckOptions, CheckTask};
1414
use ra_ide::{Canceled, FeatureFlags, FileId, LibraryData, SourceRootId};
1515
use ra_prof::profile;
16-
use ra_project_model::WorkspaceError;
1716
use ra_vfs::{VfsTask, Watch};
1817
use relative_path::RelativePathBuf;
1918
use rustc_hash::FxHashSet;
@@ -92,7 +91,8 @@ pub fn main_loop(
9291
Ok(workspace) => loaded_workspaces.push(workspace),
9392
Err(e) => {
9493
log::error!("loading workspace failed: {}", e);
95-
if let WorkspaceError::CargoTomlNotFound(_) = e {
94+
if let Some(ra_project_model::CargoTomlNotFoundError(_)) = e.downcast_ref()
95+
{
9696
if !feature_flags.get("notifications.cargo-toml-not-found") {
9797
continue;
9898
}

crates/ra_project_model/src/cargo_workspace.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use ra_db::Edition;
88
use rustc_hash::FxHashMap;
99
use serde::Deserialize;
1010

11-
use crate::WorkspaceError;
11+
use crate::Result;
1212

1313
/// `CargoWorkspace` represents the logical structure of, well, a Cargo
1414
/// workspace. It pretty closely mirrors `cargo metadata` output.
@@ -156,7 +156,7 @@ impl CargoWorkspace {
156156
pub fn from_cargo_metadata(
157157
cargo_toml: &Path,
158158
cargo_features: &CargoFeatures,
159-
) -> Result<CargoWorkspace, WorkspaceError> {
159+
) -> Result<CargoWorkspace> {
160160
let mut meta = MetadataCommand::new();
161161
meta.manifest_path(cargo_toml);
162162
if cargo_features.all_features {
@@ -171,7 +171,7 @@ impl CargoWorkspace {
171171
if let Some(parent) = cargo_toml.parent() {
172172
meta.current_dir(parent);
173173
}
174-
let meta = meta.exec().map_err(|e| WorkspaceError::CargoMetadataFailed(e))?;
174+
let meta = meta.exec().map_err(|e| format!("cargo metadata failed: {}", e))?;
175175
let mut pkg_by_id = FxHashMap::default();
176176
let mut packages = Arena::default();
177177
let mut targets = Arena::default();

crates/ra_project_model/src/lib.rs

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
mod cargo_workspace;
44
mod json_project;
55
mod sysroot;
6-
mod workspace_error;
76

87
use std::{
8+
error::Error,
99
fs::File,
1010
io::BufReader,
1111
path::{Path, PathBuf},
@@ -21,9 +21,27 @@ pub use crate::{
2121
cargo_workspace::{CargoFeatures, CargoWorkspace, Package, Target, TargetKind},
2222
json_project::JsonProject,
2323
sysroot::Sysroot,
24-
workspace_error::WorkspaceError,
2524
};
2625

26+
pub type Result<T> = ::std::result::Result<T, Box<dyn Error + Send + Sync>>;
27+
28+
#[derive(Clone, PartialEq, Eq, Hash)]
29+
pub struct CargoTomlNotFoundError(pub PathBuf);
30+
31+
impl std::fmt::Display for CargoTomlNotFoundError {
32+
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33+
write!(fmt, "can't find Cargo.toml at {}", self.0.display())
34+
}
35+
}
36+
37+
impl std::fmt::Debug for CargoTomlNotFoundError {
38+
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39+
write!(fmt, "can't find Cargo.toml at {}", self.0.display())
40+
}
41+
}
42+
43+
impl Error for CargoTomlNotFoundError {}
44+
2745
#[derive(Debug, Clone)]
2846
pub enum ProjectWorkspace {
2947
/// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
@@ -58,27 +76,20 @@ impl PackageRoot {
5876
}
5977

6078
impl ProjectWorkspace {
61-
pub fn discover(
62-
path: &Path,
63-
cargo_features: &CargoFeatures,
64-
) -> Result<ProjectWorkspace, WorkspaceError> {
79+
pub fn discover(path: &Path, cargo_features: &CargoFeatures) -> Result<ProjectWorkspace> {
6580
ProjectWorkspace::discover_with_sysroot(path, true, cargo_features)
6681
}
6782

6883
pub fn discover_with_sysroot(
6984
path: &Path,
7085
with_sysroot: bool,
7186
cargo_features: &CargoFeatures,
72-
) -> Result<ProjectWorkspace, WorkspaceError> {
87+
) -> Result<ProjectWorkspace> {
7388
match find_rust_project_json(path) {
7489
Some(json_path) => {
75-
let file =
76-
File::open(json_path).map_err(|err| WorkspaceError::OpenWorkspaceError(err))?;
90+
let file = File::open(json_path)?;
7791
let reader = BufReader::new(file);
78-
Ok(ProjectWorkspace::Json {
79-
project: from_reader(reader)
80-
.map_err(|err| WorkspaceError::ReadWorkspaceError(err))?,
81-
})
92+
Ok(ProjectWorkspace::Json { project: from_reader(reader)? })
8293
}
8394
None => {
8495
let cargo_toml = find_cargo_toml(path)?;
@@ -355,7 +366,7 @@ fn find_rust_project_json(path: &Path) -> Option<PathBuf> {
355366
None
356367
}
357368

358-
fn find_cargo_toml(path: &Path) -> Result<PathBuf, WorkspaceError> {
369+
fn find_cargo_toml(path: &Path) -> Result<PathBuf> {
359370
if path.ends_with("Cargo.toml") {
360371
return Ok(path.to_path_buf());
361372
}
@@ -367,7 +378,7 @@ fn find_cargo_toml(path: &Path) -> Result<PathBuf, WorkspaceError> {
367378
}
368379
curr = path.parent();
369380
}
370-
Err(WorkspaceError::CargoTomlNotFound(path.to_path_buf()))
381+
Err(Box::new(CargoTomlNotFoundError(path.to_path_buf())))
371382
}
372383

373384
pub fn get_rustc_cfg_options() -> CfgOptions {
@@ -381,16 +392,13 @@ pub fn get_rustc_cfg_options() -> CfgOptions {
381392
}
382393
}
383394

384-
match (|| -> Result<_, WorkspaceError> {
395+
match (|| -> Result<_> {
385396
// `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
386-
let output = Command::new("rustc")
387-
.args(&["--print", "cfg", "-O"])
388-
.output()
389-
.map_err(|err| WorkspaceError::RustcError(err))?;
397+
let output = Command::new("rustc").args(&["--print", "cfg", "-O"]).output()?;
390398
if !output.status.success() {
391-
Err(WorkspaceError::RustcCfgError)?;
399+
Err("failed to get rustc cfgs")?;
392400
}
393-
Ok(String::from_utf8(output.stdout).map_err(|err| WorkspaceError::RustcOutputError(err))?)
401+
Ok(String::from_utf8(output.stdout)?)
394402
})() {
395403
Ok(rustc_cfgs) => {
396404
for line in rustc_cfgs.lines() {

crates/ra_project_model/src/sysroot.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use std::{
88

99
use ra_arena::{impl_arena_id, Arena, RawId};
1010

11-
use crate::WorkspaceError;
11+
use crate::Result;
1212

1313
#[derive(Default, Debug, Clone)]
1414
pub struct Sysroot {
@@ -47,11 +47,16 @@ impl Sysroot {
4747
self.crates.iter().map(|(id, _data)| id)
4848
}
4949

50-
pub fn discover(cargo_toml: &Path) -> Result<Sysroot, WorkspaceError> {
50+
pub fn discover(cargo_toml: &Path) -> Result<Sysroot> {
5151
let src = try_find_src_path(cargo_toml)?;
5252

5353
if !src.exists() {
54-
return Err(WorkspaceError::NoStdLib(src));
54+
Err(format!(
55+
"can't load standard library from sysroot\n\
56+
{:?}\n\
57+
try running `rustup component add rust-src` or set `RUST_SRC_PATH`",
58+
src,
59+
))?;
5560
}
5661

5762
let mut sysroot = Sysroot { crates: Arena::default() };
@@ -85,21 +90,19 @@ impl Sysroot {
8590
}
8691
}
8792

88-
fn try_find_src_path(cargo_toml: &Path) -> Result<PathBuf, WorkspaceError> {
93+
fn try_find_src_path(cargo_toml: &Path) -> Result<PathBuf> {
8994
if let Ok(path) = env::var("RUST_SRC_PATH") {
9095
return Ok(path.into());
9196
}
9297

9398
let rustc_output = Command::new("rustc")
9499
.current_dir(cargo_toml.parent().unwrap())
95100
.args(&["--print", "sysroot"])
96-
.output()
97-
.map_err(|err| WorkspaceError::RustcError(err))?;
101+
.output()?;
98102
if !rustc_output.status.success() {
99-
Err(WorkspaceError::SysrootNotFound)?;
103+
Err("failed to locate sysroot")?;
100104
}
101-
let stdout = String::from_utf8(rustc_output.stdout)
102-
.map_err(|err| WorkspaceError::RustcOutputError(err))?;
105+
let stdout = String::from_utf8(rustc_output.stdout)?;
103106
let sysroot_path = Path::new(stdout.trim());
104107
Ok(sysroot_path.join("lib/rustlib/src/rust/src"))
105108
}

crates/ra_project_model/src/workspace_error.rs

Lines changed: 0 additions & 57 deletions
This file was deleted.

0 commit comments

Comments
 (0)