Skip to content

Refactor lock - #1

Merged
CppCXY merged 62 commits into
mainfrom
refactor-lock
Nov 26, 2026
Merged

CppCXY merged 62 commits into
mainfrom
refactor-lock

Conversation

@CppCXY

@CppCXY CppCXY commented Nov 26, 2026

Copy link
Copy Markdown
Owner

No description provided.

Three hover/format reports from neovim, plus the fourth one's real cause:

- **A typedef of a class was one long line**, and `typedef struct { … } T;` rendered as `using T = T;`. The alias
  line is generated, but an anonymous class body has no type spelling to generate from, so the fallback copied the
  source and collapsed its whitespace. It now keeps the declaration's own lines and strips `///<` notes; the
  self-target case uses the source `typedef` line, which is the only spelling that carries the body.
- **`typedef int64_t Integer;` answered `size 1 byte(s)`.** An alias has no members, and the empty-class rule was
  applied without looking through it. A type alias whose member list is empty is now priced by its target — `Integer`
  is 8 bytes / alignment 8 — and a member spelled with the alias gets that size.
- **A semicolon after a closing brace stood alone on the next line.** `TEXTLOCK_WRAP({ … });` expands to
  `do { … { … }; … } while (0)` — the macro body writes `code;` and the argument is a block — and the formatter split
  the brace from its `;`. The semicolon is now part of the brace's line, as `struct S { … };` and a lambda statement
  write.

The fourth report, `api_free_luaref` with no hover, was **not** an undeclared function. It is declared in neovim's
generated `build/include/lua/executor.h.generated.h:26`; this checkout also had a stale 2-byte
`build/src/nvim/auto/lua/executor.h.generated.h` earlier in the compile command's include path, which shadowed the real
declaration for the compiler and the analysis alike. Removing the placeholder makes the include resolve to the real
generated header and the card becomes `DLLEXPORT void api_free_luaref(LuaRef ref)` declared there. The previous
commit's cross-TU fallback was a workaround for that stale artifact and has been removed; it would have invented a
definition for any undeclared call. This tree does **not** compile that translation unit: MinGW GCC 15.1 under
`-std=gnu99` reports `implicit declaration of function 'api_free_luaref'` as an error, and there is no
`buffer_updates.c.obj`. The analyzer's `NotDeclaredHere` was the same truth; a clean/regenerated build removes the
placeholder and both sides see the declaration.

Measured: `lcs_chars_T` card is 17 member lines; `Integer` 8/8; `TEXTLOCK_WRAP` expansion has `};` and no lone `;`.
Tests: formatter **116 + 128**, analysis lib **903** + suite **1 157**, toolchain **165 + 31**, cpp_ls lib **197**;
clippy `-D warnings` and fmt clean.
Three failures with one more cause than the previous round:

- **A C enumerator from an included header had no jump.** `typedef enum auto_event { EVENT_BUFADD = 0, … }` puts
  `EVENT_BUFADD` in the enclosing C scope; the in-scope lookup classified `auto_event` as a class and dropped the
  enumerator, so `buffer.c`'s use answered `NotDeclaredHere`. A `.c` caller now keeps unscoped enumerators (C++'s
  `enum class` still hides them), and `EVENT_BUFADD` jumps to `auevents_enum.generated.h`.
- **The enumerator card read its value in the wrong tree.** It walked the *caller's* file at the header's offset, so
  `EVENT_BUFADD` (= 0) showed `= 3`. The value is now counted in the file that declares the enumerator, and the card
  reads `EVENT_BUFADD = 0` / "an enumerator of `auto_event`".
- **`Proc` and `proc` cycled until the stack overflowed.** `operator_returns_of` followed the first declaration of a
  name whatever its kind; a `typedef struct proc { … } Proc;` beside a `Proc proc;` variable made it follow
  `Proc` → the variable's `type_of` → `Proc` forever. Opening neovim's `channel.c` killed the `tokio-rt-worker` in
  both `undefined-field` and `param-type-check`. Only a `DeclKind::Type` declaration can be the alias arm now.

The fourth report, `cstr_as_string` "not declared", was the same stale-build artifact as the previous
`api_free_luaref`: neovim's real declaration is in `build/include/api/private/helpers.h.generated.h:26`, but **92**
two-byte CRLF placeholders in `build/src/nvim/auto/**/*.generated.h` were earlier in the compile command's include
path. They were moved to `build/stale-auto-20261124`; `cstr_as_string` now hovers as
`String cstr_as_string(const char* str)` and `buffer.c`'s diagnostic is gone. This is not C accepting an implicit
declaration: MinGW GCC 15.1 errors on it and no `buffer_updates.c.obj` exists; a fresh compile fails until the stale
directory is cleaned. The cross-TU fallback from the previous commit was removed, not extended.

