rust/crates/server/src/main_loop/mod.rs

301 lines
10 KiB
Rust
Raw Normal View History

2018-08-12 14:08:14 -05:00
mod handlers;
2018-08-30 08:27:09 -05:00
mod subscriptions;
2018-08-12 14:08:14 -05:00
2018-08-13 05:46:05 -05:00
use std::{
2018-08-31 04:04:33 -05:00
collections::{HashMap},
2018-08-13 05:46:05 -05:00
};
2018-08-12 16:09:30 -05:00
2018-08-12 14:08:14 -05:00
use threadpool::ThreadPool;
use crossbeam_channel::{Sender, Receiver};
2018-08-31 04:04:33 -05:00
use languageserver_types::{NumberOrString};
use libanalysis::{FileId, JobHandle, JobToken};
2018-08-12 16:09:30 -05:00
2018-08-12 14:08:14 -05:00
use {
req, dispatch,
2018-08-17 11:54:08 -05:00
Task, Result,
2018-08-12 16:09:30 -05:00
io::{Io, RawMsg, RawRequest, RawNotification},
2018-08-17 11:54:08 -05:00
vfs::FileEvent,
server_world::{ServerWorldState, ServerWorld},
2018-08-30 08:27:09 -05:00
main_loop::subscriptions::{Subscriptions},
2018-08-12 14:08:14 -05:00
};
pub(super) fn main_loop(
io: &mut Io,
pool: &mut ThreadPool,
2018-08-13 05:46:05 -05:00
task_sender: Sender<Task>,
task_receiver: Receiver<Task>,
fs_events_receiver: Receiver<Vec<FileEvent>>,
2018-08-12 14:08:14 -05:00
) -> Result<()> {
info!("server initialized, serving requests");
2018-08-17 11:54:08 -05:00
let mut state = ServerWorldState::new();
2018-08-31 04:04:33 -05:00
let mut pending_requests: HashMap<u64, JobHandle> = HashMap::new();
2018-08-13 05:46:05 -05:00
let mut fs_events_receiver = Some(&fs_events_receiver);
2018-08-30 08:27:09 -05:00
let mut subs = Subscriptions::new();
2018-08-12 14:08:14 -05:00
loop {
enum Event {
Msg(RawMsg),
Task(Task),
2018-08-13 05:46:05 -05:00
Fs(Vec<FileEvent>),
2018-08-12 14:08:14 -05:00
ReceiverDead,
2018-08-13 05:46:05 -05:00
FsWatcherDead,
2018-08-12 14:08:14 -05:00
}
let event = select! {
recv(io.receiver(), msg) => match msg {
Some(msg) => Event::Msg(msg),
None => Event::ReceiverDead,
},
2018-08-13 05:46:05 -05:00
recv(task_receiver, task) => Event::Task(task.unwrap()),
recv(fs_events_receiver, events) => match events {
Some(events) => Event::Fs(events),
None => Event::FsWatcherDead,
}
2018-08-12 14:08:14 -05:00
};
2018-08-30 08:27:09 -05:00
let mut state_changed = false;
2018-08-12 14:08:14 -05:00
match event {
Event::ReceiverDead => {
io.cleanup_receiver()?;
unreachable!();
}
2018-08-13 05:46:05 -05:00
Event::FsWatcherDead => {
fs_events_receiver = None;
}
2018-08-12 14:08:14 -05:00
Event::Task(task) => {
match task {
2018-08-31 04:04:33 -05:00
Task::Respond(response) => {
if let Some(handle) = pending_requests.remove(&response.id) {
assert!(handle.has_completed());
}
io.send(RawMsg::Response(response))
}
2018-08-12 14:08:14 -05:00
Task::Notify(n) =>
io.send(RawMsg::Notification(n)),
Task::Die(error) =>
return Err(error),
}
continue;
}
2018-08-13 05:46:05 -05:00
Event::Fs(events) => {
trace!("fs change, {} events", events.len());
2018-08-17 11:54:08 -05:00
state.apply_fs_changes(events);
2018-08-30 08:27:09 -05:00
state_changed = true;
2018-08-13 05:46:05 -05:00
}
2018-08-12 14:08:14 -05:00
Event::Msg(msg) => {
2018-08-12 16:09:30 -05:00
match msg {
RawMsg::Request(req) => {
2018-08-31 04:04:33 -05:00
if !on_request(io, &mut state, &mut pending_requests, pool, &task_sender, req)? {
2018-08-12 16:09:30 -05:00
return Ok(());
}
}
RawMsg::Notification(not) => {
2018-08-31 04:04:33 -05:00
on_notification(io, &mut state, &mut pending_requests, &mut subs, not)?;
2018-08-30 08:27:09 -05:00
state_changed = true;
2018-08-12 16:09:30 -05:00
}
RawMsg::Response(resp) => {
2018-08-31 04:04:33 -05:00
error!("unexpected response: {:?}", resp)
2018-08-12 16:09:30 -05:00
}
2018-08-12 14:08:14 -05:00
}
}
};
2018-08-30 08:27:09 -05:00
if state_changed {
update_file_notifications_on_threadpool(
pool,
state.snapshot(),
task_sender.clone(),
subs.subscriptions(),
)
}
2018-08-12 14:08:14 -05:00
}
}
2018-08-12 16:09:30 -05:00
fn on_request(
2018-08-12 14:08:14 -05:00
io: &mut Io,
2018-08-21 10:30:10 -05:00
world: &mut ServerWorldState,
2018-08-31 04:04:33 -05:00
pending_requests: &mut HashMap<u64, JobHandle>,
2018-08-12 16:09:30 -05:00
pool: &ThreadPool,
2018-08-12 14:08:14 -05:00
sender: &Sender<Task>,
2018-08-12 16:09:30 -05:00
req: RawRequest,
2018-08-12 14:08:14 -05:00
) -> Result<bool> {
2018-08-29 10:03:14 -05:00
let mut pool_dispatcher = PoolDispatcher {
req: Some(req),
2018-08-31 04:04:33 -05:00
res: None,
2018-08-29 10:03:14 -05:00
pool, world, sender
};
2018-08-31 04:04:33 -05:00
let req = pool_dispatcher
2018-08-29 10:03:14 -05:00
.on::<req::SyntaxTree>(handlers::handle_syntax_tree)?
.on::<req::ExtendSelection>(handlers::handle_extend_selection)?
.on::<req::FindMatchingBrace>(handlers::handle_find_matching_brace)?
.on::<req::JoinLines>(handlers::handle_join_lines)?
.on::<req::OnTypeFormatting>(handlers::handle_on_type_formatting)?
.on::<req::DocumentSymbolRequest>(handlers::handle_document_symbol)?
.on::<req::WorkspaceSymbol>(handlers::handle_workspace_symbol)?
.on::<req::GotoDefinition>(handlers::handle_goto_definition)?
.on::<req::ParentModule>(handlers::handle_parent_module)?
.on::<req::Runnables>(handlers::handle_runnables)?
.on::<req::DecorationsRequest>(handlers::handle_decorations)?
.on::<req::Completion>(handlers::handle_completion)?
2018-08-31 04:04:33 -05:00
.on::<req::CodeActionRequest>(handlers::handle_code_action)?
.finish();
match req {
Ok((id, handle)) => {
let inserted = pending_requests.insert(id, handle).is_none();
assert!(inserted, "duplicate request: {}", id);
},
Err(req) => {
let req = dispatch::handle_request::<req::Shutdown, _>(req, |(), resp| {
let resp = resp.into_response(Ok(()))?;
io.send(RawMsg::Response(resp));
Ok(())
})?;
match req {
Ok(_id) => {
info!("lifecycle: initiating shutdown");
return Ok(false);
}
Err(req) => {
error!("unknown method: {:?}", req);
io.send(RawMsg::Response(dispatch::unknown_method(req.id)?));
}
}
}
2018-08-12 16:09:30 -05:00
}
2018-08-12 14:08:14 -05:00
Ok(true)
}
2018-08-12 16:09:30 -05:00
fn on_notification(
io: &mut Io,
2018-08-17 11:54:08 -05:00
state: &mut ServerWorldState,
2018-08-31 04:04:33 -05:00
pending_requests: &mut HashMap<u64, JobHandle>,
2018-08-30 08:27:09 -05:00
subs: &mut Subscriptions,
2018-08-12 16:09:30 -05:00
not: RawNotification,
) -> Result<()> {
let mut not = Some(not);
2018-08-31 04:04:33 -05:00
dispatch::handle_notification::<req::Cancel, _>(&mut not, |params| {
let id = match params.id {
NumberOrString::Number(id) => id,
NumberOrString::String(id) => {
panic!("string id's not supported: {:?}", id);
}
};
if let Some(handle) = pending_requests.remove(&id) {
handle.cancel();
}
Ok(())
})?;
2018-08-12 16:09:30 -05:00
dispatch::handle_notification::<req::DidOpenTextDocument, _>(&mut not, |params| {
2018-08-15 09:24:20 -05:00
let uri = params.text_document.uri;
let path = uri.to_file_path()
.map_err(|()| format_err!("invalid uri: {}", uri))?;
2018-08-30 08:27:09 -05:00
let file_id = state.add_mem_file(path, params.text_document.text);
subs.add_sub(file_id);
2018-08-12 16:09:30 -05:00
Ok(())
})?;
dispatch::handle_notification::<req::DidChangeTextDocument, _>(&mut not, |mut params| {
2018-08-17 11:54:08 -05:00
let uri = params.text_document.uri;
let path = uri.to_file_path()
.map_err(|()| format_err!("invalid uri: {}", uri))?;
2018-08-12 16:09:30 -05:00
let text = params.content_changes.pop()
.ok_or_else(|| format_err!("empty changes"))?
.text;
2018-08-17 11:54:08 -05:00
state.change_mem_file(path.as_path(), text)?;
2018-08-12 16:09:30 -05:00
Ok(())
})?;
dispatch::handle_notification::<req::DidCloseTextDocument, _>(&mut not, |params| {
2018-08-17 11:54:08 -05:00
let uri = params.text_document.uri;
let path = uri.to_file_path()
.map_err(|()| format_err!("invalid uri: {}", uri))?;
2018-08-30 08:27:09 -05:00
let file_id = state.remove_mem_file(path.as_path())?;
subs.remove_sub(file_id);
let not = req::PublishDiagnosticsParams { uri, diagnostics: Vec::new() };
2018-08-12 16:09:30 -05:00
let not = dispatch::send_notification::<req::PublishDiagnostics>(not);
io.send(RawMsg::Notification(not));
Ok(())
})?;
if let Some(not) = not {
error!("unhandled notification: {:?}", not);
}
Ok(())
}
2018-08-29 10:03:14 -05:00
struct PoolDispatcher<'a> {
req: Option<RawRequest>,
2018-08-31 04:04:33 -05:00
res: Option<(u64, JobHandle)>,
2018-08-29 10:03:14 -05:00
pool: &'a ThreadPool,
world: &'a ServerWorldState,
sender: &'a Sender<Task>,
}
impl<'a> PoolDispatcher<'a> {
2018-08-31 04:04:33 -05:00
fn on<'b, R: req::ClientRequest>(
&'b mut self,
f: fn(ServerWorld, R::Params, JobToken) -> Result<R::Result>
) -> Result<&'b mut Self> {
let req = match self.req.take() {
None => return Ok(self),
Some(req) => req,
};
2018-08-29 10:03:14 -05:00
let world = self.world;
let sender = self.sender;
let pool = self.pool;
2018-08-31 04:04:33 -05:00
let (handle, token) = JobHandle::new();
let req = dispatch::handle_request::<R, _>(req, |params, resp| {
2018-08-29 10:03:14 -05:00
let world = world.snapshot();
let sender = sender.clone();
pool.execute(move || {
2018-08-31 04:04:33 -05:00
let res = f(world, params, token);
2018-08-29 10:03:14 -05:00
let task = match resp.into_response(res) {
Ok(resp) => Task::Respond(resp),
Err(e) => Task::Die(e),
};
sender.send(task);
});
Ok(())
})?;
2018-08-31 04:04:33 -05:00
match req {
Ok(id) => self.res = Some((id, handle)),
Err(req) => self.req = Some(req),
}
2018-08-29 10:03:14 -05:00
Ok(self)
}
2018-08-31 04:04:33 -05:00
fn finish(&mut self) -> ::std::result::Result<(u64, JobHandle), RawRequest> {
match (self.res.take(), self.req.take()) {
(Some(res), None) => Ok(res),
(None, Some(req)) => Err(req),
_ => unreachable!(),
}
}
2018-08-12 14:08:14 -05:00
}
fn update_file_notifications_on_threadpool(
pool: &ThreadPool,
2018-08-17 11:54:08 -05:00
world: ServerWorld,
2018-08-12 14:08:14 -05:00
sender: Sender<Task>,
2018-08-30 08:27:09 -05:00
subscriptions: Vec<FileId>,
2018-08-12 14:08:14 -05:00
) {
pool.execute(move || {
2018-08-30 08:27:09 -05:00
for file_id in subscriptions {
match handlers::publish_diagnostics(world.clone(), file_id) {
Err(e) => {
error!("failed to compute diagnostics: {:?}", e)
}
Ok(params) => {
let not = dispatch::send_notification::<req::PublishDiagnostics>(params);
sender.send(Task::Notify(not));
}
2018-08-12 14:08:14 -05:00
}
2018-08-30 08:27:09 -05:00
match handlers::publish_decorations(world.clone(), file_id) {
Err(e) => {
error!("failed to compute decorations: {:?}", e)
}
Ok(params) => {
let not = dispatch::send_notification::<req::PublishDecorations>(params);
sender.send(Task::Notify(not))
}
2018-08-12 14:08:14 -05:00
}
}
});
}