diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index e27d85dc92..333ecc8598 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs @@ -104,7 +104,7 @@ pub fn main_loop(ws_roots: Vec, config: Config, connection: Connection) if project_roots.is_empty() && config.notifications.cargo_toml_not_found { show_message( - req::MessageType::Error, + lsp_types::MessageType::Error, format!( "rust-analyzer failed to discover workspace, no Cargo.toml found, dirs searched: {}", ws_roots.iter().format_with(", ", |it, f| f(&it.display())) @@ -124,7 +124,7 @@ pub fn main_loop(ws_roots: Vec, config: Config, connection: Connection) .map_err(|err| { log::error!("failed to load workspace: {:#}", err); show_message( - req::MessageType::Error, + lsp_types::MessageType::Error, format!("rust-analyzer failed to load workspace: {:#}", err), &connection.sender, ); @@ -142,23 +142,25 @@ pub fn main_loop(ws_roots: Vec, config: Config, connection: Connection) .collect::, _>>()?; if let FilesWatcher::Client = config.files.watcher { - let registration_options = req::DidChangeWatchedFilesRegistrationOptions { + let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions { watchers: workspaces .iter() .flat_map(ProjectWorkspace::to_roots) .filter(PackageRoot::is_member) .map(|root| format!("{}/**/*.rs", root.path().display())) - .map(|glob_pattern| req::FileSystemWatcher { glob_pattern, kind: None }) + .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None }) .collect(), }; - let registration = req::Registration { + let registration = lsp_types::Registration { id: "file-watcher".to_string(), method: "workspace/didChangeWatchedFiles".to_string(), register_options: Some(serde_json::to_value(registration_options).unwrap()), }; - let params = req::RegistrationParams { registrations: vec![registration] }; - let request = - request_new::(loop_state.next_request_id(), params); + let params = lsp_types::RegistrationParams { registrations: vec![registration] }; + let request = request_new::( + loop_state.next_request_id(), + params, + ); connection.sender.send(request.into()).unwrap(); } @@ -258,14 +260,14 @@ impl fmt::Debug for Event { match self { Event::Msg(Message::Notification(not)) => { - if notification_is::(not) - || notification_is::(not) + if notification_is::(not) + || notification_is::(not) { return debug_verbose_not(not, f); } } Event::Task(Task::Notify(not)) => { - if notification_is::(not) { + if notification_is::(not) { return debug_verbose_not(not, f); } } @@ -450,7 +452,7 @@ fn loop_turn( log::error!("overly long loop turn: {:?}", loop_duration); if env::var("RA_PROFILE").is_ok() { show_message( - req::MessageType::Error, + lsp_types::MessageType::Error, format!("overly long loop turn: {:?}", loop_duration), &connection.sender, ); @@ -503,7 +505,7 @@ fn on_request( .on_sync::(|s, ()| Ok(s.collect_garbage()))? .on_sync::(|s, p| handlers::handle_join_lines(s.snapshot(), p))? .on_sync::(|s, p| handlers::handle_on_enter(s.snapshot(), p))? - .on_sync::(|s, p| { + .on_sync::(|s, p| { handlers::handle_selection_range(s.snapshot(), p) })? .on_sync::(|s, p| { @@ -512,32 +514,38 @@ fn on_request( .on::(handlers::handle_analyzer_status)? .on::(handlers::handle_syntax_tree)? .on::(handlers::handle_expand_macro)? - .on::(handlers::handle_on_type_formatting)? - .on::(handlers::handle_document_symbol)? - .on::(handlers::handle_workspace_symbol)? - .on::(handlers::handle_goto_definition)? - .on::(handlers::handle_goto_implementation)? - .on::(handlers::handle_goto_type_definition)? + .on::(handlers::handle_on_type_formatting)? + .on::(handlers::handle_document_symbol)? + .on::(handlers::handle_workspace_symbol)? + .on::(handlers::handle_goto_definition)? + .on::(handlers::handle_goto_implementation)? + .on::(handlers::handle_goto_type_definition)? .on::(handlers::handle_parent_module)? .on::(handlers::handle_runnables)? - .on::(handlers::handle_completion)? - .on::(handlers::handle_code_action)? - .on::(handlers::handle_code_lens)? - .on::(handlers::handle_code_lens_resolve)? - .on::(handlers::handle_folding_range)? - .on::(handlers::handle_signature_help)? - .on::(handlers::handle_hover)? - .on::(handlers::handle_prepare_rename)? - .on::(handlers::handle_rename)? - .on::(handlers::handle_references)? - .on::(handlers::handle_formatting)? - .on::(handlers::handle_document_highlight)? + .on::(handlers::handle_completion)? + .on::(handlers::handle_code_action)? + .on::(handlers::handle_code_lens)? + .on::(handlers::handle_code_lens_resolve)? + .on::(handlers::handle_folding_range)? + .on::(handlers::handle_signature_help)? + .on::(handlers::handle_hover)? + .on::(handlers::handle_prepare_rename)? + .on::(handlers::handle_rename)? + .on::(handlers::handle_references)? + .on::(handlers::handle_formatting)? + .on::(handlers::handle_document_highlight)? .on::(handlers::handle_inlay_hints)? - .on::(handlers::handle_call_hierarchy_prepare)? - .on::(handlers::handle_call_hierarchy_incoming)? - .on::(handlers::handle_call_hierarchy_outgoing)? - .on::(handlers::handle_semantic_tokens)? - .on::(handlers::handle_semantic_tokens_range)? + .on::(handlers::handle_call_hierarchy_prepare)? + .on::( + handlers::handle_call_hierarchy_incoming, + )? + .on::( + handlers::handle_call_hierarchy_outgoing, + )? + .on::(handlers::handle_semantic_tokens)? + .on::( + handlers::handle_semantic_tokens_range, + )? .on::(handlers::handle_ssr)? .finish(); Ok(()) @@ -549,7 +557,7 @@ fn on_notification( loop_state: &mut LoopState, not: Notification, ) -> Result<()> { - let not = match notification_cast::(not) { + let not = match notification_cast::(not) { Ok(params) => { let id: RequestId = match params.id { NumberOrString::Number(id) => id.into(), @@ -567,7 +575,7 @@ fn on_notification( } Err(not) => not, }; - let not = match notification_cast::(not) { + let not = match notification_cast::(not) { Ok(params) => { let uri = params.text_document.uri; let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?; @@ -580,7 +588,7 @@ fn on_notification( } Err(not) => not, }; - let not = match notification_cast::(not) { + let not = match notification_cast::(not) { Ok(params) => { let DidChangeTextDocumentParams { text_document, content_changes } = params; let world = state.snapshot(); @@ -595,7 +603,7 @@ fn on_notification( } Err(not) => not, }; - let not = match notification_cast::(not) { + let not = match notification_cast::(not) { Ok(_params) => { if let Some(flycheck) = &state.flycheck { flycheck.update(); @@ -604,7 +612,7 @@ fn on_notification( } Err(not) => not, }; - let not = match notification_cast::(not) { + let not = match notification_cast::(not) { Ok(params) => { let uri = params.text_document.uri; let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?; @@ -612,22 +620,22 @@ fn on_notification( loop_state.subscriptions.remove_sub(FileId(file_id.0)); } let params = - req::PublishDiagnosticsParams { uri, diagnostics: Vec::new(), version: None }; - let not = notification_new::(params); + lsp_types::PublishDiagnosticsParams { uri, diagnostics: Vec::new(), version: None }; + let not = notification_new::(params); msg_sender.send(not.into()).unwrap(); return Ok(()); } Err(not) => not, }; - let not = match notification_cast::(not) { + let not = match notification_cast::(not) { Ok(_) => { // As stated in https://github.com/microsoft/language-server-protocol/issues/676, // this notification's parameters should be ignored and the actual config queried separately. let request_id = loop_state.next_request_id(); - let request = request_new::( + let request = request_new::( request_id.clone(), - req::ConfigurationParams { - items: vec![req::ConfigurationItem { + lsp_types::ConfigurationParams { + items: vec![lsp_types::ConfigurationItem { scope_uri: None, section: Some("rust-analyzer".to_string()), }], @@ -640,7 +648,7 @@ fn on_notification( } Err(not) => not, }; - let not = match notification_cast::(not) { + let not = match notification_cast::(not) { Ok(params) => { let mut vfs = state.vfs.write(); for change in params.changes { @@ -742,11 +750,11 @@ fn on_check_task( } CheckTask::Status(progress) => { - let params = req::ProgressParams { - token: req::ProgressToken::String("rustAnalyzer/cargoWatcher".to_string()), - value: req::ProgressParamsValue::WorkDone(progress), + let params = lsp_types::ProgressParams { + token: lsp_types::ProgressToken::String("rustAnalyzer/cargoWatcher".to_string()), + value: lsp_types::ProgressParamsValue::WorkDone(progress), }; - let not = notification_new::(params); + let not = notification_new::(params); task_sender.send(Task::Notify(not)).unwrap(); } }; @@ -768,8 +776,8 @@ fn on_diagnostic_task(task: DiagnosticTask, msg_sender: &Sender, state: }; let diagnostics = state.diagnostics.diagnostics_for(file_id).cloned().collect(); - let params = req::PublishDiagnosticsParams { uri, diagnostics, version: None }; - let not = notification_new::(params); + let params = lsp_types::PublishDiagnosticsParams { uri, diagnostics, version: None }; + let not = notification_new::(params); msg_sender.send(not.into()).unwrap(); } } @@ -782,10 +790,10 @@ fn send_startup_progress(sender: &Sender, loop_state: &mut LoopState) { match (prev, loop_state.workspace_loaded) { (None, false) => { - let work_done_progress_create = request_new::( + let work_done_progress_create = request_new::( loop_state.next_request_id(), WorkDoneProgressCreateParams { - token: req::ProgressToken::String("rustAnalyzer/startup".into()), + token: lsp_types::ProgressToken::String("rustAnalyzer/startup".into()), }, ); sender.send(work_done_progress_create.into()).unwrap(); @@ -817,10 +825,11 @@ fn send_startup_progress(sender: &Sender, loop_state: &mut LoopState) { } fn send_startup_progress_notif(sender: &Sender, work_done_progress: WorkDoneProgress) { - let notif = notification_new::(req::ProgressParams { - token: req::ProgressToken::String("rustAnalyzer/startup".into()), - value: req::ProgressParamsValue::WorkDone(work_done_progress), - }); + let notif = + notification_new::(lsp_types::ProgressParams { + token: lsp_types::ProgressToken::String("rustAnalyzer/startup".into()), + value: lsp_types::ProgressParamsValue::WorkDone(work_done_progress), + }); sender.send(notif.into()).unwrap(); } } @@ -842,7 +851,7 @@ impl<'a> PoolDispatcher<'a> { f: fn(&mut WorldState, R::Params) -> Result, ) -> Result<&mut Self> where - R: req::Request + 'static, + R: lsp_types::request::Request + 'static, R::Params: DeserializeOwned + panic::UnwindSafe + 'static, R::Result: Serialize + 'static, { @@ -865,7 +874,7 @@ impl<'a> PoolDispatcher<'a> { /// Dispatches the request onto thread pool fn on(&mut self, f: fn(WorldSnapshot, R::Params) -> Result) -> Result<&mut Self> where - R: req::Request + 'static, + R: lsp_types::request::Request + 'static, R::Params: DeserializeOwned + Send + 'static, R::Result: Serialize + 'static, { @@ -891,7 +900,7 @@ impl<'a> PoolDispatcher<'a> { fn parse(&mut self) -> Option<(RequestId, R::Params)> where - R: req::Request + 'static, + R: lsp_types::request::Request + 'static, R::Params: DeserializeOwned + 'static, { let req = self.req.take()?; @@ -928,7 +937,7 @@ impl<'a> PoolDispatcher<'a> { fn result_to_task(id: RequestId, result: Result) -> Task where - R: req::Request + 'static, + R: lsp_types::request::Request + 'static, R::Params: DeserializeOwned + 'static, R::Result: Serialize + 'static, { @@ -984,10 +993,14 @@ fn update_file_notifications_on_threadpool( } } -pub fn show_message(typ: req::MessageType, message: impl Into, sender: &Sender) { +pub fn show_message( + typ: lsp_types::MessageType, + message: impl Into, + sender: &Sender, +) { let message = message.into(); - let params = req::ShowMessageParams { typ, message }; - let not = notification_new::(params); + let params = lsp_types::ShowMessageParams { typ, message }; + let not = notification_new::(params); sender.send(not.into()).unwrap(); } diff --git a/crates/rust-analyzer/src/main_loop/handlers.rs b/crates/rust-analyzer/src/main_loop/handlers.rs index 4f619654fc..7aa77d19a4 100644 --- a/crates/rust-analyzer/src/main_loop/handlers.rs +++ b/crates/rust-analyzer/src/main_loop/handlers.rs @@ -81,12 +81,12 @@ pub fn handle_expand_macro( pub fn handle_selection_range( world: WorldSnapshot, - params: req::SelectionRangeParams, -) -> Result>> { + params: lsp_types::SelectionRangeParams, +) -> Result>> { let _p = profile("handle_selection_range"); let file_id = from_proto::file_id(&world, ¶ms.text_document.uri)?; let line_index = world.analysis().file_line_index(file_id)?; - let res: Result> = params + let res: Result> = params .positions .into_iter() .map(|position| { @@ -105,12 +105,12 @@ pub fn handle_selection_range( } } } - let mut range = req::SelectionRange { + let mut range = lsp_types::SelectionRange { range: to_proto::range(&line_index, *ranges.last().unwrap()), parent: None, }; for &r in ranges.iter().rev().skip(1) { - range = req::SelectionRange { + range = lsp_types::SelectionRange { range: to_proto::range(&line_index, r), parent: Some(Box::new(range)), } @@ -156,7 +156,7 @@ pub fn handle_join_lines( pub fn handle_on_enter( world: WorldSnapshot, - params: req::TextDocumentPositionParams, + params: lsp_types::TextDocumentPositionParams, ) -> Result> { let _p = profile("handle_on_enter"); let position = from_proto::file_position(&world, params)?; @@ -169,7 +169,7 @@ pub fn handle_on_enter( // Don't forget to add new trigger characters to `ServerCapabilities` in `caps.rs`. pub fn handle_on_type_formatting( world: WorldSnapshot, - params: req::DocumentOnTypeFormattingParams, + params: lsp_types::DocumentOnTypeFormattingParams, ) -> Result>> { let _p = profile("handle_on_type_formatting"); let mut position = from_proto::file_position(&world, params.text_document_position)?; @@ -208,8 +208,8 @@ pub fn handle_on_type_formatting( pub fn handle_document_symbol( world: WorldSnapshot, - params: req::DocumentSymbolParams, -) -> Result> { + params: lsp_types::DocumentSymbolParams, +) -> Result> { let _p = profile("handle_document_symbol"); let file_id = from_proto::file_id(&world, ¶ms.text_document.uri)?; let line_index = world.analysis().file_line_index(file_id)?; @@ -276,7 +276,7 @@ pub fn handle_document_symbol( pub fn handle_workspace_symbol( world: WorldSnapshot, - params: req::WorkspaceSymbolParams, + params: lsp_types::WorkspaceSymbolParams, ) -> Result>> { let _p = profile("handle_workspace_symbol"); let all_symbols = params.query.contains('#'); @@ -320,8 +320,8 @@ pub fn handle_workspace_symbol( pub fn handle_goto_definition( world: WorldSnapshot, - params: req::GotoDefinitionParams, -) -> Result> { + params: lsp_types::GotoDefinitionParams, +) -> Result> { let _p = profile("handle_goto_definition"); let position = from_proto::file_position(&world, params.text_document_position_params)?; let nav_info = match world.analysis().goto_definition(position)? { @@ -338,8 +338,8 @@ pub fn handle_goto_definition( pub fn handle_goto_implementation( world: WorldSnapshot, - params: req::GotoImplementationParams, -) -> Result> { + params: lsp_types::request::GotoImplementationParams, +) -> Result> { let _p = profile("handle_goto_implementation"); let position = from_proto::file_position(&world, params.text_document_position_params)?; let nav_info = match world.analysis().goto_implementation(position)? { @@ -356,8 +356,8 @@ pub fn handle_goto_implementation( pub fn handle_goto_type_definition( world: WorldSnapshot, - params: req::GotoTypeDefinitionParams, -) -> Result> { + params: lsp_types::request::GotoTypeDefinitionParams, +) -> Result> { let _p = profile("handle_goto_type_definition"); let position = from_proto::file_position(&world, params.text_document_position_params)?; let nav_info = match world.analysis().goto_type_definition(position)? { @@ -374,7 +374,7 @@ pub fn handle_goto_type_definition( pub fn handle_parent_module( world: WorldSnapshot, - params: req::TextDocumentPositionParams, + params: lsp_types::TextDocumentPositionParams, ) -> Result> { let _p = profile("handle_parent_module"); let position = from_proto::file_position(&world, params)?; @@ -447,8 +447,8 @@ pub fn handle_runnables( pub fn handle_completion( world: WorldSnapshot, - params: req::CompletionParams, -) -> Result> { + params: lsp_types::CompletionParams, +) -> Result> { let _p = profile("handle_completion"); let position = from_proto::file_position(&world, params.text_document_position)?; let completion_triggered_after_single_colon = { @@ -506,8 +506,8 @@ pub fn handle_folding_range( pub fn handle_signature_help( world: WorldSnapshot, - params: req::SignatureHelpParams, -) -> Result> { + params: lsp_types::SignatureHelpParams, +) -> Result> { let _p = profile("handle_signature_help"); let position = from_proto::file_position(&world, params.text_document_position_params)?; let call_info = match world.analysis().call_info(position)? { @@ -521,14 +521,14 @@ pub fn handle_signature_help( } let sig_info = to_proto::signature_information(call_info.signature, concise); - Ok(Some(req::SignatureHelp { + Ok(Some(lsp_types::SignatureHelp { signatures: vec![sig_info], active_signature: Some(0), active_parameter, })) } -pub fn handle_hover(world: WorldSnapshot, params: req::HoverParams) -> Result> { +pub fn handle_hover(world: WorldSnapshot, params: lsp_types::HoverParams) -> Result> { let _p = profile("handle_hover"); let position = from_proto::file_position(&world, params.text_document_position_params)?; let info = match world.analysis().hover(position)? { @@ -549,7 +549,7 @@ pub fn handle_hover(world: WorldSnapshot, params: req::HoverParams) -> Result Result> { let _p = profile("handle_prepare_rename"); let position = from_proto::file_position(&world, params)?; @@ -589,7 +589,7 @@ pub fn handle_rename(world: WorldSnapshot, params: RenameParams) -> Result Result>> { let _p = profile("handle_references"); let position = from_proto::file_position(&world, params.text_document_position)?; @@ -692,7 +692,7 @@ pub fn handle_formatting( pub fn handle_code_action( world: WorldSnapshot, - params: req::CodeActionParams, + params: lsp_types::CodeActionParams, ) -> Result> { let _p = profile("handle_code_action"); let file_id = from_proto::file_id(&world, ¶ms.text_document.uri)?; @@ -806,7 +806,7 @@ pub fn handle_code_action( pub fn handle_code_lens( world: WorldSnapshot, - params: req::CodeLensParams, + params: lsp_types::CodeLensParams, ) -> Result>> { let _p = profile("handle_code_lens"); let file_id = from_proto::file_id(&world, ¶ms.text_document.uri)?; @@ -875,8 +875,8 @@ pub fn handle_code_lens( .map(|it| { let range = to_proto::range(&line_index, it.node_range); let pos = range.start; - let lens_params = req::GotoImplementationParams { - text_document_position_params: req::TextDocumentPositionParams::new( + let lens_params = lsp_types::request::GotoImplementationParams { + text_document_position_params: lsp_types::TextDocumentPositionParams::new( params.text_document.clone(), pos, ), @@ -897,7 +897,7 @@ pub fn handle_code_lens( #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] enum CodeLensResolveData { - Impls(req::GotoImplementationParams), + Impls(lsp_types::request::GotoImplementationParams), } pub fn handle_code_lens_resolve(world: WorldSnapshot, code_lens: CodeLens) -> Result { @@ -908,9 +908,9 @@ pub fn handle_code_lens_resolve(world: WorldSnapshot, code_lens: CodeLens) -> Re Some(CodeLensResolveData::Impls(lens_params)) => { let locations: Vec = match handle_goto_implementation(world, lens_params.clone())? { - Some(req::GotoDefinitionResponse::Scalar(loc)) => vec![loc], - Some(req::GotoDefinitionResponse::Array(locs)) => locs, - Some(req::GotoDefinitionResponse::Link(links)) => links + Some(lsp_types::GotoDefinitionResponse::Scalar(loc)) => vec![loc], + Some(lsp_types::GotoDefinitionResponse::Array(locs)) => locs, + Some(lsp_types::GotoDefinitionResponse::Link(links)) => links .into_iter() .map(|link| Location::new(link.target_uri, link.target_selection_range)) .collect(), @@ -947,7 +947,7 @@ pub fn handle_code_lens_resolve(world: WorldSnapshot, code_lens: CodeLens) -> Re pub fn handle_document_highlight( world: WorldSnapshot, - params: req::DocumentHighlightParams, + params: lsp_types::DocumentHighlightParams, ) -> Result>> { let _p = profile("handle_document_highlight"); let position = from_proto::file_position(&world, params.text_document_position_params)?; diff --git a/crates/rust-analyzer/src/req.rs b/crates/rust-analyzer/src/req.rs index 0dae6bad4f..aeb29370c0 100644 --- a/crates/rust-analyzer/src/req.rs +++ b/crates/rust-analyzer/src/req.rs @@ -1,23 +1,10 @@ //! Defines `rust-analyzer` specific custom messages. +use lsp_types::request::Request; use lsp_types::{Location, Position, Range, TextDocumentIdentifier}; use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; -pub use lsp_types::{ - notification::*, request::*, ApplyWorkspaceEditParams, CodeActionParams, CodeLens, - CodeLensParams, CompletionParams, CompletionResponse, ConfigurationItem, ConfigurationParams, - DiagnosticTag, DidChangeConfigurationParams, DidChangeWatchedFilesParams, - DidChangeWatchedFilesRegistrationOptions, DocumentHighlightParams, - DocumentOnTypeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse, - FileSystemWatcher, GotoDefinitionParams, GotoDefinitionResponse, Hover, HoverParams, - InitializeResult, MessageType, PartialResultParams, ProgressParams, ProgressParamsValue, - ProgressToken, PublishDiagnosticsParams, ReferenceParams, Registration, RegistrationParams, - SelectionRange, SelectionRangeParams, SemanticTokensParams, SemanticTokensRangeParams, - SemanticTokensRangeResult, SemanticTokensResult, ServerCapabilities, ShowMessageParams, - SignatureHelp, SignatureHelpParams, SymbolKind, TextDocumentEdit, TextDocumentPositionParams, - TextEdit, WorkDoneProgressParams, WorkspaceEdit, WorkspaceSymbolParams, -}; use std::path::PathBuf; pub enum AnalyzerStatus {} @@ -91,7 +78,7 @@ pub struct FindMatchingBraceParams { pub enum ParentModule {} impl Request for ParentModule { - type Params = TextDocumentPositionParams; + type Params = lsp_types::TextDocumentPositionParams; type Result = Vec; const METHOD: &'static str = "rust-analyzer/parentModule"; } @@ -114,7 +101,7 @@ pub struct JoinLinesParams { pub enum OnEnter {} impl Request for OnEnter { - type Params = TextDocumentPositionParams; + type Params = lsp_types::TextDocumentPositionParams; type Result = Option; const METHOD: &'static str = "rust-analyzer/onEnter"; } @@ -150,8 +137,8 @@ pub struct Runnable { #[serde(rename_all = "camelCase")] pub struct SourceChange { pub label: String, - pub workspace_edit: WorkspaceEdit, - pub cursor_position: Option, + pub workspace_edit: lsp_types::WorkspaceEdit, + pub cursor_position: Option, } pub enum InlayHints {}