Measured: `channel.c` diagnostics now complete with no findings, `buffer.c` likewise; `EVENT_BUFADD = 0`; the C
enumerator jump and card have regression tests, and so does the `Proc`/`proc` cycle.

Tests: analysis lib **904** + suite **1 158**, toolchain **165 + 31**, cpp_ls lib **197** + suite **118**, formatter
**116 + 128**, parser **520**; clippy `-D warnings` and fmt clean.
`assign-type-check` treated scalar-to-`_Bool` as no conversion, so neovim's `tui.c` reported a `const char *` into
`bool` twice. A pointer (through qualifiers, or an array that decays) into `bool`/`_Bool` is a standard conversion in
C and C++; the conversion relation now says so. `tui.c` diagnoses cleanly.

The neovim sweep after the generated-header cleanup and the C-enumerator/alias fixes:

```text
findings 356 (was 433)
unresolved-call-or-receiver 128 (was 180)
assign-type-check 3 (2 fixed by this change)
include-not-found 1, missing-include 3, missing-return 1
braces-around-statements 80, else-after-return 110, macro-parentheses 27, simplify-boolean-expr 3
syntax-error 0
```

`buffer.c`, `channel.c`, `buffer_updates.c`, `lua/executor.c`, `os/fs.c`, `api/buffer.c` and `eval/funcs.c` now
diagnose cleanly; `window.c` and `api/vim.c` have one finding each, `ui.c` two.

The remaining unresolved class is **macro-decorated globals whose type comes from an included header**:
`EXTERN typebuf_T typebuf`, `EXTERN VisualState Visual`, `EXTERN ScreenGrid default_grid`, `EXTERN GridView
msg_grid_adj`. The parser's known-type table is built from the file's own declarations, so it does not recognise
`EXTERN typebuf_T typebuf INIT(…)` as a declaration when `typebuf_T` is only in `input_defs.h`; `EXTERN bool …` in
the same file parses because `bool` is builtin. A two-file fixture reproduces it exactly (adding the typedef to the
same file makes it parse). This is a parser/summary gap, not a missing declaration; the fix direction is to seed the
parser's type names from the include closure, or read the unexpanded `MACRO type name` shape as a declaration.

The sweep also found a false `static` on `nvim_main`'s definition (`main.c:253`): the source is `int nvim_main`, the
fact reports STATIC (`modifiers = 64`), and the definition is in an `#ifdef MAKE_LIB` branch. Recorded in
`docs/open-questions.md` rather than guessed at.

Measured: analysis lib **905** + suite **1 158**, toolchain **165 + 31**, cpp_ls lib **197** + suite **118**, formatter
**116 + 128**; clippy `-D warnings` and fmt clean.
main.c's `#ifdef MAKE_LIB` branches merge `nvim_main` and `main` into one declaration. The `#else` side is read as an
`OldStyleParameterList`, and walking it for modifiers found a body-local `static`: the fact and the hover said
`static int nvim_main` although the source and the preceding declaration both say `int`. The modifier walk now stops
at that node; the fact is `modifiers = 0` and `FORMAT_VERSION` 62 → 63 because old summaries hold the wrong bit.

The previous round fixed the `globals.h`/`typebuf`/`Visual` sweep findings by teaching the *parser* to accept
`EXTERN typebuf_T typebuf INIT(…)` without include evidence. That was a shape heuristic and is withdrawn: in C the
header is included (api/vim.c:41), `macros_defs.h` expands EXTERN/INIT and `input_defs.h` provides `typebuf_T`;
nothing is in scope without that. A fixture shows the split exactly:

    facts typebuf in main.c      []                     raw summary, no include
    define typebuf from main.c   globals.h:3:18          cooked reading

The 128 `unresolved-call-or-receiver` in the raw sweep are that gap in the declaration query, not a C rule. The fix
belongs in the cooked-fact lookup path (`CookedFile`/`insert_cooked_in_a_program`/`the_reading_for`), with the fixture
as its test; `docs/open-questions.md` records that, the `nvim_main` defect, the platform findings and the remaining
cooked-header gap instead of claiming the heuristic fixed them.

Tests: parser **520**, analysis lib **905** + suite **1 159**; clippy -D warnings and fmt clean.
`cpp_inspect --cook` asked for `Session::cook`, which renders the requested file **alone**; `index_rendering` then files
the facts at that file's path, so a declaration written in an included header is dropped. That is why
`api/vim.c --cook define typebuf` answered `NotDeclaredHere` for

    #include "nvim/globals.h"
    EXTERN typebuf_T typebuf INIT( = { NULL, NULL, 0, … });   // globals.h, after macros_defs.h / input_defs.h

