ServerWorld

This commit is contained in:
Aleksey Kladov 2018-08-17 19:54:08 +03:00
parent 41570f60bf
commit ed7ae78c6f
9 changed files with 246 additions and 182 deletions

View file

@ -60,14 +60,18 @@ export function activate(context: vscode.ExtensionContext) {
vscode.workspace.onDidChangeTextDocument((event: vscode.TextDocumentChangeEvent) => { vscode.workspace.onDidChangeTextDocument((event: vscode.TextDocumentChangeEvent) => {
let doc = event.document let doc = event.document
if (doc.languageId != "rust") return if (doc.languageId != "rust") return
// We need to order this after LS updates, but there's no API for that. afterLs(() => {
// Hence, good old setTimeout.
setTimeout(() => {
textDocumentContentProvider.eventEmitter.fire(uris.syntaxTree) textDocumentContentProvider.eventEmitter.fire(uris.syntaxTree)
}, 10) })
}, null, context.subscriptions) }, null, context.subscriptions)
} }
// We need to order this after LS updates, but there's no API for that.
// Hence, good old setTimeout.
function afterLs(f) {
setTimeout(f, 10)
}
export function deactivate(): Thenable<void> { export function deactivate(): Thenable<void> {
if (!client) { if (!client) {
return undefined; return undefined;
@ -118,7 +122,9 @@ function startServer() {
if (editor == null) return if (editor == null) return
if (!editor.selection.isEmpty) return if (!editor.selection.isEmpty) return
let position = client.protocol2CodeConverter.asPosition(params) let position = client.protocol2CodeConverter.asPosition(params)
editor.selection = new vscode.Selection(position, position); afterLs(() => {
editor.selection = new vscode.Selection(position, position)
})
} }
) )
}) })

View file

@ -40,6 +40,7 @@ const INDEXING_THRESHOLD: usize = 128;
pub type FileResolver = dyn Fn(FileId, &Path) -> Option<FileId> + Send + Sync; pub type FileResolver = dyn Fn(FileId, &Path) -> Option<FileId> + Send + Sync;
#[derive(Debug)]
pub struct WorldState { pub struct WorldState {
data: Arc<WorldData> data: Arc<WorldData>
} }

View file

@ -71,13 +71,11 @@ fn non_trivia_sibling(node: SyntaxNodeRef, direction: Direction) -> Option<Synta
.find(|node| !node.kind().is_trivia()) .find(|node| !node.kind().is_trivia())
} }
fn find_non_trivia_leaf(syntax: SyntaxNodeRef, offset: TextUnit) -> Option<SyntaxNodeRef> {
find_leaf_at_offset(syntax, offset)
.find(|leaf| !leaf.kind().is_trivia())
}
pub fn find_node<'a, N: AstNode<&'a SyntaxRoot>>(syntax: SyntaxNodeRef<'a>, offset: TextUnit) -> Option<N> { pub fn find_node<'a, N: AstNode<&'a SyntaxRoot>>(syntax: SyntaxNodeRef<'a>, offset: TextUnit) -> Option<N> {
let leaf = find_non_trivia_leaf(syntax, offset)?; let leaves = find_leaf_at_offset(syntax, offset);
let leaf = leaves.clone()
.find(|leaf| !leaf.kind().is_trivia())
.or_else(|| leaves.right_biased())?;
ancestors(leaf) ancestors(leaf)
.filter_map(N::cast) .filter_map(N::cast)
.next() .next()

View file

@ -1,11 +1,8 @@
extern crate libeditor; extern crate libeditor;
extern crate libsyntax2; extern crate libsyntax2;
extern crate itertools;
#[macro_use] #[macro_use]
extern crate assert_eq_text; extern crate assert_eq_text;
use std::fmt;
use itertools::Itertools;
use assert_eq_text::{assert_eq_dbg}; use assert_eq_text::{assert_eq_dbg};
use libeditor::{ use libeditor::{
File, TextUnit, TextRange, ActionResult, CursorPosition, File, TextUnit, TextRange, ActionResult, CursorPosition,
@ -118,6 +115,11 @@ fn test_add_derive() {
"#[derive(<|>)]\nstruct Foo { a: i32, }", "#[derive(<|>)]\nstruct Foo { a: i32, }",
|file, off| add_derive(file, off).map(|f| f()), |file, off| add_derive(file, off).map(|f| f()),
); );
check_action(
"struct Foo { <|> a: i32, }",
"#[derive(<|>)]\nstruct Foo { a: i32, }",
|file, off| add_derive(file, off).map(|f| f()),
);
check_action( check_action(
"#[derive(Clone)]\nstruct Foo { a: i32<|>, }", "#[derive(Clone)]\nstruct Foo { a: i32<|>, }",
"#[derive(Clone<|>)]\nstruct Foo { a: i32, }", "#[derive(Clone<|>)]\nstruct Foo { a: i32, }",

View file

@ -6,7 +6,10 @@ use libeditor::{LineIndex, LineCol, Edit, AtomEdit};
use libsyntax2::{SyntaxKind, TextUnit, TextRange}; use libsyntax2::{SyntaxKind, TextUnit, TextRange};
use libanalysis::FileId; use libanalysis::FileId;
use {Result, PathMap}; use {
Result,
server_world::ServerWorld,
};
pub trait Conv { pub trait Conv {
type Output; type Output;
@ -126,57 +129,52 @@ impl<T: ConvWith> ConvWith for Option<T> {
} }
impl<'a> TryConvWith for &'a Url { impl<'a> TryConvWith for &'a Url {
type Ctx = PathMap; type Ctx = ServerWorld;
type Output = FileId; type Output = FileId;
fn try_conv_with(self, path_map: &PathMap) -> Result<FileId> { fn try_conv_with(self, world: &ServerWorld) -> Result<FileId> {
let path = self.to_file_path() world.uri_to_file_id(self)
.map_err(|()| format_err!("invalid uri: {}", self))?;
path_map.get_id(&path).ok_or_else(|| format_err!("unknown file: {}", path.display()))
} }
} }
impl TryConvWith for FileId { impl TryConvWith for FileId {
type Ctx = PathMap; type Ctx = ServerWorld;
type Output = Url; type Output = Url;
fn try_conv_with(self, path_map: &PathMap) -> Result<Url> { fn try_conv_with(self, world: &ServerWorld) -> Result<Url> {
let path = path_map.get_path(self); world.file_id_to_uri(self)
let url = Url::from_file_path(path)
.map_err(|()| format_err!("can't convert path to url: {}", path.display()))?;
Ok(url)
} }
} }
impl<'a> TryConvWith for &'a TextDocumentItem { impl<'a> TryConvWith for &'a TextDocumentItem {
type Ctx = PathMap; type Ctx = ServerWorld;
type Output = FileId; type Output = FileId;
fn try_conv_with(self, path_map: &PathMap) -> Result<FileId> { fn try_conv_with(self, world: &ServerWorld) -> Result<FileId> {
self.uri.try_conv_with(path_map) self.uri.try_conv_with(world)
} }
} }
impl<'a> TryConvWith for &'a VersionedTextDocumentIdentifier { impl<'a> TryConvWith for &'a VersionedTextDocumentIdentifier {
type Ctx = PathMap; type Ctx = ServerWorld;
type Output = FileId; type Output = FileId;
fn try_conv_with(self, path_map: &PathMap) -> Result<FileId> { fn try_conv_with(self, world: &ServerWorld) -> Result<FileId> {
self.uri.try_conv_with(path_map) self.uri.try_conv_with(world)
} }
} }
impl<'a> TryConvWith for &'a TextDocumentIdentifier { impl<'a> TryConvWith for &'a TextDocumentIdentifier {
type Ctx = PathMap; type Ctx = ServerWorld;
type Output = FileId; type Output = FileId;
fn try_conv_with(self, path_map: &PathMap) -> Result<FileId> { fn try_conv_with(self, world: &ServerWorld) -> Result<FileId> {
self.uri.try_conv_with(path_map) world.uri_to_file_id(&self.uri)
} }
} }
pub fn to_location( pub fn to_location(
file_id: FileId, file_id: FileId,
range: TextRange, range: TextRange,
path_map: &PathMap, world: &ServerWorld,
line_index: &LineIndex, line_index: &LineIndex,
) -> Result<Location> { ) -> Result<Location> {
let url = file_id.try_conv_with(path_map)?; let url = file_id.try_conv_with(world)?;
let loc = Location::new( let loc = Location::new(
url, url,
range.conv_with(line_index), range.conv_with(line_index),

View file

@ -27,15 +27,14 @@ mod conv;
mod main_loop; mod main_loop;
mod vfs; mod vfs;
mod path_map; mod path_map;
mod server_world;
use threadpool::ThreadPool; use threadpool::ThreadPool;
use crossbeam_channel::bounded; use crossbeam_channel::bounded;
use flexi_logger::{Logger, Duplicate}; use flexi_logger::{Logger, Duplicate};
use libanalysis::WorldState;
use ::{ use ::{
io::{Io, RawMsg, RawResponse, RawRequest, RawNotification}, io::{Io, RawMsg, RawResponse, RawRequest, RawNotification},
path_map::PathMap,
}; };
pub type Result<T> = ::std::result::Result<T, ::failure::Error>; pub type Result<T> = ::std::result::Result<T, ::failure::Error>;
@ -116,7 +115,6 @@ enum Task {
fn initialized(io: &mut Io) -> Result<()> { fn initialized(io: &mut Io) -> Result<()> {
{ {
let mut world = WorldState::new();
let mut pool = ThreadPool::new(4); let mut pool = ThreadPool::new(4);
let (task_sender, task_receiver) = bounded::<Task>(16); let (task_sender, task_receiver) = bounded::<Task>(16);
let (fs_events_receiver, watcher) = vfs::watch(vec![ let (fs_events_receiver, watcher) = vfs::watch(vec![
@ -125,7 +123,6 @@ fn initialized(io: &mut Io) -> Result<()> {
info!("lifecycle: handshake finished, server ready to serve requests"); info!("lifecycle: handshake finished, server ready to serve requests");
let res = main_loop::main_loop( let res = main_loop::main_loop(
io, io,
&mut world,
&mut pool, &mut pool,
task_sender, task_sender,
task_receiver.clone(), task_receiver.clone(),

View file

@ -5,35 +5,33 @@ use languageserver_types::{
Command, TextDocumentIdentifier, WorkspaceEdit, Command, TextDocumentIdentifier, WorkspaceEdit,
SymbolInformation, Position, SymbolInformation, Position,
}; };
use libanalysis::{World, Query}; use libanalysis::{Query};
use libeditor::{self, CursorPosition}; use libeditor::{self, CursorPosition};
use libsyntax2::TextUnit; use libsyntax2::TextUnit;
use serde_json::{to_value, from_value}; use serde_json::{to_value, from_value};
use ::{ use ::{
PathMap,
req::{self, Decoration}, Result, req::{self, Decoration}, Result,
conv::{Conv, ConvWith, TryConvWith, MapConvWith, to_location}, conv::{Conv, ConvWith, TryConvWith, MapConvWith, to_location},
server_world::ServerWorld,
}; };
pub fn handle_syntax_tree( pub fn handle_syntax_tree(
world: World, world: ServerWorld,
path_map: PathMap,
params: req::SyntaxTreeParams, params: req::SyntaxTreeParams,
) -> Result<String> { ) -> Result<String> {
let id = params.text_document.try_conv_with(&path_map)?; let id = params.text_document.try_conv_with(&world)?;
let file = world.file_syntax(id)?; let file = world.analysis().file_syntax(id)?;
Ok(libeditor::syntax_tree(&file)) Ok(libeditor::syntax_tree(&file))
} }
pub fn handle_extend_selection( pub fn handle_extend_selection(
world: World, world: ServerWorld,
path_map: PathMap,
params: req::ExtendSelectionParams, params: req::ExtendSelectionParams,
) -> Result<req::ExtendSelectionResult> { ) -> Result<req::ExtendSelectionResult> {
let file_id = params.text_document.try_conv_with(&path_map)?; let file_id = params.text_document.try_conv_with(&world)?;
let file = world.file_syntax(file_id)?; let file = world.analysis().file_syntax(file_id)?;
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let selections = params.selections.into_iter() let selections = params.selections.into_iter()
.map_conv_with(&line_index) .map_conv_with(&line_index)
.map(|r| libeditor::extend_selection(&file, r).unwrap_or(r)) .map(|r| libeditor::extend_selection(&file, r).unwrap_or(r))
@ -43,13 +41,12 @@ pub fn handle_extend_selection(
} }
pub fn handle_find_matching_brace( pub fn handle_find_matching_brace(
world: World, world: ServerWorld,
path_map: PathMap,
params: req::FindMatchingBraceParams, params: req::FindMatchingBraceParams,
) -> Result<Vec<Position>> { ) -> Result<Vec<Position>> {
let file_id = params.text_document.try_conv_with(&path_map)?; let file_id = params.text_document.try_conv_with(&world)?;
let file = world.file_syntax(file_id)?; let file = world.analysis().file_syntax(file_id)?;
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let res = params.offsets let res = params.offsets
.into_iter() .into_iter()
.map_conv_with(&line_index) .map_conv_with(&line_index)
@ -62,13 +59,12 @@ pub fn handle_find_matching_brace(
} }
pub fn handle_document_symbol( pub fn handle_document_symbol(
world: World, world: ServerWorld,
path_map: PathMap,
params: req::DocumentSymbolParams, params: req::DocumentSymbolParams,
) -> Result<Option<req::DocumentSymbolResponse>> { ) -> Result<Option<req::DocumentSymbolResponse>> {
let file_id = params.text_document.try_conv_with(&path_map)?; let file_id = params.text_document.try_conv_with(&world)?;
let file = world.file_syntax(file_id)?; let file = world.analysis().file_syntax(file_id)?;
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let mut parents: Vec<(DocumentSymbol, Option<usize>)> = Vec::new(); let mut parents: Vec<(DocumentSymbol, Option<usize>)> = Vec::new();
@ -102,13 +98,12 @@ pub fn handle_document_symbol(
} }
pub fn handle_code_action( pub fn handle_code_action(
world: World, world: ServerWorld,
path_map: PathMap,
params: req::CodeActionParams, params: req::CodeActionParams,
) -> Result<Option<Vec<Command>>> { ) -> Result<Option<Vec<Command>>> {
let file_id = params.text_document.try_conv_with(&path_map)?; let file_id = params.text_document.try_conv_with(&world)?;
let file = world.file_syntax(file_id)?; let file = world.analysis().file_syntax(file_id)?;
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let offset = params.range.conv_with(&line_index).start(); let offset = params.range.conv_with(&line_index).start();
let mut ret = Vec::new(); let mut ret = Vec::new();
@ -127,8 +122,7 @@ pub fn handle_code_action(
} }
pub fn handle_workspace_symbol( pub fn handle_workspace_symbol(
world: World, world: ServerWorld,
path_map: PathMap,
params: req::WorkspaceSymbolParams, params: req::WorkspaceSymbolParams,
) -> Result<Option<Vec<SymbolInformation>>> { ) -> Result<Option<Vec<SymbolInformation>>> {
let all_symbols = params.query.contains("#"); let all_symbols = params.query.contains("#");
@ -143,25 +137,25 @@ pub fn handle_workspace_symbol(
q.limit(128); q.limit(128);
q q
}; };
let mut res = exec_query(&world, &path_map, query)?; let mut res = exec_query(&world, query)?;
if res.is_empty() && !all_symbols { if res.is_empty() && !all_symbols {
let mut query = Query::new(params.query); let mut query = Query::new(params.query);
query.limit(128); query.limit(128);
res = exec_query(&world, &path_map, query)?; res = exec_query(&world, query)?;
} }
return Ok(Some(res)); return Ok(Some(res));
fn exec_query(world: &World, path_map: &PathMap, query: Query) -> Result<Vec<SymbolInformation>> { fn exec_query(world: &ServerWorld, query: Query) -> Result<Vec<SymbolInformation>> {
let mut res = Vec::new(); let mut res = Vec::new();
for (file_id, symbol) in world.world_symbols(query) { for (file_id, symbol) in world.analysis().world_symbols(query) {
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let info = SymbolInformation { let info = SymbolInformation {
name: symbol.name.to_string(), name: symbol.name.to_string(),
kind: symbol.kind.conv(), kind: symbol.kind.conv(),
location: to_location( location: to_location(
file_id, symbol.node_range, file_id, symbol.node_range,
path_map, &line_index world, &line_index
)?, )?,
container_name: None, container_name: None,
}; };
@ -172,19 +166,18 @@ pub fn handle_workspace_symbol(
} }
pub fn handle_goto_definition( pub fn handle_goto_definition(
world: World, world: ServerWorld,
path_map: PathMap,
params: req::TextDocumentPositionParams, params: req::TextDocumentPositionParams,
) -> Result<Option<req::GotoDefinitionResponse>> { ) -> Result<Option<req::GotoDefinitionResponse>> {
let file_id = params.text_document.try_conv_with(&path_map)?; let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let offset = params.position.conv_with(&line_index); let offset = params.position.conv_with(&line_index);
let mut res = Vec::new(); let mut res = Vec::new();
for (file_id, symbol) in world.approximately_resolve_symbol(file_id, offset)? { for (file_id, symbol) in world.analysis().approximately_resolve_symbol(file_id, offset)? {
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let location = to_location( let location = to_location(
file_id, symbol.node_range, file_id, symbol.node_range,
&path_map, &line_index, &world, &line_index,
)?; )?;
res.push(location) res.push(location)
} }
@ -192,8 +185,7 @@ pub fn handle_goto_definition(
} }
pub fn handle_execute_command( pub fn handle_execute_command(
world: World, world: ServerWorld,
path_map: PathMap,
mut params: req::ExecuteCommandParams, mut params: req::ExecuteCommandParams,
) -> Result<(req::ApplyWorkspaceEditParams, Option<Position>)> { ) -> Result<(req::ApplyWorkspaceEditParams, Option<Position>)> {
if params.command.as_str() != "apply_code_action" { if params.command.as_str() != "apply_code_action" {
@ -204,13 +196,13 @@ pub fn handle_execute_command(
} }
let arg = params.arguments.pop().unwrap(); let arg = params.arguments.pop().unwrap();
let arg: ActionRequest = from_value(arg)?; let arg: ActionRequest = from_value(arg)?;
let file_id = arg.text_document.try_conv_with(&path_map)?; let file_id = arg.text_document.try_conv_with(&world)?;
let file = world.file_syntax(file_id)?; let file = world.analysis().file_syntax(file_id)?;
let action_result = match arg.id { let action_result = match arg.id {
ActionId::FlipComma => libeditor::flip_comma(&file, arg.offset).map(|f| f()), ActionId::FlipComma => libeditor::flip_comma(&file, arg.offset).map(|f| f()),
ActionId::AddDerive => libeditor::add_derive(&file, arg.offset).map(|f| f()), ActionId::AddDerive => libeditor::add_derive(&file, arg.offset).map(|f| f()),
}.ok_or_else(|| format_err!("command not applicable"))?; }.ok_or_else(|| format_err!("command not applicable"))?;
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let mut changes = HashMap::new(); let mut changes = HashMap::new();
changes.insert( changes.insert(
arg.text_document.uri, arg.text_document.uri,
@ -265,13 +257,12 @@ impl ActionId {
} }
pub fn publish_diagnostics( pub fn publish_diagnostics(
world: World, world: ServerWorld,
path_map: PathMap,
uri: Url uri: Url
) -> Result<req::PublishDiagnosticsParams> { ) -> Result<req::PublishDiagnosticsParams> {
let file_id = uri.try_conv_with(&path_map)?; let file_id = world.uri_to_file_id(&uri)?;
let file = world.file_syntax(file_id)?; let file = world.analysis().file_syntax(file_id)?;
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let diagnostics = libeditor::diagnostics(&file) let diagnostics = libeditor::diagnostics(&file)
.into_iter() .into_iter()
.map(|d| Diagnostic { .map(|d| Diagnostic {
@ -286,13 +277,12 @@ pub fn publish_diagnostics(
} }
pub fn publish_decorations( pub fn publish_decorations(
world: World, world: ServerWorld,
path_map: PathMap,
uri: Url uri: Url
) -> Result<req::PublishDecorationsParams> { ) -> Result<req::PublishDecorationsParams> {
let file_id = uri.try_conv_with(&path_map)?; let file_id = world.uri_to_file_id(&uri)?;
let file = world.file_syntax(file_id)?; let file = world.analysis().file_syntax(file_id)?;
let line_index = world.file_line_index(file_id)?; let line_index = world.analysis().file_line_index(file_id)?;
let decorations = libeditor::highlight(&file) let decorations = libeditor::highlight(&file)
.into_iter() .into_iter()
.map(|h| Decoration { .map(|h| Decoration {

View file

@ -1,21 +1,20 @@
mod handlers; mod handlers;
use std::{ use std::{
collections::{HashSet, HashMap}, collections::{HashSet},
}; };
use threadpool::ThreadPool; use threadpool::ThreadPool;
use crossbeam_channel::{Sender, Receiver}; use crossbeam_channel::{Sender, Receiver};
use languageserver_types::Url; use languageserver_types::Url;
use libanalysis::{World, WorldState, FileId};
use serde_json::to_value; use serde_json::to_value;
use { use {
req, dispatch, req, dispatch,
Task, Result, PathMap, Task, Result,
io::{Io, RawMsg, RawRequest, RawNotification}, io::{Io, RawMsg, RawRequest, RawNotification},
vfs::{FileEvent, FileEventKind}, vfs::FileEvent,
conv::TryConvWith, server_world::{ServerWorldState, ServerWorld},
main_loop::handlers::{ main_loop::handlers::{
handle_syntax_tree, handle_syntax_tree,
handle_extend_selection, handle_extend_selection,
@ -32,17 +31,16 @@ use {
pub(super) fn main_loop( pub(super) fn main_loop(
io: &mut Io, io: &mut Io,
world: &mut WorldState,
pool: &mut ThreadPool, pool: &mut ThreadPool,
task_sender: Sender<Task>, task_sender: Sender<Task>,
task_receiver: Receiver<Task>, task_receiver: Receiver<Task>,
fs_events_receiver: Receiver<Vec<FileEvent>>, fs_events_receiver: Receiver<Vec<FileEvent>>,
) -> Result<()> { ) -> Result<()> {
info!("server initialized, serving requests"); info!("server initialized, serving requests");
let mut state = ServerWorldState::new();
let mut next_request_id = 0; let mut next_request_id = 0;
let mut pending_requests: HashSet<u64> = HashSet::new(); let mut pending_requests: HashSet<u64> = HashSet::new();
let mut path_map = PathMap::new();
let mut mem_map: HashMap<FileId, Option<String>> = HashMap::new();
let mut fs_events_receiver = Some(&fs_events_receiver); let mut fs_events_receiver = Some(&fs_events_receiver);
loop { loop {
enum Event { enum Event {
@ -91,37 +89,17 @@ pub(super) fn main_loop(
} }
Event::Fs(events) => { Event::Fs(events) => {
trace!("fs change, {} events", events.len()); trace!("fs change, {} events", events.len());
let changes = events.into_iter() state.apply_fs_changes(events);
.map(|event| {
let text = match event.kind {
FileEventKind::Add(text) => Some(text),
FileEventKind::Remove => None,
};
(event.path, text)
})
.map(|(path, text)| {
(path_map.get_or_insert(path), text)
})
.filter_map(|(id, text)| {
if mem_map.contains_key(&id) {
mem_map.insert(id, text);
None
} else {
Some((id, text))
}
});
world.change_files(changes);
} }
Event::Msg(msg) => { Event::Msg(msg) => {
match msg { match msg {
RawMsg::Request(req) => { RawMsg::Request(req) => {
if !on_request(io, world, &path_map, pool, &task_sender, req)? { if !on_request(io, &state, pool, &task_sender, req)? {
return Ok(()); return Ok(());
} }
} }
RawMsg::Notification(not) => { RawMsg::Notification(not) => {
on_notification(io, world, &mut path_map, pool, &task_sender, not, &mut mem_map)? on_notification(io, &mut state, pool, &task_sender, not)?
} }
RawMsg::Response(resp) => { RawMsg::Response(resp) => {
if !pending_requests.remove(&resp.id) { if !pending_requests.remove(&resp.id) {
@ -136,45 +114,40 @@ pub(super) fn main_loop(
fn on_request( fn on_request(
io: &mut Io, io: &mut Io,
world: &WorldState, world: &ServerWorldState,
path_map: &PathMap,
pool: &ThreadPool, pool: &ThreadPool,
sender: &Sender<Task>, sender: &Sender<Task>,
req: RawRequest, req: RawRequest,
) -> Result<bool> { ) -> Result<bool> {
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, path_map, 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, path_map, world, sender, handle_extend_selection, &mut req, pool, world, sender, handle_extend_selection,
)?; )?;
handle_request_on_threadpool::<req::FindMatchingBrace>( handle_request_on_threadpool::<req::FindMatchingBrace>(
&mut req, pool, path_map, world, sender, handle_find_matching_brace, &mut req, pool, world, sender, handle_find_matching_brace,
)?; )?;
handle_request_on_threadpool::<req::DocumentSymbolRequest>( handle_request_on_threadpool::<req::DocumentSymbolRequest>(
&mut req, pool, path_map, 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, path_map, world, sender, handle_code_action, &mut req, pool, world, sender, handle_code_action,
)?; )?;
handle_request_on_threadpool::<req::WorkspaceSymbol>( handle_request_on_threadpool::<req::WorkspaceSymbol>(
&mut req, pool, path_map, world, sender, handle_workspace_symbol, &mut req, pool, world, sender, handle_workspace_symbol,
)?; )?;
handle_request_on_threadpool::<req::GotoDefinition>( handle_request_on_threadpool::<req::GotoDefinition>(
&mut req, pool, path_map, world, sender, handle_goto_definition, &mut req, pool, world, sender, handle_goto_definition,
)?; )?;
dispatch::handle_request::<req::ExecuteCommand, _>(&mut req, |params, resp| { dispatch::handle_request::<req::ExecuteCommand, _>(&mut req, |params, resp| {
io.send(RawMsg::Response(resp.into_response(Ok(None))?)); io.send(RawMsg::Response(resp.into_response(Ok(None))?));
let world = world.snapshot({ let world = world.snapshot();
let pm = path_map.clone();
move |id, path| pm.resolve(id, path)
});
let path_map = path_map.clone();
let sender = sender.clone(); let sender = sender.clone();
pool.execute(move || { pool.execute(move || {
let (edit, cursor) = match handle_execute_command(world, path_map, params) { let (edit, cursor) = match handle_execute_command(world, params) {
Ok(res) => res, Ok(res) => res,
Err(e) => return sender.send(Task::Die(e)), Err(e) => return sender.send(Task::Die(e)),
}; };
@ -221,60 +194,48 @@ fn on_request(
fn on_notification( fn on_notification(
io: &mut Io, io: &mut Io,
world: &mut WorldState, state: &mut ServerWorldState,
path_map: &mut PathMap,
pool: &ThreadPool, pool: &ThreadPool,
sender: &Sender<Task>, sender: &Sender<Task>,
not: RawNotification, not: RawNotification,
mem_map: &mut HashMap<FileId, Option<String>>,
) -> Result<()> { ) -> Result<()> {
let mut not = Some(not); let mut not = Some(not);
dispatch::handle_notification::<req::DidOpenTextDocument, _>(&mut not, |params| { dispatch::handle_notification::<req::DidOpenTextDocument, _>(&mut not, |params| {
let uri = params.text_document.uri; let uri = params.text_document.uri;
let path = uri.to_file_path() let path = uri.to_file_path()
.map_err(|()| format_err!("invalid uri: {}", uri))?; .map_err(|()| format_err!("invalid uri: {}", uri))?;
let file_id = path_map.get_or_insert(path); state.add_mem_file(path, params.text_document.text);
mem_map.insert(file_id, None);
world.change_file(file_id, Some(params.text_document.text));
update_file_notifications_on_threadpool( update_file_notifications_on_threadpool(
pool, pool,
world.snapshot({ state.snapshot(),
let pm = path_map.clone();
move |id, path| pm.resolve(id, path)
}),
path_map.clone(),
sender.clone(), sender.clone(),
uri, uri,
); );
Ok(()) Ok(())
})?; })?;
dispatch::handle_notification::<req::DidChangeTextDocument, _>(&mut not, |mut params| { dispatch::handle_notification::<req::DidChangeTextDocument, _>(&mut not, |mut params| {
let file_id = params.text_document.try_conv_with(path_map)?; let uri = params.text_document.uri;
let path = uri.to_file_path()
.map_err(|()| format_err!("invalid uri: {}", uri))?;
let text = params.content_changes.pop() let text = params.content_changes.pop()
.ok_or_else(|| format_err!("empty changes"))? .ok_or_else(|| format_err!("empty changes"))?
.text; .text;
world.change_file(file_id, Some(text)); state.change_mem_file(path.as_path(), text)?;
update_file_notifications_on_threadpool( update_file_notifications_on_threadpool(
pool, pool,
world.snapshot({ state.snapshot(),
let pm = path_map.clone();
move |id, path| pm.resolve(id, path)
}),
path_map.clone(),
sender.clone(), sender.clone(),
params.text_document.uri, uri,
); );
Ok(()) Ok(())
})?; })?;
dispatch::handle_notification::<req::DidCloseTextDocument, _>(&mut not, |params| { dispatch::handle_notification::<req::DidCloseTextDocument, _>(&mut not, |params| {
let file_id = params.text_document.try_conv_with(path_map)?; let uri = params.text_document.uri;
let text = match mem_map.remove(&file_id) { let path = uri.to_file_path()
Some(text) => text, .map_err(|()| format_err!("invalid uri: {}", uri))?;
None => bail!("unmatched close notification"), state.remove_mem_file(path.as_path())?;
};
world.change_file(file_id, text);
let not = req::PublishDiagnosticsParams { let not = req::PublishDiagnosticsParams {
uri: params.text_document.uri, uri,
diagnostics: Vec::new(), diagnostics: Vec::new(),
}; };
let not = dispatch::send_notification::<req::PublishDiagnostics>(not); let not = dispatch::send_notification::<req::PublishDiagnostics>(not);
@ -291,21 +252,16 @@ fn on_notification(
fn handle_request_on_threadpool<R: req::ClientRequest>( fn handle_request_on_threadpool<R: req::ClientRequest>(
req: &mut Option<RawRequest>, req: &mut Option<RawRequest>,
pool: &ThreadPool, pool: &ThreadPool,
path_map: &PathMap, world: &ServerWorldState,
world: &WorldState,
sender: &Sender<Task>, sender: &Sender<Task>,
f: fn(World, PathMap, R::Params) -> Result<R::Result>, f: fn(ServerWorld, R::Params) -> Result<R::Result>,
) -> Result<()> ) -> Result<()>
{ {
dispatch::handle_request::<R, _>(req, |params, resp| { dispatch::handle_request::<R, _>(req, |params, resp| {
let world = world.snapshot({ let world = world.snapshot();
let pm = path_map.clone();
move |id, path| pm.resolve(id, path)
});
let path_map = path_map.clone();
let sender = sender.clone(); let sender = sender.clone();
pool.execute(move || { pool.execute(move || {
let res = f(world, path_map, params); let res = f(world, params);
let task = match resp.into_response(res) { let task = match resp.into_response(res) {
Ok(resp) => Task::Respond(resp), Ok(resp) => Task::Respond(resp),
Err(e) => Task::Die(e), Err(e) => Task::Die(e),
@ -318,13 +274,12 @@ 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: ServerWorld,
path_map: PathMap,
sender: Sender<Task>, sender: Sender<Task>,
uri: Url, uri: Url,
) { ) {
pool.execute(move || { pool.execute(move || {
match publish_diagnostics(world.clone(), path_map.clone(), uri.clone()) { match publish_diagnostics(world.clone(), uri.clone()) {
Err(e) => { Err(e) => {
error!("failed to compute diagnostics: {:?}", e) error!("failed to compute diagnostics: {:?}", e)
} }
@ -333,7 +288,7 @@ fn update_file_notifications_on_threadpool(
sender.send(Task::Notify(not)); sender.send(Task::Notify(not));
} }
} }
match publish_decorations(world, path_map.clone(), uri) { match publish_decorations(world, uri) {
Err(e) => { Err(e) => {
error!("failed to compute decorations: {:?}", e) error!("failed to compute decorations: {:?}", e)
} }

View file

@ -0,0 +1,117 @@
use std::{
path::{PathBuf, Path},
collections::HashMap,
};
use languageserver_types::Url;
use libanalysis::{FileId, WorldState, World};
use {
Result,
path_map::PathMap,
vfs::{FileEvent, FileEventKind},
};
#[derive(Debug)]
pub struct ServerWorldState {
pub analysis: WorldState,
pub path_map: PathMap,
pub mem_map: HashMap<FileId, Option<String>>,
}
#[derive(Clone)]
pub struct ServerWorld {
pub analysis: World,
pub path_map: PathMap,
}
impl ServerWorldState {
pub fn new() -> ServerWorldState {
ServerWorldState {
analysis: WorldState::new(),
path_map: PathMap::new(),
mem_map: HashMap::new(),
}
}
pub fn apply_fs_changes(&mut self, events: Vec<FileEvent>) {
let pm = &mut self.path_map;
let mm = &mut self.mem_map;
let changes = events.into_iter()
.map(|event| {
let text = match event.kind {
FileEventKind::Add(text) => Some(text),
FileEventKind::Remove => None,
};
(event.path, text)
})
.map(|(path, text)| {
(pm.get_or_insert(path), text)
})
.filter_map(|(id, text)| {
if mm.contains_key(&id) {
mm.insert(id, text);
None
} else {
Some((id, text))
}
});
self.analysis.change_files(changes);
}
pub fn add_mem_file(&mut self, path: PathBuf, text: String) {
let file_id = self.path_map.get_or_insert(path);
self.mem_map.insert(file_id, None);
self.analysis.change_file(file_id, Some(text));
}
pub fn change_mem_file(&mut self, path: &Path, text: String) -> Result<()> {
let file_id = self.path_map.get_id(path).ok_or_else(|| {
format_err!("change to unknown file: {}", path.display())
})?;
self.analysis.change_file(file_id, Some(text));
Ok(())
}
pub fn remove_mem_file(&mut self, path: &Path) -> Result<()> {
let file_id = self.path_map.get_id(path).ok_or_else(|| {
format_err!("change to unknown file: {}", path.display())
})?;
let text = match self.mem_map.remove(&file_id) {
Some(text) => text,
None => bail!("unmatched close notification"),
};
self.analysis.change_file(file_id, text);
Ok(())
}
pub fn snapshot(&self) -> ServerWorld {
let pm = self.path_map.clone();
ServerWorld {
analysis: self.analysis.snapshot(move |id, path| {
pm.resolve(id, path)
}),
path_map: self.path_map.clone()
}
}
}
impl ServerWorld {
pub fn analysis(&self) -> &World {
&self.analysis
}
pub fn uri_to_file_id(&self, uri: &Url) -> Result<FileId> {
let path = uri.to_file_path()
.map_err(|()| format_err!("invalid uri: {}", uri))?;
self.path_map.get_id(&path).ok_or_else(|| format_err!("unknown file: {}", path.display()))
}
pub fn file_id_to_uri(&self, id: FileId) -> Result<Url> {
let path = self.path_map.get_path(id);
let url = Url::from_file_path(path)
.map_err(|()| format_err!("can't convert path to url: {}", path.display()))?;
Ok(url)
}
}