2021-10-21 14:26:37 +00:00
|
|
|
use anyhow::{anyhow, Context, Result};
|
2021-10-25 22:28:40 +00:00
|
|
|
use futures::{io::BufWriter, AsyncRead, AsyncWrite};
|
2021-10-26 19:17:51 +00:00
|
|
|
use gpui::{executor, Task};
|
2021-10-25 16:11:52 +00:00
|
|
|
use parking_lot::{Mutex, RwLock};
|
|
|
|
use postage::{barrier, oneshot, prelude::Stream, sink::Sink};
|
2021-10-21 14:26:37 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
2021-10-25 17:46:33 +00:00
|
|
|
use serde_json::{json, value::RawValue, Value};
|
2021-10-21 14:26:37 +00:00
|
|
|
use smol::{
|
|
|
|
channel,
|
|
|
|
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
|
|
|
|
process::Command,
|
|
|
|
};
|
|
|
|
use std::{
|
|
|
|
collections::HashMap,
|
|
|
|
future::Future,
|
|
|
|
io::Write,
|
2021-10-25 17:46:33 +00:00
|
|
|
str::FromStr,
|
2021-10-21 14:26:37 +00:00
|
|
|
sync::{
|
2022-01-14 09:20:04 +00:00
|
|
|
atomic::{AtomicUsize, Ordering::SeqCst},
|
2021-10-21 14:26:37 +00:00
|
|
|
Arc,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
use std::{path::Path, process::Stdio};
|
|
|
|
use util::TryFutureExt;
|
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
pub use lsp_types::*;
|
|
|
|
|
2021-10-21 14:26:37 +00:00
|
|
|
const JSON_RPC_VERSION: &'static str = "2.0";
|
|
|
|
const CONTENT_LEN_HEADER: &'static str = "Content-Length: ";
|
|
|
|
|
2022-01-04 16:38:45 +00:00
|
|
|
type NotificationHandler = Box<dyn Send + Sync + FnMut(&str)>;
|
2021-10-25 16:11:52 +00:00
|
|
|
type ResponseHandler = Box<dyn Send + FnOnce(Result<&str, Error>)>;
|
|
|
|
|
2021-10-21 14:26:37 +00:00
|
|
|
pub struct LanguageServer {
|
|
|
|
next_id: AtomicUsize,
|
2021-11-02 19:16:25 +00:00
|
|
|
outbound_tx: RwLock<Option<channel::Sender<Vec<u8>>>>,
|
2021-10-25 16:11:52 +00:00
|
|
|
notification_handlers: Arc<RwLock<HashMap<&'static str, NotificationHandler>>>,
|
2021-10-21 14:26:37 +00:00
|
|
|
response_handlers: Arc<Mutex<HashMap<usize, ResponseHandler>>>,
|
2021-11-01 18:57:21 +00:00
|
|
|
executor: Arc<executor::Background>,
|
2021-11-02 19:16:25 +00:00
|
|
|
io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
|
2021-10-25 10:29:28 +00:00
|
|
|
initialized: barrier::Receiver,
|
2021-11-02 19:16:25 +00:00
|
|
|
output_done_rx: Mutex<Option<barrier::Receiver>>,
|
2021-10-21 14:26:37 +00:00
|
|
|
}
|
|
|
|
|
2021-10-25 16:11:52 +00:00
|
|
|
pub struct Subscription {
|
|
|
|
method: &'static str,
|
|
|
|
notification_handlers: Arc<RwLock<HashMap<&'static str, NotificationHandler>>>,
|
|
|
|
}
|
2021-10-21 14:26:37 +00:00
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
#[derive(Serialize, Deserialize)]
|
|
|
|
struct Request<'a, T> {
|
|
|
|
jsonrpc: &'a str,
|
2021-10-21 14:26:37 +00:00
|
|
|
id: usize,
|
2021-10-25 22:28:40 +00:00
|
|
|
method: &'a str,
|
2021-10-21 14:26:37 +00:00
|
|
|
params: T,
|
|
|
|
}
|
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
#[derive(Serialize, Deserialize)]
|
|
|
|
struct AnyResponse<'a> {
|
2021-10-21 17:27:10 +00:00
|
|
|
id: usize,
|
|
|
|
#[serde(default)]
|
|
|
|
error: Option<Error>,
|
2021-10-25 16:11:52 +00:00
|
|
|
#[serde(borrow)]
|
2021-11-02 13:58:00 +00:00
|
|
|
result: Option<&'a RawValue>,
|
2021-10-21 17:27:10 +00:00
|
|
|
}
|
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
#[derive(Serialize, Deserialize)]
|
|
|
|
struct Notification<'a, T> {
|
|
|
|
#[serde(borrow)]
|
|
|
|
jsonrpc: &'a str,
|
|
|
|
#[serde(borrow)]
|
|
|
|
method: &'a str,
|
2021-10-21 17:27:10 +00:00
|
|
|
params: T,
|
2021-10-21 14:26:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
2021-10-25 22:28:40 +00:00
|
|
|
struct AnyNotification<'a> {
|
2021-10-21 17:27:10 +00:00
|
|
|
#[serde(borrow)]
|
|
|
|
method: &'a str,
|
2021-10-21 14:26:37 +00:00
|
|
|
#[serde(borrow)]
|
|
|
|
params: &'a RawValue,
|
|
|
|
}
|
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
2021-10-21 17:27:10 +00:00
|
|
|
struct Error {
|
|
|
|
message: String,
|
2021-10-21 14:26:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl LanguageServer {
|
2021-10-25 16:11:52 +00:00
|
|
|
pub fn new(
|
2021-10-26 19:17:51 +00:00
|
|
|
binary_path: &Path,
|
2021-10-25 16:11:52 +00:00
|
|
|
root_path: &Path,
|
2021-11-01 18:57:21 +00:00
|
|
|
background: Arc<executor::Background>,
|
2021-10-25 16:11:52 +00:00
|
|
|
) -> Result<Arc<Self>> {
|
2021-10-26 19:17:51 +00:00
|
|
|
let mut server = Command::new(binary_path)
|
2021-10-21 14:26:37 +00:00
|
|
|
.stdin(Stdio::piped())
|
|
|
|
.stdout(Stdio::piped())
|
|
|
|
.stderr(Stdio::inherit())
|
|
|
|
.spawn()?;
|
2021-10-25 22:28:40 +00:00
|
|
|
let stdin = server.stdin.take().unwrap();
|
|
|
|
let stdout = server.stdout.take().unwrap();
|
2021-10-26 19:17:51 +00:00
|
|
|
Self::new_internal(stdin, stdout, root_path, background)
|
2021-10-25 22:28:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn new_internal<Stdin, Stdout>(
|
|
|
|
stdin: Stdin,
|
|
|
|
stdout: Stdout,
|
2021-10-26 19:17:51 +00:00
|
|
|
root_path: &Path,
|
2021-11-01 18:57:21 +00:00
|
|
|
executor: Arc<executor::Background>,
|
2021-10-25 22:28:40 +00:00
|
|
|
) -> Result<Arc<Self>>
|
|
|
|
where
|
|
|
|
Stdin: AsyncWrite + Unpin + Send + 'static,
|
|
|
|
Stdout: AsyncRead + Unpin + Send + 'static,
|
|
|
|
{
|
|
|
|
let mut stdin = BufWriter::new(stdin);
|
|
|
|
let mut stdout = BufReader::new(stdout);
|
2021-10-21 14:26:37 +00:00
|
|
|
let (outbound_tx, outbound_rx) = channel::unbounded::<Vec<u8>>();
|
2021-10-25 16:11:52 +00:00
|
|
|
let notification_handlers = Arc::new(RwLock::new(HashMap::<_, NotificationHandler>::new()));
|
|
|
|
let response_handlers = Arc::new(Mutex::new(HashMap::<_, ResponseHandler>::new()));
|
2021-11-01 18:57:21 +00:00
|
|
|
let input_task = executor.spawn(
|
2021-10-21 14:26:37 +00:00
|
|
|
{
|
2021-10-25 16:11:52 +00:00
|
|
|
let notification_handlers = notification_handlers.clone();
|
2021-10-21 14:26:37 +00:00
|
|
|
let response_handlers = response_handlers.clone();
|
|
|
|
async move {
|
|
|
|
let mut buffer = Vec::new();
|
|
|
|
loop {
|
|
|
|
buffer.clear();
|
|
|
|
stdout.read_until(b'\n', &mut buffer).await?;
|
|
|
|
stdout.read_until(b'\n', &mut buffer).await?;
|
|
|
|
let message_len: usize = std::str::from_utf8(&buffer)?
|
|
|
|
.strip_prefix(CONTENT_LEN_HEADER)
|
|
|
|
.ok_or_else(|| anyhow!("invalid header"))?
|
|
|
|
.trim_end()
|
|
|
|
.parse()?;
|
|
|
|
|
|
|
|
buffer.resize(message_len, 0);
|
|
|
|
stdout.read_exact(&mut buffer).await?;
|
2021-10-25 16:11:52 +00:00
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
if let Ok(AnyNotification { method, params }) =
|
2021-10-25 16:11:52 +00:00
|
|
|
serde_json::from_slice(&buffer)
|
|
|
|
{
|
2022-01-04 16:38:45 +00:00
|
|
|
if let Some(handler) = notification_handlers.write().get_mut(method) {
|
2021-10-25 16:11:52 +00:00
|
|
|
handler(params.get());
|
2021-10-25 17:46:33 +00:00
|
|
|
} else {
|
|
|
|
log::info!(
|
|
|
|
"unhandled notification {}:\n{}",
|
|
|
|
method,
|
|
|
|
serde_json::to_string_pretty(
|
|
|
|
&Value::from_str(params.get()).unwrap()
|
|
|
|
)
|
|
|
|
.unwrap()
|
|
|
|
);
|
2021-10-25 16:11:52 +00:00
|
|
|
}
|
2021-10-25 22:28:40 +00:00
|
|
|
} else if let Ok(AnyResponse { id, error, result }) =
|
2021-10-21 14:26:37 +00:00
|
|
|
serde_json::from_slice(&buffer)
|
|
|
|
{
|
|
|
|
if let Some(handler) = response_handlers.lock().remove(&id) {
|
2021-10-25 16:11:52 +00:00
|
|
|
if let Some(error) = error {
|
2021-10-21 14:26:37 +00:00
|
|
|
handler(Err(error));
|
2021-11-02 13:58:00 +00:00
|
|
|
} else if let Some(result) = result {
|
2021-10-25 16:11:52 +00:00
|
|
|
handler(Ok(result.get()));
|
2021-11-02 13:58:00 +00:00
|
|
|
} else {
|
|
|
|
handler(Ok("null"));
|
2021-10-21 14:26:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return Err(anyhow!(
|
|
|
|
"failed to deserialize message:\n{}",
|
|
|
|
std::str::from_utf8(&buffer)?
|
|
|
|
));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
.log_err(),
|
|
|
|
);
|
2021-11-01 18:57:21 +00:00
|
|
|
let (output_done_tx, output_done_rx) = barrier::channel();
|
|
|
|
let output_task = executor.spawn(
|
2021-10-21 14:26:37 +00:00
|
|
|
async move {
|
|
|
|
let mut content_len_buffer = Vec::new();
|
2021-11-01 18:57:21 +00:00
|
|
|
while let Ok(message) = outbound_rx.recv().await {
|
2021-10-25 16:11:52 +00:00
|
|
|
content_len_buffer.clear();
|
2021-10-21 14:26:37 +00:00
|
|
|
write!(content_len_buffer, "{}", message.len()).unwrap();
|
|
|
|
stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
|
|
|
|
stdin.write_all(&content_len_buffer).await?;
|
|
|
|
stdin.write_all("\r\n\r\n".as_bytes()).await?;
|
|
|
|
stdin.write_all(&message).await?;
|
2021-10-25 22:28:40 +00:00
|
|
|
stdin.flush().await?;
|
2021-10-21 14:26:37 +00:00
|
|
|
}
|
2021-11-01 18:57:21 +00:00
|
|
|
drop(output_done_tx);
|
|
|
|
Ok(())
|
2021-10-21 14:26:37 +00:00
|
|
|
}
|
|
|
|
.log_err(),
|
|
|
|
);
|
|
|
|
|
2021-10-25 10:29:28 +00:00
|
|
|
let (initialized_tx, initialized_rx) = barrier::channel();
|
2021-10-21 14:26:37 +00:00
|
|
|
let this = Arc::new(Self {
|
2021-10-25 16:11:52 +00:00
|
|
|
notification_handlers,
|
2021-10-21 14:26:37 +00:00
|
|
|
response_handlers,
|
|
|
|
next_id: Default::default(),
|
2021-11-02 19:16:25 +00:00
|
|
|
outbound_tx: RwLock::new(Some(outbound_tx)),
|
2021-11-01 18:57:21 +00:00
|
|
|
executor: executor.clone(),
|
2021-11-02 19:16:25 +00:00
|
|
|
io_tasks: Mutex::new(Some((input_task, output_task))),
|
2021-10-25 10:29:28 +00:00
|
|
|
initialized: initialized_rx,
|
2021-11-02 19:16:25 +00:00
|
|
|
output_done_rx: Mutex::new(Some(output_done_rx)),
|
2021-10-21 14:26:37 +00:00
|
|
|
});
|
2021-10-25 10:29:28 +00:00
|
|
|
|
2022-01-20 11:10:01 +00:00
|
|
|
let root_uri = Url::from_file_path(root_path).map_err(|_| anyhow!("invalid root path"))?;
|
2021-11-01 18:57:21 +00:00
|
|
|
executor
|
2021-10-25 10:29:28 +00:00
|
|
|
.spawn({
|
|
|
|
let this = this.clone();
|
|
|
|
async move {
|
2021-10-25 16:11:52 +00:00
|
|
|
this.init(root_uri).log_err().await;
|
2021-10-25 10:29:28 +00:00
|
|
|
drop(initialized_tx);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.detach();
|
2021-10-21 14:26:37 +00:00
|
|
|
|
|
|
|
Ok(this)
|
|
|
|
}
|
|
|
|
|
2022-01-20 11:10:01 +00:00
|
|
|
async fn init(self: Arc<Self>, root_uri: Url) -> Result<()> {
|
2021-10-25 22:28:40 +00:00
|
|
|
#[allow(deprecated)]
|
2022-01-20 11:10:01 +00:00
|
|
|
let params = InitializeParams {
|
2021-10-25 16:11:52 +00:00
|
|
|
process_id: Default::default(),
|
|
|
|
root_path: Default::default(),
|
|
|
|
root_uri: Some(root_uri),
|
2022-01-04 16:38:45 +00:00
|
|
|
initialization_options: Default::default(),
|
2022-01-20 11:10:01 +00:00
|
|
|
capabilities: ClientCapabilities {
|
|
|
|
text_document: Some(TextDocumentClientCapabilities {
|
|
|
|
definition: Some(GotoCapability {
|
|
|
|
link_support: Some(true),
|
|
|
|
..Default::default()
|
|
|
|
}),
|
2022-01-31 18:09:29 +00:00
|
|
|
completion: Some(CompletionClientCapabilities {
|
|
|
|
completion_item: Some(CompletionItemCapability {
|
|
|
|
resolve_support: Some(CompletionItemCapabilityResolveSupport {
|
|
|
|
properties: vec!["additionalTextEdits".to_string()],
|
|
|
|
}),
|
|
|
|
..Default::default()
|
|
|
|
}),
|
|
|
|
..Default::default()
|
|
|
|
}),
|
2022-01-20 11:10:01 +00:00
|
|
|
..Default::default()
|
|
|
|
}),
|
2021-10-25 16:11:52 +00:00
|
|
|
experimental: Some(json!({
|
|
|
|
"serverStatusNotification": true,
|
|
|
|
})),
|
2022-01-20 11:10:01 +00:00
|
|
|
window: Some(WindowClientCapabilities {
|
2022-01-04 16:38:45 +00:00
|
|
|
work_done_progress: Some(true),
|
|
|
|
..Default::default()
|
|
|
|
}),
|
2021-10-25 16:11:52 +00:00
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
trace: Default::default(),
|
|
|
|
workspace_folders: Default::default(),
|
|
|
|
client_info: Default::default(),
|
|
|
|
locale: Default::default(),
|
2021-10-25 22:28:40 +00:00
|
|
|
};
|
|
|
|
|
2021-11-01 18:57:21 +00:00
|
|
|
let this = self.clone();
|
2022-01-20 11:10:01 +00:00
|
|
|
let request = Self::request_internal::<request::Initialize>(
|
2021-11-01 18:57:21 +00:00
|
|
|
&this.next_id,
|
|
|
|
&this.response_handlers,
|
2021-11-02 19:16:25 +00:00
|
|
|
this.outbound_tx.read().as_ref(),
|
2021-11-01 18:57:21 +00:00
|
|
|
params,
|
2021-11-02 19:16:25 +00:00
|
|
|
);
|
|
|
|
request.await?;
|
2022-01-20 11:10:01 +00:00
|
|
|
Self::notify_internal::<notification::Initialized>(
|
2021-11-02 19:16:25 +00:00
|
|
|
this.outbound_tx.read().as_ref(),
|
2022-01-20 11:10:01 +00:00
|
|
|
InitializedParams {},
|
2021-11-01 18:57:21 +00:00
|
|
|
)?;
|
2021-10-21 14:26:37 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-11-02 19:16:25 +00:00
|
|
|
pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Result<()>>> {
|
|
|
|
if let Some(tasks) = self.io_tasks.lock().take() {
|
|
|
|
let response_handlers = self.response_handlers.clone();
|
|
|
|
let outbound_tx = self.outbound_tx.write().take();
|
|
|
|
let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
|
|
|
|
let mut output_done = self.output_done_rx.lock().take().unwrap();
|
|
|
|
Some(async move {
|
2022-01-20 11:10:01 +00:00
|
|
|
Self::request_internal::<request::Shutdown>(
|
2021-11-02 19:16:25 +00:00
|
|
|
&next_id,
|
|
|
|
&response_handlers,
|
|
|
|
outbound_tx.as_ref(),
|
|
|
|
(),
|
|
|
|
)
|
|
|
|
.await?;
|
2022-01-20 11:10:01 +00:00
|
|
|
Self::notify_internal::<notification::Exit>(outbound_tx.as_ref(), ())?;
|
2021-11-02 19:16:25 +00:00
|
|
|
drop(outbound_tx);
|
|
|
|
output_done.recv().await;
|
|
|
|
drop(tasks);
|
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-04 16:38:45 +00:00
|
|
|
pub fn on_notification<T, F>(&self, mut f: F) -> Subscription
|
2021-10-25 16:11:52 +00:00
|
|
|
where
|
2022-01-20 11:10:01 +00:00
|
|
|
T: notification::Notification,
|
2022-01-04 16:38:45 +00:00
|
|
|
F: 'static + Send + Sync + FnMut(T::Params),
|
2021-10-25 16:11:52 +00:00
|
|
|
{
|
|
|
|
let prev_handler = self.notification_handlers.write().insert(
|
|
|
|
T::METHOD,
|
|
|
|
Box::new(
|
|
|
|
move |notification| match serde_json::from_str(notification) {
|
|
|
|
Ok(notification) => f(notification),
|
|
|
|
Err(err) => log::error!("error parsing notification {}: {}", T::METHOD, err),
|
|
|
|
},
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
assert!(
|
|
|
|
prev_handler.is_none(),
|
|
|
|
"registered multiple handlers for the same notification"
|
|
|
|
);
|
|
|
|
|
|
|
|
Subscription {
|
|
|
|
method: T::METHOD,
|
|
|
|
notification_handlers: self.notification_handlers.clone(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-20 11:10:01 +00:00
|
|
|
pub fn request<T: request::Request>(
|
|
|
|
self: &Arc<Self>,
|
2021-10-21 14:26:37 +00:00
|
|
|
params: T::Params,
|
|
|
|
) -> impl Future<Output = Result<T::Result>>
|
2021-10-25 10:29:28 +00:00
|
|
|
where
|
|
|
|
T::Result: 'static + Send,
|
|
|
|
{
|
2021-10-25 16:11:52 +00:00
|
|
|
let this = self.clone();
|
|
|
|
async move {
|
|
|
|
this.initialized.clone().recv().await;
|
2021-11-01 18:57:21 +00:00
|
|
|
Self::request_internal::<T>(
|
|
|
|
&this.next_id,
|
|
|
|
&this.response_handlers,
|
2021-11-02 19:16:25 +00:00
|
|
|
this.outbound_tx.read().as_ref(),
|
2021-11-01 18:57:21 +00:00
|
|
|
params,
|
|
|
|
)
|
|
|
|
.await
|
2021-10-25 16:11:52 +00:00
|
|
|
}
|
2021-10-25 10:29:28 +00:00
|
|
|
}
|
|
|
|
|
2022-01-20 11:10:01 +00:00
|
|
|
fn request_internal<T: request::Request>(
|
2021-11-01 18:57:21 +00:00
|
|
|
next_id: &AtomicUsize,
|
|
|
|
response_handlers: &Mutex<HashMap<usize, ResponseHandler>>,
|
2021-11-02 19:16:25 +00:00
|
|
|
outbound_tx: Option<&channel::Sender<Vec<u8>>>,
|
2021-10-25 10:29:28 +00:00
|
|
|
params: T::Params,
|
2021-11-02 19:16:25 +00:00
|
|
|
) -> impl 'static + Future<Output = Result<T::Result>>
|
2021-10-21 14:26:37 +00:00
|
|
|
where
|
|
|
|
T::Result: 'static + Send,
|
|
|
|
{
|
2021-11-01 18:57:21 +00:00
|
|
|
let id = next_id.fetch_add(1, SeqCst);
|
2021-10-21 14:26:37 +00:00
|
|
|
let message = serde_json::to_vec(&Request {
|
|
|
|
jsonrpc: JSON_RPC_VERSION,
|
|
|
|
id,
|
|
|
|
method: T::METHOD,
|
|
|
|
params,
|
|
|
|
})
|
|
|
|
.unwrap();
|
2021-11-01 18:57:21 +00:00
|
|
|
let mut response_handlers = response_handlers.lock();
|
2021-10-25 16:11:52 +00:00
|
|
|
let (mut tx, mut rx) = oneshot::channel();
|
2021-10-21 14:26:37 +00:00
|
|
|
response_handlers.insert(
|
|
|
|
id,
|
|
|
|
Box::new(move |result| {
|
|
|
|
let response = match result {
|
|
|
|
Ok(response) => {
|
|
|
|
serde_json::from_str(response).context("failed to deserialize response")
|
|
|
|
}
|
|
|
|
Err(error) => Err(anyhow!("{}", error.message)),
|
|
|
|
};
|
2021-10-25 16:11:52 +00:00
|
|
|
let _ = tx.try_send(response);
|
2021-10-21 14:26:37 +00:00
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
2021-11-02 19:16:25 +00:00
|
|
|
let send = outbound_tx
|
|
|
|
.as_ref()
|
|
|
|
.ok_or_else(|| {
|
|
|
|
anyhow!("tried to send a request to a language server that has been shut down")
|
|
|
|
})
|
|
|
|
.and_then(|outbound_tx| {
|
|
|
|
outbound_tx.try_send(message)?;
|
|
|
|
Ok(())
|
|
|
|
});
|
2021-10-21 14:26:37 +00:00
|
|
|
async move {
|
2021-11-01 18:57:21 +00:00
|
|
|
send?;
|
2021-10-25 16:11:52 +00:00
|
|
|
rx.recv().await.unwrap()
|
2021-10-21 14:26:37 +00:00
|
|
|
}
|
|
|
|
}
|
2021-10-21 17:27:10 +00:00
|
|
|
|
2022-01-20 11:10:01 +00:00
|
|
|
pub fn notify<T: notification::Notification>(
|
2021-10-25 10:29:28 +00:00
|
|
|
self: &Arc<Self>,
|
|
|
|
params: T::Params,
|
|
|
|
) -> impl Future<Output = Result<()>> {
|
2021-10-25 16:11:52 +00:00
|
|
|
let this = self.clone();
|
|
|
|
async move {
|
|
|
|
this.initialized.clone().recv().await;
|
2021-11-02 19:16:25 +00:00
|
|
|
Self::notify_internal::<T>(this.outbound_tx.read().as_ref(), params)?;
|
2021-11-01 18:57:21 +00:00
|
|
|
Ok(())
|
2021-10-25 16:11:52 +00:00
|
|
|
}
|
2021-10-25 10:29:28 +00:00
|
|
|
}
|
|
|
|
|
2022-01-20 11:10:01 +00:00
|
|
|
fn notify_internal<T: notification::Notification>(
|
2021-11-02 19:16:25 +00:00
|
|
|
outbound_tx: Option<&channel::Sender<Vec<u8>>>,
|
2021-10-21 17:27:10 +00:00
|
|
|
params: T::Params,
|
2021-11-01 18:57:21 +00:00
|
|
|
) -> Result<()> {
|
2021-10-25 22:28:40 +00:00
|
|
|
let message = serde_json::to_vec(&Notification {
|
2021-10-21 17:27:10 +00:00
|
|
|
jsonrpc: JSON_RPC_VERSION,
|
|
|
|
method: T::METHOD,
|
|
|
|
params,
|
|
|
|
})
|
|
|
|
.unwrap();
|
2021-11-02 19:16:25 +00:00
|
|
|
let outbound_tx = outbound_tx
|
|
|
|
.as_ref()
|
|
|
|
.ok_or_else(|| anyhow!("tried to notify a language server that has been shut down"))?;
|
2021-11-01 18:57:21 +00:00
|
|
|
outbound_tx.try_send(message)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
2021-10-25 10:29:28 +00:00
|
|
|
|
2021-11-01 18:57:21 +00:00
|
|
|
impl Drop for LanguageServer {
|
|
|
|
fn drop(&mut self) {
|
2021-11-02 19:16:25 +00:00
|
|
|
if let Some(shutdown) = self.shutdown() {
|
|
|
|
self.executor.spawn(shutdown).detach();
|
|
|
|
}
|
2021-10-21 17:27:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
impl Subscription {
|
|
|
|
pub fn detach(mut self) {
|
|
|
|
self.method = "";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-25 16:11:52 +00:00
|
|
|
impl Drop for Subscription {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
self.notification_handlers.write().remove(self.method);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
#[cfg(any(test, feature = "test-support"))]
|
|
|
|
pub struct FakeLanguageServer {
|
|
|
|
buffer: Vec<u8>,
|
|
|
|
stdin: smol::io::BufReader<async_pipe::PipeReader>,
|
|
|
|
stdout: smol::io::BufWriter<async_pipe::PipeWriter>,
|
2022-01-14 09:20:04 +00:00
|
|
|
pub started: Arc<std::sync::atomic::AtomicBool>,
|
2021-10-25 22:28:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(any(test, feature = "test-support"))]
|
|
|
|
pub struct RequestId<T> {
|
|
|
|
id: usize,
|
|
|
|
_type: std::marker::PhantomData<T>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(any(test, feature = "test-support"))]
|
|
|
|
impl LanguageServer {
|
2021-11-01 18:57:21 +00:00
|
|
|
pub async fn fake(executor: Arc<executor::Background>) -> (Arc<Self>, FakeLanguageServer) {
|
2021-10-25 22:28:40 +00:00
|
|
|
let stdin = async_pipe::pipe();
|
|
|
|
let stdout = async_pipe::pipe();
|
2021-10-26 01:04:27 +00:00
|
|
|
let mut fake = FakeLanguageServer {
|
|
|
|
stdin: smol::io::BufReader::new(stdin.1),
|
|
|
|
stdout: smol::io::BufWriter::new(stdout.0),
|
|
|
|
buffer: Vec::new(),
|
2022-01-14 09:20:04 +00:00
|
|
|
started: Arc::new(std::sync::atomic::AtomicBool::new(true)),
|
2021-10-26 01:04:27 +00:00
|
|
|
};
|
|
|
|
|
2021-10-26 19:17:51 +00:00
|
|
|
let server = Self::new_internal(stdin.0, stdout.1, Path::new("/"), executor).unwrap();
|
2021-10-26 01:04:27 +00:00
|
|
|
|
|
|
|
let (init_id, _) = fake.receive_request::<request::Initialize>().await;
|
|
|
|
fake.respond(init_id, InitializeResult::default()).await;
|
|
|
|
fake.receive_notification::<notification::Initialized>()
|
|
|
|
.await;
|
|
|
|
|
|
|
|
(server, fake)
|
2021-10-25 22:28:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(any(test, feature = "test-support"))]
|
|
|
|
impl FakeLanguageServer {
|
|
|
|
pub async fn notify<T: notification::Notification>(&mut self, params: T::Params) {
|
2021-11-03 00:41:01 +00:00
|
|
|
if !self.started.load(std::sync::atomic::Ordering::SeqCst) {
|
|
|
|
panic!("can't simulate an LSP notification before the server has been started");
|
|
|
|
}
|
2021-10-25 22:28:40 +00:00
|
|
|
let message = serde_json::to_vec(&Notification {
|
|
|
|
jsonrpc: JSON_RPC_VERSION,
|
|
|
|
method: T::METHOD,
|
|
|
|
params,
|
|
|
|
})
|
|
|
|
.unwrap();
|
|
|
|
self.send(message).await;
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn respond<'a, T: request::Request>(
|
|
|
|
&mut self,
|
|
|
|
request_id: RequestId<T>,
|
|
|
|
result: T::Result,
|
|
|
|
) {
|
|
|
|
let result = serde_json::to_string(&result).unwrap();
|
|
|
|
let message = serde_json::to_vec(&AnyResponse {
|
|
|
|
id: request_id.id,
|
|
|
|
error: None,
|
2021-11-02 13:58:00 +00:00
|
|
|
result: Some(&RawValue::from_string(result).unwrap()),
|
2021-10-25 22:28:40 +00:00
|
|
|
})
|
|
|
|
.unwrap();
|
|
|
|
self.send(message).await;
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn receive_request<T: request::Request>(&mut self) -> (RequestId<T>, T::Params) {
|
2022-01-12 17:01:20 +00:00
|
|
|
loop {
|
|
|
|
self.receive().await;
|
|
|
|
if let Ok(request) = serde_json::from_slice::<Request<T::Params>>(&self.buffer) {
|
|
|
|
assert_eq!(request.method, T::METHOD);
|
|
|
|
assert_eq!(request.jsonrpc, JSON_RPC_VERSION);
|
|
|
|
return (
|
|
|
|
RequestId {
|
|
|
|
id: request.id,
|
|
|
|
_type: std::marker::PhantomData,
|
|
|
|
},
|
|
|
|
request.params,
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
println!(
|
|
|
|
"skipping message in fake language server {:?}",
|
|
|
|
std::str::from_utf8(&self.buffer)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2021-10-25 22:28:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
|
|
|
|
self.receive().await;
|
|
|
|
let notification = serde_json::from_slice::<Notification<T::Params>>(&self.buffer).unwrap();
|
|
|
|
assert_eq!(notification.method, T::METHOD);
|
|
|
|
notification.params
|
|
|
|
}
|
|
|
|
|
2022-01-06 16:32:08 +00:00
|
|
|
pub async fn start_progress(&mut self, token: impl Into<String>) {
|
|
|
|
self.notify::<notification::Progress>(ProgressParams {
|
|
|
|
token: NumberOrString::String(token.into()),
|
|
|
|
value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
|
|
|
|
})
|
|
|
|
.await;
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn end_progress(&mut self, token: impl Into<String>) {
|
|
|
|
self.notify::<notification::Progress>(ProgressParams {
|
|
|
|
token: NumberOrString::String(token.into()),
|
|
|
|
value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
|
|
|
|
})
|
|
|
|
.await;
|
|
|
|
}
|
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
async fn send(&mut self, message: Vec<u8>) {
|
|
|
|
self.stdout
|
|
|
|
.write_all(CONTENT_LEN_HEADER.as_bytes())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
self.stdout
|
|
|
|
.write_all((format!("{}", message.len())).as_bytes())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
self.stdout.write_all("\r\n\r\n".as_bytes()).await.unwrap();
|
|
|
|
self.stdout.write_all(&message).await.unwrap();
|
|
|
|
self.stdout.flush().await.unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn receive(&mut self) {
|
|
|
|
self.buffer.clear();
|
|
|
|
self.stdin
|
|
|
|
.read_until(b'\n', &mut self.buffer)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
self.stdin
|
|
|
|
.read_until(b'\n', &mut self.buffer)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
let message_len: usize = std::str::from_utf8(&self.buffer)
|
|
|
|
.unwrap()
|
|
|
|
.strip_prefix(CONTENT_LEN_HEADER)
|
|
|
|
.unwrap()
|
|
|
|
.trim_end()
|
|
|
|
.parse()
|
|
|
|
.unwrap();
|
|
|
|
self.buffer.resize(message_len, 0);
|
|
|
|
self.stdin.read_exact(&mut self.buffer).await.unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-21 17:27:10 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use gpui::TestAppContext;
|
2021-10-25 22:28:40 +00:00
|
|
|
use simplelog::SimpleLogger;
|
2021-10-25 16:11:52 +00:00
|
|
|
use unindent::Unindent;
|
|
|
|
use util::test::temp_tree;
|
2021-10-21 17:27:10 +00:00
|
|
|
|
|
|
|
#[gpui::test]
|
2022-01-28 20:11:26 +00:00
|
|
|
async fn test_rust_analyzer(cx: TestAppContext) {
|
2021-10-25 17:46:33 +00:00
|
|
|
let lib_source = r#"
|
|
|
|
fn fun() {
|
|
|
|
let hello = "world";
|
|
|
|
}
|
|
|
|
"#
|
|
|
|
.unindent();
|
2021-10-25 16:11:52 +00:00
|
|
|
let root_dir = temp_tree(json!({
|
|
|
|
"Cargo.toml": r#"
|
|
|
|
[package]
|
|
|
|
name = "temp"
|
|
|
|
version = "0.1.0"
|
|
|
|
edition = "2018"
|
|
|
|
"#.unindent(),
|
|
|
|
"src": {
|
2021-10-25 17:46:33 +00:00
|
|
|
"lib.rs": &lib_source
|
2021-10-25 16:11:52 +00:00
|
|
|
}
|
|
|
|
}));
|
2022-01-20 11:10:01 +00:00
|
|
|
let lib_file_uri = Url::from_file_path(root_dir.path().join("src/lib.rs")).unwrap();
|
2021-10-25 16:11:52 +00:00
|
|
|
|
2021-10-26 19:17:51 +00:00
|
|
|
let server = cx.read(|cx| {
|
2021-11-01 18:57:21 +00:00
|
|
|
LanguageServer::new(
|
|
|
|
Path::new("rust-analyzer"),
|
|
|
|
root_dir.path(),
|
|
|
|
cx.background().clone(),
|
|
|
|
)
|
|
|
|
.unwrap()
|
2021-10-26 19:17:51 +00:00
|
|
|
});
|
2021-10-25 16:11:52 +00:00
|
|
|
server.next_idle_notification().await;
|
|
|
|
|
2021-10-25 17:46:33 +00:00
|
|
|
server
|
2022-01-20 11:10:01 +00:00
|
|
|
.notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
|
|
|
|
text_document: TextDocumentItem::new(
|
|
|
|
lib_file_uri.clone(),
|
|
|
|
"rust".to_string(),
|
|
|
|
0,
|
|
|
|
lib_source,
|
|
|
|
),
|
|
|
|
})
|
2021-10-25 17:46:33 +00:00
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
2021-10-25 16:11:52 +00:00
|
|
|
let hover = server
|
2022-01-20 11:10:01 +00:00
|
|
|
.request::<request::HoverRequest>(HoverParams {
|
|
|
|
text_document_position_params: TextDocumentPositionParams {
|
|
|
|
text_document: TextDocumentIdentifier::new(lib_file_uri),
|
|
|
|
position: Position::new(1, 21),
|
2021-10-25 16:11:52 +00:00
|
|
|
},
|
|
|
|
work_done_progress_params: Default::default(),
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
.unwrap()
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(
|
|
|
|
hover.contents,
|
2022-01-20 11:10:01 +00:00
|
|
|
HoverContents::Markup(MarkupContent {
|
2022-01-28 20:11:26 +00:00
|
|
|
kind: MarkupKind::PlainText,
|
2021-10-25 16:11:52 +00:00
|
|
|
value: "&str".to_string()
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-10-25 22:28:40 +00:00
|
|
|
#[gpui::test]
|
|
|
|
async fn test_fake(cx: TestAppContext) {
|
|
|
|
SimpleLogger::init(log::LevelFilter::Info, Default::default()).unwrap();
|
|
|
|
|
2021-11-01 18:57:21 +00:00
|
|
|
let (server, mut fake) = LanguageServer::fake(cx.background()).await;
|
2021-10-25 22:28:40 +00:00
|
|
|
|
|
|
|
let (message_tx, message_rx) = channel::unbounded();
|
|
|
|
let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
|
|
|
|
server
|
|
|
|
.on_notification::<notification::ShowMessage, _>(move |params| {
|
|
|
|
message_tx.try_send(params).unwrap()
|
|
|
|
})
|
|
|
|
.detach();
|
|
|
|
server
|
|
|
|
.on_notification::<notification::PublishDiagnostics, _>(move |params| {
|
|
|
|
diagnostics_tx.try_send(params).unwrap()
|
|
|
|
})
|
|
|
|
.detach();
|
|
|
|
|
|
|
|
server
|
|
|
|
.notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
|
|
|
|
text_document: TextDocumentItem::new(
|
|
|
|
Url::from_str("file://a/b").unwrap(),
|
|
|
|
"rust".to_string(),
|
|
|
|
0,
|
|
|
|
"".to_string(),
|
|
|
|
),
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(
|
|
|
|
fake.receive_notification::<notification::DidOpenTextDocument>()
|
|
|
|
.await
|
|
|
|
.text_document
|
|
|
|
.uri
|
|
|
|
.as_str(),
|
|
|
|
"file://a/b"
|
|
|
|
);
|
|
|
|
|
|
|
|
fake.notify::<notification::ShowMessage>(ShowMessageParams {
|
|
|
|
typ: MessageType::ERROR,
|
|
|
|
message: "ok".to_string(),
|
|
|
|
})
|
|
|
|
.await;
|
|
|
|
fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
|
|
|
|
uri: Url::from_str("file://b/c").unwrap(),
|
|
|
|
version: Some(5),
|
|
|
|
diagnostics: vec![],
|
|
|
|
})
|
|
|
|
.await;
|
|
|
|
assert_eq!(message_rx.recv().await.unwrap().message, "ok");
|
|
|
|
assert_eq!(
|
|
|
|
diagnostics_rx.recv().await.unwrap().uri.as_str(),
|
|
|
|
"file://b/c"
|
|
|
|
);
|
2021-11-01 18:57:21 +00:00
|
|
|
|
|
|
|
drop(server);
|
2022-01-20 11:10:01 +00:00
|
|
|
let (shutdown_request, _) = fake.receive_request::<request::Shutdown>().await;
|
2021-11-01 18:57:21 +00:00
|
|
|
fake.respond(shutdown_request, ()).await;
|
2022-01-20 11:10:01 +00:00
|
|
|
fake.receive_notification::<notification::Exit>().await;
|
2021-10-25 22:28:40 +00:00
|
|
|
}
|
|
|
|
|
2021-10-25 16:11:52 +00:00
|
|
|
impl LanguageServer {
|
|
|
|
async fn next_idle_notification(self: &Arc<Self>) {
|
|
|
|
let (tx, rx) = channel::unbounded();
|
|
|
|
let _subscription =
|
|
|
|
self.on_notification::<ServerStatusNotification, _>(move |params| {
|
|
|
|
if params.quiescent {
|
|
|
|
tx.try_send(()).unwrap();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
let _ = rx.recv().await;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub enum ServerStatusNotification {}
|
|
|
|
|
2022-01-20 11:10:01 +00:00
|
|
|
impl notification::Notification for ServerStatusNotification {
|
2021-10-25 16:11:52 +00:00
|
|
|
type Params = ServerStatusParams;
|
|
|
|
const METHOD: &'static str = "experimental/serverStatus";
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize, Serialize, PartialEq, Eq, Clone)]
|
|
|
|
pub struct ServerStatusParams {
|
|
|
|
pub quiescent: bool,
|
2021-10-21 17:27:10 +00:00
|
|
|
}
|
2021-10-21 14:26:37 +00:00
|
|
|
}
|