even though `globals.h` plainly declares it. The parser-shape rule that papered over this was wrong and has been
withdrawn: C does not make a macro-decorated unknown type a declaration without the include and the expansions.

The tool now performs the same **unit read** the server pump does (`Session::read_the_unit`) and keeps the per-file
cook only as the fallback for a fixture with no compile command. `index_unit_rendering` files each declaration under
the file that wrote it, so the lookup can see it.

Measured on the real project:

    define typebuf from api/vim.c   globals.h:575:18  typebuf  variable type `typebuf_T`
    hover typebuf from api/vim.c    `typebuf` — a variable of type `typebuf_T`, declared in globals.h:575:18
    diagnostics api/vim.c / window.c / ui.c / ex_docmd.c   none

`sweep` still uses the per-file cook for each file, so its 128 unresolved entries remain a measurement of that tool
path, not of the language server (which reads units through the pump). The parser tests are back to **520**, the
analysis suite is **905 + 1 159**, and clippy/fmt are clean.
`m = cmdline_win ? a : b` was parsed as `(m = cmdline_win) ? a : b`: the conditional's condition was read at the full
binary ladder, so the assignment was already inside it. `assign-type-check` then compared `cmdline_win`'s `win_T*`
against `m`'s `int`, which is neovim's `ex_getln.c:3055` false positive. The condition now starts above the assignment
family, and a new `parse_assignment_expr_inner` folds the assignment after the conditional, right-associatively, with
the `>>=` spelling the lexer leaves in three tokens and the braced right-hand side (`x = {1, 2};`) kept. The parser
fixture that had pinned the old nesting was corrected, and `a_pointer_conditioned_ternary_is_not_an_assignment_of_the_condition`
pins the check.

`cpp_inspect --cook` asked `Session::cook`, which renders the requested file alone and drops declarations written in
included headers. It now performs the same unit read the server pump does (`Session::read_the_unit`), then the
per-file cook so the requested file still has its own reading. `define typebuf` from `api/vim.c` lands in
`globals.h:575`, and `api/vim.c`, `window.c`, `ui.c`, `ex_docmd.c`, `ex_getln.c` diagnose cleanly.

`sweep` reads one representative unit before its per-file loop, so the header facts exist for its checks; the
unresolved class drops from 128 to the one platform fixture (`getsid`). Its three remaining `missing-include` entries
are the per-file cook's blind spot for a header that only the checked file includes; `--cook` on those files answers
`none`, and that distinction is recorded in `docs/open-questions.md`.

Tests: parser **520**, analysis lib **906** + suite **1 159**, cpp_ls **197 + 118** (the latency suite passed on a
quiet run), formatter **116 + 128**; clippy `-D warnings` and fmt clean.
…tion

Three reports from editing `channel.c`:

- **`ids.size`** — `kvec_t(int64_t) ids = …` is an anonymous struct after the preprocessor and an expression statement
  before it, so the plain reading had no binding for `ids`; the hover card said `` `ids` has no member `size` ``. A
  card that is a failed member lookup now re-asks the rendering, and it reads `size_t size` at the declaration's line.
- **`uint64_t`** — `map_defs.h` has `#ifdef __NetBSD__ / #define uint64_t uint64_t / #endif`; on Windows the
  conditional, self-identical macro was shown as the answer. Pass-through macros are skipped, and the standard
  fixed-width typedefs have their own card (the 64-bit unsigned integer type from `<stdint.h>`).
- **Completion of a macro while its declaration is incomplete** — `kvec` before `kvec_t(int64_t) ids` is an
  expression statement until the `(`, so the declaration-shaped name query offered none of kvec.h's macros. Ordinary
  code completion now includes the file's own and its direct includes' macros, filtered by the prefix; `kvec`, `KV_I`
  and `KV_INI` keep their candidates.

Completion latency is not claimed fixed: the server's per-request `prepare`/`catch_up` path and the client's renewal
of an incomplete list still need a real neovim timing run. That is recorded in `docs/open-questions.md`.

Tests: parser **520**, analysis lib **906** + suite **1 160**, cpp_ls **197 + 118**, formatter **116 + 128**;
clippy `-D warnings` and fmt clean.
The completion handler called `AnalysisState::prepare` on every request. That path takes the analysis read lock to
find out whether the file is open — a fact `OpenDocuments` already holds — so while the pump was reading a program a
one-line edit could make the first completion wait:

    after edit   476 / 708 / 1857 / 762 / 95 / 93 ms
                  the 1857 ms one spent 1609 ms in prepare and 157 ms in modules

