Skip to content

internal: Restructure some modules in rust-analyzer crate #15548

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

Merged
merged 1 commit into from
Sep 2, 2023
Merged
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
10 changes: 6 additions & 4 deletions crates/rust-analyzer/src/caps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ use lsp_types::{
};
use serde_json::json;

use crate::config::{Config, RustfmtConfig};
use crate::line_index::PositionEncoding;
use crate::lsp_ext::negotiated_encoding;
use crate::semantic_tokens;
use crate::{
config::{Config, RustfmtConfig},
line_index::PositionEncoding,
lsp::semantic_tokens,
lsp_ext::negotiated_encoding,
};

pub fn server_capabilities(config: &Config) -> ServerCapabilities {
ServerCapabilities {
Expand Down
2 changes: 1 addition & 1 deletion crates/rust-analyzer/src/cli/lsif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use vfs::{AbsPathBuf, Vfs};
use crate::{
cli::flags,
line_index::{LineEndings, LineIndex, PositionEncoding},
to_proto,
lsp::to_proto,
version::version,
};

Expand Down
40 changes: 39 additions & 1 deletion crates/rust-analyzer/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use nohash_hasher::{IntMap, IntSet};
use rustc_hash::FxHashSet;
use triomphe::Arc;

use crate::lsp_ext;
use crate::{global_state::GlobalStateSnapshot, lsp, lsp_ext};

pub(crate) type CheckFixes = Arc<IntMap<usize, IntMap<FileId, Vec<Fix>>>>;

Expand Down Expand Up @@ -122,3 +122,41 @@ fn are_diagnostics_equal(left: &lsp_types::Diagnostic, right: &lsp_types::Diagno
&& left.range == right.range
&& left.message == right.message
}

pub(crate) fn fetch_native_diagnostics(
snapshot: GlobalStateSnapshot,
subscriptions: Vec<FileId>,
) -> Vec<(FileId, Vec<lsp_types::Diagnostic>)> {
let _p = profile::span("fetch_native_diagnostics");
let _ctx = stdx::panic_context::enter("fetch_native_diagnostics".to_owned());
subscriptions
.into_iter()
.filter_map(|file_id| {
let line_index = snapshot.file_line_index(file_id).ok()?;
let diagnostics = snapshot
.analysis
.diagnostics(
&snapshot.config.diagnostics(),
ide::AssistResolveStrategy::None,
file_id,
)
.ok()?
.into_iter()
.map(move |d| lsp_types::Diagnostic {
range: lsp::to_proto::range(&line_index, d.range),
severity: Some(lsp::to_proto::diagnostic_severity(d.severity)),
code: Some(lsp_types::NumberOrString::String(d.code.as_str().to_string())),
code_description: Some(lsp_types::CodeDescription {
href: lsp_types::Url::parse(&d.code.url()).unwrap(),
}),
source: Some("rust-analyzer".to_string()),
message: d.message,
related_information: None,
tags: d.unused.then(|| vec![lsp_types::DiagnosticTag::UNNECESSARY]),
data: None,
})
.collect::<Vec<_>>();
Some((file_id, diagnostics))
})
.collect()
}
4 changes: 2 additions & 2 deletions crates/rust-analyzer/src/diagnostics/to_proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use stdx::format_to;
use vfs::{AbsPath, AbsPathBuf};

use crate::{
global_state::GlobalStateSnapshot, line_index::PositionEncoding, lsp_ext,
to_proto::url_from_abs_path,
global_state::GlobalStateSnapshot, line_index::PositionEncoding,
lsp::to_proto::url_from_abs_path, lsp_ext,
};

use super::{DiagnosticsMapConfig, Fix};
Expand Down
2 changes: 1 addition & 1 deletion crates/rust-analyzer/src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use stdx::thread::ThreadIntent;

use crate::{
global_state::{GlobalState, GlobalStateSnapshot},
lsp::LspError,
main_loop::Task,
version::version,
LspError,
};

/// A visitor for routing a raw JSON request to an appropriate handler function.
Expand Down
6 changes: 3 additions & 3 deletions crates/rust-analyzer/src/global_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,14 @@ use vfs::{AnchoredPathBuf, Vfs};
use crate::{
config::{Config, ConfigError},
diagnostics::{CheckFixes, DiagnosticCollection},
from_proto,
line_index::{LineEndings, LineIndex},
lsp::{from_proto, to_proto::url_from_abs_path},
lsp_ext,
main_loop::Task,
mem_docs::MemDocs,
op_queue::OpQueue,
reload,
task_pool::TaskPool,
to_proto::url_from_abs_path,
};

// Enforces drop order
Expand All @@ -40,7 +39,7 @@ pub(crate) struct Handle<H, C> {
}

pub(crate) type ReqHandler = fn(&mut GlobalState, lsp_server::Response);
pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;

/// `GlobalState` is the primary mutable state of the language server
///
Expand All @@ -49,6 +48,7 @@ pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
/// incremental salsa database.
///
/// Note that this struct has more than one impl in various modules!
#[doc(alias = "GlobalMess")]
pub(crate) struct GlobalState {
sender: Sender<lsp_server::Message>,
req_queue: ReqQueue,
Expand Down
8 changes: 6 additions & 2 deletions crates/rust-analyzer/src/handlers/notification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@ use triomphe::Arc;
use vfs::{AbsPathBuf, ChangeKind, VfsPath};

use crate::{
config::Config, from_proto, global_state::GlobalState, lsp_ext::RunFlycheckParams,
lsp_utils::apply_document_changes, mem_docs::DocumentData, reload,
config::Config,
global_state::GlobalState,
lsp::{from_proto, utils::apply_document_changes},
lsp_ext::RunFlycheckParams,
mem_docs::DocumentData,
reload,
};

pub(crate) fn handle_cancel(state: &mut GlobalState, params: CancelParams) -> anyhow::Result<()> {
Expand Down
8 changes: 5 additions & 3 deletions crates/rust-analyzer/src/handlers/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,17 @@ use crate::{
cargo_target_spec::CargoTargetSpec,
config::{Config, RustfmtConfig, WorkspaceSymbolConfig},
diff::diff,
from_proto,
global_state::{GlobalState, GlobalStateSnapshot},
line_index::LineEndings,
lsp::{
from_proto, to_proto,
utils::{all_edits_are_disjoint, invalid_params_error},
LspError,
},
lsp_ext::{
self, CrateInfoResult, ExternalDocsPair, ExternalDocsResponse, FetchDependencyListParams,
FetchDependencyListResult, PositionOrRange, ViewCrateGraphParams, WorkspaceSymbolParams,
},
lsp_utils::{all_edits_are_disjoint, invalid_params_error},
to_proto, LspError,
};

pub(crate) fn handle_workspace_reload(state: &mut GlobalState, _: ()) -> anyhow::Result<()> {
Expand Down
29 changes: 2 additions & 27 deletions crates/rust-analyzer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,14 @@ mod cargo_target_spec;
mod diagnostics;
mod diff;
mod dispatch;
mod from_proto;
mod global_state;
mod line_index;
mod lsp_utils;
mod main_loop;
mod markdown;
mod mem_docs;
mod op_queue;
mod reload;
mod semantic_tokens;
mod task_pool;
mod to_proto;
mod version;

mod handlers {
Expand All @@ -43,13 +39,12 @@ mod handlers {
}

pub mod config;
pub mod lsp_ext;
pub mod lsp;
use self::lsp::ext as lsp_ext;

#[cfg(test)]
mod integrated_benchmarks;

use std::fmt;

use serde::de::DeserializeOwned;

pub use crate::{caps::server_capabilities, main_loop::main_loop, version::version};
Expand All @@ -61,23 +56,3 @@ pub fn from_json<T: DeserializeOwned>(
serde_json::from_value(json.clone())
.map_err(|e| anyhow::format_err!("Failed to deserialize {what}: {e}; {json}"))
}

#[derive(Debug)]
struct LspError {
code: i32,
message: String,
}

impl LspError {
fn new(code: i32, message: String) -> LspError {
LspError { code, message }
}
}

impl fmt::Display for LspError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Language Server request failed with {}. ({})", self.code, self.message)
}
}

impl std::error::Error for LspError {}
29 changes: 29 additions & 0 deletions crates/rust-analyzer/src/lsp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//! Custom LSP definitions and protocol conversions.

use core::fmt;

pub(crate) mod utils;
pub(crate) mod semantic_tokens;
pub mod ext;
pub(crate) mod from_proto;
pub(crate) mod to_proto;

#[derive(Debug)]
pub(crate) struct LspError {
pub(crate) code: i32,
pub(crate) message: String,
}

impl LspError {
pub(crate) fn new(code: i32, message: String) -> LspError {
LspError { code, message }
}
}

impl fmt::Display for LspError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Language Server request failed with {}. ({})", self.code, self.message)
}
}

impl std::error::Error for LspError {}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use crate::{
from_json,
global_state::GlobalStateSnapshot,
line_index::{LineIndex, PositionEncoding},
lsp::utils::invalid_params_error,
lsp_ext,
lsp_utils::invalid_params_error,
};

pub(crate) fn abs_path(url: &lsp_types::Url) -> anyhow::Result<AbsPathBuf> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ use crate::{
config::{CallInfoConfig, Config},
global_state::GlobalStateSnapshot,
line_index::{LineEndings, LineIndex, PositionEncoding},
lsp::{
semantic_tokens::{self, standard_fallback_type},
utils::invalid_params_error,
LspError,
},
lsp_ext::{self, SnippetTextEdit},
lsp_utils::invalid_params_error,
semantic_tokens::{self, standard_fallback_type},
};

pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
Expand Down Expand Up @@ -1425,8 +1428,8 @@ pub(crate) mod command {

use crate::{
global_state::GlobalStateSnapshot,
lsp::to_proto::{location, location_link},
lsp_ext,
to_proto::{location, location_link},
};

pub(crate) fn show_references(
Expand Down Expand Up @@ -1532,7 +1535,7 @@ pub(crate) fn markup_content(
lsp_types::MarkupContent { kind, value }
}

pub(crate) fn rename_error(err: RenameError) -> crate::LspError {
pub(crate) fn rename_error(err: RenameError) -> LspError {
// This is wrong, but we don't have a better alternative I suppose?
// https://github.com/microsoft/language-server-protocol/issues/1341
invalid_params_error(err.to_string())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ use lsp_types::request::Request;
use triomphe::Arc;

use crate::{
from_proto,
global_state::GlobalState,
line_index::{LineEndings, LineIndex, PositionEncoding},
lsp_ext, LspError,
lsp::{from_proto, LspError},
lsp_ext,
};

pub(crate) fn invalid_params_error(message: String) -> LspError {
Expand Down
Loading