Skip to main content

fatou_parser/parser/
reparse.rs

1//! Incremental reparse: turn a text edit plus the previous parse into a new
2//! tree without re-lexing and re-parsing the whole file.
3//!
4//! Modelled on rust-analyzer's `reparsing.rs` and arity's `reparse.rs`: try
5//! the cheapest strategy first and fall back to progressively more work, with
6//! a full [`parse`](crate::parser::parse) as the always-correct last resort.
7//! The staged plan lives in `TODO.md` (`### Incremental`). Two tiers are in:
8//! the token tier ([`reparse_token`]) relexes an edit confined to a single
9//! `Ident`, comment, or whitespace leaf in isolation and splices it into the
10//! previous green tree ([`try_splice_plain_token`]), or — for a `StringContent`
11//! leaf, whose lexing depends on the enclosing delimiter's mode — relexes the
12//! whole enclosing string literal in isolation and requires it to reproduce its
13//! own token run ([`try_splice_string_content`]); the top-level statement tier
14//! ([`reparse_toplevel`]) reparses the run of `ROOT` children touching the edit
15//! with the public [`parse`](crate::parser::parse) and splices the resulting
16//! children and diagnostics in place, provided the boundary guards prove the
17//! region decoupled from its neighbors.
18//!
19//! Two entry points sit above those tiers. [`reparse_edits`] takes the precise
20//! chain the language server staged from a `didChange` batch and replays it one
21//! edit at a time; [`reparse`] takes a single edit, which is what the host's
22//! `fatou::incremental` recovers with [`diff_edit`] from a pair of whole texts
23//! when no chain is available. The chain is tried first: a collapsed diff of
24//! scattered edits spans everything between them, and the region that produces
25//! is wide enough that [`region_is_too_wide`] declines it outright, where
26//! replaying the chain splices each edit on its own. The Tenet-4 oracle
27//! ([`assert_matches_full_parse`] plus `tests/incremental_reparse.rs`) checks
28//! every splice against a full parse.
29//!
30//! **Correctness invariant (Tenet 4):** a successful reparse must yield a
31//! green tree *and* diagnostics byte-identical to a full parse of the edited
32//! text. A reparse is an output-pure performance hint: the salsa layer only
33//! ever sees text changes, and a miss is a full parse, never an error.
34
35use rowan::{GreenNode, GreenToken, TextRange, TextSize, TokenAtOffset};
36
37use crate::parser::ParseDiagnostic;
38use crate::parser::diagnostics::DIAGNOSTIC_STREAMS;
39use crate::parser::lexer::lex;
40use crate::parser::tree_builder::syntax_kind_for;
41use crate::syntax::{SyntaxKind, SyntaxNode, SyntaxToken};
42
43/// The edit currency, defined in the sibling `edit` module and re-exported
44/// here so `parser::Edit` stays the path the parser layer uses.
45pub use super::edit::{Edit, apply_edits, diff_edit, try_apply_edits};
46
47/// Structural fingerprint of a tree: one line per descendant element with
48/// `kind@range` plus the token text (empty for nodes). Two trees with equal
49/// fingerprints are byte-identical. Oracle/debug support: the Tenet-4 assert
50/// in [`reparse`] and the `tests/incremental_reparse.rs` harness share this
51/// definition so they can never diverge.
52pub fn fingerprint(node: &SyntaxNode) -> String {
53    use std::fmt::Write;
54
55    let mut out = String::new();
56    for el in node.descendants_with_tokens() {
57        let text = el
58            .as_token()
59            .map(|t| t.text().to_string())
60            .unwrap_or_default();
61        let _ = writeln!(out, "{:?}@{:?} {:?}", el.kind(), el.text_range(), text);
62    }
63    out
64}
65
66/// Which strategy produced a [`Reparsed`]. Surfaced for tests and benchmarks.
67/// Ordered cheapest-first, so a chain of reparses can report the most
68/// expensive tier it had to reach with [`Ord::max`].
69#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
70pub enum ReparseTier {
71    /// A single leaf token was relexed in isolation and spliced in place.
72    Token,
73    /// A run of top-level statements was reparsed and spliced under `ROOT`.
74    TopLevel,
75}
76
77/// The result of a successful incremental reparse: the new whole-file green
78/// tree and its parse diagnostics (absolute offsets in the new text).
79#[derive(Debug, Clone)]
80pub struct Reparsed {
81    pub green: GreenNode,
82    pub diagnostics: Vec<ParseDiagnostic>,
83    pub tier: ReparseTier,
84}
85
86/// Attempt an incremental reparse of the previous parse (`prev_green`, parsed
87/// from `prev_text` with `prev_diags`) under `edit`, which transforms
88/// `prev_text` into `new_text`. Returns `None` when no incremental strategy
89/// applies — the caller must then do a full parse.
90///
91/// In debug builds every successful reparse is checked against a full parse
92/// of `new_text` (Tenet 4): tree fingerprint and diagnostics vector must be
93/// identical.
94///
95/// `edit` is not trusted, for the same reason [`reparse_edits`]'s chain is
96/// not: one that does not fit `prev_text` — a stale range, a buffer that moved
97/// underneath it — is rejected here rather than applied at offsets that would
98/// panic on a slice.
99pub fn reparse(
100    prev_text: &str,
101    prev_green: &GreenNode,
102    prev_diags: &[ParseDiagnostic],
103    edit: &Edit,
104    new_text: &str,
105) -> Option<Reparsed> {
106    if !fits(prev_text, edit) {
107        return None;
108    }
109    let result = reparse_impl(prev_text, prev_green, prev_diags, edit, new_text)?;
110    assert_matches_full_parse(&result, new_text);
111    Some(result)
112}
113
114/// Attempt an incremental reparse across a *chain* of edits, each expressed
115/// against the text its predecessors produced — the shape an LSP `didChange`
116/// batch arrives in (see `fatou::text::apply_content_changes` host-side).
117///
118/// This is for the case [`diff_edit`] cannot express: when the edits are
119/// scattered, collapsing them into one spanning edit covers everything between
120/// the first and the last change and blows both tiers' guards, while replaying
121/// them one at a time keeps each splice small. Try this *before* the collapsed
122/// edit: a wide span is the one shape the collapsed edit can never answer, so
123/// offering it first is the difference between a hit and a
124/// `region_is_too_wide` bail (`benches/reparse.rs`).
125///
126/// Fewer than two edits returns `None` immediately: a single edit's span
127/// always contains [`diff_edit`]'s for the same transform, so there is nothing
128/// to gain over the caller's next step.
129///
130/// `edits` is not trusted: a slice that is not the exact transform from
131/// `prev_text` to `new_text` (a stale chain, a buffer that moved underneath
132/// it) is rejected rather than applied at meaningless offsets. Each step is
133/// proven to `fits` the text its predecessors produced *before* that text is
134/// sliced, and the composed result is proven to be `new_text` before anything
135/// is returned — so a stale chain costs at most the splices it got through,
136/// bounded by the caller's chain budget (`incremental::MAX_CHAIN_EDITS`).
137///
138/// Validating step by step rather than pre-folding the whole chain with
139/// [`try_apply_edits`] keeps the replay to one application: the fold would have
140/// to redo every `replace_range` the loop below already does, which on a
141/// 131 KB buffer is the same order as the splice it is guarding
142/// (`benches/reparse.rs`, `precise_chain`).
143pub fn reparse_edits(
144    prev_text: &str,
145    prev_green: &GreenNode,
146    prev_diags: &[ParseDiagnostic],
147    edits: &[Edit],
148    new_text: &str,
149) -> Option<Reparsed> {
150    if edits.len() < 2 {
151        return None;
152    }
153
154    let mut text = prev_text.to_string();
155    let mut green = prev_green.clone();
156    let mut diagnostics = prev_diags.to_vec();
157    let mut tier = ReparseTier::Token;
158
159    for edit in edits {
160        if !fits(&text, edit) {
161            return None;
162        }
163        let next = edit.apply(&text);
164        let step = reparse_impl(&text, &green, &diagnostics, edit, &next)?;
165        tier = tier.max(step.tier);
166        text = next;
167        green = step.green;
168        diagnostics = step.diagnostics;
169    }
170
171    // The chain applied cleanly, but that alone does not make it the transform
172    // the caller is asking about: a stale chain can fit and still land
173    // somewhere else entirely. This check is what the Tenet-4 assert below
174    // relies on to be comparing the same two texts.
175    if text != new_text {
176        return None;
177    }
178
179    let result = Reparsed {
180        green,
181        diagnostics,
182        tier,
183    };
184    assert_matches_full_parse(&result, new_text);
185    Some(result)
186}
187
188/// Tenet 4: a successful reparse yields a green tree *and* diagnostics
189/// byte-identical to a full parse of the edited text.
190///
191/// Debug builds only — this runs a whole `parse` plus two whole-tree
192/// [`fingerprint`] builds, so it is far too expensive to leave on. A chain
193/// asserts once on its composed result rather than once per step, which would
194/// otherwise make a debug-build language server unusable on a large file.
195#[cfg(debug_assertions)]
196fn assert_matches_full_parse(result: &Reparsed, new_text: &str) {
197    let full = crate::parser::parse(new_text);
198    debug_assert_eq!(
199        fingerprint(&SyntaxNode::new_root(result.green.clone())),
200        fingerprint(&full.cst),
201        "Tenet 4: reparse ({:?}) tree differs from full parse",
202        result.tier,
203    );
204    debug_assert_eq!(
205        result.diagnostics, full.diagnostics,
206        "Tenet 4: reparse ({:?}) diagnostics differ from full parse",
207        result.tier,
208    );
209}
210
211#[cfg(not(debug_assertions))]
212fn assert_matches_full_parse(_result: &Reparsed, _new_text: &str) {}
213
214/// Whether `edit`'s range is a well-formed byte range of `text`. Both tiers
215/// slice `prev_text` at the edit's offsets, so an edit that does not fit is a
216/// panic rather than a miss.
217fn fits(text: &str, edit: &Edit) -> bool {
218    edit.range.start <= edit.range.end
219        && edit.range.end <= text.len()
220        && text.is_char_boundary(edit.range.start)
221        && text.is_char_boundary(edit.range.end)
222}
223
224/// Tier dispatch: cheapest first.
225fn reparse_impl(
226    prev_text: &str,
227    prev_green: &GreenNode,
228    prev_diags: &[ParseDiagnostic],
229    edit: &Edit,
230    new_text: &str,
231) -> Option<Reparsed> {
232    reparse_token(prev_text, prev_green, prev_diags, edit)
233        .or_else(|| reparse_toplevel(prev_text, prev_green, prev_diags, edit, new_text))
234}
235
236/// Leaf kinds proved by the isolated single-token relex plus the two join
237/// probes ([`try_splice_plain_token`]). Their text never spans a newline and
238/// their lexing is local enough for those probes to prove a splice sound.
239/// Deliberately absent: `NEWLINE` (statement structure), `CHAR` and the
240/// numeric kinds (quote-context and juxtaposition traps outweigh the win), and
241/// the string prefix/suffix kinds (glued to their delimiters).
242/// `STRING_CONTENT` is handled too, but by a different proof — its lexing
243/// depends on the enclosing delimiter's mode, so it takes the whole-literal
244/// relex in [`try_splice_string_content`] instead.
245const TOKEN_REPARSE_KINDS: &[SyntaxKind] = &[
246    SyntaxKind::IDENT,
247    SyntaxKind::COMMENT,
248    SyntaxKind::BLOCK_COMMENT,
249    SyntaxKind::WHITESPACE,
250];
251
252/// Literal node kinds a `STRING_CONTENT` leaf may sit directly under. Error
253/// recovery can leave one under an `ERROR` node instead, which
254/// [`try_splice_string_content`] rejects: the proof needs the delimiters.
255const STRING_LITERAL_KINDS: &[SyntaxKind] = &[
256    SyntaxKind::STRING_LITERAL,
257    SyntaxKind::CMD_LITERAL,
258    // `var"…"`, a non-standard *identifier*. Nothing keys on its content text
259    // either, so a content edit is as safe here as in a plain string.
260    SyntaxKind::NONSTANDARD_IDENTIFIER,
261];
262
263/// Identifier texts the parser treats structurally even though they lex as
264/// plain `Ident`, so a same-kind relex proves nothing about the tree shape.
265/// True keywords (`where`, `mutable`, …) need no entry: they lex as their own
266/// kinds, and the same-kind guard rejects them.
267///
268/// This list is the one guard here with no compile-time link to what it
269/// describes, and the Tenet-4 oracle only catches an omission if a seeded edit
270/// happens to spell the missing word — so
271/// [`every_contextual_ident_is_listed`](tests::every_contextual_ident_is_listed)
272/// scans the grammar for `Ident`-text comparisons and fails if one names a word
273/// that is not here.
274const CONTEXTUAL_IDENTS: &[&str] = &[
275    "as",        // import alias (structural.rs)
276    "abstract",  // `abstract type` (expr.rs)
277    "primitive", // `primitive type` (expr.rs)
278    "type",      // the `type` in `abstract`/`primitive` type decls (expr.rs)
279    "typegroup", // `typegroup` declaration (expr.rs)
280    "public",    // top-level `public` statement (expr.rs)
281    "var",       // `var"..."` quoting prefix (expr.rs)
282    "in",        // iteration spec / infix operator (expr.rs)
283    "∈",         // Unicode `in` (expr.rs)
284    "isa",       // infix operator (expr.rs)
285    "doc",       // `doc"..."` / `@doc` marker (expr.rs)
286    "outer",     // future `for outer i` support
287];
288
289/// The token tier: when the edit is confined to a single eligible leaf, relex
290/// that leaf in isolation and splice it via [`SyntaxToken::replace_with`].
291///
292/// A pure insertion at a token boundary is ambiguous (it could extend either
293/// neighbor), so both candidates are tried, left first; whichever passes the
294/// guards yields the same new file text, and the guards plus the Tenet-4
295/// oracle arbitrate tree equality. Any guard failure returns `None`, which
296/// the caller answers with a full parse, so every bail here is safe.
297fn reparse_token(
298    prev_text: &str,
299    prev_green: &GreenNode,
300    prev_diags: &[ParseDiagnostic],
301    edit: &Edit,
302) -> Option<Reparsed> {
303    let root = SyntaxNode::new_root(prev_green.clone());
304    let (s, e) = (edit.range.start, edit.range.end);
305    let mut candidates: Vec<SyntaxToken> = Vec::with_capacity(2);
306    if s == e {
307        match root.token_at_offset(TextSize::new(s as u32)) {
308            TokenAtOffset::None => return None,
309            TokenAtOffset::Single(t) => candidates.push(t),
310            TokenAtOffset::Between(l, r) => candidates.extend([l, r]),
311        }
312    } else {
313        // A range spanning a token boundary covers a node, not a token, and
314        // bails here.
315        let range = TextRange::new(TextSize::new(s as u32), TextSize::new(e as u32));
316        candidates.push(root.covering_element(range).into_token()?);
317    }
318
319    candidates
320        .into_iter()
321        .find_map(|token| try_splice_token(prev_text, prev_diags, edit, &token))
322}
323
324/// Dispatch one candidate leaf to the proof its kind takes.
325fn try_splice_token(
326    prev_text: &str,
327    prev_diags: &[ParseDiagnostic],
328    edit: &Edit,
329    token: &SyntaxToken,
330) -> Option<Reparsed> {
331    match token.kind() {
332        SyntaxKind::STRING_CONTENT => try_splice_string_content(prev_text, prev_diags, edit, token),
333        kind if TOKEN_REPARSE_KINDS.contains(&kind) => {
334            try_splice_plain_token(prev_text, prev_diags, edit, token)
335        }
336        _ => None,
337    }
338}
339
340/// Run the stage-2 guards against one candidate leaf and splice on success.
341fn try_splice_plain_token(
342    prev_text: &str,
343    prev_diags: &[ParseDiagnostic],
344    edit: &Edit,
345    token: &SyntaxToken,
346) -> Option<Reparsed> {
347    // Newline ban: these kinds either cannot contain a newline or (block
348    // comments) rarely see one edited, and a newline moves statement
349    // boundaries, so bail early. The single-token relex guard below would
350    // catch most of these anyway; this is the cheap early-out. It does not
351    // apply to `STRING_CONTENT`, whose run legitimately spans newlines and
352    // whose proof does not depend on line structure.
353    if edit.insert.contains(['\n', '\r']) || prev_text[edit.range.clone()].contains(['\n', '\r']) {
354        return None;
355    }
356
357    let tr = token.text_range();
358    let (t0, t1) = (usize::from(tr.start()), usize::from(tr.end()));
359
360    // The leaf's new text, with the edit applied at its relative offset. A
361    // whole-leaf deletion leaves it empty, which the relex guard rejects.
362    let mut new_leaf = token.text().to_string();
363    new_leaf.replace_range((edit.range.start - t0)..(edit.range.end - t0), &edit.insert);
364
365    // Isolated relex: still exactly one token, same kind, spanning all of it.
366    // This alone rejects kind flips (ident ⇒ keyword, whitespace ⇒ newline)
367    // and splits (`=#` typed into a block comment).
368    let relexed = lex(&new_leaf);
369    let [only] = relexed.as_slice() else {
370        return None;
371    };
372    if only.start != 0 || only.end != new_leaf.len() || syntax_kind_for(only.kind) != token.kind() {
373        return None;
374    }
375
376    // Contextual identifiers parse structurally, so text changes into or out
377    // of one can reshape the tree under an unchanged token kind.
378    if token.kind() == SyntaxKind::IDENT
379        && (CONTEXTUAL_IDENTS.contains(&token.text())
380            || CONTEXTUAL_IDENTS.contains(&new_leaf.as_str()))
381    {
382        return None;
383    }
384
385    // Forward join: the next source character must not extend the token
386    // (`r` + `"…"` fusing into a prefixed string, an unterminated block
387    // comment swallowing its neighbor). At EOF probe with `\n`, which no
388    // eligible kind can absorb, so a leaf left unterminated at EOF (`#=` typed
389    // into the last block comment) still fails here.
390    let next_char = prev_text[t1..].chars().next().unwrap_or('\n');
391    let mut probe = new_leaf.clone();
392    probe.push(next_char);
393    let first = lex(&probe).into_iter().next()?;
394    if first.end != new_leaf.len() || syntax_kind_for(first.kind) != token.kind() {
395        return None;
396    }
397
398    // Backward join: the previous leaf plus the new text must relex to the
399    // same two tokens. Catches juxtaposition fusing (`2` + `e10` ⇒ one
400    // `Float`), and conservatively bails whenever the previous leaf's
401    // isolated lex diverges from its in-context one (e.g. a closing string
402    // delimiter reopening as a string).
403    if let Some(prev) = token.prev_token() {
404        let mut probe = prev.text().to_string();
405        let boundary = probe.len();
406        probe.push_str(&new_leaf);
407        let relexed = lex(&probe);
408        let [a, b] = relexed.as_slice() else {
409            return None;
410        };
411        if a.end != boundary
412            || syntax_kind_for(a.kind) != prev.kind()
413            || b.end != probe.len()
414            || syntax_kind_for(b.kind) != token.kind()
415        {
416            return None;
417        }
418    }
419
420    // Keep diagnostic remapping trivial: bail when any diagnostic touches the
421    // leaf, boundaries included. A clean same-kind relex introduces none of
422    // its own, so the rest keep their meaning and only need shifting.
423    if prev_diags.iter().any(|d| d.start <= t1 && d.end >= t0) {
424        return None;
425    }
426    let delta = edit.delta();
427    let shift = |pos: usize| (pos as isize + delta) as usize;
428    let diagnostics = prev_diags
429        .iter()
430        .map(|d| {
431            let mut d = d.clone();
432            if d.start >= t1 {
433                d.start = shift(d.start);
434                d.end = shift(d.end);
435            }
436            d
437        })
438        .collect();
439
440    let green = token.replace_with(GreenToken::new(token.kind().into(), &new_leaf));
441    Some(Reparsed {
442        green,
443        diagnostics,
444        tier: ReparseTier::Token,
445    })
446}
447
448/// `text` — the slice of the previous buffer starting at absolute offset
449/// `base` — with `edit` applied at its relative offset.
450fn edited_slice(text: &str, base: usize, edit: &Edit) -> String {
451    let mut out = text.to_string();
452    out.replace_range(
453        (edit.range.start - base)..(edit.range.end - base),
454        &edit.insert,
455    );
456    out
457}
458
459/// Every token under `node` as `(kind, end)`, with `end` relative to the node
460/// start. Tokens tile the node's text contiguously from `0` and the tree
461/// synthesizes none of its own (`tree_builder`), so this *is* the lexer's
462/// token run for that span and the ends alone pin every range.
463fn literal_token_ends(node: &SyntaxNode) -> Vec<(SyntaxKind, usize)> {
464    let base = usize::from(node.text_range().start());
465    node.descendants_with_tokens()
466        .filter_map(|el| el.into_token())
467        .map(|t| (t.kind(), usize::from(t.text_range().end()) - base))
468        .collect()
469}
470
471/// Whether an isolated [`lex`] of `text` reproduces `expected`: the same kinds
472/// in the same order, with the same ends, covering all of `text`. `grown`
473/// names the index whose end — and every end after it — is expected to have
474/// moved by that delta.
475fn relex_matches(
476    text: &str,
477    expected: &[(SyntaxKind, usize)],
478    grown: Option<(usize, isize)>,
479) -> bool {
480    let tokens = lex(text);
481    if tokens.len() != expected.len() {
482        return false;
483    }
484    for (i, (got, &(kind, end))) in tokens.iter().zip(expected).enumerate() {
485        let shift = match grown {
486            Some((from, delta)) if i >= from => delta,
487            _ => 0,
488        };
489        // A shift that runs an end past zero cannot describe any token, so it
490        // simply fails to match rather than wrapping into a huge `usize`.
491        let Ok(want) = usize::try_from(end as isize + shift) else {
492            return false;
493        };
494        if syntax_kind_for(got.kind) != kind || got.end != want {
495            return false;
496        }
497    }
498    tokens.last().is_some_and(|t| t.end == text.len())
499}
500
501/// The token tier's `STRING_CONTENT` path: relex the *whole enclosing string
502/// literal* in isolation and require it to reproduce its own token run with
503/// only the edited content leaf resized.
504///
505/// A content leaf cannot take [`try_splice_plain_token`]'s proof, because both
506/// of its probes assume a leaf that lexes the same standing alone: `abc` in
507/// isolation is an `Ident`, never `StringContent`, and a leaf following an
508/// interpolation (`"a$x b"`) has an `Ident` before it, which blows the
509/// two-token backward probe. Taking the delimiters along instead puts the
510/// isolated lexer into the right mode for free, so triple/raw/prefixed need no
511/// hand-written character table.
512///
513/// Why this is sound. Nothing outside the lexer reads `StringContent` *text*:
514/// the parser only pushes the token, docstring eligibility tests the first
515/// token's kind, and the flag passes are kind-based — so preserving the node's
516/// token-kind sequence preserves both the tree and the diagnostics. (Nor does
517/// triple-quoted dedenting intrude: that lives in the test-only JuliaSyntax
518/// projector, which rebuilds the string at projection time.) Given that:
519///
520/// * The bytes before the node are unchanged and the lexer is a deterministic
521///   left-to-right machine, so its mode stack at the node start is identical.
522///   That subsumes the backward join probe.
523/// * The relex proves the kinds are unchanged and that only the edited leaf's
524///   end, and the ends after it, moved by the delta. The bytes after the leaf
525///   *within* the node are therefore byte-identical — including the close
526///   delimiter and any suffix — so the mode stack is back to its starting
527///   depth at the node end and the rest of the file lexes identically, merely
528///   shifted. That subsumes the forward join probe, which could not have
529///   expressed a delimiter-plus-suffix tail with its one probe character
530///   anyway.
531///
532/// The second bullet needs the literal to be *terminated*, which gets its own
533/// check rather than leaning on an `UnterminatedLiteral` diagnostic's anchor.
534///
535/// Newlines are allowed here, unlike in [`try_splice_plain_token`]: a content
536/// run spans them freely (a triple-quoted body, and a single-quoted one too —
537/// no newline stops the run, which is why an unterminated literal reaches EOF),
538/// and a newline *inside* one emits no `NEWLINE` token, so no statement
539/// boundary moves. Diagnostics are byte offsets and do not care about lines.
540/// That is what puts Enter in a docstring on this tier.
541///
542/// The faithfulness relex (the unedited node text must reproduce the node's own
543/// tokens) is what makes the second bullet an induction rather than an
544/// assumption: an isolated [`lex`] starts from an empty mode stack and no token
545/// history, while in context the node may sit under a `Str`/`Interp` frame and
546/// `prev_ends_value` consults the preceding token. Proving faithfulness for the
547/// old text, plus an identical kind sequence, carries it to the new text.
548fn try_splice_string_content(
549    prev_text: &str,
550    prev_diags: &[ParseDiagnostic],
551    edit: &Edit,
552    token: &SyntaxToken,
553) -> Option<Reparsed> {
554    let node = token.parent()?;
555    if !STRING_LITERAL_KINDS.contains(&node.kind()) {
556        return None;
557    }
558    let nr = node.text_range();
559    let (n0, n1) = (usize::from(nr.start()), usize::from(nr.end()));
560
561    // Bail when any diagnostic touches the literal, boundaries included. The
562    // relex proves the token sequence unchanged, so the four string-related
563    // kinds would in fact survive a shift — but "no diagnostic may touch the
564    // literal we splice" is an invariant that keeps holding as diagnostics are
565    // added, and what it gives up (`x = "abc`, `"a"b`, `var"x"y`) is the error
566    // path, not the keystroke path.
567    //
568    // This runs *first*, before either relex: an unterminated literal runs to
569    // EOF, so its node is the rest of the file, and every keystroke inside one
570    // would otherwise pay two whole-file lexes to learn what a diagnostic
571    // already says (`benches/reparse.rs`, `rejected_attempt`).
572    if prev_diags.iter().any(|d| d.start <= n1 && d.end >= n0) {
573        return None;
574    }
575
576    let expected = literal_token_ends(&node);
577    let tr = token.text_range();
578    let (t0, t1) = (usize::from(tr.start()), usize::from(tr.end()));
579    // Ends are unique (tokens tile with positive width), so this identifies the
580    // leaf by index — which the edited relex then pins as the one that resized.
581    let leaf = expected
582        .iter()
583        .position(|&(kind, end)| kind == SyntaxKind::STRING_CONTENT && end == t1 - n0)?;
584
585    // Terminated: a matching close delimiter must follow the leaf. A prefixed
586    // literal's suffix is lexed as part of the same node, so nothing but the
587    // close can end the run.
588    let close = if node.kind() == SyntaxKind::CMD_LITERAL {
589        SyntaxKind::CMD_DELIM_CLOSE
590    } else {
591        SyntaxKind::STRING_DELIM_CLOSE
592    };
593    if !expected[leaf + 1..].iter().any(|&(kind, _)| kind == close) {
594        return None;
595    }
596
597    let old_node_text = &prev_text[n0..n1];
598    if !relex_matches(old_node_text, &expected, None) {
599        return None;
600    }
601    let delta = edit.delta();
602    let edited = edited_slice(old_node_text, n0, edit);
603    if !relex_matches(&edited, &expected, Some((leaf, delta))) {
604        return None;
605    }
606
607    let new_leaf = &edited[(t0 - n0)..((t1 - n0) as isize + delta) as usize];
608
609    // Every surviving diagnostic lies wholly outside the literal, so the ones
610    // past it shift and the rest keep their positions.
611    let shift = |pos: usize| (pos as isize + delta) as usize;
612    let diagnostics = prev_diags
613        .iter()
614        .map(|d| {
615            let mut d = d.clone();
616            if d.start >= n1 {
617                d.start = shift(d.start);
618                d.end = shift(d.end);
619            }
620            d
621        })
622        .collect();
623
624    let green = token.replace_with(GreenToken::new(SyntaxKind::STRING_CONTENT.into(), new_leaf));
625    Some(Reparsed {
626        green,
627        diagnostics,
628        tier: ReparseTier::Token,
629    })
630}
631
632/// Whether a token kind is trivia. Mirrors `TokKind::is_trivia` on the CST
633/// side.
634fn is_trivia_kind(kind: SyntaxKind) -> bool {
635    matches!(
636        kind,
637        SyntaxKind::WHITESPACE
638            | SyntaxKind::NEWLINE
639            | SyntaxKind::COMMENT
640            | SyntaxKind::BLOCK_COMMENT
641    )
642}
643
644/// Whether a `ROOT` child carries statement-level content: a positive-width
645/// node, or a loose non-trivia token (the unparseable-token recovery emits
646/// bare tokens at the root, without an `ERROR` wrapper). Zero-width nodes and
647/// trivia are gap material.
648fn is_significant_child(el: &crate::syntax::SyntaxElement) -> bool {
649    match el {
650        rowan::NodeOrToken::Node(n) => !n.text_range().is_empty(),
651        rowan::NodeOrToken::Token(t) => !is_trivia_kind(t.kind()),
652    }
653}
654
655/// Below this the tier always tries, whatever fraction of the file the region
656/// is: on a small file every parse in play is small, and the fraction test
657/// alone would refuse the common case of a file with one or two statements.
658const REGION_ALWAYS_TRY_BYTES: usize = 4 * 1024;
659
660/// Above this fraction of the file, a region is wide enough that answering it
661/// costs more than the full parse it is trying to avoid.
662const REGION_MAX_FRACTION: usize = 4;
663
664/// Whether a region is too wide to be worth attempting. The tier answers a
665/// region with a fragment parse of it *plus* up to three neighbor-sized
666/// boundary parses, so the attempt scales with the region — and a miss pays
667/// the full parse on top. A collapsed [`diff_edit`] of scattered edits spans
668/// everything between the first and the last, which is exactly how a region
669/// grows to most of the file; on ~131 KB that attempt cost about 12 ms against
670/// a 6.3 ms full parse (`benches/reparse.rs`, `scattered_via_diff_edit`).
671/// Bailing on the cheap evidence — the region's byte span, known before any
672/// parse — caps the loss at the full parse the caller was going to pay anyway.
673///
674/// This is a performance guard only. Like every other bail here it returns the
675/// caller to a full parse, so it cannot affect what a reparse yields.
676fn region_is_too_wide(region_len: usize, text_len: usize) -> bool {
677    region_len > REGION_ALWAYS_TRY_BYTES && region_len > text_len / REGION_MAX_FRACTION
678}
679
680/// The reparse region at the top-level tier: a contiguous run of `ROOT`
681/// children (statement nodes and loose trivia tokens both), identified by
682/// child index and old-text byte range. The boundary child kinds
683/// disambiguate zero-width diagnostics anchored exactly on a boundary.
684struct Region {
685    first: usize,
686    last: usize,
687    start: usize,
688    end: usize,
689    first_is_node: bool,
690    last_is_node: bool,
691}
692
693/// Select the contiguous run of `ROOT` children whose closed range touches
694/// the edit. Closed-interval touch makes boundary insertions extend into the
695/// neighbor they abut (blank-line typing selects the surrounding newline
696/// tokens; deleting a newline pulls in both neighbor statements). A
697/// zero-width child abutting the region start is absorbed: stray-closer
698/// recovery pairs a zero-width `ERROR` with its byte-bearing run at the same
699/// offset, and the fragment reparse regenerates both, so leaving it outside
700/// would duplicate it. `None` when the run covers every child (the fragment
701/// reparse would be the full parse) or `ROOT` is empty.
702fn select_region(root: &SyntaxNode, edit: &Edit) -> Option<Region> {
703    let (s, e) = (edit.range.start, edit.range.end);
704    let children: Vec<_> = root.children_with_tokens().collect();
705    let touches = |el: &crate::syntax::SyntaxElement| {
706        let r = el.text_range();
707        usize::from(r.start()) <= e && usize::from(r.end()) >= s
708    };
709    let mut first = children.iter().position(touches)?;
710    let last = children.len() - 1 - children.iter().rev().position(touches)?;
711
712    let start = usize::from(children[first].text_range().start());
713    while first > 0
714        && children[first - 1].text_range() == TextRange::empty(TextSize::new(start as u32))
715    {
716        first -= 1;
717    }
718
719    if first == 0 && last == children.len() - 1 {
720        return None;
721    }
722    Some(Region {
723        first,
724        last,
725        start,
726        end: usize::from(children[last].text_range().end()),
727        first_is_node: children[first].as_node().is_some(),
728        last_is_node: children[last].as_node().is_some(),
729    })
730}
731
732/// The nearest positive-width `ROOT` child nodes outside the region. Trivia
733/// tokens are gap material, and a zero-width `ERROR` node contributes no text
734/// (taking one as the forward neighbor would make the boundary guard
735/// vacuous), so both are skipped.
736fn sibling_nodes(root: &SyntaxNode, region: &Region) -> (Option<SyntaxNode>, Option<SyntaxNode>) {
737    let positive_node =
738        |el: crate::syntax::SyntaxElement| el.into_node().filter(|n| !n.text_range().is_empty());
739    let prev = root
740        .children_with_tokens()
741        .take(region.first)
742        .filter_map(positive_node)
743        .last();
744    let next = root
745        .children_with_tokens()
746        .skip(region.last + 1)
747        .find_map(positive_node);
748    (prev, next)
749}
750
751/// Whether no `ROOT` child (node or loose token) of `cst` straddles `seam`.
752/// Children tile the text, so no-straddle is equivalent to a boundary
753/// existing exactly at the seam: the two sides parse independently. A
754/// straddling node is a cross-boundary statement (trailing-operator
755/// continuation, a docstring fold, an unterminated block absorbing its
756/// neighbor); a straddling token is a lexical fusion (`#=` swallowing
757/// trailing trivia, an unterminated string).
758fn no_straddle(cst: &SyntaxNode, seam: usize) -> bool {
759    let seam = TextSize::new(seam as u32);
760    cst.children_with_tokens().all(|el| {
761        let r = el.text_range();
762        !(r.start() < seam && seam < r.end())
763    })
764}
765
766/// Splice the fragment's diagnostics into the previous ones, stream by
767/// stream ([`DiagnosticKind::stream`](crate::parser::diagnostics::DiagnosticKind::stream)):
768/// keep those before the region, drop those the fragment reparse
769/// regenerates, and shift those after by the edit delta. Emission order
770/// within a stream is positional across statements (the drive loop is
771/// per-line sequential, the flag passes walk in document order), so
772/// `before ++ fragment ++ after` per stream, concatenated in stream order,
773/// reproduces a full parse's vector.
774///
775/// A zero-width diagnostic exactly on a region boundary is ambiguous by
776/// position alone and is disambiguated by the boundary child's kind: a
777/// statement node owns a start-anchored marker at `start` (`const x` at the
778/// region's front) and an end-anchored one at `end`, while a trivia boundary
779/// child owns nothing, so the marker belongs to the statement just outside.
780/// This is sound only because the decoupling guards already rejected
781/// zero-gap node adjacency at the boundaries. A diagnostic genuinely
782/// straddling a boundary aborts the splice (`None`); regions are whole
783/// children and diagnostics never outgrow their statement, so this arm
784/// should be unreachable and is purely defensive.
785///
786/// A stream index outside [`DIAGNOSTIC_STREAMS`] aborts the splice too, rather
787/// than indexing out of bounds. [`DiagnosticKind::stream`] is an exhaustive
788/// match today, so this cannot fire — but a bail returns the caller to a full
789/// parse, whereas a panic here takes down an analysis query, and this module
790/// buys its whole safety argument from every failure being a bail.
791fn splice_diagnostics(
792    prev_diags: &[ParseDiagnostic],
793    frag_diags: &[ParseDiagnostic],
794    region: &Region,
795    delta: isize,
796) -> Option<Vec<ParseDiagnostic>> {
797    enum Class {
798        Before,
799        Drop,
800        After,
801    }
802    let classify = |d: &ParseDiagnostic| -> Option<Class> {
803        let (rs, re) = (region.start, region.end);
804        if d.start == d.end && d.start == rs {
805            return Some(if region.first_is_node {
806                Class::Drop
807            } else {
808                Class::Before
809            });
810        }
811        if d.start == d.end && d.start == re {
812            return Some(if region.last_is_node {
813                Class::Drop
814            } else {
815                Class::After
816            });
817        }
818        if d.end <= rs {
819            return Some(Class::Before);
820        }
821        if d.start >= re {
822            return Some(Class::After);
823        }
824        if d.start >= rs && d.end <= re {
825            return Some(Class::Drop);
826        }
827        None
828    };
829
830    let mut before: [Vec<ParseDiagnostic>; DIAGNOSTIC_STREAMS] = Default::default();
831    let mut after: [Vec<ParseDiagnostic>; DIAGNOSTIC_STREAMS] = Default::default();
832    for d in prev_diags {
833        let class = classify(d)?;
834        let stream = d.kind.stream();
835        if stream >= DIAGNOSTIC_STREAMS {
836            debug_assert!(false, "diagnostic stream {stream} is out of range");
837            return None;
838        }
839        match class {
840            Class::Before => before[stream].push(d.clone()),
841            Class::Drop => {}
842            Class::After => {
843                let mut d = d.clone();
844                d.start = (d.start as isize + delta) as usize;
845                d.end = (d.end as isize + delta) as usize;
846                after[stream].push(d);
847            }
848        }
849    }
850
851    let mut out = Vec::with_capacity(prev_diags.len() + frag_diags.len());
852    for stream in 0..DIAGNOSTIC_STREAMS {
853        out.append(&mut before[stream]);
854        out.extend(
855            frag_diags
856                .iter()
857                .filter(|d| d.kind.stream() == stream)
858                .map(|d| {
859                    let mut d = d.clone();
860                    d.start += region.start;
861                    d.end += region.start;
862                    d
863                }),
864        );
865        out.append(&mut after[stream]);
866    }
867    Some(out)
868}
869
870/// The top-level statement tier: reparse the run of `ROOT` children touching
871/// the edit with the public [`parse`](crate::parser::parse) (which reruns
872/// `fold_docstrings` and the flag passes on the fragment) and splice the
873/// resulting children and diagnostics in place.
874///
875/// The guards, in order: decoupling scans require a newline between each
876/// untouched sibling statement and the fragment's non-trivia content, because
877/// the drive loop's per-line junk recovery couples same-line siblings; the
878/// boundary parses then prove the seam survives — the neighbor plus the
879/// actual gap bytes plus the fragment must parse with a boundary exactly at
880/// the old one, which rejects trailing-operator continuation, docstring
881/// folds, forward absorption by an unterminated block, and lexical fusion.
882/// Diagnostics splice last (see [`splice_diagnostics`]).
883fn reparse_toplevel(
884    prev_text: &str,
885    prev_green: &GreenNode,
886    prev_diags: &[ParseDiagnostic],
887    edit: &Edit,
888    new_text: &str,
889) -> Option<Reparsed> {
890    let root = SyntaxNode::new_root(prev_green.clone());
891    let region = select_region(&root, edit)?;
892    if region_is_too_wide(region.end - region.start, prev_text.len()) {
893        return None;
894    }
895    let delta = edit.delta();
896    let frag_end = (region.end as isize + delta) as usize;
897    let fragment = &new_text[region.start..frag_end];
898
899    let frag = crate::parser::parse(fragment);
900    let (prev_node, next_node) = sibling_nodes(&root, &region);
901
902    let positive_nodes = |node: &SyntaxNode| {
903        node.children_with_tokens()
904            .filter_map(|el| el.into_node())
905            .filter(|n| !n.text_range().is_empty())
906    };
907
908    // Backward decoupling: a newline must separate the last significant
909    // content before the region (a statement node or a loose junk token, not
910    // just `prev_node`) from the fragment's first significant content (or
911    // all of a trivia-only fragment). The drive loop's per-line junk
912    // recovery couples same-line siblings, and the newline often lives in
913    // the unchanged gap outside the region, so scan `new_text`.
914    let prev_significant_end = root
915        .children_with_tokens()
916        .take(region.first)
917        .filter(is_significant_child)
918        .last()
919        .map(|el| usize::from(el.text_range().end()));
920    if let Some(from) = prev_significant_end {
921        let anchor = frag
922            .cst
923            .children_with_tokens()
924            .find(is_significant_child)
925            .map(|el| usize::from(el.text_range().start()))
926            .unwrap_or(fragment.len());
927        if !new_text[from..region.start + anchor].contains('\n') {
928            return None;
929        }
930    }
931
932    // Forward decoupling, in both texts: the next statement is kept, not
933    // reparsed, so its line must have been decoupled from the old region
934    // content too (deleting `x` from `x y` puts the kept junk `y` at line
935    // start, where a full parse reads it as a plain statement). The new-text
936    // scan anchors at the fragment's last statement *node* end, not its last
937    // token: an unterminated bracket consumes the separating newline into
938    // the statement, and a consumed newline decouples nothing.
939    if let Some(next) = &next_node {
940        let anchor = frag
941            .cst
942            .children_with_tokens()
943            .filter(is_significant_child)
944            .last()
945            .map(|el| usize::from(el.text_range().end()))
946            .unwrap_or(0);
947        let to = (usize::from(next.text_range().start()) as isize + delta) as usize;
948        if !new_text[region.start + anchor..to].contains('\n') {
949            return None;
950        }
951
952        let old_anchor = root
953            .children_with_tokens()
954            .skip(region.first)
955            .take(region.last + 1 - region.first)
956            .filter(is_significant_child)
957            .last()
958            .map(|el| usize::from(el.text_range().end()))
959            .or(prev_significant_end)
960            .unwrap_or(0);
961        if !prev_text[old_anchor..usize::from(next.text_range().start())].contains('\n') {
962            return None;
963        }
964    }
965
966    // Cross-region coupling: when the fragment carries no significant content,
967    // the two neighbors sit next to each other across it and can couple in a
968    // way neither boundary parse can see, because each concatenation contains
969    // only one of them. Deleting the `]` from `"doc" ]\nf() = 1` is the shape:
970    // the stray closer was all that kept the string from being the statement
971    // below it, and once it goes `fold_docstrings` folds the pair into a `DOC`
972    // spanning both seams. Parse the neighbors together, through the real gap
973    // bytes, and require both seams to survive. Only reachable when the region
974    // is reduced to trivia, so the extra parse is rare and neighbor-sized.
975    if !frag
976        .cst
977        .children_with_tokens()
978        .any(|el| is_significant_child(&el))
979        && let (Some(prev), Some(next)) = (&prev_node, &next_node)
980    {
981        let back_gap = &prev_text[usize::from(prev.text_range().end())..region.start];
982        let fwd_gap = &prev_text[region.end..usize::from(next.text_range().start())];
983        let guard = format!(
984            "{}{}{}{}{}",
985            prev.text(),
986            back_gap,
987            fragment,
988            fwd_gap,
989            next.text()
990        );
991        let back_seam = usize::from(prev.text_range().len()) + back_gap.len();
992        let fwd_seam = back_seam + fragment.len();
993        let parsed = crate::parser::parse(&guard);
994        if !no_straddle(&parsed.cst, back_seam) || !no_straddle(&parsed.cst, fwd_seam) {
995            return None;
996        }
997    }
998
999    // A zero-width diagnostic exactly on a guard seam is disambiguated by
1000    // the fragment's own boundary child, mirroring `splice_diagnostics`: a
1001    // statement node owns a start-anchored marker at its start and an
1002    // end-anchored one at its end; a trivia boundary child owns nothing.
1003    let frag_starts_with_node = frag
1004        .cst
1005        .children_with_tokens()
1006        .next()
1007        .is_some_and(|el| el.as_node().is_some());
1008    let frag_ends_with_node = frag
1009        .cst
1010        .children_with_tokens()
1011        .last()
1012        .is_some_and(|el| el.as_node().is_some());
1013
1014    // Backward boundary parse: previous statement + gap trivia + fragment
1015    // must keep a boundary exactly at the old one, and the fragment must
1016    // parse in context with exactly the diagnostics it produced in
1017    // isolation.
1018    if let Some(prev) = &prev_node {
1019        let back_gap = &prev_text[usize::from(prev.text_range().end())..region.start];
1020        let guard = format!("{}{}{}", prev.text(), back_gap, fragment);
1021        let seam = guard.len() - fragment.len();
1022        let parsed = crate::parser::parse(&guard);
1023        if !no_straddle(&parsed.cst, seam) {
1024            return None;
1025        }
1026        let guard_frag: Vec<ParseDiagnostic> = parsed
1027            .diagnostics
1028            .iter()
1029            .filter(|d| {
1030                d.start > seam
1031                    || (d.start == seam && d.end > seam)
1032                    || (d.start == seam && d.end == seam && frag_starts_with_node)
1033            })
1034            .map(|d| {
1035                let mut d = d.clone();
1036                d.start -= seam;
1037                d.end -= seam;
1038                d
1039            })
1040            .collect();
1041        if guard_frag != frag.diagnostics {
1042            return None;
1043        }
1044    }
1045
1046    // Forward boundary parse: fragment + gap trivia + next statement (or the
1047    // trailing trivia to EOF when no statement follows). Three checks
1048    // against one parse of the concatenation: no element straddles the seam;
1049    // the fragment reparses exactly as it did in isolation (an EOF-adjacent
1050    // junk run wraps differently once text follows it); and the kept next
1051    // statement reappears untouched — same start, kind, and length — since a
1052    // fragment ending in an unterminated bracket can consume the separating
1053    // newline and demote the next line to flat junk without anything
1054    // straddling the seam.
1055    let tail = match &next_node {
1056        Some(next) => {
1057            let gap = &prev_text[region.end..usize::from(next.text_range().start())];
1058            format!("{}{}", gap, next.text())
1059        }
1060        None => prev_text[region.end..].to_string(),
1061    };
1062    if !tail.is_empty() {
1063        let guard = format!("{fragment}{tail}");
1064        let seam = fragment.len();
1065        let parsed = crate::parser::parse(&guard);
1066        if !no_straddle(&parsed.cst, seam) {
1067            return None;
1068        }
1069        let signature = |el: crate::syntax::SyntaxElement| {
1070            (
1071                usize::from(el.text_range().start()),
1072                el.as_node().is_some(),
1073                el.kind(),
1074                usize::from(el.text_range().len()),
1075            )
1076        };
1077        let frag_sig: Vec<_> = frag.cst.children_with_tokens().map(signature).collect();
1078        let pre_seam: Vec<_> = parsed
1079            .cst
1080            .children_with_tokens()
1081            .filter(|el| {
1082                let r = el.text_range();
1083                // A zero-width child exactly at the seam pairs with a junk
1084                // run on the far side; it belongs to the tail.
1085                usize::from(r.end()) <= seam && !(r.is_empty() && usize::from(r.start()) == seam)
1086            })
1087            .map(signature)
1088            .collect();
1089        if pre_seam != frag_sig {
1090            return None;
1091        }
1092        // The fragment's in-context diagnostics must also match: a trailing
1093        // token at the fragment's EOF can emit differently once text follows
1094        // it (`:` with a newline after it flags `QuoteColonWhitespace`; at
1095        // EOF it does not).
1096        let guard_frag: Vec<ParseDiagnostic> = parsed
1097            .diagnostics
1098            .iter()
1099            .filter(|d| {
1100                d.end < seam
1101                    || (d.end == seam && d.start < seam)
1102                    || (d.start == seam && d.end == seam && frag_ends_with_node)
1103            })
1104            .cloned()
1105            .collect();
1106        if guard_frag != frag.diagnostics {
1107            return None;
1108        }
1109        if let Some(next) = &next_node {
1110            let gap_len = usize::from(next.text_range().start()) - region.end;
1111            let reparsed_next =
1112                positive_nodes(&parsed.cst).find(|n| usize::from(n.text_range().start()) >= seam);
1113            let intact = reparsed_next.is_some_and(|n| {
1114                usize::from(n.text_range().start()) == seam + gap_len
1115                    && n.kind() == next.kind()
1116                    && n.text_range().len() == next.text_range().len()
1117            });
1118            if !intact {
1119                return None;
1120            }
1121        }
1122    }
1123
1124    let diagnostics = splice_diagnostics(prev_diags, &frag.diagnostics, &region, delta)?;
1125
1126    let frag_green = frag.cst.green();
1127    let green = prev_green.splice_children(
1128        region.first..=region.last,
1129        frag_green.children().map(|c| c.to_owned()),
1130    );
1131    Some(Reparsed {
1132        green,
1133        diagnostics,
1134        tier: ReparseTier::TopLevel,
1135    })
1136}
1137
1138#[cfg(test)]
1139mod tests {
1140    use super::*;
1141
1142    fn edit(range: std::ops::Range<usize>, insert: &str) -> Edit {
1143        Edit {
1144            range,
1145            insert: insert.to_string(),
1146        }
1147    }
1148
1149    /// The grammar decides some tree shapes by an identifier's *text*, and the
1150    /// token tier's same-kind relex cannot see such a change — so every such
1151    /// word has to be in [`CONTEXTUAL_IDENTS`]. Nothing in the type system says
1152    /// so, and the oracle only surfaces an omission by luck, so scan the
1153    /// grammar for the two spellings those comparisons take and check the words
1154    /// they name.
1155    ///
1156    /// The known words are asserted to have been *found*, not just listed: if a
1157    /// comparison is ever rewritten into a shape this scan does not recognize,
1158    /// the test fails loudly rather than quietly covering nothing.
1159    #[test]
1160    fn every_contextual_ident_is_listed() {
1161        // `t.kind == TokKind::Ident && t.text == "word"` and the `matches!`
1162        // form `matches!(t.text.as_ref(), "word" | "other")`. Both are keyed on
1163        // `t.text`, which is what makes them text-structural.
1164        fn words_after(haystack: &str, marker: &str) -> Vec<String> {
1165            let mut out = Vec::new();
1166            for tail in haystack.split(marker).skip(1) {
1167                // Take the literals in the comparison that follows, stopping at
1168                // the first token that ends it.
1169                let stop = tail.find([';', '{', '}']).unwrap_or(tail.len());
1170                let mut rest = &tail[..stop];
1171                while let Some(open) = rest.find('"') {
1172                    let Some(close) = rest[open + 1..].find('"') else {
1173                        break;
1174                    };
1175                    out.push(rest[open + 1..open + 1 + close].to_string());
1176                    rest = &rest[open + 1 + close + 1..];
1177                }
1178            }
1179            out
1180        }
1181
1182        // The grammar files, read from source: this is a lint over the code,
1183        // not over anything the crate exposes at runtime.
1184        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/parser");
1185        let mut found: Vec<String> = Vec::new();
1186        for name in ["expr.rs", "structural.rs", "core.rs", "recovery.rs"] {
1187            let src = std::fs::read_to_string(dir.join(name))
1188                .unwrap_or_else(|e| panic!("read {name}: {e}"));
1189            found.extend(words_after(&src, "t.text =="));
1190            found.extend(words_after(&src, "t.text.as_ref(),"));
1191            found.extend(words_after(&src, "next.text =="));
1192        }
1193        assert!(
1194            !found.is_empty(),
1195            "the scan matched nothing — the grammar's `Ident`-text comparisons \
1196             have been rewritten, and this guard is no longer guarding anything"
1197        );
1198
1199        for word in &found {
1200            assert!(
1201                CONTEXTUAL_IDENTS.contains(&word.as_str()),
1202                "the grammar branches on the identifier text {word:?}, so an \
1203                 edit into or out of it can reshape the tree under an unchanged \
1204                 token kind. Add it to CONTEXTUAL_IDENTS.",
1205            );
1206        }
1207
1208        // Every word the scan is known to reach today. A rewrite that hides one
1209        // from the scan trips this rather than silently narrowing the guard.
1210        for expected in ["as", "abstract", "primitive", "type", "typegroup", "public"] {
1211            assert!(
1212                found.iter().any(|w| w == expected),
1213                "the scan no longer finds the {expected:?} comparison",
1214            );
1215        }
1216    }
1217
1218    #[test]
1219    fn fingerprint_is_stable_and_discriminating() {
1220        let a1 = fingerprint(&crate::parser::parse("x = 1\n").cst);
1221        let a2 = fingerprint(&crate::parser::parse("x = 1\n").cst);
1222        let b = fingerprint(&crate::parser::parse("x = 2\n").cst);
1223        assert_eq!(a1, a2);
1224        assert_ne!(a1, b);
1225    }
1226
1227    /// A numeric literal is deliberately outside `TOKEN_REPARSE_KINDS`, and a
1228    /// lone `x = 1` statement is the whole `ROOT`, so the top-level tier finds
1229    /// no decoupled region either.
1230    #[test]
1231    fn a_number_edit_in_a_lone_statement_falls_back() {
1232        let parsed = crate::parser::parse("x = 1\n");
1233        let green = parsed.cst.green().to_owned();
1234        let e = diff_edit("x = 1\n", "x = 2\n");
1235        assert!(reparse("x = 1\n", &green, &parsed.diagnostics, &e, "x = 2\n").is_none());
1236    }
1237
1238    /// The point of the `STRING_CONTENT` path: a docstring body edit stays at
1239    /// the token tier. `fold_docstrings` folds a docstring with the definition
1240    /// it documents into one `ROOT` child, so the statement tier would answer
1241    /// this by reparsing the docstring *and* the whole function under it.
1242    #[test]
1243    fn a_docstring_body_edit_stays_at_the_token_tier() {
1244        let old = "\"\"\"\ndoc\n\"\"\"\nfunction f(x)\n    x + 1\nend\n";
1245        let parsed = crate::parser::parse(old);
1246        let green = parsed.cst.green().to_owned();
1247        let e = edit(5..5, "s");
1248        let new = e.apply(old);
1249
1250        let out = reparse(old, &green, &parsed.diagnostics, &e, &new)
1251            .expect("a docstring body edit is spliceable");
1252        assert_eq!(out.tier, ReparseTier::Token);
1253    }
1254
1255    /// An unterminated literal runs to EOF, so its node is the rest of the
1256    /// file. The diagnostic bail must reject a content edit inside one — and
1257    /// must do so before either relex, which is why it is hoisted to the top
1258    /// of `try_splice_string_content`.
1259    #[test]
1260    fn a_content_edit_in_an_unterminated_literal_falls_back() {
1261        let old = "x = 1\ny = \"abc\nz = 2\n";
1262        let parsed = crate::parser::parse(old);
1263        let green = parsed.cst.green().to_owned();
1264        // Offset 12 is inside the content run, which here swallows the rest of
1265        // the file; `UnterminatedLiteral` is anchored at the literal's start.
1266        let token = SyntaxNode::new_root(green.clone())
1267            .token_at_offset(TextSize::new(12))
1268            .right_biased()
1269            .expect("a leaf at offset 12");
1270        assert_eq!(token.kind(), SyntaxKind::STRING_CONTENT);
1271
1272        let e = edit(12..13, "X");
1273        let new = e.apply(old);
1274        assert!(try_splice_string_content(old, &parsed.diagnostics, &e, &token).is_none());
1275        // The statement tier may still answer it (the in-crate Tenet-4 assert
1276        // validates that splice); what matters is that the token tier declined.
1277        let tier = reparse(old, &green, &parsed.diagnostics, &e, &new).map(|r| r.tier);
1278        assert_ne!(tier, Some(ReparseTier::Token));
1279    }
1280
1281    /// An edit that does not fit `prev_text` is rejected rather than applied at
1282    /// offsets that would panic on a slice. `reparse_edits` proves its chain
1283    /// with `try_apply_edits`; the single-edit entry point has to check too.
1284    #[test]
1285    fn reparse_rejects_an_edit_that_does_not_fit() {
1286        let old = "α = 1\n";
1287        let parsed = crate::parser::parse(old);
1288        let green = parsed.cst.green().to_owned();
1289        // `new_text` is deliberately not the edit's result: a misfitting edit
1290        // has none, which is the whole point.
1291        let run = |e: Edit| reparse(old, &green, &parsed.diagnostics, &e, old);
1292
1293        // Past the end of the text.
1294        assert!(run(edit(99..99, "x")).is_none());
1295        // Off a char boundary (α is two bytes).
1296        assert!(run(edit(1..1, "x")).is_none());
1297        // Inverted range (built by hand: a literal `4..2` is a clippy error).
1298        let inverted = Edit {
1299            range: std::ops::Range { start: 4, end: 2 },
1300            insert: "x".to_string(),
1301        };
1302        assert!(run(inverted).is_none());
1303    }
1304
1305    /// A region wide enough that answering it costs more than the full parse it
1306    /// avoids is declined on the cheap evidence, before any fragment parse. The
1307    /// shape is a collapsed `diff_edit` of scattered edits, which spans
1308    /// everything between the first and the last.
1309    #[test]
1310    fn a_region_covering_most_of_a_large_file_is_declined() {
1311        let mut old = String::new();
1312        for i in 0..2000 {
1313            old.push_str(&format!("var_{i} = {i}\n"));
1314        }
1315        let parsed = crate::parser::parse(&old);
1316        let green = parsed.cst.green().to_owned();
1317
1318        // A narrow edit near the end still splices: the guard keys on the
1319        // region, not on the file size.
1320        let narrow = edit(old.len()..old.len(), "tail = 1\n");
1321        assert!(
1322            reparse(
1323                &old,
1324                &green,
1325                &parsed.diagnostics,
1326                &narrow,
1327                &narrow.apply(&old)
1328            )
1329            .is_some()
1330        );
1331
1332        // The same net change seen as one collapsed edit spanning most of the
1333        // file: `select_region` returns nearly every child, and the tier bails.
1334        // Both sites are inside an identifier, and the second is expressed
1335        // against the text the first produced (one byte longer), so the chain
1336        // below stays at the token tier. The last line is `var_1999 = 1999\n`,
1337        // 16 bytes, whose name runs from its start.
1338        let scattered = vec![edit(4..4, "X"), edit(old.len() - 11..old.len() - 11, "X")];
1339        let new = apply_edits(&old, &scattered);
1340        let collapsed = diff_edit(&old, &new);
1341        assert!(collapsed.range.len() > old.len() / 2, "{collapsed:?}");
1342        assert!(reparse(&old, &green, &parsed.diagnostics, &collapsed, &new).is_none());
1343
1344        // Replaying the chain still answers it at the token tier — the guard
1345        // costs the precise-edit path nothing.
1346        let out = reparse_edits(&old, &green, &parsed.diagnostics, &scattered, &new)
1347            .expect("the precise chain is unaffected");
1348        assert_eq!(out.tier, ReparseTier::Token);
1349    }
1350
1351    /// The width guard is a fraction *and* a floor: a small file's region is
1352    /// always worth trying, however much of the file it covers.
1353    #[test]
1354    fn the_region_width_guard_leaves_small_files_alone() {
1355        assert!(!region_is_too_wide(4 * 1024, 4 * 1024));
1356        assert!(!region_is_too_wide(64 * 1024, 1024 * 1024));
1357        assert!(region_is_too_wide(64 * 1024, 128 * 1024));
1358    }
1359
1360    /// The shape `reparse_edits` exists for: two identifier edits far apart,
1361    /// which `diff_edit` would collapse into one span covering both statements.
1362    #[test]
1363    fn reparse_edits_chains_scattered_edits() {
1364        let old = "alpha = 1\nfiller = 2\nomega = 3\n";
1365        let parsed = crate::parser::parse(old);
1366        let green = parsed.cst.green().to_owned();
1367        // `alpha` -> `alphaX`, then `omega` -> `omegaX` at its post-first-edit
1368        // offset (one byte further along).
1369        let edits = vec![edit(5..5, "X"), edit(27..27, "X")];
1370        let new = apply_edits(old, &edits);
1371        assert_eq!(new, "alphaX = 1\nfiller = 2\nomegaX = 3\n");
1372
1373        // The collapsed diff spans from `alpha` all the way to `omega`, so the
1374        // cheap token tier cannot touch it and the whole run of statements has
1375        // to be reparsed. Replaying the chain keeps both splices at the token
1376        // tier. On three statements that is a wash; on a real file the
1377        // difference is two orders of magnitude (`benches/reparse.rs`), which
1378        // is why the chain is tried first.
1379        let collapsed = diff_edit(old, &new);
1380        assert!(collapsed.range.len() > 20, "{collapsed:?} should be coarse");
1381        let via_diff = reparse(old, &green, &parsed.diagnostics, &collapsed, &new)
1382            .expect("the whole-file region is still spliceable at this size");
1383        assert_eq!(via_diff.tier, ReparseTier::TopLevel);
1384
1385        let out = reparse_edits(old, &green, &parsed.diagnostics, &edits, &new)
1386            .expect("two identifier edits should chain");
1387        assert_eq!(out.tier, ReparseTier::Token);
1388        assert_eq!(
1389            fingerprint(&SyntaxNode::new_root(out.green)),
1390            fingerprint(&crate::parser::parse(&new).cst),
1391        );
1392    }
1393
1394    /// The chain reports the most expensive tier it had to reach.
1395    #[test]
1396    fn reparse_edits_reports_the_max_tier() {
1397        let old = "alpha = 1\nfiller = 2\nomega = 3\n";
1398        let parsed = crate::parser::parse(old);
1399        let green = parsed.cst.green().to_owned();
1400        // An ident edit (token tier) plus a whole added statement (top level),
1401        // appended at the post-first-edit end of the buffer.
1402        let edits = vec![edit(5..5, "X"), edit(32..32, "beta = 4\n")];
1403        let new = apply_edits(old, &edits);
1404
1405        let out = reparse_edits(old, &green, &parsed.diagnostics, &edits, &new)
1406            .expect("ident edit plus a new statement should chain");
1407        assert_eq!(out.tier, ReparseTier::TopLevel);
1408    }
1409
1410    /// Fewer than two edits is always `diff_edit`'s job: its span for the same
1411    /// transform is contained in the single edit's, and the caller tried it.
1412    #[test]
1413    fn reparse_edits_declines_short_chains() {
1414        let old = "alpha = 1\nomega = 3\n";
1415        let parsed = crate::parser::parse(old);
1416        let green = parsed.cst.green().to_owned();
1417
1418        assert!(reparse_edits(old, &green, &parsed.diagnostics, &[], old).is_none());
1419        let one = vec![edit(5..5, "X")];
1420        let new = apply_edits(old, &one);
1421        assert!(reparse_edits(old, &green, &parsed.diagnostics, &one, &new).is_none());
1422    }
1423
1424    /// A chain that is not the exact transform between the two texts is
1425    /// rejected before any offset is trusted — both when it simply does not
1426    /// reproduce the target, and when it does not fit the source at all.
1427    #[test]
1428    fn reparse_edits_rejects_a_stale_chain() {
1429        let old = "alpha = 1\nfiller = 2\nomega = 3\n";
1430        let parsed = crate::parser::parse(old);
1431        let green = parsed.cst.green().to_owned();
1432
1433        // Applies cleanly, but the buffer moved on underneath it.
1434        let edits = vec![edit(5..5, "X"), edit(26..26, "X")];
1435        let elsewhere = "alphaX = 1\nfiller = 2\nomegaX = 3\nextra = 4\n";
1436        assert!(reparse_edits(old, &green, &parsed.diagnostics, &edits, elsewhere).is_none());
1437
1438        // Does not even fit the source text.
1439        let past_end = vec![edit(500..500, "X"), edit(501..501, "X")];
1440        assert!(reparse_edits(old, &green, &parsed.diagnostics, &past_end, old).is_none());
1441    }
1442
1443    /// One unhandleable step aborts the whole chain — the caller full-parses.
1444    #[test]
1445    fn reparse_edits_aborts_on_an_unhandleable_step() {
1446        let old = "alpha = 1\nfiller = 2\nomega = 3\n";
1447        let parsed = crate::parser::parse(old);
1448        let green = parsed.cst.green().to_owned();
1449        // The second edit opens an unterminated string, which no tier splices.
1450        let edits = vec![edit(5..5, "X"), edit(26..26, "\"")];
1451        let new = apply_edits(old, &edits);
1452        assert!(reparse_edits(old, &green, &parsed.diagnostics, &edits, &new).is_none());
1453    }
1454}