rust/crates/gen_lsp_server/src/lib.rs

160 lines
5.2 KiB
Rust
Raw Normal View History

2018-10-09 04:55:23 -05:00
//! A language server scaffold, exposing synchroneous crossbeam-channel based API.
//! This crate handles protocol handshaking and parsing messages, while you
//! control the message dispatch loop yourself.
//!
//! Run with `RUST_LOG=sync_lsp_server=debug` to see all the messages.
//!
//! ```no_run
//! extern crate gen_lsp_server;
//! extern crate languageserver_types;
//! extern crate failure;
//! extern crate crossbeam_channel;
//!
//! use crossbeam_channel::{Sender, Receiver};
//! use languageserver_types::{ServerCapabilities, InitializeParams, request::{GotoDefinition, GotoDefinitionResponse}};
//! use gen_lsp_server::{run_server, stdio_transport, handle_shutdown, RawMessage, RawResponse};
//!
//! fn main() -> Result<(), failure::Error> {
//! let (receiver, sender, io_threads) = stdio_transport();
//! gen_lsp_server::run_server(
//! ServerCapabilities::default(),
//! receiver,
//! sender,
//! main_loop,
//! )?;
//! io_threads.join()?;
//! Ok(())
//! }
//!
//! fn main_loop(
//! _params: InitializeParams,
//! receiver: &Receiver<RawMessage>,
//! sender: &Sender<RawMessage>,
//! ) -> Result<(), failure::Error> {
//! for msg in receiver {
//! match msg {
//! RawMessage::Request(req) => {
//! let req = match handle_shutdown(req, sender) {
//! None => return Ok(()),
//! Some(req) => req,
//! };
//! let req = match req.cast::<GotoDefinition>() {
//! Ok((id, _params)) => {
//! let resp = RawResponse::ok::<GotoDefinition>(
//! id,
//! &Some(GotoDefinitionResponse::Array(Vec::new())),
//! );
//! sender.send(RawMessage::Response(resp));
//! continue;
//! },
//! Err(req) => req,
//! };
//! // ...
//! }
//! RawMessage::Response(_resp) => (),
//! RawMessage::Notification(_not) => (),
//! }
//! }
//! Ok(())
//! }
//! ```
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::{
2018-09-05 13:38:43 -05:00
ServerCapabilities, InitializeResult, InitializeParams,
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},
};
2018-10-09 04:55:23 -05:00
/// Main entry point: runs the server from initialization to shutdown.
/// To attach server to standard input/output streams, use `stdio_transport`
/// function to create corresponding `sender` and `receiver` pair.
///
///`server` should use `handle_shutdown` function to handle the `Shutdown`
/// request.
2018-09-01 08:18:02 -05:00
pub fn run_server(
caps: ServerCapabilities,
2018-10-09 04:55:23 -05:00
receiver: Receiver<RawMessage>,
sender: Sender<RawMessage>,
2018-09-05 13:38:43 -05:00
server: impl FnOnce(
InitializeParams,
2018-10-09 04:55:23 -05:00
&Receiver<RawMessage>,
&Sender<RawMessage>,
2018-09-05 13:38:43 -05:00
) -> Result<()>,
2018-09-01 08:18:02 -05:00
) -> Result<()> {
info!("lsp server initializes");
2018-10-09 04:55:23 -05:00
let params = initialize(&receiver, &sender, caps)?;
2018-09-01 08:18:02 -05:00
info!("lsp server initialized, serving requests");
2018-10-09 04:55:23 -05:00
server(params, &receiver, &sender)?;
2018-09-01 08:18:02 -05:00
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-10-09 04:55:23 -05:00
/// if `req` is `Shutdown`, respond to it and return `None`, otherwise return `Some(req)`
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(
2018-10-09 04:55:23 -05:00
receiver: &Receiver<RawMessage>,
sender: &Sender<RawMessage>,
2018-09-01 08:18:02 -05:00
caps: ServerCapabilities,
2018-09-05 13:38:43 -05:00
) -> Result<InitializeParams> {
let (id, params) = match receiver.recv() {
2018-09-01 08:18:02 -05:00
Some(RawMessage::Request(req)) => match req.cast::<Initialize>() {
Err(req) => bail!("expected initialize request, got {:?}", req),
2018-09-05 13:38:43 -05:00
Ok(req) => req,
2018-09-01 08:18:02 -05:00
}
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"),
}
2018-09-05 13:38:43 -05:00
Ok(params)
2018-09-01 08:18:02 -05:00
}