Add validation in LspCommand::to_lsp + check for inverted ranges (#22731)

#22690 logged errors and flipped the range in this case. Instead it
brings more visibility to the issue to return errors.

Release Notes:

- N/A
This commit is contained in:
Michael Sloan 2025-01-06 15:00:36 -07:00 committed by GitHub
parent 1c223d8940
commit 141393232e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 134 additions and 162 deletions

View file

@ -1,4 +1,5 @@
use crate::{range_to_lsp, Diagnostic};
use anyhow::Result;
use collections::HashMap;
use lsp::LanguageServerId;
use std::{
@ -54,16 +55,16 @@ pub struct Summary {
impl DiagnosticEntry<PointUtf16> {
/// Returns a raw LSP diagnostic used to provide diagnostic context to LSP
/// codeAction request
pub fn to_lsp_diagnostic_stub(&self) -> lsp::Diagnostic {
pub fn to_lsp_diagnostic_stub(&self) -> Result<lsp::Diagnostic> {
let code = self
.diagnostic
.code
.clone()
.map(lsp::NumberOrString::String);
let range = range_to_lsp(self.range.clone());
let range = range_to_lsp(self.range.clone())?;
lsp::Diagnostic {
Ok(lsp::Diagnostic {
code,
range,
severity: Some(self.diagnostic.severity),
@ -71,7 +72,7 @@ impl DiagnosticEntry<PointUtf16> {
message: self.diagnostic.message.clone(),
data: self.diagnostic.data.clone(),
..Default::default()
}
})
}
}

View file

@ -1849,14 +1849,19 @@ pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
Unclipped(PointUtf16::new(point.line, point.character))
}
pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
let mut start = point_to_lsp(range.start);
let mut end = point_to_lsp(range.end);
if start > end {
log::error!("range_to_lsp called with inverted range {start:?}-{end:?}");
mem::swap(&mut start, &mut end);
pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
if range.start > range.end {
Err(anyhow!(
"Inverted range provided to an LSP request: {:?}-{:?}",
range.start,
range.end
))
} else {
Ok(lsp::Range {
start: point_to_lsp(range.start),
end: point_to_lsp(range.end),
})
}
lsp::Range { start, end }
}
pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {