Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 38 additions & 3 deletions crates/project-model/src/project_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ pub struct ProjectJson {
runnables: Vec<Runnable>,
}

impl std::ops::Index<CrateArrayIdx> for ProjectJson {
type Output = Crate;
fn index(&self, index: CrateArrayIdx) -> &Self::Output {
&self.crates[index.0]
}
}

impl ProjectJson {
/// Create a new ProjectJson instance.
///
Expand Down Expand Up @@ -194,12 +201,11 @@ impl ProjectJson {
&self.project_root
}

pub fn crate_by_root(&self, root: &AbsPath) -> Option<Crate> {
pub fn crate_by_root(&self, root: &AbsPath) -> Option<&Crate> {
self.crates
.iter()
.filter(|krate| krate.is_workspace_member)
.find(|krate| krate.root_module == root)
.cloned()
}

/// Returns the path to the project's manifest, if it exists.
Expand All @@ -213,8 +219,17 @@ impl ProjectJson {
self.crates
.iter()
.filter(|krate| krate.is_workspace_member)
.filter_map(|krate| krate.build.clone())
.filter_map(|krate| krate.build.as_ref())
.find(|build| build.build_file.as_std_path() == path)
.cloned()
}

pub fn crate_by_label(&self, label: &str) -> Option<&Crate> {
// this is fast enough for now, but it's unfortunate that this is O(crates).
self.crates
.iter()
.filter(|krate| krate.is_workspace_member)
.find(|krate| krate.build.as_ref().is_some_and(|build| build.label == label))
}

/// Returns the path to the project's manifest or root folder, if no manifest exists.
Expand All @@ -230,6 +245,10 @@ impl ProjectJson {
pub fn runnables(&self) -> &[Runnable] {
&self.runnables
}

pub fn runnable_template(&self, kind: RunnableKind) -> Option<&Runnable> {
self.runnables().iter().find(|r| r.kind == kind)
}
}

/// A crate points to the root module of a crate and lists the dependencies of the crate. This is
Expand All @@ -255,6 +274,12 @@ pub struct Crate {
pub build: Option<Build>,
}

impl Crate {
pub fn iter_deps(&self) -> impl ExactSizeIterator<Item = CrateArrayIdx> {
self.deps.iter().map(|dep| dep.krate)
}
}

/// Additional, build-specific data about a crate.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Build {
Expand Down Expand Up @@ -325,13 +350,21 @@ pub struct Runnable {
/// The kind of runnable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunnableKind {
/// `cargo check`, basically, with human-readable output.
Check,

/// Can run a binary.
/// May include {label} which will get the label from the `build` section of a crate.
Run,

/// Run a single test.
/// May include {label} which will get the label from the `build` section of a crate.
/// May include {test_id} which will get the test clicked on by the user.
TestOne,

/// Template for checking a target, emitting rustc JSON diagnostics.
/// May include {label} which will get the label from the `build` section of a crate.
Flycheck,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
Expand Down Expand Up @@ -436,6 +469,7 @@ pub struct RunnableData {
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum RunnableKindData {
Flycheck,
Check,
Run,
TestOne,
Expand Down Expand Up @@ -506,6 +540,7 @@ impl From<RunnableKindData> for RunnableKind {
RunnableKindData::Check => RunnableKind::Check,
RunnableKindData::Run => RunnableKind::Run,
RunnableKindData::TestOne => RunnableKind::TestOne,
RunnableKindData::Flycheck => RunnableKind::Flycheck,
}
}
}
Expand Down
47 changes: 29 additions & 18 deletions crates/rust-analyzer/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,8 +474,8 @@ config_data! {

/// Enables automatic discovery of projects using [`DiscoverWorkspaceConfig::command`].
///
/// [`DiscoverWorkspaceConfig`] also requires setting `progress_label` and `files_to_watch`.
/// `progress_label` is used for the title in progress indicators, whereas `files_to_watch`
/// [`DiscoverWorkspaceConfig`] also requires setting `progressLabel` and `filesToWatch`.
/// `progressLabel` is used for the title in progress indicators, whereas `filesToWatch`
/// is used to determine which build system-specific files should be watched in order to
/// reload rust-analyzer.
///
Expand All @@ -484,16 +484,17 @@ config_data! {
/// "rust-analyzer.workspace.discoverConfig": {
/// "command": [
/// "rust-project",
/// "develop-json"
/// "develop-json",
/// "{arg}"
/// ],
/// "progressLabel": "rust-analyzer",
/// "progressLabel": "buck2/rust-project",
/// "filesToWatch": [
/// "BUCK"
/// ]
/// }
/// ```
///
/// ## On `DiscoverWorkspaceConfig::command`
/// ## Workspace Discovery Protocol
///
/// **Warning**: This format is provisional and subject to change.
///
Expand Down Expand Up @@ -861,10 +862,18 @@ config_data! {
/// (i.e., the folder containing the `Cargo.toml`). This can be overwritten
/// by changing `#rust-analyzer.check.invocationStrategy#`.
///
/// If `$saved_file` is part of the command, rust-analyzer will pass
/// the absolute path of the saved file to the provided command. This is
/// intended to be used with non-Cargo build systems.
/// Note that `$saved_file` is experimental and may be removed in the future.
/// It supports two interpolation syntaxes, both mainly intended to be used with
/// [non-Cargo build systems](./non_cargo_based_projects.md):
///
/// - If `{saved_file}` is part of the command, rust-analyzer will pass
/// the absolute path of the saved file to the provided command.
/// (A previous version, `$saved_file`, also works.)
/// - If `{label}` is part of the command, rust-analyzer will pass the
/// Cargo package ID, which can be used with `cargo check -p`, or a build label from
/// `rust-project.json`. If `{label}` is included, rust-analyzer behaves much like
/// [`"rust-analyzer.check.workspace": false`](#check.workspace).
///
///
///
/// An example command would be:
///
Expand Down Expand Up @@ -2382,6 +2391,8 @@ impl Config {

pub(crate) fn cargo_test_options(&self, source_root: Option<SourceRootId>) -> CargoOptions {
CargoOptions {
// Might be nice to allow users to specify test_command = "nextest"
subcommand: "test".into(),
target_tuples: self.cargo_target(source_root).clone().into_iter().collect(),
all_targets: false,
no_default_features: *self.cargo_noDefaultFeatures(source_root),
Expand Down Expand Up @@ -2415,9 +2426,9 @@ impl Config {
},
}
}
Some(_) | None => FlycheckConfig::CargoCommand {
command: self.check_command(source_root).clone(),
options: CargoOptions {
Some(_) | None => FlycheckConfig::Automatic {
cargo_options: CargoOptions {
subcommand: self.check_command(source_root).clone(),
target_tuples: self
.check_targets(source_root)
.clone()
Expand Down Expand Up @@ -4117,8 +4128,8 @@ mod tests {
assert_eq!(config.cargo_targetDir(None), &None);
assert!(matches!(
config.flycheck(None),
FlycheckConfig::CargoCommand {
options: CargoOptions { target_dir_config: TargetDirectoryConfig::None, .. },
FlycheckConfig::Automatic {
cargo_options: CargoOptions { target_dir_config: TargetDirectoryConfig::None, .. },
..
}
));
Expand All @@ -4141,8 +4152,8 @@ mod tests {
Utf8PathBuf::from(std::env::var("CARGO_TARGET_DIR").unwrap_or("target".to_owned()));
assert!(matches!(
config.flycheck(None),
FlycheckConfig::CargoCommand {
options: CargoOptions { target_dir_config, .. },
FlycheckConfig::Automatic {
cargo_options: CargoOptions { target_dir_config, .. },
..
} if target_dir_config.target_dir(Some(&ws_target_dir)).map(Cow::into_owned)
== Some(ws_target_dir.join("rust-analyzer"))
Expand All @@ -4167,8 +4178,8 @@ mod tests {
);
assert!(matches!(
config.flycheck(None),
FlycheckConfig::CargoCommand {
options: CargoOptions { target_dir_config, .. },
FlycheckConfig::Automatic {
cargo_options: CargoOptions { target_dir_config, .. },
..
} if target_dir_config.target_dir(None).map(Cow::into_owned)
== Some(Utf8PathBuf::from("other_folder"))
Expand Down
16 changes: 9 additions & 7 deletions crates/rust-analyzer/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ pub(crate) mod flycheck_to_proto;

use std::mem;

use cargo_metadata::PackageId;
use ide::FileId;
use ide_db::{FxHashMap, base_db::DbPanicContext};
use itertools::Itertools;
Expand All @@ -12,10 +11,13 @@ use smallvec::SmallVec;
use stdx::iter_eq_by;
use triomphe::Arc;

use crate::{global_state::GlobalStateSnapshot, lsp, lsp_ext, main_loop::DiagnosticsTaskKind};
use crate::{
flycheck::PackageSpecifier, global_state::GlobalStateSnapshot, lsp, lsp_ext,
main_loop::DiagnosticsTaskKind,
};

pub(crate) type CheckFixes =
Arc<Vec<FxHashMap<Option<Arc<PackageId>>, FxHashMap<FileId, Vec<Fix>>>>>;
Arc<Vec<FxHashMap<Option<PackageSpecifier>, FxHashMap<FileId, Vec<Fix>>>>>;

#[derive(Debug, Default, Clone)]
pub struct DiagnosticsMapConfig {
Expand All @@ -29,7 +31,7 @@ pub(crate) type DiagnosticsGeneration = usize;

#[derive(Debug, Clone, Default)]
pub(crate) struct WorkspaceFlycheckDiagnostic {
pub(crate) per_package: FxHashMap<Option<Arc<PackageId>>, PackageFlycheckDiagnostic>,
pub(crate) per_package: FxHashMap<Option<PackageSpecifier>, PackageFlycheckDiagnostic>,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -85,7 +87,7 @@ impl DiagnosticCollection {
pub(crate) fn clear_check_for_package(
&mut self,
flycheck_id: usize,
package_id: Arc<PackageId>,
package_id: PackageSpecifier,
) {
let Some(check) = self.check.get_mut(flycheck_id) else {
return;
Expand Down Expand Up @@ -124,7 +126,7 @@ impl DiagnosticCollection {
pub(crate) fn clear_check_older_than_for_package(
&mut self,
flycheck_id: usize,
package_id: Arc<PackageId>,
package_id: PackageSpecifier,
generation: DiagnosticsGeneration,
) {
let Some(check) = self.check.get_mut(flycheck_id) else {
Expand Down Expand Up @@ -154,7 +156,7 @@ impl DiagnosticCollection {
&mut self,
flycheck_id: usize,
generation: DiagnosticsGeneration,
package_id: &Option<Arc<PackageId>>,
package_id: &Option<PackageSpecifier>,
file_id: FileId,
diagnostic: lsp_types::Diagnostic,
fix: Option<Box<Fix>>,
Expand Down
Loading