Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Contextualize flycheck config loading #18911

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 5 additions & 3 deletions crates/rust-analyzer/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use vfs::{AbsPath, AbsPathBuf, VfsPath};

use crate::{
diagnostics::DiagnosticsMapConfig,
flycheck::{CargoOptions, FlycheckConfig},
flycheck::command::{CargoOptions, FlycheckConfig},
lsp::capabilities::ClientCapabilities,
lsp_ext::{WorkspaceSymbolSearchKind, WorkspaceSymbolSearchScope},
};
Expand Down Expand Up @@ -2082,9 +2082,11 @@ impl Config {
args,
extra_env: self.check_extra_env(source_root),
invocation_strategy: match self.check_invocationStrategy(source_root) {
InvocationStrategy::Once => crate::flycheck::InvocationStrategy::Once,
InvocationStrategy::Once => {
crate::flycheck::command::InvocationStrategy::Once
}
InvocationStrategy::PerWorkspace => {
crate::flycheck::InvocationStrategy::PerWorkspace
crate::flycheck::command::InvocationStrategy::PerWorkspace
}
},
}
Expand Down
226 changes: 37 additions & 189 deletions crates/rust-analyzer/src/flycheck.rs
Original file line number Diff line number Diff line change
@@ -1,103 +1,24 @@
//! Flycheck provides the functionality needed to run `cargo check` to provide
//! LSP diagnostics based on the output of the command.

use std::{fmt, io, process::Command, time::Duration};
use std::{fmt, io, time::Duration};

use cargo_metadata::PackageId;
use command::{check_command, FlycheckConfig, Target};
use crossbeam_channel::{select_biased, unbounded, Receiver, Sender};
use ide_db::FxHashSet;
use paths::{AbsPath, AbsPathBuf, Utf8PathBuf};
use rustc_hash::FxHashMap;
use paths::AbsPathBuf;
use serde::Deserialize as _;
use serde_derive::Deserialize;

pub(crate) use cargo_metadata::diagnostic::{
Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
};
use toolchain::Tool;
use triomphe::Arc;

use crate::command::{CommandHandle, ParseFromLine};

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) enum InvocationStrategy {
Once,
#[default]
PerWorkspace,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CargoOptions {
pub(crate) target_tuples: Vec<String>,
pub(crate) all_targets: bool,
pub(crate) no_default_features: bool,
pub(crate) all_features: bool,
pub(crate) features: Vec<String>,
pub(crate) extra_args: Vec<String>,
pub(crate) extra_test_bin_args: Vec<String>,
pub(crate) extra_env: FxHashMap<String, String>,
pub(crate) target_dir: Option<Utf8PathBuf>,
}

#[derive(Clone, Debug)]
pub(crate) enum Target {
Bin(String),
Example(String),
Benchmark(String),
Test(String),
}

impl CargoOptions {
pub(crate) fn apply_on_command(&self, cmd: &mut Command) {
for target in &self.target_tuples {
cmd.args(["--target", target.as_str()]);
}
if self.all_targets {
cmd.arg("--all-targets");
}
if self.all_features {
cmd.arg("--all-features");
} else {
if self.no_default_features {
cmd.arg("--no-default-features");
}
if !self.features.is_empty() {
cmd.arg("--features");
cmd.arg(self.features.join(" "));
}
}
if let Some(target_dir) = &self.target_dir {
cmd.arg("--target-dir").arg(target_dir);
}
cmd.envs(&self.extra_env);
}
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum FlycheckConfig {
CargoCommand {
command: String,
options: CargoOptions,
ansi_color_output: bool,
},
CustomCommand {
command: String,
args: Vec<String>,
extra_env: FxHashMap<String, String>,
invocation_strategy: InvocationStrategy,
},
}

impl fmt::Display for FlycheckConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FlycheckConfig::CargoCommand { command, .. } => write!(f, "cargo {command}"),
FlycheckConfig::CustomCommand { command, args, .. } => {
write!(f, "{command} {}", args.join(" "))
}
}
}
}
pub(crate) mod command;

