//! Applying a `didChange`'s edits to a buffer. //! //! With `TextDocumentSyncKind::INCREMENTAL` the client stops sending the whole //! file on every keystroke and sends the ranges it touched instead. The server //! is then the only holder of the buffer's text, so this module is the one //! place a wrong offset silently rewrites what the user is looking at — hence //! a pure function, a second implementation to cross-check it against, and no //! slicing that can panic. The exact clamping rules are in //! `docs/features/incremental-sync/README.md`. use lsp_types::TextDocumentContentChangeEvent; use vlog_parser::LineIndex; use crate::convert::Positions; /// Apply one `didChange`'s content changes to a buffer, in the order the /// client sent them, and return the buffer that results. /// /// A change with no range replaces the whole document — what a full-sync /// client sends, and what still works if one arrives mid-batch. /// /// `#[cfg(test)]` since the server reads where the edit ended too /// ([`apply_changes_at`]); the tests, and the cross-check against the /// reference implementation, come in by this door. #[cfg(test)] pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String { apply_changes_at(text, changes).0 } /// `apply_changes`, and where the last change ended in the text that /// results: the byte offset just past what it inserted. `None` when the last /// change replaced the whole document — that says nothing about where anyone /// is typing (`docs/features/port-entry-grace/README.md`). pub fn apply_changes_at( text: &str, changes: &[TextDocumentContentChangeEvent], ) -> (String, Option) { let mut text = text.to_string(); let mut edit_end = None; for change in changes { let Some(range) = change.range else { // The whole document. This also resets the state that the ranges // after it in the same batch are positioned against. text.clone_from(&change.text); edit_end = None; continue; }; // A fresh line table per change: each range is positioned against the // document as the *previous* changes in this batch left it. That is // O(changes × file) per notification, which at Verilog file sizes is // microseconds and buys a function with no incremental state to get // out of step. let index = LineIndex::new(&text); let positions = Positions::new(&text, &index); let start = positions.offset(range.start) as usize; // A range that runs backwards is a client desync. Reading it as an // insertion at `start` is the one interpretation that deletes nothing: // we have no resync mechanism, so the safe direction is to keep text. let end = (positions.offset(range.end) as usize).max(start); let (Some(before), Some(after)) = (text.get(..start), text.get(end..)) else { // Unreachable: `Positions::offset` only ever returns character // boundaries. Written as a skip rather than a slice because the // slice would panic, and a panic here takes the buffer with it. continue; }; text = format!("{before}{}{after}", change.text); edit_end = u32::try_from(start + change.text.len()).ok(); } (text, edit_end) } #[cfg(test)] mod tests { use super::*; use lsp_types::{Position, Range}; fn pos(line: u32, character: u32) -> Position { Position { line, character } } /// A ranged change, the way a client sends one. fn edit( start: (u32, u32), end: (u32, u32), text: &str, ) -> lsp_types::TextDocumentContentChangeEvent { TextDocumentContentChangeEvent { range: Some(Range { start: pos(start.0, start.1), end: pos(end.0, end.1) }), range_length: None, text: text.to_string(), } } /// A rangeless change: the whole buffer, as a full-sync client sends it. fn whole(text: &str) -> TextDocumentContentChangeEvent { TextDocumentContentChangeEvent { range: None, range_length: None, text: text.to_string() } } #[test] fn an_insert_lands_where_the_range_is_empty() { let text = "module m;\n wire a;\nendmodule\n"; let after = apply_changes(text, &[edit((1, 8), (1, 8), "b")]); assert_eq!(after, "module m;\n wire ab;\nendmodule\n"); } /// Where the last change ended is the offset just past what it inserted, /// in the text that results — the cursor's place after typing it. #[test] fn the_edit_end_is_just_past_the_inserted_text() { let text = "module m;\n wire a;\nendmodule\n"; let (after, end) = apply_changes_at(text, &[edit((1, 8), (1, 8), "bc")]); assert_eq!(after, "module m;\n wire abc;\nendmodule\n"); assert_eq!(end, Some(20), "just past the `bc`"); assert_eq!(&after[..20], "module m;\n wire abc"); let (_, end) = apply_changes_at(text, &[edit((1, 7), (1, 8), "")]); assert_eq!(end, Some(17), "a delete ends where it started"); } /// The last change of a batch decides, and a rangeless one — a whole /// document — says nothing about where anyone is typing. #[test] fn the_edit_end_follows_the_last_change_and_a_whole_document_has_none() { let text = "module m;\nendmodule\n"; let (_, end) = apply_changes_at(text, &[edit((0, 0), (0, 0), "x"), whole("module n;\n")]); assert_eq!(end, None); let (_, end) = apply_changes_at(text, &[whole("module n;\n"), edit((0, 9), (0, 9), "\n")]); assert_eq!(end, Some(10)); assert_eq!(apply_changes_at(text, &[]), (text.to_string(), None)); } #[test] fn a_delete_removes_exactly_the_range() { let text = "module m;\n wire aaa;\nendmodule\n"; let after = apply_changes(text, &[edit((1, 7), (1, 10), "")]); assert_eq!(after, "module m;\n wire ;\nendmodule\n"); } #[test] fn a_replace_swaps_the_range_for_the_text() { let text = "module m;\n wire a;\nendmodule\n"; let after = apply_changes(text, &[edit((1, 2), (1, 6), "logic")]); assert_eq!(after, "module m;\n logic a;\nendmodule\n"); } #[test] fn a_multi_line_range_collapses_the_lines_it_spans() { let text = "a\nb\nc\n"; let after = apply_changes(text, &[edit((0, 1), (2, 0), "X")]); assert_eq!(after, "aXc\n"); } #[test] fn later_changes_see_what_the_earlier_ones_did() { // The batch a real editor sends for "type `wire w;` on a new line", // split into three: each range is against the state after the last. let text = "module m;\nendmodule\n"; let after = apply_changes( text, &[ edit((1, 0), (1, 0), "\n"), // open a line edit((1, 0), (1, 0), " wire "), // the keyword edit((1, 7), (1, 7), "w;"), // the name ], ); assert_eq!(after, "module m;\n wire w;\nendmodule\n"); } #[test] fn a_later_range_positioned_against_the_original_text_would_be_wrong() { // The regression this whole module exists to prevent: if the line // table were built once, the second range below would land on the old // line 1 and the result would differ. let text = "aaa\nbbb\n"; let after = apply_changes(text, &[edit((0, 0), (0, 0), "x\n"), edit((1, 1), (1, 2), "Z")]); assert_eq!(after, "x\naZa\nbbb\n"); } #[test] fn a_two_byte_character_is_one_utf16_unit_to_the_edit_too() { let text = "// é ok\n"; let after = apply_changes(text, &[edit((0, 5), (0, 7), "no")]); assert_eq!(after, "// é no\n"); } #[test] fn an_astral_character_takes_two_units_and_is_never_split() { // `🎉` is 2 UTF-16 units. A boundary on its low half rounds forward // past the whole character, so no edit can ever cut it in half. let text = "// 🎉 ok\n"; assert_eq!(apply_changes(text, &[edit((0, 3), (0, 5), "X")]), "// X ok\n"); // Start inside the pair: the emoji survives, the edit begins after it. assert_eq!(apply_changes(text, &[edit((0, 4), (0, 6), "X")]), "// 🎉Xok\n"); // End inside the pair: rounds forward, so the emoji goes with it. assert_eq!(apply_changes(text, &[edit((0, 3), (0, 4), "X")]), "// X ok\n"); for change in [edit((0, 4), (0, 4), "!"), edit((0, 4), (0, 5), "!")] { let out = apply_changes(text, &[change]); assert!(out.is_char_boundary(out.len()), "still valid UTF-8: {out:?}"); } } #[test] fn an_edit_after_an_emoji_counts_from_the_right_column() { let text = "// 🎉 wire a;\n"; // "wire" starts at UTF-16 unit 6: `/`,`/`,` `,🎉(2),` `. let after = apply_changes(text, &[edit((0, 6), (0, 10), "logic")]); assert_eq!(after, "// 🎉 logic a;\n"); } #[test] fn crlf_line_ends_survive_an_edit_on_the_line() { let text = "module m;\r\n wire a;\r\nendmodule\r\n"; let after = apply_changes(text, &[edit((1, 7), (1, 8), "bb")]); assert_eq!(after, "module m;\r\n wire bb;\r\nendmodule\r\n"); } #[test] fn a_crlf_line_can_be_joined_to_the_next() { let text = "ab\r\ncd\r\n"; let after = apply_changes(text, &[edit((0, 2), (1, 0), "")]); assert_eq!(after, "abcd\r\n", "the whole `\\r\\n` goes"); } #[test] fn an_edit_at_the_start_of_the_document() { assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 0), "// ")]), "// wire a;\n"); assert_eq!(apply_changes("wire a;\n", &[edit((0, 0), (0, 4), "logic")]), "logic a;\n"); } #[test] fn an_edit_at_end_of_file() { // The empty last line a trailing newline opens. assert_eq!(apply_changes("a\n", &[edit((1, 0), (1, 0), "b\n")]), "a\nb\n"); } #[test] fn an_insert_at_the_end_of_a_last_line_with_no_trailing_newline() { assert_eq!(apply_changes("endmodule", &[edit((0, 9), (0, 9), "\n")]), "endmodule\n"); } #[test] fn an_edit_into_an_empty_document() { assert_eq!(apply_changes("", &[edit((0, 0), (0, 0), "module m;")]), "module m;"); } #[test] fn a_rangeless_change_replaces_the_whole_document() { assert_eq!(apply_changes("old\n", &[whole("new\n")]), "new\n"); } #[test] fn the_last_of_several_rangeless_changes_wins() { // What the full-sync handler did before this feature, unchanged. assert_eq!(apply_changes("old\n", &[whole("a\n"), whole("b\n"), whole("c\n")]), "c\n"); } #[test] fn a_rangeless_change_resets_what_the_next_range_is_against() { let after = apply_changes("anything\n", &[whole("abc\ndef\n"), edit((1, 1), (1, 2), "X")]); assert_eq!(after, "abc\ndXf\n"); } #[test] fn no_changes_is_the_buffer_unchanged() { assert_eq!(apply_changes("wire a;\n", &[]), "wire a;\n"); } #[test] fn a_line_past_the_end_clamps_to_the_end_of_the_document() { let text = "a\nb\n"; assert_eq!(apply_changes(text, &[edit((99, 0), (99, 5), "X")]), "a\nb\nX"); // And a range that *starts* in the document and ends past it. assert_eq!(apply_changes(text, &[edit((1, 0), (99, 0), "X")]), "a\nX"); } #[test] fn a_character_past_the_end_of_a_line_clamps_to_its_content() { assert_eq!(apply_changes("ab\ncd\n", &[edit((0, 99), (0, 99), "!")]), "ab!\ncd\n"); assert_eq!(apply_changes("ab\r\ncd\r\n", &[edit((0, 99), (0, 99), "!")]), "ab!\r\ncd\r\n"); } #[test] fn a_range_that_runs_backwards_deletes_nothing() { // Clamping `end` up to `start` turns a desynced range into a pure // insertion — the only reading that cannot lose the user's text. assert_eq!(apply_changes("abcdef\n", &[edit((0, 4), (0, 1), "X")]), "abcdXef\n"); assert_eq!(apply_changes("ab\ncd\n", &[edit((1, 1), (0, 0), "X")]), "ab\ncXd\n"); } // ------------------------------------------------------------------ // randomized cross-check against a second implementation // ------------------------------------------------------------------ /// A fixed-seed linear congruential generator — deterministic randomness /// with no dependency. The constants are Knuth's MMIX. struct Lcg(u64); impl Lcg { fn next(&mut self) -> u64 { self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); self.0 >> 33 } fn below(&mut self, n: u64) -> u64 { self.next() % n.max(1) } } /// The same rules, implemented a second way: a flat `Vec` with the /// line starts scanned out of it, rather than byte offsets off a /// `LineIndex`. Sharing no code with `apply_changes` is the point. fn reference_apply(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String { let mut text = text.to_string(); for change in changes { let Some(range) = change.range else { text.clone_from(&change.text); continue; }; let chars: Vec = text.chars().collect(); let start = reference_index(&chars, range.start); let end = reference_index(&chars, range.end).max(start); let mut out: String = chars[..start].iter().collect(); out.push_str(&change.text); out.extend(chars[end..].iter()); text = out; } text } /// The index into `chars` that a position names: lines are `\n`- /// terminated, one `\r` before that terminator is not content, a /// character past a line's content clamps to it, a line past the last /// clamps to the end of the text, and a character landing inside a /// surrogate pair rounds forward past the whole character. fn reference_index(chars: &[char], position: Position) -> usize { let mut starts = vec![0usize]; for (i, c) in chars.iter().enumerate() { if *c == '\n' { starts.push(i + 1); } } let Some(&start) = starts.get(position.line as usize) else { return chars.len(); }; // The line's content ends before its `\n`, and before one `\r`. let mut end = match starts.get(position.line as usize + 1) { Some(&next) => next - 1, None => chars.len(), }; if end > start && chars[end - 1] == '\r' { end -= 1; } let mut units = 0u32; let mut at = start; while at < end && units < position.character { units += chars[at].len_utf16() as u32; at += 1; } at } /// A random document over an alphabet that mixes every width and both /// line endings — including a bare `\r`, which is an ordinary character. fn random_text(rng: &mut Lcg) -> String { const ALPHABET: [&str; 8] = ["a", "b", " ", ";", "\n", "\r\n", "é", "🎉"]; let len = rng.below(24); (0..len).map(|_| ALPHABET[rng.below(8) as usize]).collect() } /// A random change: mostly ranged, occasionally a whole-document reset, /// with positions that are often — but deliberately not always — inside /// the document. fn random_change(rng: &mut Lcg, text: &str) -> TextDocumentContentChangeEvent { if rng.below(10) == 0 { return whole(&random_text(rng)); } let lines = text.matches('\n').count() as u32 + 1; let position = |rng: &mut Lcg| Position { line: rng.below(u64::from(lines) + 2) as u32, character: rng.below(12) as u32, }; let (first, second) = (position(rng), position(rng)); TextDocumentContentChangeEvent { range: Some(Range { start: first, end: second }), range_length: None, text: random_text(rng), } } #[test] fn random_edit_sequences_agree_with_the_reference_model() { let mut rng = Lcg(0x5EED_1CE5); let mut ranged = 0usize; for case in 0..400 { let text = random_text(&mut rng); let mut changes = Vec::new(); let mut running = text.clone(); for _ in 0..rng.below(5) + 1 { let change = random_change(&mut rng, &running); ranged += usize::from(change.range.is_some()); // The next range is against the state this one leaves. running = apply_changes(&running, std::slice::from_ref(&change)); changes.push(change); } let ours = apply_changes(&text, &changes); assert_eq!(ours, reference_apply(&text, &changes), "case {case}, from {text:?}"); assert_eq!(ours, running, "case {case}: one batch equals the changes one at a time"); } assert!(ranged > 500, "the cases must be mostly ranged edits, got {ranged}"); } // ------------------------------------------------------------------ // QA additions (2026-08-26) — see docs/features/incremental-sync/README.md // QA log for the full writeup of each of these. // ------------------------------------------------------------------ #[test] fn a_deletion_starting_at_the_low_surrogate_index_preserves_the_character() { // Character 4 is the low half of `🎉`'s pair (the emoji starts at 3, // ends at 5). A *start* boundary landing there rounds forward past // the whole character, so the emoji is excluded from — and survives // — a deletion that begins mid-pair. let text = "// 🎉 ok\n"; let after = apply_changes(text, &[edit((0, 4), (0, 6), "")]); assert_eq!(after, "// 🎉ok\n", "the emoji stays, only the trailing space is deleted"); } #[test] fn a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character() { // Symmetric case: an *end* boundary on the low half also rounds // forward, but here that means the deletion is widened to swallow // the whole character rather than stopping short of it. let text = "// 🎉 ok\n"; let after = apply_changes(text, &[edit((0, 3), (0, 4), "")]); assert_eq!(after, "// ok\n", "the whole emoji is gone, both flanking spaces remain"); } #[test] fn crlf_split_across_two_changes_in_one_batch_reorders_the_bytes() { // QA finding (docs/features/incremental-sync/README.md QA log, // 2026-08-26): pinning present, *surprising* behavior rather than // asserting it is correct. `convert.rs::line_content_end` treats a // trailing bare `\r` as "not content" whether or not a `\n` will // follow it, so a second change in the same batch that targets "end // of line" after a first change appended a lone `\r` lands *before* // that `\r`, not after it. A client that split one `\r\n` insertion // into two ranged changes this way would get `\n\r`, not `\r\n`. No // real editor's diff algorithm is known to do this, and no panic or // data loss occurs — but if this test's expected string ever needs // to change to `"ab\r\n"`, that is a deliberate fix to // `Positions::offset`/`line_content_end`, not an accidental one. let text = "ab"; let after = apply_changes(text, &[edit((0, 2), (0, 2), "\r"), edit((0, 2), (0, 2), "\n")]); assert_eq!(after, "ab\n\r", "known edge case: see the comment above"); } #[test] fn a_change_covering_the_final_newline_removes_exactly_it() { let text = "a\nb\n"; let after = apply_changes(text, &[edit((1, 1), (2, 0), "")]); assert_eq!(after, "a\nb", "the trailing newline is gone, nothing else is"); } #[test] fn zero_width_inserts_at_the_same_position_compose_in_batch_order() { // Not a bug: per protocol, each change is positioned against what the // previous ones in the batch left, so two inserts naming the same // literal position land with the *second* one first — a client that // wants "12" must advance the second insert's position past the // first's text, exactly as it would need to for a non-zero-width // range. Pinned so a future refactor cannot silently change the // batch's ordering semantics. let text = "x"; let after = apply_changes(text, &[edit((0, 0), (0, 0), "1"), edit((0, 0), (0, 0), "2")]); assert_eq!(after, "21x"); } }