дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
fix(lsp): clamp out-of-range positions instead of rejecting the server's answer (#8201)
Reformat Code on a shell script changed nothing and format on save failed silently: bash-language-server answers formatting with an edit ending at Position.create(Number.MAX_VALUE, Number.MAX_VALUE), which arrives as the float 1.7976931348623157e+308, and reading it into lsp-types' u32 positions rejected the whole answer. The same refused a workspace/applyEdit and dropped a diagnostic with such a position. The line and character of each position in a request's answer, an edit to apply and a diagnostic are now saturated to the u32 range before they are read (opaque data and arguments payloads are left untouched); the editor already clamps a position past the end of the text. Co-authored-by: ntbang0901 <[email protected]>
Цей коміт міститься в:
1 джерело
b01ba2da03
коміт
4baa407e25
4 files changed
+125
No files matched your search
@@ -102,6 +102,41 @@ pub fn lsp_text_edit(text: &DocText, enc: Encoding, e: &TextEdit) -> lsp::TextEd
|
||||
lsp::TextEdit { range: lsp_range(text, enc, e.range), new_text: e.new_text.clone() }
|
||||
}
|
||||
|
||||
/// Saturates the `line` and `character` of each position in a server's message to `u32`, the type
|
||||
/// they are read into, where one out of range rejects the whole message. bash-language-server
|
||||
/// formats a file up to `Number.MAX_VALUE` (a float on the wire); applying an edit clamps a
|
||||
/// position past the end of the text.
|
||||
pub(crate) fn clamp_positions(value: &mut Value) {
|
||||
match value {
|
||||
Value::Array(values) => values.iter_mut().for_each(clamp_positions),
|
||||
Value::Object(fields) => {
|
||||
if fields.contains_key("line") && fields.contains_key("character") {
|
||||
for key in ["line", "character"] {
|
||||
if let Some(number) = fields.get_mut(key) {
|
||||
saturate(number);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (key, value) in fields.iter_mut() {
|
||||
// Opaque payloads must survive resolve/execute round trips unchanged.
|
||||
if !matches!(key.as_str(), "data" | "arguments") {
|
||||
clamp_positions(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes a number that isn't a `u32` one: saturated, without its fraction.
|
||||
fn saturate(number: &mut Value) {
|
||||
let Some(n) = number.as_f64() else { return };
|
||||
let saturated = n.clamp(0.0, f64::from(u32::MAX)) as u32;
|
||||
if number.as_u64() != Some(u64::from(saturated)) {
|
||||
*number = saturated.into();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- kinds
|
||||
|
||||
pub fn symbol_kind(k: lsp::SymbolKind) -> SymbolKind {
|
||||
@@ -1163,6 +1198,26 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn positions_are_saturated_to_u32_and_nothing_else_changes() {
|
||||
let mut value = json!({
|
||||
"range": { "start": { "line": -1, "character": 2.5 }, "end": { "line": f64::MAX, "character": 7 } },
|
||||
"position": { "line": 4_294_967_296_u64, "character": 3 },
|
||||
"foldingRange": { "startLine": 1e10, "endLine": 2 },
|
||||
"data": { "line": -1, "character": 0.5 },
|
||||
});
|
||||
clamp_positions(&mut value);
|
||||
assert_eq!(
|
||||
value,
|
||||
json!({
|
||||
"range": { "start": { "line": 0, "character": 2 }, "end": { "line": u32::MAX, "character": 7 } },
|
||||
"position": { "line": u32::MAX, "character": 3 },
|
||||
"foldingRange": { "startLine": 1e10, "endLine": 2 },
|
||||
"data": { "line": -1, "character": 0.5 },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_action_diagnostics_use_ide_coordinates_and_round_trip_for_resolve() {
|
||||
let path = Path::new("/go.mod");
|
||||
|
||||
@@ -61,6 +61,7 @@ pub(crate) fn lenient_diagnostics(server: &str, items: Value) -> Vec<lsp::Diagno
|
||||
.into_iter()
|
||||
.filter_map(|mut item| {
|
||||
crate::virtual_doc::normalize_uris(&mut item);
|
||||
crate::convert::clamp_positions(&mut item);
|
||||
match serde_json::from_value(item) {
|
||||
Ok(diagnostic) => Some(diagnostic),
|
||||
Err(_) => {
|
||||
@@ -649,6 +650,7 @@ impl ClientHandler {
|
||||
params.get("edit").cloned().ok_or_else(|| (codes::INVALID_PARAMS, "missing edit".to_owned())).and_then(
|
||||
|mut e| {
|
||||
crate::virtual_doc::normalize_uris(&mut e);
|
||||
crate::convert::clamp_positions(&mut e);
|
||||
serde_json::from_value(e).map_err(|e| (codes::INVALID_PARAMS, e.to_string()))
|
||||
},
|
||||
)?;
|
||||
|
||||
@@ -1837,6 +1837,7 @@ impl LspManager {
|
||||
let fut = async {
|
||||
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel).await?;
|
||||
virtual_doc::normalize_uris(&mut value);
|
||||
convert::clamp_positions(&mut value);
|
||||
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
|
||||
};
|
||||
let result = match tokio::time::timeout(timeout, fut).await {
|
||||
|
||||
@@ -7823,6 +7823,73 @@ async fn gopls_interactive_command_validates_before_execution_and_applies_edits(
|
||||
assert_eq!(created, vec![new_file]);
|
||||
}
|
||||
|
||||
/// bash-language-server formats a whole file with `Position.create(Number.MAX_VALUE,
|
||||
/// Number.MAX_VALUE)` as its end, a float far past `u32` on the wire.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_formatting_answer_past_the_u32_range_is_kept() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (doc, _) = h.open("probe.mk", "if true; then\n echo hi\nfi\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
let end = json!({ "line": f64::MAX, "character": f64::MAX });
|
||||
s.respond(
|
||||
"textDocument/formatting",
|
||||
json!([{ "range": { "start": { "line": 0, "character": 0 }, "end": end }, "newText": "if true; then\n echo hi\nfi\n" }]),
|
||||
);
|
||||
let options = FormatOptions { tab_size: 2, insert_spaces: true, on_save: false, tool: None };
|
||||
let edits = h.mgr.format(doc, None, options).await.unwrap();
|
||||
// Applying it clamps the end to the document's.
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].range, rng(0, 0, u32::MAX, u32::MAX));
|
||||
assert_eq!(edits[0].new_text, "if true; then\n echo hi\nfi\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_edit_to_apply_with_positions_past_the_u32_range_is_kept() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (_, path) = h.open("probe.mk", "x\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
let applied = Arc::new(Mutex::new(Vec::new()));
|
||||
let received = applied.clone();
|
||||
h.mgr.set_apply_edit_hook(Box::new(move |edit| {
|
||||
received.lock().push(edit);
|
||||
true
|
||||
}));
|
||||
let range = json!({ "start": { "line": -1, "character": 2.5 }, "end": { "line": f64::MAX, "character": 1e10 } });
|
||||
let edit = json!({ "changes": { uri_of(&path): [{ "range": range, "newText": "" }] } });
|
||||
let reply: Result<Value, _> = s.peer().request("workspace/applyEdit", json!({ "edit": edit }), None).await;
|
||||
assert_eq!(reply.unwrap(), json!({ "applied": true }));
|
||||
let applied = applied.lock();
|
||||
let FileEdit::Edit { edits, .. } = &applied[0].files[0] else { panic!("{:?}", applied[0]) };
|
||||
assert_eq!(edits[0].range, rng(0, 2, u32::MAX, u32::MAX));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_diagnostic_past_the_u32_range_is_kept() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (_, path) = h.open("a.mk", "x\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
let range = json!({ "start": { "line": 0, "character": 0 }, "end": { "line": f64::MAX, "character": f64::MAX } });
|
||||
let diagnostic = json!({ "range": range, "message": "whole file" });
|
||||
s.peer()
|
||||
.notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&path), "diagnostics": [diagnostic] }))
|
||||
.unwrap();
|
||||
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Diagnostics { .. }))).await;
|
||||
let items = h
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { items, .. } => Some(items.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(items.len(), 1, "{items:?}");
|
||||
assert_eq!(items[0].range, rng(0, 0, u32::MAX, u32::MAX));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn interactive_capability_is_scoped_to_gopls() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
Reference in new issue
Заблокувати користувача