`prepare_for_completion` answers an open buffer from the provider chain without the lock; `catch_up` still rebuilds
the summary the edit dropped. Over the wire on neovim's `channel.c`:

    after edit   91 / 229 / 90 / 110 / 90 / 88 ms   (steady 90–110 ms)
    prepare      0 ms on every request

The measurement is kept as `latency::measure_neovim_completion_before_and_after_an_edit`, `#[ignore]`d and driven by
`CPPLS_NEovim_PROJECT`, so the next change to this path has a real file to run against rather than a fixture.

The first completion after an edit still pays the view parse/lock (up to ~500 ms in one run, 0 once warm), and the
query itself is ~85–110 ms; both are recorded in `docs/open-questions.md` as the next targets. No request waits in
`prepare` any more.

Tests: cpp_ls lib **197** + suite **118** (11 ignored), analysis suite **1 160**; clippy `-D warnings` and fmt clean.
A macro-declared local is invisible to the file's own parse: `kvec_t(int64_t) ids` is an expression statement before
the preprocessor and an anonymous struct after it, so `ids.` completed nothing. The handler keeps the file view (the
text the client edits) and, when its answer is empty, asks the rendered view; the returned `replace` range is mapped
back through `FileView::file_offset_of` before the client sees it. Over the wire on neovim's `channel.c`:

    ids.  -> capacity, items, size
    KV_   -> KV_INITIAL_VALUE (among the macros, with the declaration incomplete)

The measurement is in `latency::measure_neovim_completion_before_and_after_an_edit`, with the two screenshots as
assertions.

**Not fixed, and recorded rather than papered over:** `ids` typed by name after a fresh insertion still misses its own
local, because no rendering exists for the edited buffer at that moment; and `ids.items` hover still says the type of
`ids` is not known, because the occurrence is inside `DICT_OBJ(...)`'s argument and the symbol walk never binds it. The
design gap and the three ways out are in `docs/open-questions.md`; the raw tree cannot answer either while it remains
the semantic source.

Tests: cpp_ls **197 + 118** (11 ignored), analysis suite **1 161**; clippy `-D warnings` and fmt clean.
The three symptoms shared one cause: answers that need macro expansion were being read from the file's own unexpanded
tree, or mapped to the wrong expansion token.

- Completion (`ids` after an insertion): the file's own completion is asked first, in its own coordinates. When that
  list has **no row beginning with the typed word** — `ids`, or the empty prefix after `ids.` — the handler builds a
  rendering of the current buffer with `view_of_the_rendering`, asks the same question there, and maps the `replace`
  range back through `FileView::file_offset_of`. A prefix the file's own list can answer (`KV_IN`, `kvec`) never pays
  the cook.
- Hover (`ids.items` inside `DICT_OBJ(...)`): a macro argument can lose its `written` span when it is substituted into
  a body, so the reverse start-offset map answered with the `ids` of the `for` loop ten lines above. The mapping now
  prefers a span that contains the written offset, and for one that kept only `reported` it matches the spelling plus
  its surrounding context (`ids.` before, `[` after).
- A focused test in `rendered_reading` pins the mapping of a local inside a macro argument; the over-the-wire neovim
  test pins `ids.` members, `ids` by name, `KV_`, and the `ids.items` hover together, and reports the timing.

Measured over the wire on `channel.c` (release):

    before edit   min 87 ms, mean 149 ms, max 450 ms
    after edit    min 89 ms, mean  90 ms, max  92 ms

Tests: parser **520**, toolchain **165 + 31**, analysis lib **906**, analysis suite **1 162**, cpp_ls **197 + 118**,
formatter **116 + 128**; clippy `-D warnings` and fmt clean.
The semantic fallback added for macro-declared locals called `view_of_the_rendering` from the completion request. That
builds a rendering while holding the analysis, and a client that asks for a completion on every edit can starve the
pump; a workspace reload showed "235 files to read, 8 to re-read" and the server process did not survive the storm.

The fallback now asks only for a **cached** rendering of the current buffer. When it is not there yet, the ordinary
list is returned with `incomplete: true`, which the handler already translates into `isIncomplete`, so the client asks
again after the pump has cooked the edit. The pump gets the edit from `didChange`; no request builds a unit.

Over the wire on `channel.c` (release): `ids.` members, `ids` by name, `KV_`, and the `ids.items` hover still pass;
after edit min 98 / mean 102 / max 108 ms. The first request after an insertion may be the ordinary list; the next
request is the semantic one.

Tests: cpp_ls lib **197** + suite **118** (11 ignored); clippy `-D warnings` and fmt clean.
Phase 0 + the first half of Phase 1 from `docs/refactor-plan.md`.

- `process_batch` is ordered: `Opened`/`Closed`/other events are boundaries, so a `Changed(A)` can no longer be
  applied before an `Opened(B)` in the same client run.
