365 lines
12 KiB
Rust
Raw Normal View History

2018-08-13 02:38:34 +03:00
use std::collections::HashMap;
2018-08-12 21:02:56 +03:00
use languageserver_types::{
Diagnostic, DiagnosticSeverity, Url, DocumentSymbol,
2018-08-13 15:35:53 +03:00
Command, TextDocumentIdentifier, WorkspaceEdit,
2018-08-23 22:14:51 +03:00
SymbolInformation, Position, Location, TextEdit,
2018-08-12 21:02:56 +03:00
};
2018-08-24 13:41:25 +03:00
use serde_json::{to_value, from_value};
2018-08-17 19:54:08 +03:00
use libanalysis::{Query};
2018-08-22 12:58:34 +03:00
use libeditor;
2018-08-24 13:41:25 +03:00
use libsyntax2::{
TextUnit,
text_utils::contains_offset_nonstrict,
};
2018-08-10 23:30:11 +03:00
2018-08-11 00:12:31 +03:00
use ::{
2018-08-11 00:55:32 +03:00
req::{self, Decoration}, Result,
2018-08-15 17:24:20 +03:00
conv::{Conv, ConvWith, TryConvWith, MapConvWith, to_location},
2018-08-17 19:54:08 +03:00
server_world::ServerWorld,
2018-08-11 00:12:31 +03:00
};
2018-08-10 21:13:39 +03:00
pub fn handle_syntax_tree(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-10 22:23:17 +03:00
params: req::SyntaxTreeParams,
2018-08-10 21:13:39 +03:00
) -> Result<String> {
2018-08-17 19:54:08 +03:00
let id = params.text_document.try_conv_with(&world)?;
let file = world.analysis().file_syntax(id)?;
2018-08-10 21:13:39 +03:00
Ok(libeditor::syntax_tree(&file))
}
2018-08-10 22:23:17 +03:00
pub fn handle_extend_selection(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-10 22:23:17 +03:00
params: req::ExtendSelectionParams,
) -> Result<req::ExtendSelectionResult> {
2018-08-17 19:54:08 +03:00
let file_id = params.text_document.try_conv_with(&world)?;
let file = world.analysis().file_syntax(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-10 22:23:17 +03:00
let selections = params.selections.into_iter()
2018-08-13 02:38:34 +03:00
.map_conv_with(&line_index)
2018-08-12 21:02:56 +03:00
.map(|r| libeditor::extend_selection(&file, r).unwrap_or(r))
2018-08-13 02:38:34 +03:00
.map_conv_with(&line_index)
2018-08-10 22:23:17 +03:00
.collect();
Ok(req::ExtendSelectionResult { selections })
}
2018-08-16 00:23:22 +03:00
pub fn handle_find_matching_brace(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-16 00:23:22 +03:00
params: req::FindMatchingBraceParams,
) -> Result<Vec<Position>> {
2018-08-17 19:54:08 +03:00
let file_id = params.text_document.try_conv_with(&world)?;
let file = world.analysis().file_syntax(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-16 00:23:22 +03:00
let res = params.offsets
.into_iter()
.map_conv_with(&line_index)
.map(|offset| {
libeditor::matching_brace(&file, offset).unwrap_or(offset)
})
.map_conv_with(&line_index)
.collect();
Ok(res)
}
2018-08-23 22:14:51 +03:00
pub fn handle_join_lines(
world: ServerWorld,
params: req::JoinLinesParams,
) -> Result<Vec<TextEdit>> {
let file_id = params.text_document.try_conv_with(&world)?;
let file = world.analysis().file_syntax(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?;
let range = params.range.conv_with(&line_index);
let res = libeditor::join_lines(&file, range);
Ok(res.edit.conv_with(&line_index))
}
2018-08-11 14:44:12 +03:00
pub fn handle_document_symbol(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-11 14:44:12 +03:00
params: req::DocumentSymbolParams,
) -> Result<Option<req::DocumentSymbolResponse>> {
2018-08-17 19:54:08 +03:00
let file_id = params.text_document.try_conv_with(&world)?;
let file = world.analysis().file_syntax(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-11 14:44:12 +03:00
2018-08-14 11:20:09 +03:00
let mut parents: Vec<(DocumentSymbol, Option<usize>)> = Vec::new();
2018-08-11 14:44:12 +03:00
2018-08-14 11:20:09 +03:00
for symbol in libeditor::file_structure(&file) {
2018-08-11 14:44:12 +03:00
let doc_symbol = DocumentSymbol {
2018-08-14 11:20:09 +03:00
name: symbol.label,
detail: Some("".to_string()),
2018-08-12 21:02:56 +03:00
kind: symbol.kind.conv(),
2018-08-11 14:44:12 +03:00
deprecated: None,
2018-08-12 21:02:56 +03:00
range: symbol.node_range.conv_with(&line_index),
2018-08-14 11:20:09 +03:00
selection_range: symbol.navigation_range.conv_with(&line_index),
2018-08-11 14:44:12 +03:00
children: None,
};
2018-08-14 11:20:09 +03:00
parents.push((doc_symbol, symbol.parent));
}
let mut res = Vec::new();
while let Some((node, parent)) = parents.pop() {
match parent {
None => res.push(node),
Some(i) => {
let children = &mut parents[i].0.children;
if children.is_none() {
*children = Some(Vec::new());
}
children.as_mut().unwrap().push(node);
2018-08-11 14:44:12 +03:00
}
}
}
2018-08-14 11:20:09 +03:00
2018-08-11 14:44:12 +03:00
Ok(Some(req::DocumentSymbolResponse::Nested(res)))
}
2018-08-12 21:02:56 +03:00
pub fn handle_code_action(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-12 21:02:56 +03:00
params: req::CodeActionParams,
) -> Result<Option<Vec<Command>>> {
2018-08-17 19:54:08 +03:00
let file_id = params.text_document.try_conv_with(&world)?;
let file = world.analysis().file_syntax(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-12 21:02:56 +03:00
let offset = params.range.conv_with(&line_index).start();
2018-08-24 13:41:25 +03:00
let mut res = Vec::new();
2018-08-14 13:33:44 +03:00
let actions = &[
(ActionId::FlipComma, libeditor::flip_comma(&file, offset).is_some()),
(ActionId::AddDerive, libeditor::add_derive(&file, offset).is_some()),
2018-08-22 19:02:37 +03:00
(ActionId::AddImpl, libeditor::add_impl(&file, offset).is_some()),
2018-08-14 13:33:44 +03:00
];
for (id, edit) in actions {
if *edit {
let cmd = apply_code_action_cmd(*id, params.text_document.clone(), offset);
2018-08-24 13:41:25 +03:00
res.push(cmd);
}
}
for runnable in libeditor::runnables(&file) {
if !contains_offset_nonstrict(runnable.range, offset) {
continue;
}
#[derive(Serialize)]
struct ProcessSpec {
bin: String,
args: Vec<String>,
env: HashMap<String, String>,
2018-08-14 13:33:44 +03:00
}
2018-08-24 13:41:25 +03:00
let spec = ProcessSpec {
bin: "cargo".to_string(),
args: match runnable.kind {
libeditor::RunnableKind::Test { name } => {
vec![
"test".to_string(),
"--".to_string(),
name,
"--nocapture".to_string(),
]
}
libeditor::RunnableKind::Bin => vec!["run".to_string()]
},
env: {
let mut m = HashMap::new();
m.insert(
"RUST_BACKTRACE".to_string(),
"short".to_string(),
);
m
}
};
let cmd = Command {
title: "Run ...".to_string(),
command: "libsyntax-rust.run".to_string(),
arguments: Some(vec![to_value(spec).unwrap()]),
};
res.push(cmd);
2018-08-14 13:33:44 +03:00
}
2018-08-24 13:41:25 +03:00
return Ok(Some(res));
2018-08-12 21:02:56 +03:00
}
2018-08-13 15:35:53 +03:00
pub fn handle_workspace_symbol(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-13 15:35:53 +03:00
params: req::WorkspaceSymbolParams,
) -> Result<Option<Vec<SymbolInformation>>> {
2018-08-14 13:33:44 +03:00
let all_symbols = params.query.contains("#");
2018-08-13 16:07:05 +03:00
let query = {
let query: String = params.query.chars()
.filter(|&c| c != '#')
.collect();
let mut q = Query::new(query);
if !all_symbols {
q.only_types();
}
2018-08-13 17:19:27 +03:00
q.limit(128);
2018-08-13 16:07:05 +03:00
q
};
2018-08-17 19:54:08 +03:00
let mut res = exec_query(&world, query)?;
2018-08-14 13:33:44 +03:00
if res.is_empty() && !all_symbols {
let mut query = Query::new(params.query);
query.limit(128);
2018-08-17 19:54:08 +03:00
res = exec_query(&world, query)?;
2018-08-14 13:33:44 +03:00
}
2018-08-13 16:07:05 +03:00
2018-08-14 13:33:44 +03:00
return Ok(Some(res));
2018-08-17 19:54:08 +03:00
fn exec_query(world: &ServerWorld, query: Query) -> Result<Vec<SymbolInformation>> {
2018-08-14 13:33:44 +03:00
let mut res = Vec::new();
2018-08-17 19:54:08 +03:00
for (file_id, symbol) in world.analysis().world_symbols(query) {
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-14 13:33:44 +03:00
let info = SymbolInformation {
name: symbol.name.to_string(),
kind: symbol.kind.conv(),
2018-08-15 17:24:20 +03:00
location: to_location(
file_id, symbol.node_range,
2018-08-17 19:54:08 +03:00
world, &line_index
2018-08-15 17:24:20 +03:00
)?,
2018-08-14 13:33:44 +03:00
container_name: None,
};
res.push(info);
2018-08-13 15:35:53 +03:00
};
2018-08-14 13:33:44 +03:00
Ok(res)
}
2018-08-13 15:35:53 +03:00
}
2018-08-13 16:35:17 +03:00
pub fn handle_goto_definition(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-13 16:35:17 +03:00
params: req::TextDocumentPositionParams,
) -> Result<Option<req::GotoDefinitionResponse>> {
2018-08-17 19:54:08 +03:00
let file_id = params.text_document.try_conv_with(&world)?;
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-13 16:35:17 +03:00
let offset = params.position.conv_with(&line_index);
let mut res = Vec::new();
2018-08-17 19:54:08 +03:00
for (file_id, symbol) in world.analysis().approximately_resolve_symbol(file_id, offset)? {
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-15 17:24:20 +03:00
let location = to_location(
file_id, symbol.node_range,
2018-08-17 19:54:08 +03:00
&world, &line_index,
2018-08-15 17:24:20 +03:00
)?;
2018-08-13 16:35:17 +03:00
res.push(location)
}
Ok(Some(req::GotoDefinitionResponse::Array(res)))
}
2018-08-22 10:18:58 +03:00
pub fn handle_parent_module(
world: ServerWorld,
params: TextDocumentIdentifier,
) -> Result<Vec<Location>> {
let file_id = params.try_conv_with(&world)?;
let mut res = Vec::new();
for (file_id, symbol) in world.analysis().parent_module(file_id) {
let line_index = world.analysis().file_line_index(file_id)?;
let location = to_location(
file_id, symbol.node_range,
&world, &line_index
)?;
res.push(location);
}
Ok(res)
}
2018-08-13 02:38:34 +03:00
pub fn handle_execute_command(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-13 02:38:34 +03:00
mut params: req::ExecuteCommandParams,
2018-08-16 13:46:31 +03:00
) -> Result<(req::ApplyWorkspaceEditParams, Option<Position>)> {
2018-08-13 02:38:34 +03:00
if params.command.as_str() != "apply_code_action" {
bail!("unknown cmd: {:?}", params.command);
}
if params.arguments.len() != 1 {
bail!("expected single arg, got {}", params.arguments.len());
}
let arg = params.arguments.pop().unwrap();
let arg: ActionRequest = from_value(arg)?;
2018-08-17 19:54:08 +03:00
let file_id = arg.text_document.try_conv_with(&world)?;
let file = world.analysis().file_syntax(file_id)?;
2018-08-15 23:24:20 +03:00
let action_result = match arg.id {
ActionId::FlipComma => libeditor::flip_comma(&file, arg.offset).map(|f| f()),
ActionId::AddDerive => libeditor::add_derive(&file, arg.offset).map(|f| f()),
2018-08-22 19:02:37 +03:00
ActionId::AddImpl => libeditor::add_impl(&file, arg.offset).map(|f| f()),
2018-08-16 13:46:31 +03:00
}.ok_or_else(|| format_err!("command not applicable"))?;
2018-08-17 19:54:08 +03:00
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-14 13:33:44 +03:00
let mut changes = HashMap::new();
changes.insert(
arg.text_document.uri,
2018-08-16 13:46:31 +03:00
action_result.edit.conv_with(&line_index),
2018-08-14 13:33:44 +03:00
);
let edit = WorkspaceEdit {
changes: Some(changes),
document_changes: None,
};
2018-08-16 13:46:31 +03:00
let edit = req::ApplyWorkspaceEditParams { edit };
2018-08-22 12:58:34 +03:00
let cursor_pos = action_result.cursor_position
.map(|off| off.conv_with(&line_index));
2018-08-16 13:46:31 +03:00
Ok((edit, cursor_pos))
2018-08-13 02:38:34 +03:00
}
#[derive(Serialize, Deserialize)]
struct ActionRequest {
id: ActionId,
text_document: TextDocumentIdentifier,
offset: TextUnit,
}
fn apply_code_action_cmd(id: ActionId, doc: TextDocumentIdentifier, offset: TextUnit) -> Command {
2018-08-24 13:41:25 +03:00
let action_request = ActionRequest { id, text_document: doc, offset };
2018-08-12 21:02:56 +03:00
Command {
title: id.title().to_string(),
command: "apply_code_action".to_string(),
2018-08-13 02:38:34 +03:00
arguments: Some(vec![to_value(action_request).unwrap()]),
2018-08-12 21:02:56 +03:00
}
}
#[derive(Serialize, Deserialize, Clone, Copy)]
enum ActionId {
2018-08-14 13:33:44 +03:00
FlipComma,
AddDerive,
2018-08-22 19:02:37 +03:00
AddImpl,
2018-08-12 21:02:56 +03:00
}
impl ActionId {
fn title(&self) -> &'static str {
match *self {
ActionId::FlipComma => "Flip `,`",
2018-08-14 13:33:44 +03:00
ActionId::AddDerive => "Add `#[derive]`",
2018-08-22 19:02:37 +03:00
ActionId::AddImpl => "Add impl",
2018-08-12 21:02:56 +03:00
}
2018-08-11 14:44:12 +03:00
}
}
2018-08-15 17:24:20 +03:00
pub fn publish_diagnostics(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-15 17:24:20 +03:00
uri: Url
) -> Result<req::PublishDiagnosticsParams> {
2018-08-17 19:54:08 +03:00
let file_id = world.uri_to_file_id(&uri)?;
let file = world.analysis().file_syntax(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-10 23:30:11 +03:00
let diagnostics = libeditor::diagnostics(&file)
.into_iter()
.map(|d| Diagnostic {
2018-08-12 21:02:56 +03:00
range: d.range.conv_with(&line_index),
2018-08-10 23:30:11 +03:00
severity: Some(DiagnosticSeverity::Error),
code: None,
source: Some("libsyntax2".to_string()),
message: d.msg,
related_information: None,
}).collect();
Ok(req::PublishDiagnosticsParams { uri, diagnostics })
}
2018-08-15 17:24:20 +03:00
pub fn publish_decorations(
2018-08-17 19:54:08 +03:00
world: ServerWorld,
2018-08-15 17:24:20 +03:00
uri: Url
) -> Result<req::PublishDecorationsParams> {
2018-08-17 19:54:08 +03:00
let file_id = world.uri_to_file_id(&uri)?;
let file = world.analysis().file_syntax(file_id)?;
let line_index = world.analysis().file_line_index(file_id)?;
2018-08-11 00:55:32 +03:00
let decorations = libeditor::highlight(&file)
.into_iter()
.map(|h| Decoration {
2018-08-12 21:02:56 +03:00
range: h.range.conv_with(&line_index),
2018-08-11 00:55:32 +03:00
tag: h.tag,
}).collect();
Ok(req::PublishDecorationsParams { uri, decorations })
}