rust/crates/gen_lsp_server/src/lib.rs

87 lines
2.6 KiB
Rust
Raw Normal View History

2018-09-01 08:18:02 -05:00
#[macro_use]
extern crate failure;
#[macro_use]
extern crate log;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate crossbeam_channel;
extern crate languageserver_types;
mod msg;
mod stdio;
use crossbeam_channel::{Sender, Receiver};
use languageserver_types::{
ServerCapabilities, InitializeResult,
2018-09-01 12:21:11 -05:00
request::{Initialize, Shutdown},
2018-09-01 08:18:02 -05:00
notification::{Initialized, Exit},
};
pub type Result<T> = ::std::result::Result<T, failure::Error>;
pub use {
2018-09-01 09:40:45 -05:00
msg::{RawMessage, RawRequest, RawResponse, RawResponseError, RawNotification, ErrorCode},
2018-09-01 08:18:02 -05:00
stdio::{stdio_transport, Threads},
};
pub fn run_server(
caps: ServerCapabilities,
2018-09-01 10:03:57 -05:00
server: impl FnOnce(&mut Receiver<RawMessage>, &mut Sender<RawMessage>) -> Result<()>,
2018-09-01 08:18:02 -05:00
mut receiver: Receiver<RawMessage>,
mut sender: Sender<RawMessage>,
) -> Result<()> {
info!("lsp server initializes");
initialize(&mut receiver, &mut sender, caps)?;
info!("lsp server initialized, serving requests");
server(&mut receiver, &mut sender)?;
info!("lsp server waiting for exit notification");
match receiver.recv() {
Some(RawMessage::Notification(n)) => {
n.cast::<Exit>().map_err(|n| format_err!(
"unexpected notification during shutdown: {:?}", n
))?
}
m => bail!("unexpected message during shutdown: {:?}", m)
}
info!("lsp server shutdown complete");
Ok(())
}
2018-09-01 12:21:11 -05:00
pub fn handle_shutdown(req: RawRequest, sender: &Sender<RawMessage>) -> Option<RawRequest> {
match req.cast::<Shutdown>() {
Ok((id, ())) => {
2018-09-02 07:18:43 -05:00
let resp = RawResponse::ok::<Shutdown>(id, &());
2018-09-01 12:21:11 -05:00
sender.send(RawMessage::Response(resp));
None
}
Err(req) => Some(req),
}
}
2018-09-01 08:18:02 -05:00
fn initialize(
receiver: &mut Receiver<RawMessage>,
sender: &mut Sender<RawMessage>,
caps: ServerCapabilities,
) -> Result<()> {
let id = match receiver.recv() {
Some(RawMessage::Request(req)) => match req.cast::<Initialize>() {
Err(req) => bail!("expected initialize request, got {:?}", req),
Ok(req) => req.0,
}
msg =>
bail!("expected initialize request, got {:?}", msg),
};
2018-09-02 07:18:43 -05:00
let resp = RawResponse::ok::<Initialize>(id, &InitializeResult { capabilities: caps });
2018-09-01 08:18:02 -05:00
sender.send(RawMessage::Response(resp));
match receiver.recv() {
Some(RawMessage::Notification(n)) => {
n.cast::<Initialized>().map_err(|_| format_err!(
"expected initialized notification"
))?;
}
_ => bail!("expected initialized notification"),
}
Ok(())
}