- The content `update_session` now only replaces text. `session.catch_up` is out of the write lock; each affected
  file, and each open file as the conservative header-dependents set, is caught up by a focus worker.
- A per-file semantic-ready event (`AnalysisState::mark_*` / `wait_for_semantic`) replaces the global expectation:
  completion and inlay wait for their own file, cancellation-aware and without a timeout; unrelated files do not wait.
- `Closed` stays on the ordered side-effecting path (diagnostics + inactive regions clear, disk fallback).

Over the wire (`channel.c`, release):

    ids. members / ids.items hover / ids name / KV_   all pass
    after edit completion                              min 90 / mean 94 / max 100 ms

Large-edit fixture:

    unrelated completion   p50 3 ms, p95 5 ms, max 13 ms
    same-file completion    p50 417 ms, p95 446 ms

The same-file number is the Phase 2 target (Preamble/body-only reuse), not a reason to put catch-up back under the
write lock.

Tests: cpp_ls **118** (11 ignored), analysis suite **1 162**; clippy `-D warnings` and fmt clean.
Switch the interactive path back to the single-writer/many-reader model. Requests take the read side only; there is no semantic gate, focus worker, per-file watch or wait.

The writer applies all queued document text and then catches up/cooks the changed files under one session write. A header edit includes the open includers; a source edit does not. Writer phases are logged (catch_up and cook separately) so the next step targets the real cost.

The latency fixture now uses a 1 000-line edited file, matching the reported case: unrelated completion p95 62 ms, same-file 76 ms, diagnostic 64 ms. The 10 000-line case still shows ~1 s and is the Preamble target, not a lock-tuning problem.

Tests: cpp_ls 118 passed, 11 ignored.
Add the composition primitive a body-only cook needs: cut a verified rendering at a file offset, and join a fresh suffix render behind it while preserving written/reported file coordinates and shifting only cooked spans. Not wired into the session yet.
RenderedCook carries the raw rendering; commit caches prefix_through(preamble_end); cooking_materials only offers it when the source prefix and preamble_end still match; render_cook cooks only suffix tokens and joins the prefix.

channel.c over-the-wire after an edit: mean 155 ms -> 88 ms, max 375 ms -> 91 ms. The 1000-line no-directive fixture has no reusable prefix and stays at writer cost (same-file p95 73 ms).
Open channel.c, buffer.c, message.c and eval.c; edit one file at a time; pipeline completion, codeLens, inlayHint, semanticTokens/full and diagnostic. Report per-provider and aggregate latency plus sequential five-provider comparison.

20 requests all answered. On channel.c the five providers sequentially total 5022 ms and concurrently p50 3812 / p95 6839 ms: no parallel speedup, the work is sharing the analysis. Writer batches were 454-1837 ms while catch_up+cook was 424-541 ms.
The neovim four-file run pins the blockers: index-slice tail commits 8-16 cooked renderings under one write lock (3520-6207 ms), diagnostics request-time prepare holds 231-265 ms each, diagnostic rendering commits hold 237-256 ms, and apply client content holds 431-539 ms. Provider concurrency is not the bottleneck.

Removing request-time prepare was tried and reverted: 8 handshake tests fail because didOpen only catches up, so the writer must cook first.
With a 45 s settle the index is still cooking: channel.c's edit shows an 8771 ms content batch while catch_up+cook+apply is 889 ms, so the batch is waiting for index-slice publication. Concurrent p95 5632 ms and completion p50 4815 ms describe cold start, not steady state. Add the longer-settle numbers and keep the index-idle run as the next measurement.
…rites

Cooked readings are no longer written to redb inside the commit/write lock. commit_a_cooked marks a path; a background pass wakes every 2 s and persists only entries quiet for 2 s, under the read side.

Diagnostics and code actions no longer call prepare_for_a_diagnostic. This intentionally breaks the current handshake expectations for unopened files and diagnostics-on-open: 10 tests fail and are left for the follow-up that gives the writer the didOpen cook and routes unopened pulls through the writer.

Measured on neovim: content batch 458-1067 ms (was 1471-8871 ms); concurrent 20-request p95 3796 ms (was 5632), completion max 3893 ms (was 5632).
RenderedCooked::join inserted no separator between the cached prefix and fresh suffix, so a prefix ending in one token could merge with the next body token and produce false syntax errors after an edit. Insert a newline and shift suffix spans by it.

Completion sets isIncomplete only when this answer is actually incomplete/truncated. pending_work/pending_units/is_locally_ready are true for seconds while a project indexes; clients then treat every list as provisional. The completion list's own flags are the facts about the answer.
index_one now takes whether it may build a translation timeline. catch_up uses false for the edited open file: its own summary is the whole job, and the closure walk was the 200-300 ms in every keystroke. Includes and pump reads still walk as before.

