Provide diagnostic context to codeAction

Co-authored-by: Max Brunsfeld <max@zed.dev>
This commit is contained in:
Keith Simmons 2022-03-31 15:39:52 -07:00
parent 9385690b98
commit 564225c401
5 changed files with 59 additions and 45 deletions

View file

@ -34,6 +34,23 @@ pub struct Summary {
count: usize, count: usize,
} }
impl<T> DiagnosticEntry<T> {
// Used to provide diagnostic context to lsp codeAction request
pub fn to_lsp_diagnostic_stub(&self) -> lsp::Diagnostic {
let code = self
.diagnostic
.code
.clone()
.map(lsp::NumberOrString::String);
lsp::Diagnostic {
code,
severity: Some(self.diagnostic.severity),
..Default::default()
}
}
}
impl DiagnosticSet { impl DiagnosticSet {
pub fn from_sorted_entries<I>(iter: I, buffer: &text::BufferSnapshot) -> Self pub fn from_sorted_entries<I>(iter: I, buffer: &text::BufferSnapshot) -> Self
where where

View file

@ -662,18 +662,21 @@ impl LspAdapter for FakeLspAdapter {
} }
} }
impl ToLspPosition for PointUtf16 { pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
fn to_lsp_position(self) -> lsp::Position { lsp::Position::new(point.row, point.column)
lsp::Position::new(self.row, self.column)
}
} }
pub fn point_from_lsp(point: lsp::Position) -> PointUtf16 { pub fn point_from_lsp(point: lsp::Position) -> PointUtf16 {
PointUtf16::new(point.line, point.character) PointUtf16::new(point.line, point.character)
} }
pub fn range_from_lsp(range: lsp::Range) -> Range<PointUtf16> { pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
let start = PointUtf16::new(range.start.line, range.start.character); lsp::Range {
let end = PointUtf16::new(range.end.line, range.end.character); start: point_to_lsp(range.start),
start..end end: point_to_lsp(range.end),
}
}
pub fn range_from_lsp(range: lsp::Range) -> Range<PointUtf16> {
point_from_lsp(range.start)..point_from_lsp(range.end)
} }

View file

@ -4,9 +4,9 @@ use async_trait::async_trait;
use client::{proto, PeerId}; use client::{proto, PeerId};
use gpui::{AppContext, AsyncAppContext, ModelHandle}; use gpui::{AppContext, AsyncAppContext, ModelHandle};
use language::{ use language::{
point_from_lsp, point_from_lsp, point_to_lsp,
proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version}, proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},
range_from_lsp, Anchor, Bias, Buffer, PointUtf16, ToLspPosition, ToPointUtf16, range_from_lsp, Anchor, Bias, Buffer, PointUtf16, ToPointUtf16,
}; };
use lsp::{DocumentHighlightKind, ServerCapabilities}; use lsp::{DocumentHighlightKind, ServerCapabilities};
use std::{cmp::Reverse, ops::Range, path::Path}; use std::{cmp::Reverse, ops::Range, path::Path};
@ -91,7 +91,7 @@ impl LspCommand for PrepareRename {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: lsp::Url::from_file_path(path).unwrap(), uri: lsp::Url::from_file_path(path).unwrap(),
}, },
position: self.position.to_lsp_position(), position: point_to_lsp(self.position),
} }
} }
@ -208,7 +208,7 @@ impl LspCommand for PerformRename {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: lsp::Url::from_file_path(path).unwrap(), uri: lsp::Url::from_file_path(path).unwrap(),
}, },
position: self.position.to_lsp_position(), position: point_to_lsp(self.position),
}, },
new_name: self.new_name.clone(), new_name: self.new_name.clone(),
work_done_progress_params: Default::default(), work_done_progress_params: Default::default(),
@ -325,7 +325,7 @@ impl LspCommand for GetDefinition {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: lsp::Url::from_file_path(path).unwrap(), uri: lsp::Url::from_file_path(path).unwrap(),
}, },
position: self.position.to_lsp_position(), position: point_to_lsp(self.position),
}, },
work_done_progress_params: Default::default(), work_done_progress_params: Default::default(),
partial_result_params: Default::default(), partial_result_params: Default::default(),
@ -497,7 +497,7 @@ impl LspCommand for GetReferences {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: lsp::Url::from_file_path(path).unwrap(), uri: lsp::Url::from_file_path(path).unwrap(),
}, },
position: self.position.to_lsp_position(), position: point_to_lsp(self.position),
}, },
work_done_progress_params: Default::default(), work_done_progress_params: Default::default(),
partial_result_params: Default::default(), partial_result_params: Default::default(),
@ -659,7 +659,7 @@ impl LspCommand for GetDocumentHighlights {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: lsp::Url::from_file_path(path).unwrap(), uri: lsp::Url::from_file_path(path).unwrap(),
}, },
position: self.position.to_lsp_position(), position: point_to_lsp(self.position),
}, },
work_done_progress_params: Default::default(), work_done_progress_params: Default::default(),
partial_result_params: Default::default(), partial_result_params: Default::default(),

