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",     // `for outer i in xs` iteration spec (expr.rs)
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/// A region wider than `1 / REGION_MAX_FILE_DIVISOR` of the file is wide enough
661/// that answering it costs more than the full parse it is trying to avoid. A
662/// divisor rather than a fraction, so `4` here means a quarter.
663const REGION_MAX_FILE_DIVISOR: usize = 4;
664
665/// Whether a region is too wide to be worth attempting. The tier answers a
666/// region with a fragment parse of it *plus* up to three neighbor-sized
667/// boundary parses, so the attempt scales with the region — and a miss pays
668/// the full parse on top. A collapsed [`diff_edit`] of scattered edits spans
669/// everything between the first and the last, which is exactly how a region
670/// grows to most of the file; on ~131 KB that attempt cost about 12 ms against
671/// a 6.3 ms full parse (`benches/reparse.rs`, `scattered_via_diff_edit`).
672/// Bailing on the cheap evidence — the region's byte span, known before any
673/// parse — caps the loss at the full parse the caller was going to pay anyway.
674///
675/// This is a performance guard only. Like every other bail here it returns the
676/// caller to a full parse, so it cannot affect what a reparse yields.
677fn region_is_too_wide(region_len: usize, text_len: usize) -> bool {
678    region_len > REGION_ALWAYS_TRY_BYTES && region_len > text_len / REGION_MAX_FILE_DIVISOR
679}
680
681/// The reparse region at the top-level tier: a contiguous run of `ROOT`
682/// children (statement nodes and loose trivia tokens both), identified by
683/// child index and old-text byte range. The boundary child kinds
684/// disambiguate zero-width diagnostics anchored exactly on a boundary.
685struct Region {
686    first: usize,
687    last: usize,
688    start: usize,
689    end: usize,
690    first_is_node: bool,
691    last_is_node: bool,
692}
693
694/// Select the contiguous run of `ROOT` children whose closed range touches
695/// the edit. Closed-interval touch makes boundary insertions extend into the
696/// neighbor they abut (blank-line typing selects the surrounding newline
697/// tokens; deleting a newline pulls in both neighbor statements). A
698/// zero-width child abutting the region start is absorbed: stray-closer
699/// recovery pairs a zero-width `ERROR` with its byte-bearing run at the same
700/// offset, and the fragment reparse regenerates both, so leaving it outside
701/// would duplicate it. `None` when the run covers every child (the fragment
702/// reparse would be the full parse) or `ROOT` is empty.
703fn select_region(root: &SyntaxNode, edit: &Edit) -> Option<Region> {
704    let (s, e) = (edit.range.start, edit.range.end);
705    let children: Vec<_> = root.children_with_tokens().collect();
706    let touches = |el: &crate::syntax::SyntaxElement| {
707        let r = el.text_range();
708        usize::from(r.start()) <= e && usize::from(r.end()) >= s
709    };
710    let mut first = children.iter().position(touches)?;
711    let last = children.len() - 1 - children.iter().rev().position(touches)?;
712
713    let start = usize::from(children[first].text_range().start());
714    while first > 0
715        && children[first - 1].text_range() == TextRange::empty(TextSize::new(start as u32))
716    {
717        first -= 1;
718    }
719
720    if first == 0 && last == children.len() - 1 {
721        return None;
722    }
723    Some(Region {
724        first,
725        last,
726        start,
727        end: usize::from(children[last].text_range().end()),
728        first_is_node: children[first].as_node().is_some(),
729        last_is_node: children[last].as_node().is_some(),
730    })
731}
732
733/// The nearest positive-width `ROOT` child nodes outside the region. Trivia
734/// tokens are gap material, and a zero-width `ERROR` node contributes no text
735/// (taking one as the forward neighbor would make the boundary guard
736/// vacuous), so both are skipped.
737fn sibling_nodes(root: &SyntaxNode, region: &Region) -> (Option<SyntaxNode>, Option<SyntaxNode>) {
738    let positive_node =
739        |el: crate::syntax::SyntaxElement| el.into_node().filter(|n| !n.text_range().is_empty());
740    let prev = root
741        .children_with_tokens()
742        .take(region.first)
743        .filter_map(positive_node)
744        .last();
745    let next = root
746        .children_with_tokens()
747        .skip(region.last + 1)
748        .find_map(positive_node);
749    (prev, next)
750}
751
752/// Whether no `ROOT` child (node or loose token) of `cst` straddles `seam`.
753/// Children tile the text, so no-straddle is equivalent to a boundary
754/// existing exactly at the seam: the two sides parse independently. A
755/// straddling node is a cross-boundary statement (trailing-operator
756/// continuation, a docstring fold, an unterminated block absorbing its
757/// neighbor); a straddling token is a lexical fusion (`#=` swallowing
758/// trailing trivia, an unterminated string).
759fn no_straddle(cst: &SyntaxNode, seam: usize) -> bool {
760    let seam = TextSize::new(seam as u32);
761    cst.children_with_tokens().all(|el| {
762        let r = el.text_range();
763        !(r.start() < seam && seam < r.end())
764    })
765}
766
767/// Splice the fragment's diagnostics into the previous ones, stream by
768/// stream ([`DiagnosticKind::stream`](crate::parser::diagnostics::DiagnosticKind::stream)):
769/// keep those before the region, drop those the fragment reparse
770/// regenerates, and shift those after by the edit delta. Emission order
771/// within a stream is positional across statements (the drive loop is
772/// per-line sequential, the flag passes walk in document order), so
773/// `before ++ fragment ++ after` per stream, concatenated in stream order,
774/// reproduces a full parse's vector.
775///
776/// A zero-width diagnostic exactly on a region boundary is ambiguous by
777/// position alone and is disambiguated by the boundary child's kind: a
778/// statement node owns a start-anchored marker at `start` (`const x` at the
779/// region's front) and an end-anchored one at `end`, while a trivia boundary
780/// child owns nothing, so the marker belongs to the statement just outside.
781/// This is sound only because the decoupling guards already rejected
782/// zero-gap node adjacency at the boundaries. A diagnostic genuinely
783/// straddling a boundary aborts the splice (`None`); regions are whole
784/// children and diagnostics never outgrow their statement, so this arm
785/// should be unreachable and is purely defensive.
786///
787/// A stream index outside [`DIAGNOSTIC_STREAMS`] aborts the splice too, rather
788/// than indexing out of bounds. [`DiagnosticKind::stream`] is an exhaustive
789/// match today, so this cannot fire — but a bail returns the caller to a full
790/// parse, whereas a panic here takes down an analysis query, and this module
791/// buys its whole safety argument from every failure being a bail.
792fn splice_diagnostics(
793    prev_diags: &[ParseDiagnostic],
794    frag_diags: &[ParseDiagnostic],
795    region: &Region,
796    delta: isize,
797) -> Option<Vec<ParseDiagnostic>> {
798    enum Class {
799        Before,
800        Drop,
801        After,
802    }
803    let classify = |d: &ParseDiagnostic| -> Option<Class> {
804        let (rs, re) = (region.start, region.end);
805        if d.start == d.end && d.start == rs {
806            return Some(if region.first_is_node {
807                Class::Drop
808            } else {
809                Class::Before
810            });
811        }
812        if d.start == d.end && d.start == re {
813            return Some(if region.last_is_node {
814                Class::Drop
815            } else {
816                Class::After
817            });
818        }
819        if d.end <= rs {
820            return Some(Class::Before);
821        }
822        if d.start >= re {
823            return Some(Class::After);
824        }
825        if d.start >= rs && d.end <= re {
826            return Some(Class::Drop);
827        }
828        None
829    };
830
831    let mut before: [Vec<ParseDiagnostic>; DIAGNOSTIC_STREAMS] = Default::default();
832    let mut after: [Vec<ParseDiagnostic>; DIAGNOSTIC_STREAMS] = Default::default();
833    for d in prev_diags {
834        let class = classify(d)?;
835        let stream = d.kind.stream();
836        if stream >= DIAGNOSTIC_STREAMS {
837            debug_assert!(false, "diagnostic stream {stream} is out of range");
838            return None;
839        }
840        match class {
841            Class::Before => before[stream].push(d.clone()),
842            Class::Drop => {}
843            Class::After => {
844                let mut d = d.clone();
845                d.start = (d.start as isize + delta) as usize;
846                d.end = (d.end as isize + delta) as usize;
847                after[stream].push(d);
848            }
849        }
850    }
851
852    let mut out = Vec::with_capacity(prev_diags.len() + frag_diags.len());
853    for stream in 0..DIAGNOSTIC_STREAMS {
854        out.append(&mut before[stream]);
855        out.extend(
856            frag_diags
857                .iter()
858                .filter(|d| d.kind.stream() == stream)
859                .map(|d| {
860                    let mut d = d.clone();
861                    d.start += region.start;
862                    d.end += region.start;
863                    d
864                }),
865        );
866        out.append(&mut after[stream]);
867    }
868    Some(out)
869}
870
871/// The top-level statement tier: reparse the run of `ROOT` children touching
872/// the edit with the public [`parse`](crate::parser::parse) (which reruns
873/// `fold_docstrings` and the flag passes on the fragment) and splice the
874/// resulting children and diagnostics in place.
875///
876/// The guards, in order: decoupling scans require a newline between each
877/// untouched sibling statement and the fragment's non-trivia content, because
878/// the drive loop's per-line junk recovery couples same-line siblings; the
879/// boundary parses then prove the seam survives — the neighbor plus the
880/// actual gap bytes plus the fragment must parse with a boundary exactly at
881/// the old one, which rejects trailing-operator continuation, docstring
882/// folds, forward absorption by an unterminated block, and lexical fusion.
883/// Diagnostics splice last (see [`splice_diagnostics`]).
884fn reparse_toplevel(
885    prev_text: &str,
886    prev_green: &GreenNode,
887    prev_diags: &[ParseDiagnostic],
888    edit: &Edit,
889    new_text: &str,
890) -> Option<Reparsed> {
891    let root = SyntaxNode::new_root(prev_green.clone());
892    let region = select_region(&root, edit)?;
893    if region_is_too_wide(region.end - region.start, prev_text.len()) {
894        return None;
895    }
896    let delta = edit.delta();
897    let frag_end = (region.end as isize + delta) as usize;
898    let fragment = &new_text[region.start..frag_end];
899
900    let frag = crate::parser::parse(fragment);
901    let (prev_node, next_node) = sibling_nodes(&root, &region);
902
903    let positive_nodes = |node: &SyntaxNode| {
904        node.children_with_tokens()
905            .filter_map(|el| el.into_node())
906            .filter(|n| !n.text_range().is_empty())
907    };
908
909    // Backward decoupling: a newline must separate the last significant
910    // content before the region (a statement node or a loose junk token, not
911    // just `prev_node`) from the fragment's first significant content (or
912    // all of a trivia-only fragment). The drive loop's per-line junk
913    // recovery couples same-line siblings, and the newline often lives in
914    // the unchanged gap outside the region, so scan `new_text`.
915    let prev_significant_end = root
916        .children_with_tokens()
917        .take(region.first)
918        .filter(is_significant_child)
919        .last()
920        .map(|el| usize::from(el.text_range().end()));
921    if let Some(from) = prev_significant_end {
922        let anchor = frag
923            .cst
924            .children_with_tokens()
925            .find(is_significant_child)
926            .map(|el| usize::from(el.text_range().start()))
927            .unwrap_or(fragment.len());
928        if !new_text[from..region.start + anchor].contains('\n') {
929            return None;
930        }
931    }
932
933    // Forward decoupling, in both texts: the next statement is kept, not
934    // reparsed, so its line must have been decoupled from the old region
935    // content too (deleting `x` from `x y` puts the kept junk `y` at line
936    // start, where a full parse reads it as a plain statement). The new-text
937    // scan anchors at the fragment's last statement *node* end, not its last
938    // token: an unterminated bracket consumes the separating newline into
939    // the statement, and a consumed newline decouples nothing.
940    if let Some(next) = &next_node {
941        let anchor = frag
942            .cst
943            .children_with_tokens()
944            .filter(is_significant_child)
945            .last()
946            .map(|el| usize::from(el.text_range().end()))
947            .unwrap_or(0);
948        let to = (usize::from(next.text_range().start()) as isize + delta) as usize;
949        if !new_text[region.start + anchor..to].contains('\n') {
950            return None;
951        }
952
953        let old_anchor = root
954            .children_with_tokens()
955            .skip(region.first)
956            .take(region.last + 1 - region.first)
957            .filter(is_significant_child)
958            .last()
959            .map(|el| usize::from(el.text_range().end()))
960            .or(prev_significant_end)
961            .unwrap_or(0);
962        if !prev_text[old_anchor..usize::from(next.text_range().start())].contains('\n') {
963            return None;
964        }
965    }
966
967    // Cross-region coupling: when the fragment carries no significant content,
968    // the two neighbors sit next to each other across it and can couple in a
969    // way neither boundary parse can see, because each concatenation contains
970    // only one of them. Deleting the `]` from `"doc" ]\nf() = 1` is the shape:
971    // the stray closer was all that kept the string from being the statement
972    // below it, and once it goes `fold_docstrings` folds the pair into a `DOC`
973    // spanning both seams. Parse the neighbors together, through the real gap
974    // bytes, and require both seams to survive. Only reachable when the region
975    // is reduced to trivia, so the extra parse is rare and neighbor-sized.
976    if !frag
977        .cst
978        .children_with_tokens()
979        .any(|el| is_significant_child(&el))
980        && let (Some(prev), Some(next)) = (&prev_node, &next_node)
981    {
982        let back_gap = &prev_text[usize::from(prev.text_range().end())..region.start];
983        let fwd_gap = &prev_text[region.end..usize::from(next.text_range().start())];
984        let guard = format!(
985            "{}{}{}{}{}",
986            prev.text(),
987            back_gap,
988            fragment,
989            fwd_gap,
990            next.text()
991        );
992        let back_seam = usize::from(prev.text_range().len()) + back_gap.len();
993        let fwd_seam = back_seam + fragment.len();
994        let parsed = crate::parser::parse(&guard);
995        if !no_straddle(&parsed.cst, back_seam) || !no_straddle(&parsed.cst, fwd_seam) {
996            return None;
997        }
998    }
999
1000    // A zero-width diagnostic exactly on a guard seam is disambiguated by
1001    // the fragment's own boundary child, mirroring `splice_diagnostics`: a
1002    // statement node owns a start-anchored marker at its start and an
1003    // end-anchored one at its end; a trivia boundary child owns nothing.
1004    let frag_starts_with_node = frag
1005        .cst
1006        .children_with_tokens()
1007        .next()
1008        .is_some_and(|el| el.as_node().is_some());
1009    let frag_ends_with_node = frag
1010        .cst
1011        .children_with_tokens()
1012        .last()
1013        .is_some_and(|el| el.as_node().is_some());
1014
1015    // Backward boundary parse: previous statement + gap trivia + fragment
1016    // must keep a boundary exactly at the old one, and the fragment must
1017    // parse in context with exactly the diagnostics it produced in
1018    // isolation.
1019    if let Some(prev) = &prev_node {
1020        let back_gap = &prev_text[usize::from(prev.text_range().end())..region.start];
1021        let guard = format!("{}{}{}", prev.text(), back_gap, fragment);
1022        let seam = guard.len() - fragment.len();
1023        let parsed = crate::parser::parse(&guard);
1024        if !no_straddle(&parsed.cst, seam) {
1025            return None;
1026        }
1027        let guard_frag: Vec<ParseDiagnostic> = parsed
1028            .diagnostics
1029            .iter()
1030            .filter(|d| {
1031                d.start > seam
1032                    || (d.start == seam && d.end > seam)
1033                    || (d.start == seam && d.end == seam && frag_starts_with_node)
1034            })
1035            .map(|d| {
1036                let mut d = d.clone();
1037                d.start -= seam;
1038                d.end -= seam;
1039                d
1040            })
1041            .collect();
1042        if guard_frag != frag.diagnostics {
1043            return None;
1044        }
1045    }
1046
1047    // Forward boundary parse: fragment + gap trivia + next statement (or the
1048    // trailing trivia to EOF when no statement follows). Three checks
1049    // against one parse of the concatenation: no element straddles the seam;
1050    // the fragment reparses exactly as it did in isolation (an EOF-adjacent
1051    // junk run wraps differently once text follows it); and the kept next
1052    // statement reappears untouched — same start, kind, and length — since a
1053    // fragment ending in an unterminated bracket can consume the separating
1054    // newline and demote the next line to flat junk without anything
1055    // straddling the seam.
1056    let tail = match &next_node {
1057        Some(next) => {
1058            let gap = &prev_text[region.end..usize::from(next.text_range().start())];
1059            format!("{}{}", gap, next.text())
1060        }
1061        None => prev_text[region.end..].to_string(),
1062    };
1063    if !tail.is_empty() {
1064        let guard = format!("{fragment}{tail}");
1065        let seam = fragment.len();
1066        let parsed = crate::parser::parse(&guard);
1067        if !no_straddle(&parsed.cst, seam) {
1068            return None;
1069        }
1070        let signature = |el: crate::syntax::SyntaxElement| {
1071            (
1072                usize::from(el.text_range().start()),
1073                el.as_node().is_some(),
1074                el.kind(),
1075                usize::from(el.text_range().len()),
1076            )
1077        };
1078        let frag_sig: Vec<_> = frag.cst.children_with_tokens().map(signature).collect();
1079        let pre_seam: Vec<_> = parsed
1080            .cst
1081            .children_with_tokens()
1082            .filter(|el| {
1083                let r = el.text_range();
1084                // A zero-width child exactly at the seam pairs with a junk
1085                // run on the far side; it belongs to the tail.
1086                usize::from(r.end()) <= seam && !(r.is_empty() && usize::from(r.start()) == seam)
1087            })
1088            .map(signature)
1089            .collect();
1090        if pre_seam != frag_sig {
1091            return None;
1092        }
1093        // The fragment's in-context diagnostics must also match: a trailing
1094        // token at the fragment's EOF can emit differently once text follows
1095        // it (`:` with a newline after it flags `QuoteColonWhitespace`; at
1096        // EOF it does not).
1097        let guard_frag: Vec<ParseDiagnostic> = parsed
1098            .diagnostics
1099            .iter()
1100            .filter(|d| {
1101                d.end < seam
1102                    || (d.end == seam && d.start < seam)
1103                    || (d.start == seam && d.end == seam && frag_ends_with_node)
1104            })
1105            .cloned()
1106            .collect();
1107        if guard_frag != frag.diagnostics {
1108            return None;
1109        }
1110        if let Some(next) = &next_node {
1111            let gap_len = usize::from(next.text_range().start()) - region.end;
1112            let reparsed_next =
1113                positive_nodes(&parsed.cst).find(|n| usize::from(n.text_range().start()) >= seam);
1114            let intact = reparsed_next.is_some_and(|n| {
1115                usize::from(n.text_range().start()) == seam + gap_len
1116                    && n.kind() == next.kind()
1117                    && n.text_range().len() == next.text_range().len()
1118            });
1119            if !intact {
1120                return None;
1121            }
1122        }
1123    }
1124
1125    let diagnostics = splice_diagnostics(prev_diags, &frag.diagnostics, &region, delta)?;
1126
1127    let frag_green = frag.cst.green();
1128    let green = prev_green.splice_children(
1129        region.first..=region.last,
1130        frag_green.children().map(|c| c.to_owned()),
1131    );
1132    Some(Reparsed {
1133        green,
1134        diagnostics,
1135        tier: ReparseTier::TopLevel,
1136    })
1137}
1138
1139#[cfg(test)]
1140mod tests {
1141    use super::*;
1142
1143    fn edit(range: std::ops::Range<usize>, insert: &str) -> Edit {
1144        Edit {
1145            range,
1146            insert: insert.to_string(),
1147        }
1148    }
1149
1150    /// The grammar decides some tree shapes by an identifier's *text*, and the
1151    /// token tier's same-kind relex cannot see such a change — so every such
1152    /// word has to be in [`CONTEXTUAL_IDENTS`]. Nothing in the type system says
1153    /// so, and the oracle only surfaces an omission by luck, so scan the
1154    /// grammar for the two spellings those comparisons take and check the words
1155    /// they name.
1156    ///
1157    /// The known words are asserted to have been *found*, not just listed: if a
1158    /// comparison is ever rewritten into a shape this scan does not recognize,
1159    /// the test fails loudly rather than quietly covering nothing.
1160    #[test]
1161    fn every_contextual_ident_is_listed() {
1162        // `t.kind == TokKind::Ident && t.text == "word"` and the `matches!`
1163        // form `matches!(t.text.as_ref(), "word" | "other")`. Both are keyed on
1164        // `t.text`, which is what makes them text-structural.
1165        fn words_after(haystack: &str, marker: &str) -> Vec<String> {
1166            let mut out = Vec::new();
1167            for tail in haystack.split(marker).skip(1) {
1168                // Take the literals in the comparison that follows, stopping at
1169                // the first token that ends it.
1170                let stop = tail.find([';', '{', '}']).unwrap_or(tail.len());
1171                let mut rest = &tail[..stop];
1172                while let Some(open) = rest.find('"') {
1173                    let Some(close) = rest[open + 1..].find('"') else {
1174                        break;
1175                    };
1176                    out.push(rest[open + 1..open + 1 + close].to_string());
1177                    rest = &rest[open + 1 + close + 1..];
1178                }
1179            }
1180            out
1181        }
1182
1183        // The grammar files, read from source: this is a lint over the code,
1184        // not over anything the crate exposes at runtime.
1185        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/parser");
1186        let mut found: Vec<String> = Vec::new();
1187        for name in ["expr.rs", "structural.rs", "core.rs", "recovery.rs"] {
1188            let src = std::fs::read_to_string(dir.join(name))
1189                .unwrap_or_else(|e| panic!("read {name}: {e}"));
1190            found.extend(words_after(&src, "t.text =="));
1191            found.extend(words_after(&src, "t.text.as_ref(),"));
1192            found.extend(words_after(&src, "next.text =="));
1193        }
1194        assert!(
1195            !found.is_empty(),
1196            "the scan matched nothing — the grammar's `Ident`-text comparisons \
1197             have been rewritten, and this guard is no longer guarding anything"
1198        );
1199
1200        for word in &found {
1201            assert!(
1202                CONTEXTUAL_IDENTS.contains(&word.as_str()),
1203                "the grammar branches on the identifier text {word:?}, so an \
1204                 edit into or out of it can reshape the tree under an unchanged \
1205                 token kind. Add it to CONTEXTUAL_IDENTS.",
1206            );
1207        }
1208
1209        // Every word the scan is known to reach today. A rewrite that hides one
1210        // from the scan trips this rather than silently narrowing the guard.
1211        for expected in ["as", "abstract", "primitive", "type", "typegroup", "public"] {
1212            assert!(
1213                found.iter().any(|w| w == expected),
1214                "the scan no longer finds the {expected:?} comparison",
1215            );
1216        }
1217    }
1218
1219    #[test]
1220    fn fingerprint_is_stable_and_discriminating() {
1221        let a1 = fingerprint(&crate::parser::parse("x = 1\n").cst);
1222        let a2 = fingerprint(&crate::parser::parse("x = 1\n").cst);
1223        let b = fingerprint(&crate::parser::parse("x = 2\n").cst);
1224        assert_eq!(a1, a2);
1225        assert_ne!(a1, b);
1226    }
1227
1228    /// A numeric literal is deliberately outside `TOKEN_REPARSE_KINDS`, and a
1229    /// lone `x = 1` statement is the whole `ROOT`, so the top-level tier finds
1230    /// no decoupled region either.
1231    #[test]
1232    fn a_number_edit_in_a_lone_statement_falls_back() {
1233        let parsed = crate::parser::parse("x = 1\n");
1234        let green = parsed.cst.green().to_owned();
1235        let e = diff_edit("x = 1\n", "x = 2\n");
1236        assert!(reparse("x = 1\n", &green, &parsed.diagnostics, &e, "x = 2\n").is_none());
1237    }
1238
1239    /// The point of the `STRING_CONTENT` path: a docstring body edit stays at
1240    /// the token tier. `fold_docstrings` folds a docstring with the definition
1241    /// it documents into one `ROOT` child, so the statement tier would answer
1242    /// this by reparsing the docstring *and* the whole function under it.
1243    #[test]
1244    fn a_docstring_body_edit_stays_at_the_token_tier() {
1245        let old = "\"\"\"\ndoc\n\"\"\"\nfunction f(x)\n    x + 1\nend\n";
1246        let parsed = crate::parser::parse(old);
1247        let green = parsed.cst.green().to_owned();
1248        let e = edit(5..5, "s");
1249        let new = e.apply(old);
1250
1251        let out = reparse(old, &green, &parsed.diagnostics, &e, &new)
1252            .expect("a docstring body edit is spliceable");
1253        assert_eq!(out.tier, ReparseTier::Token);
1254    }
1255
1256    /// An unterminated literal runs to EOF, so its node is the rest of the
1257    /// file. The diagnostic bail must reject a content edit inside one — and
1258    /// must do so before either relex, which is why it is hoisted to the top
1259    /// of `try_splice_string_content`.
1260    #[test]
1261    fn a_content_edit_in_an_unterminated_literal_falls_back() {
1262        let old = "x = 1\ny = \"abc\nz = 2\n";
1263        let parsed = crate::parser::parse(old);
1264        let green = parsed.cst.green().to_owned();
1265        // Offset 12 is inside the content run, which here swallows the rest of
1266        // the file; `UnterminatedLiteral` is anchored at the literal's start.
1267        let token = SyntaxNode::new_root(green.clone())
1268            .token_at_offset(TextSize::new(12))
1269            .right_biased()
1270            .expect("a leaf at offset 12");
1271        assert_eq!(token.kind(), SyntaxKind::STRING_CONTENT);
1272
1273        let e = edit(12..13, "X");
1274        let new = e.apply(old);
1275        assert!(try_splice_string_content(old, &parsed.diagnostics, &e, &token).is_none());
1276        // The statement tier may still answer it (the in-crate Tenet-4 assert
1277        // validates that splice); what matters is that the token tier declined.
1278        let tier = reparse(old, &green, &parsed.diagnostics, &e, &new).map(|r| r.tier);
1279        assert_ne!(tier, Some(ReparseTier::Token));
1280    }
1281
1282    /// An edit that does not fit `prev_text` is rejected rather than applied at
1283    /// offsets that would panic on a slice. `reparse_edits` proves its chain
1284    /// with `try_apply_edits`; the single-edit entry point has to check too.
1285    #[test]
1286    fn reparse_rejects_an_edit_that_does_not_fit() {
1287        let old = "α = 1\n";
1288        let parsed = crate::parser::parse(old);
1289        let green = parsed.cst.green().to_owned();
1290        // `new_text` is deliberately not the edit's result: a misfitting edit
1291        // has none, which is the whole point.
1292        let run = |e: Edit| reparse(old, &green, &parsed.diagnostics, &e, old);
1293
1294        // Past the end of the text.
1295        assert!(run(edit(99..99, "x")).is_none());
1296        // Off a char boundary (α is two bytes).
1297        assert!(run(edit(1..1, "x")).is_none());
1298        // Inverted range (built by hand: a literal `4..2` is a clippy error).
1299        let inverted = Edit {
1300            range: std::ops::Range { start: 4, end: 2 },
1301            insert: "x".to_string(),
1302        };
1303        assert!(run(inverted).is_none());
1304    }
1305
1306    /// A region wide enough that answering it costs more than the full parse it
1307    /// avoids is declined on the cheap evidence, before any fragment parse. The
1308    /// shape is a collapsed `diff_edit` of scattered edits, which spans
1309    /// everything between the first and the last.
1310    #[test]
1311    fn a_region_covering_most_of_a_large_file_is_declined() {
1312        let mut old = String::new();
1313        for i in 0..2000 {
1314            old.push_str(&format!("var_{i} = {i}\n"));
1315        }
1316        let parsed = crate::parser::parse(&old);
1317        let green = parsed.cst.green().to_owned();
1318
1319        // A narrow edit near the end still splices: the guard keys on the
1320        // region, not on the file size.
1321        let narrow = edit(old.len()..old.len(), "tail = 1\n");
1322        assert!(
1323            reparse(
1324                &old,
1325                &green,
1326                &parsed.diagnostics,
1327                &narrow,
1328                &narrow.apply(&old)
1329            )
1330            .is_some()
1331        );
1332
1333        // The same net change seen as one collapsed edit spanning most of the
1334        // file: `select_region` returns nearly every child, and the tier bails.
1335        // Both sites are inside an identifier, and the second is expressed
1336        // against the text the first produced (one byte longer), so the chain
1337        // below stays at the token tier. The last line is `var_1999 = 1999\n`,
1338        // 16 bytes, whose name runs from its start.
1339        let scattered = vec![edit(4..4, "X"), edit(old.len() - 11..old.len() - 11, "X")];
1340        let new = apply_edits(&old, &scattered);
1341        let collapsed = diff_edit(&old, &new);
1342        assert!(collapsed.range.len() > old.len() / 2, "{collapsed:?}");
1343        assert!(reparse(&old, &green, &parsed.diagnostics, &collapsed, &new).is_none());
1344
1345        // Replaying the chain still answers it at the token tier — the guard
1346        // costs the precise-edit path nothing.
1347        let out = reparse_edits(&old, &green, &parsed.diagnostics, &scattered, &new)
1348            .expect("the precise chain is unaffected");
1349        assert_eq!(out.tier, ReparseTier::Token);
1350    }
1351
1352    /// The width guard is a fraction *and* a floor: a small file's region is
1353    /// always worth trying, however much of the file it covers.
1354    #[test]
1355    fn the_region_width_guard_leaves_small_files_alone() {
1356        assert!(!region_is_too_wide(4 * 1024, 4 * 1024));
1357        assert!(!region_is_too_wide(64 * 1024, 1024 * 1024));
1358        assert!(region_is_too_wide(64 * 1024, 128 * 1024));
1359    }
1360
1361    /// The shape `reparse_edits` exists for: two identifier edits far apart,
1362    /// which `diff_edit` would collapse into one span covering both statements.
1363    #[test]
1364    fn reparse_edits_chains_scattered_edits() {
1365        let old = "alpha = 1\nfiller = 2\nomega = 3\n";
1366        let parsed = crate::parser::parse(old);
1367        let green = parsed.cst.green().to_owned();
1368        // `alpha` -> `alphaX`, then `omega` -> `omegaX` at its post-first-edit
1369        // offset (one byte further along).
1370        let edits = vec![edit(5..5, "X"), edit(27..27, "X")];
1371        let new = apply_edits(old, &edits);
1372        assert_eq!(new, "alphaX = 1\nfiller = 2\nomegaX = 3\n");
1373
1374        // The collapsed diff spans from `alpha` all the way to `omega`, so the
1375        // cheap token tier cannot touch it and the whole run of statements has
1376        // to be reparsed. Replaying the chain keeps both splices at the token
1377        // tier. On three statements that is a wash; on a real file the
1378        // difference is two orders of magnitude (`benches/reparse.rs`), which
1379        // is why the chain is tried first.
1380        let collapsed = diff_edit(old, &new);
1381        assert!(collapsed.range.len() > 20, "{collapsed:?} should be coarse");
1382        let via_diff = reparse(old, &green, &parsed.diagnostics, &collapsed, &new)
1383            .expect("the whole-file region is still spliceable at this size");
1384        assert_eq!(via_diff.tier, ReparseTier::TopLevel);
1385
1386        let out = reparse_edits(old, &green, &parsed.diagnostics, &edits, &new)
1387            .expect("two identifier edits should chain");
1388        assert_eq!(out.tier, ReparseTier::Token);
1389        assert_eq!(
1390            fingerprint(&SyntaxNode::new_root(out.green)),
1391            fingerprint(&crate::parser::parse(&new).cst),
1392        );
1393    }
1394
1395    /// The chain reports the most expensive tier it had to reach.
1396    #[test]
1397    fn reparse_edits_reports_the_max_tier() {
1398        let old = "alpha = 1\nfiller = 2\nomega = 3\n";
1399        let parsed = crate::parser::parse(old);
1400        let green = parsed.cst.green().to_owned();
1401        // An ident edit (token tier) plus a whole added statement (top level),
1402        // appended at the post-first-edit end of the buffer.
1403        let edits = vec![edit(5..5, "X"), edit(32..32, "beta = 4\n")];
1404        let new = apply_edits(old, &edits);
1405
1406        let out = reparse_edits(old, &green, &parsed.diagnostics, &edits, &new)
1407            .expect("ident edit plus a new statement should chain");
1408        assert_eq!(out.tier, ReparseTier::TopLevel);
1409    }
1410
1411    /// Fewer than two edits is always `diff_edit`'s job: its span for the same
1412    /// transform is contained in the single edit's, and the caller tried it.
1413    #[test]
1414    fn reparse_edits_declines_short_chains() {
1415        let old = "alpha = 1\nomega = 3\n";
1416        let parsed = crate::parser::parse(old);
1417        let green = parsed.cst.green().to_owned();
1418
1419        assert!(reparse_edits(old, &green, &parsed.diagnostics, &[], old).is_none());
1420        let one = vec![edit(5..5, "X")];
1421        let new = apply_edits(old, &one);
1422        assert!(reparse_edits(old, &green, &parsed.diagnostics, &one, &new).is_none());
1423    }
1424
1425    /// A chain that is not the exact transform between the two texts is
1426    /// rejected before any offset is trusted — both when it simply does not
1427    /// reproduce the target, and when it does not fit the source at all.
1428    #[test]
1429    fn reparse_edits_rejects_a_stale_chain() {
1430        let old = "alpha = 1\nfiller = 2\nomega = 3\n";
1431        let parsed = crate::parser::parse(old);
1432        let green = parsed.cst.green().to_owned();
1433
1434        // Applies cleanly, but the buffer moved on underneath it.
1435        let edits = vec![edit(5..5, "X"), edit(26..26, "X")];
1436        let elsewhere = "alphaX = 1\nfiller = 2\nomegaX = 3\nextra = 4\n";
1437        assert!(reparse_edits(old, &green, &parsed.diagnostics, &edits, elsewhere).is_none());
1438
1439        // Does not even fit the source text.
1440        let past_end = vec![edit(500..500, "X"), edit(501..501, "X")];
1441        assert!(reparse_edits(old, &green, &parsed.diagnostics, &past_end, old).is_none());
1442    }
1443
1444    /// One unhandleable step aborts the whole chain — the caller full-parses.
1445    #[test]
1446    fn reparse_edits_aborts_on_an_unhandleable_step() {
1447        let old = "alpha = 1\nfiller = 2\nomega = 3\n";
1448        let parsed = crate::parser::parse(old);
1449        let green = parsed.cst.green().to_owned();
1450        // The second edit opens an unterminated string, which no tier splices.
1451        let edits = vec![edit(5..5, "X"), edit(26..26, "\"")];
1452        let new = apply_edits(old, &edits);
1453        assert!(reparse_edits(old, &green, &parsed.diagnostics, &edits, &new).is_none());
1454    }
1455}