Measured on neovim: catch_up 199-303 ms -> 40-116 ms; content batch 458-1067 ms -> 275-837 ms; concurrent p95 3796 -> 3446 ms.

Completion now always answers isIncomplete:false; the flags were either true for seconds during indexing or true for the 1000-item cap, and clients then stopped filtering the names they already had. Diagnostic joins insert a newline between prefix and suffix, preventing token merges that produced false syntax errors.
DirectiveSignature now carries the leading directive boundary (clangd-shaped) separately from the conservative last-directive preamble_end used by the unit cache. PreambleRendering stores the prefix's parsed IndexedRendering; a body-only cook parses the suffix alone and merges prefix/body summaries, with a full-parse fallback when the body does not parse or the prefix is not top-level.

Measured on neovim: the fast path does not trigger for channel.c because the leading prefix's rendering is empty (its leading block is #includes, which contribute no file tokens), and eagerly parsing that prefix doubled cook 245->500 ms. Empty prefixes are now excluded; the text-level join remains for those files. A true PCH-shaped parse still needs a parser entry that consumes a cached prefix AST rather than a file rendering.
RenderedCooked contains the file's own tokens, not included header text; a leading #include block therefore has no rendered prefix to reuse. prefix_through/join, PreambleRendering, the prefix AST cache and the body-only merge are removed.

Add phase timers around parse, scopes, facts and map in index_rendering so the 1000-line cost can be attributed. First measurement on channel.c: scopes 5.9 ms, so the parser is not the 240 ms; facts/map are the next suspects.
A 1000-line synthetic file measures: parse 12 ms, scopes 32 ms, facts 80 ms, map 1 ms. The parser is not the hundreds of milliseconds; scope and fact construction are. Kept as probes for the algorithm work.
qualified_declarations, fill_the_frees and fill_the_reflection each walk the whole AST. A file with no :: has no qualified declaration, and a file that spells none of the reflection/free markers cannot match those sweeps. Gate each by a substring of the rendered text.

1000-line synthetic file: facts 157 ms -> 120 ms (qualified 13 -> 0.3, frees 5.5 -> 0, reflection 4.5 -> 0). Parse remains 14 ms; scopes 35-37 ms and the fact loop ~45 ms are the remaining algorithm cost.
fact_for called Name::text, which allocates a String for every identifier and then immediately copied it into a SmolStr. Use Name::spelled (Cow) through the qualified split and the type/return readers, and materialise once at DeclFact construction. The same borrow replaces three other per-binding text() calls.
Delete cpp_parser/cpp_toolchain/cpp_ls probe modules, replace probe calls with their default-off paths, and remove CPPLS_* reads from libraries and tests. Restore the two negated switches that gate normal behavior (guard filtering and whole-program reads) rather than leaving them disabled.

Remaining environment reads are the toolchain's compiler/include discovery and PATH lookup in the formatter. cpp_ls suite is 117 passed, 1 failed: latency::no_update_holds_the_analysis_for_longer_than_its_budget times out, so this cleanup is not yet fully verified.
Remove every remaining if false / Option::None probe block, the trace/tracing/traced locals they guarded, and the cpp_check summary-trace print. No probe call, probe module, CPPLS_* env read, or probe-only dead branch remains; only toolchain compiler/include discovery and the formatter PATH lookup read the environment.

The full cpp_ls suite is 117 passed, 1 failed, 12 ignored. The remaining failure is latency::no_update_holds_the_analysis_for_longer_than_its_budget, which never finishes indexing within its 180 s deadline; that is a runtime regression to investigate next, not a reason to restore probes.
Delete all remaining if false / Option::None probe blocks, trace variables, ignored-test env inputs and the CPPLS_* reads in probe tests. Remove the CPPLS_TRIVIA assertion that became unconditional and panicked the index thread, which was the cause of the latency test never finishing.

Keep only normal environment reads: toolchain compiler/include discovery (INCLUDE/CXX/CC/PATH/PATHEXT/WindowsSdkDir/VCToolsInstallDir), formatter PATH, and logger home directories. No probe module, CPPLS_* read, probe call or if false remains in library code.

Verification: cpp_ls suite 118 passed, 0 failed, 12 ignored; cpp_parser 520 passed; cpp_toolchain 164 + 31 passed; cargo check --workspace --all-targets passes.
Remove timing computations left behind when probes were deleted instead of prefixing them with underscores: every unused Instant::now/elapsed pair is gone, not merely silenced. Delete the unused ParserCounts fields, the prepared-stage counters, the composed-environment trace helper, and two unused latency constants.