View file

@ -15,11 +15,12 @@ use gpui::{
MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle, MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
}; };
use language::{ use language::{
point_to_lsp,
proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version}, proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},
range_from_lsp, Anchor, Bias, Buffer, CodeAction, CodeLabel, Completion, Diagnostic, range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CodeAction, CodeLabel, Completion,
DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _, Language, LanguageRegistry, Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _, Language,
LanguageServerName, LocalFile, LspAdapter, OffsetRangeExt, Operation, Patch, PointUtf16, LanguageRegistry, LanguageServerName, LocalFile, LspAdapter, OffsetRangeExt, Operation, Patch,
TextBufferSnapshot, ToLspPosition, ToOffset, ToPointUtf16, Transaction, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction,
}; };
use lsp::{DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer}; use lsp::{DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer};
use lsp_command::*; use lsp_command::*;
@ -1215,8 +1216,8 @@ impl Project {
.collect(); .collect();
lsp::TextDocumentContentChangeEvent { lsp::TextDocumentContentChangeEvent {
range: Some(lsp::Range::new( range: Some(lsp::Range::new(
edit_start.to_lsp_position(), point_to_lsp(edit_start),
edit_end.to_lsp_position(), point_to_lsp(edit_end),
)), )),
range_length: None, range_length: None,
text: new_text, text: new_text,
@ -2061,9 +2062,8 @@ impl Project {
.map_or(false, |provider| *provider != lsp::OneOf::Left(false)) .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
{ {
let buffer_start = lsp::Position::new(0, 0); let buffer_start = lsp::Position::new(0, 0);
let buffer_end = buffer let buffer_end =
.read_with(&cx, |buffer, _| buffer.max_point_utf16()) buffer.read_with(&cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
.to_lsp_position();
language_server language_server
.request::<lsp::request::RangeFormatting>( .request::<lsp::request::RangeFormatting>(
lsp::DocumentRangeFormattingParams { lsp::DocumentRangeFormattingParams {
@ -2337,7 +2337,7 @@ impl Project {
lsp::TextDocumentIdentifier::new( lsp::TextDocumentIdentifier::new(
lsp::Url::from_file_path(buffer_abs_path).unwrap(), lsp::Url::from_file_path(buffer_abs_path).unwrap(),
), ),
position.to_lsp_position(), point_to_lsp(position),
), ),
context: Default::default(), context: Default::default(),
work_done_progress_params: Default::default(), work_done_progress_params: Default::default(),
@ -2511,7 +2511,7 @@ impl Project {
} }
} }
pub fn code_actions<T: ToOffset>( pub fn code_actions<T: Clone + ToOffset>(
&self, &self,
buffer_handle: &ModelHandle<Buffer>, buffer_handle: &ModelHandle<Buffer>,
range: Range<T>, range: Range<T>,
@ -2519,6 +2519,11 @@ impl Project {
) -> Task<Result<Vec<CodeAction>>> { ) -> Task<Result<Vec<CodeAction>>> {
let buffer_handle = buffer_handle.clone(); let buffer_handle = buffer_handle.clone();
let buffer = buffer_handle.read(cx); let buffer = buffer_handle.read(cx);
let snapshot = buffer.snapshot();
let relevant_diagnostics = snapshot
.diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
.map(|entry| entry.to_lsp_diagnostic_stub())
.collect();
let buffer_id = buffer.remote_id(); let buffer_id = buffer.remote_id();
let worktree; let worktree;
let buffer_abs_path; let buffer_abs_path;
@ -2539,10 +2544,7 @@ impl Project {
return Task::ready(Ok(Default::default())); return Task::ready(Ok(Default::default()));
}; };
let lsp_range = lsp::Range::new( let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
range.start.to_point_utf16(buffer).to_lsp_position(),
range.end.to_point_utf16(buffer).to_lsp_position(),
);
cx.foreground().spawn(async move { cx.foreground().spawn(async move {
if !lang_server.capabilities().code_action_provider.is_some() { if !lang_server.capabilities().code_action_provider.is_some() {
return Ok(Default::default()); return Ok(Default::default());
@ -2557,11 +2559,12 @@ impl Project {
work_done_progress_params: Default::default(), work_done_progress_params: Default::default(),
partial_result_params: Default::default(), partial_result_params: Default::default(),
context: lsp::CodeActionContext { context: lsp::CodeActionContext {
diagnostics: Default::default(), diagnostics: relevant_diagnostics,
only: Some(vec![ only: Some(vec![
lsp::CodeActionKind::QUICKFIX, lsp::CodeActionKind::QUICKFIX,
lsp::CodeActionKind::REFACTOR, lsp::CodeActionKind::REFACTOR,
lsp::CodeActionKind::REFACTOR_EXTRACT, lsp::CodeActionKind::REFACTOR_EXTRACT,
lsp::CodeActionKind::SOURCE,
]), ]),
}, },
}) })
@ -2636,11 +2639,7 @@ impl Project {
.and_then(|d| d.get_mut("codeActionParams")) .and_then(|d| d.get_mut("codeActionParams"))
.and_then(|d| d.get_mut("range")) .and_then(|d| d.get_mut("range"))
{ {
*lsp_range = serde_json::to_value(&lsp::Range::new( *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
range.start.to_lsp_position(),
range.end.to_lsp_position(),
))
.unwrap();
action.lsp_action = lang_server action.lsp_action = lang_server
.request::<lsp::request::CodeActionResolveRequest>(action.lsp_action) .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
.await?; .await?;

View file

@ -1088,8 +1088,8 @@ mod tests {
}; };
use gpui::{executor, geometry::vector::vec2f, ModelHandle, TestAppContext, ViewHandle}; use gpui::{executor, geometry::vector::vec2f, ModelHandle, TestAppContext, ViewHandle};
use language::{ use language::{
tree_sitter_rust, Diagnostic, DiagnosticEntry, FakeLspAdapter, Language, LanguageConfig, range_to_lsp, tree_sitter_rust, Diagnostic, DiagnosticEntry, FakeLspAdapter, Language,
LanguageRegistry, OffsetRangeExt, Point, ToLspPosition, LanguageConfig, LanguageRegistry, OffsetRangeExt, Point,
}; };
use lsp::{self, FakeLanguageServer}; use lsp::{self, FakeLanguageServer};
use parking_lot::Mutex; use parking_lot::Mutex;
@ -4979,14 +4979,9 @@ mod tests {
for _ in 0..highlight_count { for _ in 0..highlight_count {
let range = let range =
buffer.random_byte_range(prev_end, &mut *rng.lock()); buffer.random_byte_range(prev_end, &mut *rng.lock());
let start = buffer
.offset_to_point_utf16(range.start)
.to_lsp_position();
let end = buffer
.offset_to_point_utf16(range.end)
.to_lsp_position();
highlights.push(lsp::DocumentHighlight { highlights.push(lsp::DocumentHighlight {
range: lsp::Range::new(start, end), range: range_to_lsp(range.to_point_utf16(buffer)),
kind: Some(lsp::DocumentHighlightKind::READ), kind: Some(lsp::DocumentHighlightKind::READ),
}); });
prev_end = range.end; prev_end = range.end;