Convert Thunk to Task

This commit is contained in:
Aleksey Kladov 2018-08-12 21:34:17 +03:00
parent 23c06db9c2
commit 8dad14b5cd
3 changed files with 79 additions and 77 deletions

View file

@ -19,38 +19,27 @@ pub struct Responder<R: ClientRequest> {
ph: PhantomData<fn(R)>, ph: PhantomData<fn(R)>,
} }
impl<R: ClientRequest> Responder<R> impl<R: ClientRequest> Responder<R> {
{ pub fn into_response(mut self, result: Result<R::Result>) -> Result<RawResponse> {
pub fn response(self, io: &mut Io, resp: Result<R::Result>) -> Result<()> { self.bomb.defuse();
match resp { let res = match result {
Ok(res) => self.result(io, res)?, Ok(result) => {
Err(e) => { RawResponse {
self.error(io)?; id: Some(self.id),
return Err(e); result: serde_json::to_value(result)?,
error: serde_json::Value::Null,
}
} }
} Err(_) => {
Ok(()) error_response(self.id, ErrorCode::InternalError, "internal error")?
} }
};
pub fn result(mut self, io: &mut Io, result: R::Result) -> Result<()> { Ok(res)
self.bomb.defuse();
io.send(RawMsg::Response(RawResponse {
id: Some(self.id),
result: serde_json::to_value(result)?,
error: serde_json::Value::Null,
}));
Ok(())
}
pub fn error(mut self, io: &mut Io) -> Result<()> {
self.bomb.defuse();
error(io, self.id, ErrorCode::InternalError, "internal error")
} }
} }
fn parse_request_as<R: ClientRequest>(raw: RawRequest) fn parse_request_as<R: ClientRequest>(raw: RawRequest)
-> Result<::std::result::Result<(R::Params, Responder<R>), RawRequest>> -> Result<::std::result::Result<(R::Params, Responder<R>), RawRequest>>
{ {
if raw.method != R::METHOD { if raw.method != R::METHOD {
return Ok(Err(raw)); return Ok(Err(raw));
@ -77,13 +66,13 @@ pub fn handle_request<R, F>(req: &mut Option<RawRequest>, f: F) -> Result<()>
Err(r) => { Err(r) => {
*req = Some(r); *req = Some(r);
Ok(()) Ok(())
}, }
} }
} }
} }
pub fn expect_request<R: ClientRequest>(io: &mut Io, raw: RawRequest) pub fn expect_request<R: ClientRequest>(io: &mut Io, raw: RawRequest)
-> Result<Option<(R::Params, Responder<R>)>> -> Result<Option<(R::Params, Responder<R>)>>
{ {
let ret = match parse_request_as::<R>(raw)? { let ret = match parse_request_as::<R>(raw)? {
Ok(x) => Some(x), Ok(x) => Some(x),
@ -120,21 +109,21 @@ pub fn handle_notification<N, F>(not: &mut Option<RawNotification>, f: F) -> Res
Err(n) => { Err(n) => {
*not = Some(n); *not = Some(n);
Ok(()) Ok(())
}, }
} }
} }
} }
pub fn send_notification<N>(io: &mut Io, params: N::Params) -> Result<()> pub fn send_notification<N>(params: N::Params) -> RawNotification
where where
N: Notification, N: Notification,
N::Params: Serialize N::Params: Serialize
{ {
io.send(RawMsg::Notification(RawNotification { RawNotification {
method: N::METHOD.to_string(), method: N::METHOD.to_string(),
params: serde_json::to_value(params)?, params: serde_json::to_value(params)
})); .unwrap(),
Ok(()) }
} }
@ -142,20 +131,26 @@ pub fn unknown_method(io: &mut Io, raw: RawRequest) -> Result<()> {
error(io, raw.id, ErrorCode::MethodNotFound, "unknown method") error(io, raw.id, ErrorCode::MethodNotFound, "unknown method")
} }
fn error(io: &mut Io, id: u64, code: ErrorCode, message: &'static str) -> Result<()> { fn error_response(id: u64, code: ErrorCode, message: &'static str) -> Result<RawResponse> {
#[derive(Serialize)] #[derive(Serialize)]
struct Error { struct Error {
code: i32, code: i32,
message: &'static str, message: &'static str,
} }
io.send(RawMsg::Response(RawResponse { let resp = RawResponse {
id: Some(id), id: Some(id),
result: serde_json::Value::Null, result: serde_json::Value::Null,
error: serde_json::to_value(Error { error: serde_json::to_value(Error {
code: code as i32, code: code as i32,
message, message,
})?, })?,
})); };
Ok(resp)
}
fn error(io: &mut Io, id: u64, code: ErrorCode, message: &'static str) -> Result<()> {
let resp = error_response(id, code, message)?;
io.send(RawMsg::Response(resp));
Ok(()) Ok(())
} }

View file