cargo fmt --check passes; cargo clippy --workspace --all-targets --all-features -- -D warnings passes; cpp_ls suite 118 passed, 0 failed, 12 ignored; cpp_parser 520 passed; cpp_toolchain 164 + 31 passed.
Remove the unused member-name closure, the interested-name closure, condition counters, and the remaining length/computation bindings that existed only for probe traces. These were real work (iterators, atomics, clones, counts), not just unused names; they are deleted rather than prefixed with an underscore. Restore the pump's commit_them call that the cleanup had accidentally detached from its render.

Verification: cargo fmt --check, clippy -D warnings, cpp_ls suite 118 passed, cpp_parser 520 passed.
Add lint/crate_paths.py, a stdlib-only tool that reports non-use crate:: paths and can rewrite them to module-qualified names. Fix mode imports the first segment, rewrites only code, deduplicates imports, and verifies the whole workspace with cargo check; if verification fails it restores every changed file.

Wire the incremental check into CI and pre-commit through --changed, so only touched Rust files are enforced while the legacy tree is migrated. Apply it to the lexer as the first crate, reducing crate::features/text paths to imported module names.
Masking now preserves every newline, so scope line numbers stay aligned; imports are inserted in the module that owns each path instead of always at file top. Macro definition bodies are excluded from both check and fix, and replacement uses masked offsets so comments and rustdoc links are never rewritten.

Add a unit test covering the three cases: rustdoc links untouched, test-module import placed inside mod tests, and macro body untouched. Migrate align.rs as the first test-module example.
Root scope used lines[start-1:end], and start-1 is -1 for the file scope, so existing use items were read from the last line only. That made the fixer add imports already present in use groups. Slice from max(start-1, 0), normalize CRLF before parsing, and split grouped use items.

Migrate session/signature.rs as the regression case: use crate::sema and use crate::DeclKind are added, while the existing grouped Known import is left alone. Extend the unit test with the grouped-import case.
USE only matched pub use, so pub(crate) use fell through to the code path and had its crate:: paths shortened, corrupting re-exports. Match any visibility modifier on use, and add regression assertions for pub(crate) use crate::Existing and pub(crate) use crate::other::Exported.
MOD was anchored at start of line, so #[cfg(test)] mod tests { was not recognized as a module scope. Paths inside it were treated as file-root paths and their imports were inserted at the root, where the nested module cannot see them. Search for the module keyword anywhere in the masked line instead, and cover the same-line attribute in the test.
A use tree such as use crate::{config::{AlignConfig, CommentConfig}} flattened to a token config::, which was recorded as an already-imported name. The fixer therefore shortened crate::config::LuaFormatConfig to config::LuaFormatConfig without adding use crate::config. Parse use trees recursively, only adding actual leaves, aliases and self entries as imported names.

Verified on EmmyLuaAnalyzer-Rust comment_tests.rs: use crate::config is now generated inside mod tests and cargo check -p emmylua_formatter passes.
Restore the in_completion path: the global header names are collected once per declaration revision into a file-order snapshot, and a completion filters that snapshot instead of walking the whole visible closure and cloning every declaration on each keystroke. The root's own names are still read from its current summary, so a body edit never serves stale root offsets.

A declaration shape (names, scopes, kinds, types, parameters, bases, guards, includes and macros; offsets and locals excluded) now decides whether a summary or cooked reading changed the declaration set. A body edit keeps definition/type answers about other files; a declaration change still clears them. Cooked readings are compared the same way instead of clearing every definition answer globally.

Tests: a body edit reuses the completion snapshot and keeps a header's definition answer; a header declaration change rebuilds the snapshot. cpp_code_analysis lib 907 passed; completion suite 79 passed; clippy/fmt pass.
answer_the_guards now records the files its macro walk actually visited and keys the installed verdicts by the walk-inputs fingerprint of those files, not by the global index revision. A body edit changes the revision but none of the includes, guards or macro facts the verdicts depend on, so semantic classification keeps the guard answers instead of walking the closure again; a header or directive change still invalidates them.
The C++ header test returned false on the first full report. After didOpen that report can be the startup reading, where the checks are withheld until the header's cooked reading exists; a C++ project then looks as if it has no cstyle-cast finding. Keep polling until the timeout, remember whether a full report was seen at all, and only then answer false. This is the readiness race the test's own comment described.

cpp_ls suite: 118 passed, 0 failed, 12 ignored.
The lexer hands wchar_t, char8_t, char16_t and char32_t over as identifiers because it has no keyword kind for them. The semantic pass asked the index, which holds no declaration for a builtin, so the token was unclassified or took a header declaration of the spelling and was drawn as a variable. Recognise the language's builtin spellings directly and emit NameKind::Type with a Builtin provenance.

