⬆️ lsp-server

This commit is contained in:
Aleksey Kladov 2019-08-30 20:18:57 +03:00
parent 72a3722470
commit 7cc14a7596
5 changed files with 85 additions and 85 deletions

7
Cargo.lock generated
View File

@ -662,7 +662,7 @@ dependencies = [
[[package]] [[package]]
name = "lsp-server" name = "lsp-server"
version = "0.1.0" version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [ dependencies = [
"crossbeam-channel 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-channel 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
@ -1074,8 +1074,9 @@ version = "0.1.0"
dependencies = [ dependencies = [
"crossbeam-channel 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-channel 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
"flexi_logger 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", "flexi_logger 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)",
"jod-thread 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"lsp-server 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "lsp-server 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"lsp-types 0.60.0 (registry+https://github.com/rust-lang/crates.io-index)", "lsp-types 0.60.0 (registry+https://github.com/rust-lang/crates.io-index)",
"parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
"ra_ide_api 0.1.0", "ra_ide_api 0.1.0",
@ -1937,7 +1938,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum linked-hash-map 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "ae91b68aebc4ddb91978b11a1b02ddd8602a05ec19002801c5666000e05e0f83" "checksum linked-hash-map 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "ae91b68aebc4ddb91978b11a1b02ddd8602a05ec19002801c5666000e05e0f83"
"checksum lock_api 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f8912e782533a93a167888781b836336a6ca5da6175c05944c86cf28c31104dc" "checksum lock_api 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f8912e782533a93a167888781b836336a6ca5da6175c05944c86cf28c31104dc"
"checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7"
"checksum lsp-server 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "47632ec528046c1a39f14448f1ee7d66d4b7b83e1771590b62e6c08665dea053" "checksum lsp-server 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "148cfb1c0b3295c23d9fb4a20fd1b242f5e6f46c525fdcc7f5c0a65710362012"
"checksum lsp-types 0.60.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fe3edefcd66dde1f7f1df706f46520a3c93adc5ca4bc5747da6621195e894efd" "checksum lsp-types 0.60.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fe3edefcd66dde1f7f1df706f46520a3c93adc5ca4bc5747da6621195e894efd"
"checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" "checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08"
"checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e" "checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e"

View File

@ -21,12 +21,13 @@ thread_worker = { path = "../thread_worker" }
ra_syntax = { path = "../ra_syntax" } ra_syntax = { path = "../ra_syntax" }
ra_text_edit = { path = "../ra_text_edit" } ra_text_edit = { path = "../ra_text_edit" }
ra_ide_api = { path = "../ra_ide_api" } ra_ide_api = { path = "../ra_ide_api" }
lsp-server = "0.1.0" lsp-server = "0.2.0"
ra_project_model = { path = "../ra_project_model" } ra_project_model = { path = "../ra_project_model" }
ra_prof = { path = "../ra_prof" } ra_prof = { path = "../ra_prof" }
ra_vfs_glob = { path = "../ra_vfs_glob" } ra_vfs_glob = { path = "../ra_vfs_glob" }
[dev-dependencies] [dev-dependencies]
jod-thread = "0.1.0"
tempfile = "3" tempfile = "3"
test_utils = { path = "../test_utils" } test_utils = { path = "../test_utils" }

View File

@ -1,5 +1,5 @@
use flexi_logger::{Duplicate, Logger}; use flexi_logger::{Duplicate, Logger};
use lsp_server::{run_server, stdio_transport, LspServerError}; use lsp_server::Connection;
use ra_lsp_server::{show_message, Result, ServerConfig}; use ra_lsp_server::{show_message, Result, ServerConfig};
use ra_prof; use ra_prof;
@ -29,46 +29,46 @@ fn main() -> Result<()> {
} }
fn main_inner() -> Result<()> { fn main_inner() -> Result<()> {
let (sender, receiver, io_threads) = stdio_transport();
let cwd = std::env::current_dir()?; let cwd = std::env::current_dir()?;
let caps = serde_json::to_value(ra_lsp_server::server_capabilities()).unwrap(); let (connection, io_threads) = Connection::stdio();
run_server(caps, sender, receiver, |params, s, r| { let server_capabilities = serde_json::to_value(ra_lsp_server::server_capabilities()).unwrap();
let params: lsp_types::InitializeParams = serde_json::from_value(params)?;
let root = params.root_uri.and_then(|it| it.to_file_path().ok()).unwrap_or(cwd);
let workspace_roots = params let initialize_params = connection.initialize(server_capabilities)?;
.workspace_folders let initialize_params: lsp_types::InitializeParams = serde_json::from_value(initialize_params)?;
.map(|workspaces| {
workspaces
.into_iter()
.filter_map(|it| it.uri.to_file_path().ok())
.collect::<Vec<_>>()
})
.filter(|workspaces| !workspaces.is_empty())
.unwrap_or_else(|| vec![root]);
let server_config: ServerConfig = params let root = initialize_params.root_uri.and_then(|it| it.to_file_path().ok()).unwrap_or(cwd);
.initialization_options
.and_then(|v| { let workspace_roots = initialize_params
serde_json::from_value(v) .workspace_folders
.map_err(|e| { .map(|workspaces| {
log::error!("failed to deserialize config: {}", e); workspaces.into_iter().filter_map(|it| it.uri.to_file_path().ok()).collect::<Vec<_>>()
show_message( })
lsp_types::MessageType::Error, .filter(|workspaces| !workspaces.is_empty())
format!("failed to deserialize config: {}", e), .unwrap_or_else(|| vec![root]);
s,
); let server_config: ServerConfig = initialize_params
}) .initialization_options
.ok() .and_then(|v| {
}) serde_json::from_value(v)
.unwrap_or_default(); .map_err(|e| {
log::error!("failed to deserialize config: {}", e);
show_message(
lsp_types::MessageType::Error,
format!("failed to deserialize config: {}", e),
&connection.sender,
);
})
.ok()
})
.unwrap_or_default();
ra_lsp_server::main_loop(
workspace_roots,
initialize_params.capabilities,
server_config,
&connection,
)?;
ra_lsp_server::main_loop(workspace_roots, params.capabilities, server_config, r, s)
})
.map_err(|err| match err {
LspServerError::ProtocolError(err) => err.into(),
LspServerError::ServerError(err) => err,
})?;
log::info!("shutting down IO..."); log::info!("shutting down IO...");
io_threads.join()?; io_threads.join()?;
log::info!("... IO is down"); log::info!("... IO is down");

View File

@ -5,7 +5,7 @@ pub(crate) mod pending_requests;
use std::{error::Error, fmt, path::PathBuf, sync::Arc, time::Instant}; use std::{error::Error, fmt, path::PathBuf, sync::Arc, time::Instant};
use crossbeam_channel::{select, unbounded, Receiver, RecvError, Sender}; use crossbeam_channel::{select, unbounded, Receiver, RecvError, Sender};
use lsp_server::{handle_shutdown, ErrorCode, Message, Notification, Request, RequestId, Response}; use lsp_server::{Connection, ErrorCode, Message, Notification, Request, RequestId, Response};
use lsp_types::{ClientCapabilities, NumberOrString}; use lsp_types::{ClientCapabilities, NumberOrString};
use ra_ide_api::{Canceled, FeatureFlags, FileId, LibraryData}; use ra_ide_api::{Canceled, FeatureFlags, FileId, LibraryData};
use ra_prof::profile; use ra_prof::profile;
@ -51,8 +51,7 @@ pub fn main_loop(
ws_roots: Vec<PathBuf>, ws_roots: Vec<PathBuf>,
client_caps: ClientCapabilities, client_caps: ClientCapabilities,
config: ServerConfig, config: ServerConfig,
msg_receiver: &Receiver<Message>, connection: &Connection,
msg_sender: &Sender<Message>,
) -> Result<()> { ) -> Result<()> {
log::info!("server_config: {:#?}", config); log::info!("server_config: {:#?}", config);
// FIXME: support dynamic workspace loading. // FIXME: support dynamic workspace loading.
@ -69,7 +68,7 @@ pub fn main_loop(
show_message( show_message(
req::MessageType::Error, req::MessageType::Error,
format!("rust-analyzer failed to load workspace: {}", e), format!("rust-analyzer failed to load workspace: {}", e),
msg_sender, &connection.sender,
); );
} }
} }
@ -89,7 +88,7 @@ pub fn main_loop(
show_message( show_message(
req::MessageType::Error, req::MessageType::Error,
format!("unknown feature flag: {:?}", flag), format!("unknown feature flag: {:?}", flag),
msg_sender, &connection.sender,
); );
} }
} }
@ -119,8 +118,7 @@ pub fn main_loop(
log::info!("server initialized, serving requests"); log::info!("server initialized, serving requests");
let main_res = main_loop_inner( let main_res = main_loop_inner(
&pool, &pool,
msg_sender, connection,
msg_receiver,
task_sender, task_sender,
task_receiver.clone(), task_receiver.clone(),
&mut state, &mut state,
@ -130,7 +128,7 @@ pub fn main_loop(
log::info!("waiting for tasks to finish..."); log::info!("waiting for tasks to finish...");
task_receiver task_receiver
.into_iter() .into_iter()
.for_each(|task| on_task(task, msg_sender, &mut pending_requests, &mut state)); .for_each(|task| on_task(task, &connection.sender, &mut pending_requests, &mut state));
log::info!("...tasks have finished"); log::info!("...tasks have finished");
log::info!("joining threadpool..."); log::info!("joining threadpool...");
drop(pool); drop(pool);
@ -196,8 +194,7 @@ impl fmt::Debug for Event {
fn main_loop_inner( fn main_loop_inner(
pool: &ThreadPool, pool: &ThreadPool,
msg_sender: &Sender<Message>, connection: &Connection,
msg_receiver: &Receiver<Message>,
task_sender: Sender<Task>, task_sender: Sender<Task>,
task_receiver: Receiver<Task>, task_receiver: Receiver<Task>,
state: &mut WorldState, state: &mut WorldState,
@ -214,7 +211,7 @@ fn main_loop_inner(
loop { loop {
log::trace!("selecting"); log::trace!("selecting");
let event = select! { let event = select! {
recv(msg_receiver) -> msg => match msg { recv(&connection.receiver) -> msg => match msg {
Ok(msg) => Event::Msg(msg), Ok(msg) => Event::Msg(msg),
Err(RecvError) => Err("client exited without shutdown")?, Err(RecvError) => Err("client exited without shutdown")?,
}, },
@ -238,7 +235,7 @@ fn main_loop_inner(
let mut state_changed = false; let mut state_changed = false;
match event { match event {
Event::Task(task) => { Event::Task(task) => {
on_task(task, msg_sender, pending_requests, state); on_task(task, &connection.sender, pending_requests, state);
state.maybe_collect_garbage(); state.maybe_collect_garbage();
} }
Event::Vfs(task) => { Event::Vfs(task) => {
@ -252,7 +249,7 @@ fn main_loop_inner(
} }
Event::Msg(msg) => match msg { Event::Msg(msg) => match msg {
Message::Request(req) => { Message::Request(req) => {
if handle_shutdown(&req, msg_sender) { if connection.handle_shutdown(&req)? {
return Ok(()); return Ok(());
}; };
on_request( on_request(
@ -260,13 +257,13 @@ fn main_loop_inner(
pending_requests, pending_requests,
pool, pool,
&task_sender, &task_sender,
msg_sender, &connection.sender,
loop_start, loop_start,
req, req,
)? )?
} }
Message::Notification(not) => { Message::Notification(not) => {
on_notification(msg_sender, state, pending_requests, &mut subs, not)?; on_notification(&connection.sender, state, pending_requests, &mut subs, not)?;
state_changed = true; state_changed = true;
} }
Message::Response(resp) => log::error!("unexpected response: {:?}", resp), Message::Response(resp) => log::error!("unexpected response: {:?}", resp),
@ -294,7 +291,7 @@ fn main_loop_inner(
let n_packages: usize = state.workspaces.iter().map(|it| it.n_packages()).sum(); let n_packages: usize = state.workspaces.iter().map(|it| it.n_packages()).sum();
if state.feature_flags().get("notifications.workspace-loaded") { if state.feature_flags().get("notifications.workspace-loaded") {
let msg = format!("workspace loaded, {} rust packages", n_packages); let msg = format!("workspace loaded, {} rust packages", n_packages);
show_message(req::MessageType::Info, msg, msg_sender); show_message(req::MessageType::Info, msg, &connection.sender);
} }
// Only send the notification first time // Only send the notification first time
send_workspace_notification = false; send_workspace_notification = false;

View File

@ -8,16 +8,17 @@ use std::{
use crossbeam_channel::{after, select, Receiver}; use crossbeam_channel::{after, select, Receiver};
use flexi_logger::Logger; use flexi_logger::Logger;
use lsp_server::{Message, Notification, Request}; use lsp_server::{Connection, Message, Notification, Request};
use lsp_types::{ use lsp_types::{
request::Shutdown, ClientCapabilities, DidOpenTextDocumentParams, GotoCapability, notification::{DidOpenTextDocument, Exit},
TextDocumentClientCapabilities, TextDocumentIdentifier, TextDocumentItem, Url, request::Shutdown,
ClientCapabilities, DidOpenTextDocumentParams, GotoCapability, TextDocumentClientCapabilities,
TextDocumentIdentifier, TextDocumentItem, Url,
}; };
use serde::Serialize; use serde::Serialize;
use serde_json::{to_string_pretty, Value}; use serde_json::{to_string_pretty, Value};
use tempfile::TempDir; use tempfile::TempDir;
use test_utils::{find_mismatch, parse_fixture}; use test_utils::{find_mismatch, parse_fixture};
use thread_worker::Worker;
use ra_lsp_server::{main_loop, req, ServerConfig}; use ra_lsp_server::{main_loop, req, ServerConfig};
@ -83,7 +84,8 @@ pub struct Server {
req_id: Cell<u64>, req_id: Cell<u64>,
messages: RefCell<Vec<Message>>, messages: RefCell<Vec<Message>>,
dir: TempDir, dir: TempDir,
worker: Worker<Message, Message>, _thread: jod_thread::JoinHandle<()>,
client: Connection,
} }
impl Server { impl Server {
@ -96,11 +98,11 @@ impl Server {
let path = dir.path().to_path_buf(); let path = dir.path().to_path_buf();
let roots = if roots.is_empty() { vec![path] } else { roots }; let roots = if roots.is_empty() { vec![path] } else { roots };
let (connection, client) = Connection::memory();
let worker = Worker::<Message, Message>::spawn( let _thread = jod_thread::Builder::new()
"test server", .name("test server".to_string())
128, .spawn(move || {
move |msg_receiver, msg_sender| {
main_loop( main_loop(
roots, roots,
ClientCapabilities { ClientCapabilities {
@ -116,26 +118,24 @@ impl Server {
experimental: None, experimental: None,
}, },
ServerConfig { with_sysroot, ..ServerConfig::default() }, ServerConfig { with_sysroot, ..ServerConfig::default() },
&msg_receiver, &connection,
&msg_sender,
) )
.unwrap() .unwrap()
}, })
); .expect("failed to spawn a thread");
let res = Server { req_id: Cell::new(1), dir, messages: Default::default(), worker };
let res =
Server { req_id: Cell::new(1), dir, messages: Default::default(), client, _thread };
for (path, text) in files { for (path, text) in files {
res.send_notification(Notification::new( res.notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
"textDocument/didOpen".to_string(), text_document: TextDocumentItem {
&DidOpenTextDocumentParams { uri: Url::from_file_path(path).unwrap(),
text_document: TextDocumentItem { language_id: "rust".to_string(),
uri: Url::from_file_path(path).unwrap(), version: 0,
language_id: "rust".to_string(), text,
version: 0,
text,
},
}, },
)) })
} }
res res
} }
@ -184,7 +184,7 @@ impl Server {
} }
fn send_request_(&self, r: Request) -> Value { fn send_request_(&self, r: Request) -> Value {
let id = r.id.clone(); let id = r.id.clone();
self.worker.sender().send(r.into()).unwrap(); self.client.sender.send(r.into()).unwrap();
while let Some(msg) = self.recv() { while let Some(msg) = self.recv() {
match msg { match msg {
Message::Request(req) => panic!("unexpected request: {:?}", req), Message::Request(req) => panic!("unexpected request: {:?}", req),
@ -225,13 +225,13 @@ impl Server {
} }
} }
fn recv(&self) -> Option<Message> { fn recv(&self) -> Option<Message> {
recv_timeout(&self.worker.receiver()).map(|msg| { recv_timeout(&self.client.receiver).map(|msg| {
self.messages.borrow_mut().push(msg.clone()); self.messages.borrow_mut().push(msg.clone());
msg msg
}) })
} }
fn send_notification(&self, not: Notification) { fn send_notification(&self, not: Notification) {
self.worker.sender().send(Message::Notification(not)).unwrap(); self.client.sender.send(Message::Notification(not)).unwrap();
} }
pub fn path(&self) -> &Path { pub fn path(&self) -> &Path {
@ -241,7 +241,8 @@ impl Server {
impl Drop for Server { impl Drop for Server {
fn drop(&mut self) { fn drop(&mut self) {
self.send_request::<Shutdown>(()); self.request::<Shutdown>((), Value::Null);
self.notification::<Exit>(());
} }
} }