Lutra/crates/lsp/src/documents.rs
danny 81831c90e0 M3.2: LSP client core (framing, supervision, requests, document sync)
crates/lsp is now a library: Content-Length JSON-RPC framing over stdio
(32 MiB cap, malformed frames dropped and reported, fuzzed), Server::spawn
with initialize/initialized (utf-16, incremental sync, completion, hover,
signatureHelp, definition, references, rename, publishDiagnostics),
typed requests with timeouts and $/cancelRequest, answers to server
requests (configuration nulls, MethodNotFound), events on a bounded
channel, supervision with backoff restarts that reopen documents and
give up after 5 crashes in 2 min, shutdown/exit, and incremental
document sync from lutra_text edits. Tested against a scripted fake
server binary; docs: architecture, G6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 00:57:10 +02:00

175 lines
6.6 KiB
Rust

//! The client's copy of every open document and the conversion of
//! `lutra_text` edits into LSP content changes.
//!
//! The client keeps each open document's text in a [`Buffer`] so it can
//! convert byte-range edits to UTF-16 positions, send the whole text when a
//! server wants full sync, and reopen every document after a restart.
use lutra_text::{Buffer, ColumnUnit, Edit, TextError};
use serde_json::{Value, json};
use crate::types::{Range, position_to_json};
/// One open document.
#[derive(Debug, Clone)]
pub(crate) struct Document {
/// The LSP language id (`php`, …).
pub language_id: String,
/// The version last sent (or to be sent on reopen); starts at 1.
pub version: i32,
/// The current text.
pub buffer: Buffer,
}
/// Applies `edits` to `buffer` and returns the matching LSP
/// `TextDocumentContentChangeEvent`s (`{range, text}`, UTF-16 columns).
///
/// `edits` follow [`Buffer::apply`]: every range refers to the text before
/// the call, in any order. LSP applies content changes one after another,
/// each against the result of the previous one, so:
///
/// - Edits that touch (one ends where the next starts, including several
/// insertions at one offset) are merged into one change, their texts in
/// the order `Buffer::apply` uses. Otherwise a change could put a `\n`
/// right after a `\r` and move the line break under a position computed
/// for the next change.
/// - The merged changes are emitted from the end of the text to the start.
/// Each one then only changes text after every change still to come, with
/// at least one untouched character in between, so positions computed on
/// the old text stay valid.
///
/// # Errors
/// The [`TextError`] of the first range that is not a valid position (inside
/// a character or a CRLF, past the end) or of a batch `Buffer::apply`
/// rejects; the buffer is unchanged then.
pub fn content_changes(buffer: &mut Buffer, edits: &[Edit]) -> Result<Vec<Value>, TextError> {
let mut resolved = Vec::with_capacity(edits.len());
for edit in edits {
let start = buffer.offset_to_position(edit.range.start, ColumnUnit::Utf16)?;
let end = buffer.offset_to_position(edit.range.end, ColumnUnit::Utf16)?;
resolved.push((edit.range.clone(), Range { start, end }, edit.text.as_str()));
}
let mut updated = buffer.clone();
updated.apply(edits)?;
*buffer = updated;
resolved.sort_by_key(|(bytes, _, _)| (bytes.start, bytes.end));
let mut groups: Vec<(usize, Range, String)> = Vec::new();
for (bytes, range, text) in resolved {
match groups.last_mut() {
Some((end, group, merged)) if *end == bytes.start => {
*end = bytes.end;
group.end = range.end;
merged.push_str(text);
}
_ => groups.push((bytes.end, range, text.to_string())),
}
}
Ok(groups
.into_iter()
.rev()
.map(|(_, range, text)| json!({"range": range.to_json(), "text": text}))
.collect())
}
/// The `TextDocumentItem` of a `didOpen`.
pub(crate) fn text_document_item(uri: &str, document: &Document) -> Value {
json!({
"textDocument": {
"uri": uri,
"languageId": document.language_id,
"version": document.version,
"text": document.buffer.text(),
}
})
}
/// The params of a `textDocument/{definition, hover, …}` request.
pub(crate) fn text_document_position(uri: &str, position: lutra_text::Position) -> Value {
json!({"textDocument": {"uri": uri}, "position": position_to_json(position)})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::position_from_json;
use proptest::prelude::*;
/// Applies LSP content changes one after another, as a server does.
fn apply_sequentially(text: &str, changes: &[Value]) -> String {
let mut buffer = Buffer::new(text);
for change in changes {
let start = position_from_json(&change["range"]["start"]).unwrap();
let end = position_from_json(&change["range"]["end"]).unwrap();
let start = buffer.position_to_offset(start, ColumnUnit::Utf16).unwrap();
let end = buffer.position_to_offset(end, ColumnUnit::Utf16).unwrap();
let replacement = change["text"].as_str().unwrap();
buffer
.apply(&[Edit::replace(start..end, replacement)])
.unwrap();
}
buffer.text()
}
#[test]
fn utf16_columns_and_order() {
let mut buffer = Buffer::new("a😀b\r\nc");
let changes = content_changes(
&mut buffer,
&[
Edit::insert(0, "X"),
Edit::replace(5..6, "B"),
Edit::insert(9, "!"),
],
)
.unwrap();
assert_eq!(buffer.text(), "Xa😀B\r\nc!");
assert_eq!(
changes[0]["range"]["start"],
json!({"line": 1, "character": 1})
);
assert_eq!(
changes[1]["range"]["start"],
json!({"line": 0, "character": 3})
);
assert_eq!(apply_sequentially("a😀b\r\nc", &changes), buffer.text());
}
#[test]
fn rejects_bad_edits_unchanged() {
let mut buffer = Buffer::new("é");
assert!(content_changes(&mut buffer, &[Edit::insert(1, "x")]).is_err());
assert!(content_changes(&mut buffer, &[Edit::insert(9, "x")]).is_err());
assert_eq!(buffer.text(), "é");
}
fn text_and_edits() -> impl Strategy<Value = (String, Vec<(usize, usize, String)>)> {
"[a-c\u{e9}\u{1F600}\r\n]{0,24}".prop_flat_map(|text| {
let edits = proptest::collection::vec(
(0..=text.len(), 0..=4usize, "[x\u{1F600}\n\r]{0,3}"),
0..5,
);
(Just(text), edits)
})
}
proptest! {
#[test]
fn sequential_changes_match_apply((text, raw) in text_and_edits()) {
let mut buffer = Buffer::new(&text);
let edits: Vec<Edit> = raw
.into_iter()
.map(|(start, len, insert)| Edit::replace(start..(start + len).min(text.len()), insert))
.collect();
let mut expected = Buffer::new(&text);
let applied = expected.apply(&edits);
match content_changes(&mut buffer, &edits) {
Ok(changes) => {
prop_assert!(applied.is_ok());
prop_assert_eq!(buffer.text(), expected.text());
prop_assert_eq!(apply_sequentially(&text, &changes), expected.text());
}
Err(_) => prop_assert_eq!(buffer.text(), text),
}
}
}
}