Adds a semantic test for all four spellings. cpp_ls suite 118 passed; cpp_code_analysis semantic 65 passed; clippy/fmt pass.
Measured through the real server on neovim's channel.c: the raw completion cost 100-115 ms and the rendered completion 116-135 ms, and both were computed on every keystroke. The rendered list answered with 1000 items while raw answered with 2 and was then discarded. Compute the rendered list first and only build the raw fallback when the rendered list is empty or misses the typed prefix.

Real neovim after-edit completion mean fell from 299 ms/317 ms to 205 ms in the same test; cpp_ls suite 118 passed, completion tests 79 passed, clippy/fmt pass.
The load progress message now names the three queues the pump drains: files to read, files to cook and files the second pass still has to re-read. The index slice logs also report the summary cache outcome per wave: reused, built, unstored and missing. A warm start can now be told apart from a cold parse by the reused count instead of by wall time alone.
The per-wave reused/built counts say whether the disk cache helped; the first five built paths say which files did not. On the local neovim checkout a warm start reuses every header wave and rebuilds every .c wave, which is the difference the counts now make visible.
The parser that writes a summary resolves includes with CompilerConfig::for_file: a compile command's include directories come before the project-wide ones. resolution_still_holds searched with the store's project-wide config instead, so a source whose generated header was found under build/src/nvim/auto was rechecked against build/include, declared moved, and re-parsed on every warm start. The include-search memo had the same defect: it was keyed by spelling and directory but not by the configuration asking.

The memo is now keyed by the per-file configuration, validation asks the same question the parser asked, and the stale cross-session include-search answer is no longer consulted (a path that still exists is not evidence it is still the path this search chooses). Summary writes are flushed by the existing two-second persistence pass so a process exit does not lose the records the next start reuses.

Measured on the neovim checkout: all warm waves now report 24 reused, 0 built instead of every source wave rebuilding. Regression test: a_source_file_is_validated_with_its_own_compilation. cpp_code_analysis 908 lib + 1163 suite, cpp_ls 118, clippy/fmt pass.
An edit drops the file's summary before the writer rebuilds it, and lenses_of answered that window with an empty list. A client clears every lens on an empty answer and redraws them after the refresh, so the virtual lines above each function disappeared and reappeared with every keystroke. The handler now answers Missing with the last non-empty list it gave for that document, and an empty list is treated the same way: while the references index is filling, a declaration whose places are Unknown is omitted rather than reported as zero.

The cache lives on the server context, keyed by URI; the refresh after the index drains replaces it.
The member list for ids. was found, but its replace range was mapped from the rendering with file_offset_of. At a token boundary that function answers where an offset starts, so an empty range came back at the start of the next line; the client discarded every item because the edit was not at the cursor. Measured on neovim's channel.c: members capacity/items/size, textEdit line 1086 column 0 instead of line 1085 column 6.

An empty replacement is already the editable offset the request was resolved at; use it directly and keep the start/end mapping for non-empty names. Wire test: a_member_completion_after_a_dot_edits_at_the_cursor.
The queue reaching zero is not the pump being idle. The first load still saved the sharing cache, published inactive regions and read the open file's program; the bar retired before those seconds of CPU and the machine looked busy with no indicator. The first pass now marks the load as settling and ends the task only after the program reads (or after a deferred program is known to be a later idle job). The progress sentence also names program units, which are deliberately outside pending_work for the pump's own loop.

The code-lens refresh is also narrowed to the first load: refreshing after every edit asks the client to replace its list and is entitled to clear the virtual lines first, which is the remaining source of codelens flicker.
The analysis computed CompletionItem.detail (int, int64_t *, a signature) and item_for dropped it, so a member list was three bare names. Send the one-line detail with the list; the full documentation remains completionItem/resolve's job. The member tests now assert both the range at the cursor and the detail line.
A code-lens response replaces the client's list; there is no LSP value for keep-the-current-one. The previous attempt cached a list per document, which costs memory for every tab and answers a stale number. This removes the cache: when the summary or any declaration's reference count is Unknown, lenses_of returns None and the handler answers ContentModified. The client keeps what it is showing; the refresh after the first load asks again once the count exists. A partial list is never sent.
detail alone is not drawn by every client until completionItem/resolve. labelDetails.detail is the protocol field a 3.17 client draws beside the label without a round trip, so send the same one-line type in both fields. The full declaration and documentation remain resolve's work; the list carries the type needed to tell capacity/items/size apart.
@CppCXY
CppCXY merged commit 8bad3cd into main Nov 26, 2026
14 of 15 checks passed
@CppCXY
CppCXY deleted the refactor-lock branch November 26, 2026 11:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant