Move flycheck crate into rust-analyzer main crate

This commit is contained in:
Lukas Wirth 2024-08-08 12:52:55 +02:00
parent b02c6bff7d
commit 085e4126e6
15 changed files with 71 additions and 113 deletions

20
Cargo.lock generated
View file

@ -423,23 +423,6 @@ dependencies = [
"miniz_oxide",
]
[[package]]
name = "flycheck"
version = "0.0.0"
dependencies = [
"cargo_metadata",
"crossbeam-channel",
"paths",
"process-wrap",
"project-model",
"rustc-hash",
"serde",
"serde_json",
"stdx",
"toolchain",
"tracing",
]
[[package]]
name = "form_urlencoded"
version = "1.2.1"
@ -1650,12 +1633,12 @@ version = "0.0.0"
dependencies = [
"always-assert",
"anyhow",
"cargo_metadata",
"cfg",
"crossbeam-channel",
"dirs",
"dissimilar",
"expect-test",
"flycheck",
"hir",
"hir-def",
"hir-ty",
@ -1676,6 +1659,7 @@ dependencies = [
"parser",
"paths",
"proc-macro-api",
"process-wrap",
"profile",
"project-model",
"rayon",

View file

@ -52,7 +52,6 @@ debug = 2
# local crates
base-db = { path = "./crates/base-db", version = "0.0.0" }
cfg = { path = "./crates/cfg", version = "0.0.0", features = ["tt"] }
flycheck = { path = "./crates/flycheck", version = "0.0.0" }
hir = { path = "./crates/hir", version = "0.0.0" }
hir-def = { path = "./crates/hir-def", version = "0.0.0" }
hir-expand = { path = "./crates/hir-expand", version = "0.0.0" }

View file

@ -1,31 +0,0 @@
[package]
name = "flycheck"
version = "0.0.0"
repository.workspace = true
description = "Functionality needed for rust-analyzer to run `cargo` commands in a background thread."
authors.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lib]
doctest = false
[dependencies]
cargo_metadata.workspace = true
crossbeam-channel.workspace = true
tracing.workspace = true
rustc-hash.workspace = true
serde_json.workspace = true
serde.workspace = true
process-wrap.workspace = true
# local deps
paths.workspace = true
stdx.workspace = true
toolchain.workspace = true
project-model.workspace = true
[lints]
workspace = true

View file

@ -47,9 +47,10 @@ always-assert = "0.2.0"
walkdir = "2.3.2"
semver.workspace = true
memchr = "2.7.1"
cargo_metadata.workspace = true
process-wrap.workspace = true
cfg.workspace = true
flycheck.workspace = true
hir-def.workspace = true
hir-ty.workspace = true
hir.workspace = true

View file

@ -7,7 +7,6 @@ use std::{fmt, iter, ops::Not, sync::OnceLock};
use cfg::{CfgAtom, CfgDiff};
use dirs::config_dir;
use flycheck::{CargoOptions, FlycheckConfig};
use hir::Symbol;
use ide::{
AssistConfig, CallableSnippets, CompletionConfig, DiagnosticsConfig, ExprFillDefaultMode,
@ -37,6 +36,7 @@ use vfs::{AbsPath, AbsPathBuf, VfsPath};
use crate::{
capabilities::ClientCapabilities,
diagnostics::DiagnosticsMapConfig,
flycheck::{CargoOptions, FlycheckConfig},
lsp_ext::{WorkspaceSymbolSearchKind, WorkspaceSymbolSearchScope},
};
@ -1899,7 +1899,7 @@ impl Config {
*self.check_workspace(None)
}
pub fn cargo_test_options(&self) -> CargoOptions {
pub(crate) fn cargo_test_options(&self) -> CargoOptions {
CargoOptions {
target_triples: self.cargo_target(None).clone().into_iter().collect(),
all_targets: false,
@ -1915,7 +1915,7 @@ impl Config {
}
}
pub fn flycheck(&self) -> FlycheckConfig {
pub(crate) fn flycheck(&self) -> FlycheckConfig {
match &self.check_overrideCommand(None) {
Some(args) if !args.is_empty() => {
let mut args = args.clone();
@ -1925,16 +1925,18 @@ impl Config {
args,
extra_env: self.check_extra_env(),
invocation_strategy: match self.check_invocationStrategy(None) {
InvocationStrategy::Once => flycheck::InvocationStrategy::Once,
InvocationStrategy::Once => crate::flycheck::InvocationStrategy::Once,
InvocationStrategy::PerWorkspace => {
flycheck::InvocationStrategy::PerWorkspace
crate::flycheck::InvocationStrategy::PerWorkspace
}
},
invocation_location: match self.check_invocationLocation(None) {
InvocationLocation::Root => {
flycheck::InvocationLocation::Root(self.root_path.clone())
crate::flycheck::InvocationLocation::Root(self.root_path.clone())
}
InvocationLocation::Workspace => {
crate::flycheck::InvocationLocation::Workspace
}
InvocationLocation::Workspace => flycheck::InvocationLocation::Workspace,
},
}
}

View file

@ -1,7 +1,7 @@
//! This module provides the functionality needed to convert diagnostics from
//! `cargo check` json format to the LSP diagnostic format.
use flycheck::{Applicability, DiagnosticLevel, DiagnosticSpan};
use crate::flycheck::{Applicability, DiagnosticLevel, DiagnosticSpan};
use itertools::Itertools;
use rustc_hash::FxHashMap;
use stdx::format_to;
@ -17,8 +17,8 @@ use super::{DiagnosticsMapConfig, Fix};
/// Determines the LSP severity from a diagnostic
fn diagnostic_severity(
config: &DiagnosticsMapConfig,
level: flycheck::DiagnosticLevel,
code: Option<flycheck::DiagnosticCode>,
level: crate::flycheck::DiagnosticLevel,
code: Option<crate::flycheck::DiagnosticCode>,
) -> Option<lsp_types::DiagnosticSeverity> {
let res = match level {
DiagnosticLevel::Ice => lsp_types::DiagnosticSeverity::ERROR,
@ -181,7 +181,7 @@ enum MappedRustChildDiagnostic {
fn map_rust_child_diagnostic(
config: &DiagnosticsMapConfig,
workspace_root: &AbsPath,
rd: &flycheck::Diagnostic,
rd: &crate::flycheck::Diagnostic,
snap: &GlobalStateSnapshot,
) -> MappedRustChildDiagnostic {
let spans: Vec<&DiagnosticSpan> = rd.spans.iter().filter(|s| s.is_primary).collect();
@ -284,7 +284,7 @@ pub(crate) struct MappedRustDiagnostic {
/// If the diagnostic has no primary span this will return `None`
pub(crate) fn map_rust_diagnostic_to_lsp(
config: &DiagnosticsMapConfig,
rd: &flycheck::Diagnostic,
rd: &crate::flycheck::Diagnostic,
workspace_root: &AbsPath,
snap: &GlobalStateSnapshot,
) -> Vec<MappedRustDiagnostic> {
@ -537,7 +537,8 @@ mod tests {
}
fn check_with_config(config: DiagnosticsMapConfig, diagnostics_json: &str, expect: ExpectFile) {
let diagnostic: flycheck::Diagnostic = serde_json::from_str(diagnostics_json).unwrap();
let diagnostic: crate::flycheck::Diagnostic =
serde_json::from_str(diagnostics_json).unwrap();
let workspace_root: &AbsPath = Utf8Path::new("/test/").try_into().unwrap();
let (sender, _) = crossbeam_channel::unbounded();
let state = GlobalState::new(

View file

@ -13,43 +13,42 @@ use paths::{AbsPath, AbsPathBuf, Utf8PathBuf};
use rustc_hash::FxHashMap;
use serde::Deserialize;
pub use cargo_metadata::diagnostic::{
pub(crate) use cargo_metadata::diagnostic::{
Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
DiagnosticSpanMacroExpansion,
};
use toolchain::Tool;
mod command;
pub mod project_json;
pub(crate) mod project_json;
mod test_runner;
use command::{CommandHandle, ParseFromLine};
pub use test_runner::{CargoTestHandle, CargoTestMessage, TestState, TestTarget};
pub(crate) use test_runner::{CargoTestHandle, CargoTestMessage, TestState, TestTarget};
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum InvocationStrategy {
pub(crate) enum InvocationStrategy {
Once,
#[default]
PerWorkspace,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum InvocationLocation {
pub(crate) enum InvocationLocation {
Root(AbsPathBuf),
#[default]
Workspace,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CargoOptions {
pub target_triples: Vec<String>,
pub all_targets: bool,
pub no_default_features: bool,
pub all_features: bool,
pub features: Vec<String>,
pub extra_args: Vec<String>,
pub extra_env: FxHashMap<String, String>,
pub target_dir: Option<Utf8PathBuf>,
pub(crate) struct CargoOptions {
pub(crate) target_triples: 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_env: FxHashMap<String, String>,
pub(crate) target_dir: Option<Utf8PathBuf>,
}
impl CargoOptions {
@ -79,7 +78,7 @@ impl CargoOptions {
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FlycheckConfig {
pub(crate) enum FlycheckConfig {
CargoCommand {
command: String,
options: CargoOptions,
@ -110,7 +109,7 @@ impl fmt::Display for FlycheckConfig {
/// diagnostics based on the output.
/// The spawned thread is shut down when this struct is dropped.
#[derive(Debug)]
pub struct FlycheckHandle {
pub(crate) struct FlycheckHandle {
// XXX: drop order is significant
sender: Sender<StateChange>,
_thread: stdx::thread::JoinHandle,
@ -118,7 +117,7 @@ pub struct FlycheckHandle {
}
impl FlycheckHandle {
pub fn spawn(
pub(crate) fn spawn(
id: usize,
sender: Box<dyn Fn(Message) + Send>,
config: FlycheckConfig,
@ -137,28 +136,28 @@ impl FlycheckHandle {
}
/// Schedule a re-start of the cargo check worker to do a workspace wide check.
pub fn restart_workspace(&self, saved_file: Option<AbsPathBuf>) {
pub(crate) fn restart_workspace(&self, saved_file: Option<AbsPathBuf>) {
self.sender.send(StateChange::Restart { package: None, saved_file }).unwrap();
}
/// Schedule a re-start of the cargo check worker to do a package wide check.
pub fn restart_for_package(&self, package: String) {
pub(crate) fn restart_for_package(&self, package: String) {
self.sender
.send(StateChange::Restart { package: Some(package), saved_file: None })
.unwrap();
}
/// Stop this cargo check worker.
pub fn cancel(&self) {
pub(crate) fn cancel(&self) {
self.sender.send(StateChange::Cancel).unwrap();
}
pub fn id(&self) -> usize {
pub(crate) fn id(&self) -> usize {
self.id
}
}
pub enum Message {
pub(crate) enum Message {
/// Request adding a diagnostic with fixes included to a file
AddDiagnostic { id: usize, workspace_root: AbsPathBuf, diagnostic: Diagnostic },
@ -193,7 +192,7 @@ impl fmt::Debug for Message {
}
#[derive(Debug)]
pub enum Progress {
pub(crate) enum Progress {
DidStart,
DidCheckCrate(String),
DidFinish(io::Result<()>),
@ -241,7 +240,7 @@ enum FlycheckStatus {
Finished,
}
pub const SAVED_FILE_PLACEHOLDER: &str = "$saved_file";
pub(crate) const SAVED_FILE_PLACEHOLDER: &str = "$saved_file";
impl FlycheckActor {
fn new(

View file

@ -7,21 +7,21 @@ use project_model::ProjectJsonData;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::command::{CommandHandle, ParseFromLine};
use crate::flycheck::{CommandHandle, ParseFromLine};
pub const ARG_PLACEHOLDER: &str = "{arg}";
pub(crate) const ARG_PLACEHOLDER: &str = "{arg}";
/// A command wrapper for getting a `rust-project.json`.
///
/// This is analogous to `cargo-metadata`, but for non-Cargo build systems.
pub struct Discover {
pub(crate) struct Discover {
command: Vec<String>,
sender: Sender<DiscoverProjectMessage>,
}
#[derive(PartialEq, Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum DiscoverArgument {
pub(crate) enum DiscoverArgument {
Path(#[serde(serialize_with = "serialize_abs_pathbuf")] AbsPathBuf),
Buildfile(#[serde(serialize_with = "serialize_abs_pathbuf")] AbsPathBuf),
}
@ -36,12 +36,12 @@ where
impl Discover {
/// Create a new [Discover].
pub fn new(sender: Sender<DiscoverProjectMessage>, command: Vec<String>) -> Self {
pub(crate) fn new(sender: Sender<DiscoverProjectMessage>, command: Vec<String>) -> Self {
Self { sender, command }
}
/// Spawn the command inside [Discover] and report progress, if any.
pub fn spawn(&self, discover_arg: DiscoverArgument) -> io::Result<DiscoverHandle> {
pub(crate) fn spawn(&self, discover_arg: DiscoverArgument) -> io::Result<DiscoverHandle> {
let command = &self.command[0];
let args = &self.command[1..];
@ -65,7 +65,7 @@ impl Discover {
/// A handle to a spawned [Discover].
#[derive(Debug)]
pub struct DiscoverHandle {
pub(crate) struct DiscoverHandle {
_handle: CommandHandle<DiscoverProjectMessage>,
}
@ -81,7 +81,7 @@ enum DiscoverProjectData {
}
#[derive(Debug, PartialEq, Clone)]
pub enum DiscoverProjectMessage {
pub(crate) enum DiscoverProjectMessage {
Finished { project: ProjectJsonData, buildfile: AbsPathBuf },
Error { error: String, source: Option<String> },
Progress { message: String },

View file

@ -8,14 +8,14 @@ use paths::AbsPath;
use serde::Deserialize;
use toolchain::Tool;
use crate::{
use crate::flycheck::{
command::{CommandHandle, ParseFromLine},
CargoOptions,
};
#[derive(Debug, Deserialize)]
#[serde(tag = "event", rename_all = "camelCase")]
pub enum TestState {
pub(crate) enum TestState {
Started,
Ok,
Ignored,
@ -24,7 +24,7 @@ pub enum TestState {
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum CargoTestMessage {
pub(crate) enum CargoTestMessage {
Test {
name: String,
#[serde(flatten)]
@ -54,7 +54,7 @@ impl ParseFromLine for CargoTestMessage {
}
#[derive(Debug)]
pub struct CargoTestHandle {
pub(crate) struct CargoTestHandle {
_handle: CommandHandle<CargoTestMessage>,
}
@ -64,13 +64,13 @@ pub struct CargoTestHandle {
// cargo test --package my-package --no-fail-fast -- module::func -Z unstable-options --format=json
#[derive(Debug)]
pub enum TestTarget {
pub(crate) enum TestTarget {
Workspace,
Package(String),
}
impl CargoTestHandle {
pub fn new(
pub(crate) fn new(
path: Option<&str>,
options: CargoOptions,
root: &AbsPath,

View file

@ -5,8 +5,8 @@
use std::{ops::Not as _, time::Instant};
use crate::flycheck::{self, project_json, FlycheckHandle};
use crossbeam_channel::{unbounded, Receiver, Sender};
use flycheck::{project_json, FlycheckHandle};
use hir::ChangeWithProcMacros;
use ide::{Analysis, AnalysisHost, Cancellable, FileId, SourceRootId};
use ide_db::base_db::{CrateId, ProcMacroPaths, SourceDatabase, SourceRootDatabase};

View file

@ -246,15 +246,15 @@ pub(crate) fn handle_run_test(
if let ProjectWorkspaceKind::Cargo { cargo, .. } = &ws.kind {
let test_target = if let Some(namespace_root) = namespace_root {
if let Some(package_name) = find_package_name(namespace_root, cargo) {
flycheck::TestTarget::Package(package_name)
crate::flycheck::TestTarget::Package(package_name)
} else {
flycheck::TestTarget::Workspace
crate::flycheck::TestTarget::Workspace
}
} else {
flycheck::TestTarget::Workspace
crate::flycheck::TestTarget::Workspace
};
let handle = flycheck::CargoTestHandle::new(
let handle = crate::flycheck::CargoTestHandle::new(
test_path,
state.config.cargo_test_options(),
cargo.workspace_root(),

View file

@ -15,6 +15,7 @@ mod capabilities;
mod diagnostics;
mod diff;
mod dispatch;
mod flycheck;
mod hack_recover_crate_name;
mod line_index;
mod main_loop;

View file

@ -9,7 +9,6 @@ use std::{
use always_assert::always;
use crossbeam_channel::{select, Receiver};
use flycheck::project_json;
use ide_db::base_db::{SourceDatabase, SourceRootDatabase, VfsPath};
use lsp_server::{Connection, Notification, Request};
use lsp_types::{notification::Notification as _, TextDocumentIdentifier};
@ -21,6 +20,7 @@ use crate::{
config::Config,
diagnostics::{fetch_native_diagnostics, DiagnosticsGeneration, NativeDiagnosticsFetchKind},
dispatch::{NotificationDispatcher, RequestDispatcher},
flycheck::{self, project_json},
global_state::{file_id_to_url, url_to_file_id, FetchWorkspaceRequest, GlobalState},
hack_recover_crate_name,
lsp::{

View file

@ -15,7 +15,6 @@
// FIXME: This is a mess that needs some untangling work
use std::{iter, mem};
use flycheck::{FlycheckConfig, FlycheckHandle};
use hir::{db::DefDatabase, ChangeWithProcMacros, ProcMacros, ProcMacrosBuilder};
use ide_db::{
base_db::{salsa::Durability, CrateGraph, ProcMacroPaths, Version},
@ -32,6 +31,7 @@ use vfs::{AbsPath, AbsPathBuf, ChangeKind};
use crate::{
config::{Config, FilesWatcher, LinkedProject},
flycheck::{FlycheckConfig, FlycheckHandle},
global_state::{FetchWorkspaceRequest, GlobalState},
lsp_ext,
main_loop::{DiscoverProjectParam, Task},
@ -749,12 +749,14 @@ impl GlobalState {
let config = self.config.flycheck();
let sender = self.flycheck_sender.clone();
let invocation_strategy = match config {
FlycheckConfig::CargoCommand { .. } => flycheck::InvocationStrategy::PerWorkspace,
FlycheckConfig::CargoCommand { .. } => {
crate::flycheck::InvocationStrategy::PerWorkspace
}
FlycheckConfig::CustomCommand { invocation_strategy, .. } => invocation_strategy,
};
self.flycheck = match invocation_strategy {
flycheck::InvocationStrategy::Once => vec![FlycheckHandle::spawn(
crate::flycheck::InvocationStrategy::Once => vec![FlycheckHandle::spawn(
0,
Box::new(move |msg| sender.send(msg).unwrap()),
config,
@ -762,7 +764,7 @@ impl GlobalState {
self.config.root_path().clone(),
None,
)],
flycheck::InvocationStrategy::PerWorkspace => {
crate::flycheck::InvocationStrategy::PerWorkspace => {
self.workspaces
.iter()
.enumerate()