@ -32,10 +32,10 @@ use languageserver_types::Url;
use libanalysis::{WorldState, World}; use libanalysis::{WorldState, World};
use ::{ use ::{
io::{Io, RawMsg, RawRequest}, io::{Io, RawMsg, RawRequest, RawResponse, RawNotification},
handlers::{handle_syntax_tree, handle_extend_selection, publish_diagnostics, publish_decorations, handlers::{handle_syntax_tree, handle_extend_selection, publish_diagnostics, publish_decorations,
handle_document_symbol, handle_code_action}, handle_document_symbol, handle_code_action},
util::{FilePath, FnBox} util::FilePath,
}; };
pub type Result<T> = ::std::result::Result<T, ::failure::Error>; pub type Result<T> = ::std::result::Result<T, ::failure::Error>;
@ -80,9 +80,9 @@ fn initialize(io: &mut Io) -> Result<()> {
match io.recv()? { match io.recv()? {
RawMsg::Request(req) => { RawMsg::Request(req) => {
if let Some((_params, resp)) = dispatch::expect_request::<req::Initialize>(io, req)? { if let Some((_params, resp)) = dispatch::expect_request::<req::Initialize>(io, req)? {
resp.result(io, req::InitializeResult { let res = req::InitializeResult { capabilities: caps::SERVER_CAPABILITIES };
capabilities: caps::SERVER_CAPABILITIES let resp = resp.into_response(Ok(res))?;
})?; io.send(RawMsg::Response(resp));
match io.recv()? { match io.recv()? {
RawMsg::Notification(n) => { RawMsg::Notification(n) => {
if n.method != "initialized" { if n.method != "initialized" {
@ -106,13 +106,18 @@ fn initialize(io: &mut Io) -> Result<()> {
} }
} }
type Thunk = Box<for<'a> FnBox<&'a mut Io, Result<()>>>;
enum Task {
Respond(RawResponse),
Notify(RawNotification),
Die(::failure::Error),
}
fn initialized(io: &mut Io) -> Result<()> { fn initialized(io: &mut Io) -> Result<()> {
{ {
let mut world = WorldState::new(); let mut world = WorldState::new();
let mut pool = ThreadPool::new(4); let mut pool = ThreadPool::new(4);
let (sender, receiver) = bounded::<Thunk>(16); let (sender, receiver) = bounded::<Task>(16);
info!("lifecycle: handshake finished, server ready to serve requests"); info!("lifecycle: handshake finished, server ready to serve requests");
let res = main_loop(io, &mut world, &mut pool, sender, receiver.clone()); let res = main_loop(io, &mut world, &mut pool, sender, receiver.clone());
info!("waiting for background jobs to finish..."); info!("waiting for background jobs to finish...");
@ -140,14 +145,14 @@ fn main_loop(
io: &mut Io, io: &mut Io,
world: &mut WorldState, world: &mut WorldState,
pool: &mut ThreadPool, pool: &mut ThreadPool,
sender: Sender<Thunk>, sender: Sender<Task>,
receiver: Receiver<Thunk>, receiver: Receiver<Task>,
) -> Result<()> { ) -> Result<()> {
info!("server initialized, serving requests"); info!("server initialized, serving requests");
loop { loop {
enum Event { enum Event {
Msg(RawMsg), Msg(RawMsg),
Thunk(Thunk), Task(Task),
ReceiverDead, ReceiverDead,
} }
@ -156,7 +161,7 @@ fn main_loop(
Some(msg) => Event::Msg(msg), Some(msg) => Event::Msg(msg),
None => Event::ReceiverDead, None => Event::ReceiverDead,
}, },
recv(receiver, thunk) => Event::Thunk(thunk.unwrap()), recv(receiver, task) => Event::Task(task.unwrap()),
}; };
let msg = match event { let msg = match event {
@ -164,8 +169,15 @@ fn main_loop(
io.cleanup_receiver()?; io.cleanup_receiver()?;
unreachable!(); unreachable!();
} }
Event::Thunk(thunk) => { Event::Task(task) => {
thunk.call_box(io)?; match task {
Task::Respond(response) =>
io.send(RawMsg::Response(response)),
Task::Notify(n) =>
io.send(RawMsg::Notification(n)),
Task::Die(error) =>
return Err(error),
}
continue; continue;
} }
Event::Msg(msg) => msg, Event::Msg(msg) => msg,
@ -175,21 +187,22 @@ fn main_loop(
RawMsg::Request(req) => { RawMsg::Request(req) => {
let mut req = Some(req); let mut req = Some(req);
handle_request_on_threadpool::<req::SyntaxTree>( handle_request_on_threadpool::<req::SyntaxTree>(
&mut req, pool, world, &sender, handle_syntax_tree &mut req, pool, world, &sender, handle_syntax_tree,
)?; )?;
handle_request_on_threadpool::<req::ExtendSelection>( handle_request_on_threadpool::<req::ExtendSelection>(
&mut req, pool, world, &sender, handle_extend_selection &mut req, pool, world, &sender, handle_extend_selection,
)?; )?;
handle_request_on_threadpool::<req::DocumentSymbolRequest>( handle_request_on_threadpool::<req::DocumentSymbolRequest>(
&mut req, pool, world, &sender, handle_document_symbol &mut req, pool, world, &sender, handle_document_symbol,
)?; )?;
handle_request_on_threadpool::<req::CodeActionRequest>( handle_request_on_threadpool::<req::CodeActionRequest>(
&mut req, pool, world, &sender, handle_code_action &mut req, pool, world, &sender, handle_code_action,
)?; )?;
let mut shutdown = false; let mut shutdown = false;
dispatch::handle_request::<req::Shutdown, _>(&mut req, |(), resp| { dispatch::handle_request::<req::Shutdown, _>(&mut req, |(), resp| {
resp.result(io, ())?; let resp = resp.into_response(Ok(()))?;
io.send(RawMsg::Response(resp));
shutdown = true; shutdown = true;
Ok(()) Ok(())
})?; })?;
@ -227,10 +240,12 @@ fn main_loop(
dispatch::handle_notification::<req::DidCloseTextDocument, _>(&mut not, |params| { dispatch::handle_notification::<req::DidCloseTextDocument, _>(&mut not, |params| {
let path = params.text_document.file_path()?; let path = params.text_document.file_path()?;
world.change_overlay(path, None); world.change_overlay(path, None);
dispatch::send_notification::<req::PublishDiagnostics>(io, req::PublishDiagnosticsParams { let not = req::PublishDiagnosticsParams {
uri: params.text_document.uri, uri: params.text_document.uri,
diagnostics: Vec::new(), diagnostics: Vec::new(),
})?; };
let not = dispatch::send_notification::<req::PublishDiagnostics>(not);
io.send(RawMsg::Notification(not));
Ok(()) Ok(())
})?; })?;
@ -249,7 +264,7 @@ fn handle_request_on_threadpool<R: req::ClientRequest>(
req: &mut Option<RawRequest>, req: &mut Option<RawRequest>,
pool: &ThreadPool, pool: &ThreadPool,
world: &WorldState, world: &WorldState,
sender: &Sender<Thunk>, sender: &Sender<Task>,
f: fn(World, R::Params) -> Result<R::Result>, f: fn(World, R::Params) -> Result<R::Result>,
) -> Result<()> ) -> Result<()>
{ {
@ -258,7 +273,11 @@ fn handle_request_on_threadpool<R: req::ClientRequest>(
let sender = sender.clone(); let sender = sender.clone();
pool.execute(move || { pool.execute(move || {
let res = f(world, params); let res = f(world, params);
sender.send(Box::new(|io: &mut Io| resp.response(io, res))) let task = match resp.into_response(res) {
Ok(resp) => Task::Respond(resp),
Err(e) => Task::Die(e),
};
sender.send(task);
}); });
Ok(()) Ok(())
}) })
@ -267,7 +286,7 @@ fn handle_request_on_threadpool<R: req::ClientRequest>(
fn update_file_notifications_on_threadpool( fn update_file_notifications_on_threadpool(
pool: &ThreadPool, pool: &ThreadPool,
world: World, world: World,
sender: Sender<Thunk>, sender: Sender<Task>,
uri: Url, uri: Url,
) { ) {
pool.execute(move || { pool.execute(move || {
@ -276,9 +295,8 @@ fn update_file_notifications_on_threadpool(
error!("failed to compute diagnostics: {:?}", e) error!("failed to compute diagnostics: {:?}", e)
} }
Ok(params) => { Ok(params) => {
sender.send(Box::new(|io: &mut Io| { let not = dispatch::send_notification::<req::PublishDiagnostics>(params);
dispatch::send_notification::<req::PublishDiagnostics>(io, params) sender.send(Task::Notify(not));
}))
} }
} }
match publish_decorations(world, uri) { match publish_decorations(world, uri) {
@ -286,9 +304,8 @@ fn update_file_notifications_on_threadpool(
error!("failed to compute decortions: {:?}", e) error!("failed to compute decortions: {:?}", e)
} }
Ok(params) => { Ok(params) => {
sender.send(Box::new(|io: &mut Io| { let not = dispatch::send_notification::<req::PublishDecorations>(params);
dispatch::send_notification::<req::PublishDecorations>(io, params) sender.send(Task::Notify(not))
}))
} }
} }
}); });

View file

@ -3,16 +3,6 @@ use languageserver_types::{TextDocumentItem, VersionedTextDocumentIdentifier,
TextDocumentIdentifier, Url}; TextDocumentIdentifier, Url};
use ::{Result}; use ::{Result};
pub trait FnBox<A, R>: Send {
fn call_box(self: Box<Self>, a: A) -> R;
}
impl<A, R, F: FnOnce(A) -> R + Send> FnBox<A, R> for F {
fn call_box(self: Box<F>, a: A) -> R {
(*self)(a)
}
}
pub trait FilePath { pub trait FilePath {
fn file_path(&self) -> Result<PathBuf>; fn file_path(&self) -> Result<PathBuf>;
} }