Get rid of failure: gen_lsp_server

This commit is contained in:
Muhammad Mominul Huque 2019-06-15 01:03:17 +06:00
parent 84b6610782
commit a931fb1ef6
No known key found for this signature in database
GPG key ID: 37AF141540DE557D
7 changed files with 21 additions and 21 deletions

1
Cargo.lock generated
View file

@ -490,7 +490,6 @@ name = "gen_lsp_server"
version = "0.2.0" version = "0.2.0"
dependencies = [ dependencies = [
"crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"flexi_logger 0.11.5 (registry+https://github.com/rust-lang/crates.io-index)", "flexi_logger 0.11.5 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"lsp-types 0.57.2 (registry+https://github.com/rust-lang/crates.io-index)", "lsp-types 0.57.2 (registry+https://github.com/rust-lang/crates.io-index)",

View file

@ -10,7 +10,6 @@ description = "Generic LSP server scaffold."
[dependencies] [dependencies]
lsp-types = "0.57.0" lsp-types = "0.57.0"
log = "0.4.3" log = "0.4.3"
failure = "0.1.4"
serde_json = "1.0.34" serde_json = "1.0.34"
serde = { version = "1.0.83", features = ["derive"] } serde = { version = "1.0.83", features = ["derive"] }
crossbeam-channel = "0.3.5" crossbeam-channel = "0.3.5"

View file

@ -1,3 +1,5 @@
use std::error::Error;
use crossbeam_channel::{Sender, Receiver}; use crossbeam_channel::{Sender, Receiver};
use lsp_types::{ use lsp_types::{
ServerCapabilities, InitializeParams, ServerCapabilities, InitializeParams,
@ -5,7 +7,7 @@ use lsp_types::{
}; };
use gen_lsp_server::{run_server, stdio_transport, handle_shutdown, RawMessage, RawResponse}; use gen_lsp_server::{run_server, stdio_transport, handle_shutdown, RawMessage, RawResponse};
fn main() -> Result<(), failure::Error> { fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
let (receiver, sender, io_threads) = stdio_transport(); let (receiver, sender, io_threads) = stdio_transport();
run_server(ServerCapabilities::default(), receiver, sender, main_loop)?; run_server(ServerCapabilities::default(), receiver, sender, main_loop)?;
io_threads.join()?; io_threads.join()?;
@ -16,7 +18,7 @@ fn main_loop(
_params: InitializeParams, _params: InitializeParams,
receiver: &Receiver<RawMessage>, receiver: &Receiver<RawMessage>,
sender: &Sender<RawMessage>, sender: &Sender<RawMessage>,
) -> Result<(), failure::Error> { ) -> Result<(), Box<dyn Error + Sync + Send>> {
for msg in receiver { for msg in receiver {
match msg { match msg {
RawMessage::Request(req) => { RawMessage::Request(req) => {

View file

@ -42,6 +42,8 @@
//! {"jsonrpc": "2.0", "method": "exit", "params": null} //! {"jsonrpc": "2.0", "method": "exit", "params": null}
//! ``` //! ```
use std::error::Error;
use crossbeam_channel::{Sender, Receiver}; use crossbeam_channel::{Sender, Receiver};
use lsp_types::{ use lsp_types::{
ServerCapabilities, InitializeParams, ServerCapabilities, InitializeParams,
@ -52,7 +54,7 @@ use gen_lsp_server::{
run_server, stdio_transport, handle_shutdown, RawMessage, RawResponse, RawRequest, run_server, stdio_transport, handle_shutdown, RawMessage, RawResponse, RawRequest,
}; };
fn main() -> Result<(), failure::Error> { fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// Set up logging. Because `stdio_transport` gets a lock on stdout and stdin, we must have // Set up logging. Because `stdio_transport` gets a lock on stdout and stdin, we must have
// our logging only write out to stderr. // our logging only write out to stderr.
flexi_logger::Logger::with_str("info").start().unwrap(); flexi_logger::Logger::with_str("info").start().unwrap();
@ -75,7 +77,7 @@ fn main_loop(
_params: InitializeParams, _params: InitializeParams,
receiver: &Receiver<RawMessage>, receiver: &Receiver<RawMessage>,
sender: &Sender<RawMessage>, sender: &Sender<RawMessage>,
) -> Result<(), failure::Error> { ) -> Result<(), Box<dyn Error + Sync + Send>> {
info!("starting example main loop"); info!("starting example main loop");
for msg in receiver { for msg in receiver {
info!("got msg: {:?}", msg); info!("got msg: {:?}", msg);

View file

@ -54,7 +54,7 @@
//! } //! }
//! ``` //! ```
use failure::{bail, format_err}; use std::error::Error;
mod msg; mod msg;
mod stdio; mod stdio;
@ -66,7 +66,7 @@ use lsp_types::{
InitializeParams, InitializeResult, ServerCapabilities, InitializeParams, InitializeResult, ServerCapabilities,
}; };
pub type Result<T> = ::std::result::Result<T, failure::Error>; pub type Result<T> = ::std::result::Result<T, Box<dyn Error + Send + Sync>>;
pub use crate::{ pub use crate::{
msg::{ErrorCode, RawMessage, RawNotification, RawRequest, RawResponse, RawResponseError}, msg::{ErrorCode, RawMessage, RawNotification, RawRequest, RawResponse, RawResponseError},
stdio::{stdio_transport, Threads}, stdio::{stdio_transport, Threads},
@ -92,8 +92,8 @@ pub fn run_server(
match receiver.recv() { match receiver.recv() {
Ok(RawMessage::Notification(n)) => n Ok(RawMessage::Notification(n)) => n
.cast::<Exit>() .cast::<Exit>()
.map_err(|n| format_err!("unexpected notification during shutdown: {:?}", n))?, .map_err(|n| format!("unexpected notification during shutdown: {:?}", n))?,
m => bail!("unexpected message during shutdown: {:?}", m), m => Err(format!("unexpected message during shutdown: {:?}", m))?,
} }
log::info!("lsp server shutdown complete"); log::info!("lsp server shutdown complete");
Ok(()) Ok(())
@ -118,19 +118,19 @@ fn initialize(
) -> Result<InitializeParams> { ) -> Result<InitializeParams> {
let (id, params) = match receiver.recv() { let (id, params) = match receiver.recv() {
Ok(RawMessage::Request(req)) => match req.cast::<Initialize>() { Ok(RawMessage::Request(req)) => match req.cast::<Initialize>() {
Err(req) => bail!("expected initialize request, got {:?}", req), Err(req) => Err(format!("expected initialize request, got {:?}", req))?,
Ok(req) => req, Ok(req) => req,
}, },
msg => bail!("expected initialize request, got {:?}", msg), msg => Err(format!("expected initialize request, got {:?}", msg))?,
}; };
let resp = RawResponse::ok::<Initialize>(id, &InitializeResult { capabilities: caps }); let resp = RawResponse::ok::<Initialize>(id, &InitializeResult { capabilities: caps });
sender.send(RawMessage::Response(resp)).unwrap(); sender.send(RawMessage::Response(resp)).unwrap();
match receiver.recv() { match receiver.recv() {
Ok(RawMessage::Notification(n)) => { Ok(RawMessage::Notification(n)) => {
n.cast::<Initialized>() n.cast::<Initialized>()
.map_err(|_| format_err!("expected initialized notification"))?; .map_err(|_| "expected initialized notification")?;
} }
_ => bail!("expected initialized notification"), _ => Err(format!("expected initialized notification"))?,
} }
Ok(params) Ok(params)
} }

View file

@ -3,7 +3,6 @@ use std::io::{BufRead, Write};
use lsp_types::{notification::Notification, request::Request}; use lsp_types::{notification::Notification, request::Request};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::{from_str, from_value, to_string, to_value, Value}; use serde_json::{from_str, from_value, to_string, to_value, Value};
use failure::{bail, format_err};
use crate::Result; use crate::Result;
@ -175,7 +174,7 @@ fn read_msg_text(inp: &mut impl BufRead) -> Result<Option<String>> {
return Ok(None); return Ok(None);
} }
if !buf.ends_with("\r\n") { if !buf.ends_with("\r\n") {
bail!("malformed header: {:?}", buf); Err(format!("malformed header: {:?}", buf))?;
} }
let buf = &buf[..buf.len() - 2]; let buf = &buf[..buf.len() - 2];
if buf.is_empty() { if buf.is_empty() {
@ -184,12 +183,12 @@ fn read_msg_text(inp: &mut impl BufRead) -> Result<Option<String>> {
let mut parts = buf.splitn(2, ": "); let mut parts = buf.splitn(2, ": ");
let header_name = parts.next().unwrap(); let header_name = parts.next().unwrap();
let header_value = let header_value =
parts.next().ok_or_else(|| format_err!("malformed header: {:?}", buf))?; parts.next().ok_or_else(|| format!("malformed header: {:?}", buf))?;
if header_name == "Content-Length" { if header_name == "Content-Length" {
size = Some(header_value.parse::<usize>()?); size = Some(header_value.parse::<usize>()?);
} }
} }
let size = size.ok_or_else(|| format_err!("no Content-Length"))?; let size = size.ok_or("no Content-Length")?;
let mut buf = buf.into_bytes(); let mut buf = buf.into_bytes();
buf.resize(size, 0); buf.resize(size, 0);
inp.read_exact(&mut buf)?; inp.read_exact(&mut buf)?;

View file

@ -4,7 +4,6 @@ use std::{
}; };
use crossbeam_channel::{bounded, Receiver, Sender}; use crossbeam_channel::{bounded, Receiver, Sender};
use failure::bail;
use lsp_types::notification::Exit; use lsp_types::notification::Exit;
use crate::{RawMessage, Result}; use crate::{RawMessage, Result};
@ -48,11 +47,11 @@ impl Threads {
pub fn join(self) -> Result<()> { pub fn join(self) -> Result<()> {
match self.reader.join() { match self.reader.join() {
Ok(r) => r?, Ok(r) => r?,
Err(_) => bail!("reader panicked"), Err(_) => Err("reader panicked")?,
} }
match self.writer.join() { match self.writer.join() {
Ok(r) => r, Ok(r) => r,
Err(_) => bail!("writer panicked"), Err(_) => Err("writer panicked")?,
} }
} }
} }