/// Flycheck wraps the shared state and communication machinery used for
/// running `cargo check` (or other compatible command) and providing
Expand All @@ -115,13 +36,11 @@ impl FlycheckHandle {
pub(crate) fn spawn(
id: usize,
sender: Sender<FlycheckMessage>,
config: FlycheckConfig,
sysroot_root: Option<AbsPathBuf>,
workspace_root: AbsPathBuf,
manifest_path: Option<AbsPathBuf>,
) -> FlycheckHandle {
let actor =
FlycheckActor::new(id, sender, config, sysroot_root, workspace_root, manifest_path);
let actor = FlycheckActor::new(id, sender, sysroot_root, workspace_root, manifest_path);
let (sender, receiver) = unbounded::<StateChange>();
let thread = stdx::thread::Builder::new(stdx::thread::ThreadIntent::Worker)
.name("Flycheck".to_owned())
Expand All @@ -131,14 +50,21 @@ impl FlycheckHandle {
}

/// Schedule a re-start of the cargo check worker to do a workspace wide check.
pub(crate) fn restart_workspace(&self, saved_file: Option<AbsPathBuf>) {
self.sender.send(StateChange::Restart { package: None, saved_file, target: None }).unwrap();
pub(crate) fn restart_workspace(&self, saved_file: Option<AbsPathBuf>, config: FlycheckConfig) {
self.sender
.send(StateChange::Restart { package: None, saved_file, target: None, config })
.unwrap();
}

/// Schedule a re-start of the cargo check worker to do a package wide check.
pub(crate) fn restart_for_package(&self, package: String, target: Option<Target>) {
pub(crate) fn restart_for_package(
&self,
package: String,
target: Option<Target>,
config: FlycheckConfig,
) {
self.sender
.send(StateChange::Restart { package: Some(package), saved_file: None, target })
.send(StateChange::Restart { package: Some(package), saved_file: None, target, config })
.unwrap();
}

Expand Down Expand Up @@ -208,7 +134,12 @@ pub(crate) enum Progress {
}

enum StateChange {
Restart { package: Option<String>, saved_file: Option<AbsPathBuf>, target: Option<Target> },
Restart {
package: Option<String>,
saved_file: Option<AbsPathBuf>,
target: Option<Target>,
config: FlycheckConfig,
},
Cancel,
}

Expand All @@ -218,7 +149,6 @@ struct FlycheckActor {
id: usize,

sender: Sender<FlycheckMessage>,
config: FlycheckConfig,
manifest_path: Option<AbsPathBuf>,
/// Either the workspace root of the workspace we are flychecking,
/// or the project root of the project.
Expand All @@ -243,13 +173,10 @@ enum Event {
CheckEvent(Option<CargoCheckMessage>),
}

pub(crate) const SAVED_FILE_PLACEHOLDER: &str = "$saved_file";

impl FlycheckActor {
fn new(
id: usize,
sender: Sender<FlycheckMessage>,
config: FlycheckConfig,
sysroot_root: Option<AbsPathBuf>,
workspace_root: AbsPathBuf,
manifest_path: Option<AbsPathBuf>,
Expand All @@ -258,7 +185,6 @@ impl FlycheckActor {
FlycheckActor {
id,
sender,
config,
sysroot_root,
root: Arc::new(workspace_root),
manifest_path,
Expand Down Expand Up @@ -293,7 +219,12 @@ impl FlycheckActor {
tracing::debug!(flycheck_id = self.id, "flycheck cancelled");
self.cancel_check_process();
}
Event::RequestStateChange(StateChange::Restart { package, saved_file, target }) => {
Event::RequestStateChange(StateChange::Restart {
package,
saved_file,
target,
config,
}) => {
// Cancel the previously spawned process
self.cancel_check_process();
while let Ok(restart) = inbox.recv_timeout(Duration::from_millis(50)) {
Expand All @@ -303,9 +234,15 @@ impl FlycheckActor {
}
}

let Some(command) =
self.check_command(package.as_deref(), saved_file.as_deref(), target)
else {
let Some(command) = check_command(
&self.root,
&self.sysroot_root,
&self.manifest_path,
config,
package.as_deref(),
saved_file.as_deref(),
target,
) else {
continue;
};

Expand Down Expand Up @@ -438,95 +375,6 @@ impl FlycheckActor {
self.diagnostics_received = false;
}

/// Construct a `Command` object for checking the user's code. If the user
/// has specified a custom command with placeholders that we cannot fill,
/// return None.
fn check_command(
&self,
package: Option<&str>,
saved_file: Option<&AbsPath>,
target: Option<Target>,
) -> Option<Command> {
match &self.config {
FlycheckConfig::CargoCommand { command, options, ansi_color_output } => {
let mut cmd = toolchain::command(Tool::Cargo.path(), &*self.root);
if let Some(sysroot_root) = &self.sysroot_root {
cmd.env("RUSTUP_TOOLCHAIN", AsRef::<std::path::Path>::as_ref(sysroot_root));
}
cmd.arg(command);

match package {
Some(pkg) => cmd.arg("-p").arg(pkg),
None => cmd.arg("--workspace"),
};

if let Some(tgt) = target {
match tgt {
Target::Bin(tgt) => cmd.arg("--bin").arg(tgt),
Target::Example(tgt) => cmd.arg("--example").arg(tgt),
Target::Test(tgt) => cmd.arg("--test").arg(tgt),
Target::Benchmark(tgt) => cmd.arg("--bench").arg(tgt),
};
}

cmd.arg(if *ansi_color_output {
"--message-format=json-diagnostic-rendered-ansi"
} else {
"--message-format=json"
});

if let Some(manifest_path) = &self.manifest_path {
cmd.arg("--manifest-path");
cmd.arg(manifest_path);
if manifest_path.extension() == Some("rs") {
cmd.arg("-Zscript");
}
}

cmd.arg("--keep-going");

options.apply_on_command(&mut cmd);
cmd.args(&options.extra_args);
Some(cmd)
}
FlycheckConfig::CustomCommand { command, args, extra_env, invocation_strategy } => {
let root = match invocation_strategy {
InvocationStrategy::Once => &*self.root,
InvocationStrategy::PerWorkspace => {
// FIXME: &affected_workspace
&*self.root
}
};
let mut cmd = toolchain::command(command, root);
cmd.envs(extra_env);

// If the custom command has a $saved_file placeholder, and
// we're saving a file, replace the placeholder in the arguments.
if let Some(saved_file) = saved_file {
for arg in args {
if arg == SAVED_FILE_PLACEHOLDER {
cmd.arg(saved_file);
} else {
cmd.arg(arg);
}
}
} else {
for arg in args {
if arg == SAVED_FILE_PLACEHOLDER {
// The custom command has a $saved_file placeholder,
// but we had an IDE event that wasn't a file save. Do nothing.
return None;
}

cmd.arg(arg);
}
}

Some(cmd)
}
}
}

#[track_caller]
fn send(&self, check_task: FlycheckMessage) {
self.sender.send(check_task).unwrap();
Expand Down
Loading
Loading