Skip to content

feat: add semantic tokens for the names in Lua and .menu files - #8

Merged
4Luke4 merged 6 commits into
mainfrom
feat/semantic-tokens
Oct 29, 2026
Merged

4Luke4 merged 6 commits into
mainfrom
feat/semantic-tokens

Conversation

@4Luke4

@4Luke4 4Luke4 commented Oct 29, 2026

Copy link
Copy Markdown
Owner

What and why

This is the next plan.md step after #7: semantic tokens (textDocument/semanticTokens/full, /full/delta and /range). Formatting, quick fixes and JSDoc are still missing.

The server now tells the editor what each name in the Lua is. Examples: a parameter, a local or global variable, a library function, a field, a label. Themes can then color names by meaning, which the TextMate grammar cannot know. The classification follows hover's rules (hover/resolve.ts), so a name is colored the way it hovers.

Decisions taken with the maintainer before implementation:

Question Decision
Next feature Semantic tokens
What is classified Names only: identifiers in the Lua, and in .menu files only the embedded Lua. Keywords, literals, comments and .menu syntax stay with the TextMate grammars.
Globals A custom global modifier, declared in the manifest
defaultLibrary The Lua 5.2 manual's names, the engine's print, and EE Game Lua Functions (Infinity_*, C:AddGold). EEex functions are a separate mod, so they don't get it.

Classification

Legend types (all standard LSP / VS Code types): namespace, function, method, variable, parameter, property, label.
Legend modifiers: declaration, modification, defaultLibrary (all standard), plus global (custom).

Name Type Modifiers
Local, for variable variable; function when declared with a function expression and never assigned again declaration on the declaring name
local function f function declaration on f
Parameter, implicit self (manual §3.4.10: "an extra parameter called self") parameter declaration on parameter names
Global the document assigns function or variable, from its first assignment global. No library modifier: the document's own definition wins, as in hover.
Other global From the manual (namespace for module tables, function, variable for _G/_VERSION) or EEex-Docs (function); variable otherwise global, plus defaultLibrary as decided above
_ENV, and names resolved through a local _ENV variable None. These are fields of a table, not globals (§2.2), matching hover.
t.x / t:m() property / method. Library and EEex-Docs members as documented (string.format → function, C:AddGold → method). defaultLibrary as above; global only for _G.x
function a.b:m() names after the first; named table keys property … function / method; { x = 1 } → property modification; declaration for table keys
::name::, goto name label declaration on ::name::
Any assignment target Type as in the rows above + modification

io, os, require and coroutine are plain globals here. The engine doesn't provide them, so they never get defaultLibrary.

Deviation from the approved plan: no TextMate fallback scope for global

The plan proposed a semanticTokenScopes fallback for *.global. I checked first, and no such scope exists to map to:

  • The semantic highlight guide predefines no scope for globals.
  • VS Code's built-in Lua grammar emits none.
  • LuaLS (LuaLS/vscode-lua) maps variable.global to variable.global.lua, a scope it invented. It doesn't declare a global modifier at all. (The plan's claim that LuaLS declares a global modifier was wrong.)

So the manifest only declares the global modifier, with a description localized into the 14 display languages. Globals keep the predefined fallback of their type (variable → variable.other.readwrite), and themes and users can style *.global. The README shows how with editor.semanticTokenColorCustomizations.

Commits (one concern each; please review them one by one)

# Commit What it changes
1 refactor(server): resolve hover targets per occurrence Exports variableTarget/memberTarget from hover/resolve.ts; hover is unchanged
2 perf(server): index the first assignment to each global once per document Found while measuring (see below): classifying UI.MENU took ~250 ms, mostly here. Hover benefits too.
3 feat(server): classify the names of a document for semantic tokens src/server/semanticTokens/classify.ts (pure), with the rules above and 21 unit tests
4 feat(server): add semantic tokens Handlers, capability, pushTokens, manifest modifier + 15 nls files, fixtures, integration tests, both changelogs
5 docs: document semantic tokens README, editor guide, CONTRIBUTING, CLAUDE.md
6 refactor(server): test the semantic token results kept for deltas Fixes for the project /review findings (below)

Project /review findings and what was done

Finding Severity Outcome
The /full/delta bookkeeping (last result per document, previous id, drop on close) lived inside the handlers and was untested. VS Code's vscode.provideDocumentSemanticTokens command never sends delta requests, so integration tests can't reach it. Should fix Fixed (commit 6). Moved to TokenResults, with unit tests for: edits against the last result; a full result for an unknown id, an unseen document or a closed one; chained deltas.
?? 0 fallbacks in the legend lookups would turn a legend mismatch into a namespace token Nit Fixed: typed records, so the compiler proves every lookup
One shared { data: [] } response object Nit Fixed: a fresh object per response
A cold first request on a huge .menu file: the existing shared parse plus classification can exceed 50 ms together Nit Kept. Listed under Limitations, with numbers.

The review also checked:

  • no vscode import in src/server or src/shared;
  • no client, command, setting, dependency, build or engines.vscode change, and no ID renamed;
  • every advertised capability has a handler;
  • all three handlers check cancellation and never throw.

How it was tested

Locally (Linux/WSL2):

  • Passed: check-types; lint (0 warnings); test:unit (425 passing, up from 394); check-l10n; lua-manual -- --check.
  • npm test: 43 passing on both VS Code 1.91.0 and stable (3 new). The new tests decode the server's tokens through vscode.provideDocumentSemanticTokens / …RangeSemanticTokens on the new original fixtures semantic.lua and SEMANTIC.MENU. They cover locals, parameters, library and game functions, document globals, .menu globals across chunks, and a range.
  • Packaging: package, then notices -- --check, then vsce package + vsce ls. The VSIX has 42 files, unchanged.
  • commitlint passes on all 6 commits and on the title.

Measurements (local; the game's UI.MENU, 574 KB, 3436 Lua chunks; gitignored, nothing copied). "Joined" is all its statement chunks concatenated into one 265 KB Lua file.

Parse (existing, shared per version) Classify Encode Classify + encode, cached
UI.MENU before commit 2 ~35 ms ~250 ms — —
UI.MENU ~35 ms 21–34 ms 4–8 ms ~4 ms
Joined Lua ~14 ms 6–11 ms 2–8 ms ~2.4 ms
  • A CPU profile before commit 2 showed 1.1 s of 1.3 s (five runs) spent in globalUses, which hover's firstWrite called once per member name across all chunks.
  • Equivalence audit of commit 2: for all 984 globals of UI.MENU, hover gives the same declaration site with and without the index (identity compared): 0 mismatches.
  • Invariant audit: every one of the 16,558 name tokens in UI.MENU's 3436 chunks (all of them parse without errors) gets exactly one token, sorted, non-overlapping and single-line. The unit tests check the same against the lexer.

Size (both built locally from the same tree; main in a temporary worktree):

Measure main This branch
dist/server/server.js 671,510 B 676,056 B (+4,546)
dist/client/extension.js 437,728 B unchanged
VSIX 319,049 B 321,829 B (+2,780)
Installed size (scripts/release/vsix.mts) 1,226,948 B 1,234,681 B (+7,733)

CI: results and timings against the #7 baseline will be added in a comment once the run finishes.

Limitations

  • No type inference. Same as hover and completion:
    • a local that is later assigned a function, or is reassigned after being declared with one, is variable;
    • fields of locals are plain property.
  • Cold first request on a very large .menu file. If semantic tokens are the first request on a new document version, they pay the existing parse (~35 ms on UI.MENU) plus classification (≤ 34 ms). That is above the 50 ms guideline combined, but each part is below it. Symbols and folding usually parse first on open.
  • Colors depend on the theme. Semantic highlighting must be enabled by the theme or by editor.semanticHighlighting.enabled; VS Code's default theme enables it. The global modifier has no TextMate fallback (see above).
  • Translations of the new manifest string are machine-produced, like the others. Review is welcome.

Checklist

  • npm run check-types, npm run lint and npm run test:unit pass
  • npm test (integration) passes, if activation, commands, settings or the LSP wiring changed
  • New logic has unit tests; new commands/settings have an integration test (no new commands or settings; semantic tokens have integration tests)
  • User-facing strings use vscode.l10n.t() / package.nls.json, and npm run check-l10n passes (one new manifest string, in all 15 files)
  • CHANGELOG.md and docs/CHANGELOG.vsix.md have entries under [Unreleased] (if users notice the change)
  • No setting key or command ID was renamed (breaking change), or it is called out above

🤖 Generated with Claude Code

4Luke4 and others added 6 commits October 29, 2026 19:31
Export `variableTarget` and `memberTarget` from `hover/resolve.ts`, which
`hoverTargetAt` already uses, so that semantic tokens can classify every
variable and member occurrence of a document by the same rules as hover
without an offset lookup per name. Hover is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ment

Hover looked up the first assignment to a global by collecting every use of
the name in every chunk, once per lookup. A .menu file has thousands of
chunks (3436 in the game's UI.MENU), and classifying every name of a document
for semantic tokens performs one lookup per member name: profiling showed
1.1 s of 1.3 s spent there over five classifications of UI.MENU.

`firstWrite` now builds a name -> identifier index once per parsed document
(WeakMap, as `memberIndex` and `fieldWrites` do). It keeps the global writes
(`scopes.writes` minus resolved locals) with the lowest offset, which is the
first of `definitions` because chunks are in document order. Checked on
UI.MENU: for all 984 globals, hover gives the same declaration site with and
without the index; a unit test pins that a local's assignment does not count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`semanticTokens/classify.ts` (pure) gives every name of the Lua of a document
a token type and modifiers, following the rules of hover so that a name is
colored as it hovers. Keywords, literals, comments and .menu syntax are left
to the TextMate grammars.

Types: namespace, function, method, variable, parameter, property, label.
Modifiers: declaration, modification, defaultLibrary, and `global`, which is
not a standard modifier (the manifest declares it in the next commit).

- Locals: parameters and the implicit `self` (manual §3.4.10) are
  `parameter`; `local function f`, and a local declared with a function
  expression and never assigned again, are `function`.
- Globals: `global`; assigned in the document -> `function` or `variable`
  from the first assignment, without library modifiers (the document's own
  definition wins, as in hover); otherwise from the Lua 5.2 manual
  (`namespace` for module tables) or EEex-Docs. `defaultLibrary` for the
  manual's names, the engine's `print` and EE Game Lua Functions, not for
  EEex functions (a separate mod).
- `_ENV` and names resolved through a local `_ENV`: `variable`, not global.
- Fields: `property`, `method` after `:`; library and EEex-Docs members as
  documented; `function a.b:m()` names and named table keys from the tree.
- Labels: `label`. Assignment targets: `modification`.

Results are cached per parsed document. Every name token of the code gets
exactly one token, single-line and in order (tested against the lexer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Serve `textDocument/semanticTokens/full`, `/full/delta` and `/range` with the
classification of `semanticTokens/classify.ts`, and advertise
`semanticTokensProvider: { legend, full: { delta: true }, range: true }`.

- `pushTokens` (pure, unit-tested) encodes the names in LSP's relative
  format: line, UTF-16 character, length, legend index of the type and
  modifier bit set, optionally limited to a range. Names never span lines, so
  `multilineTokenSupport` is not needed.
- `SemanticTokensBuilder` (vscode-languageserver, already a dependency) does
  the delta encoding and diffs. One builder per document keeps the last full
  result for `/full/delta`; it is dropped on close. A delta request for a
  result the server no longer has gets a full result. Range results do not
  touch the builder.
- Handlers check cancellation at entry and never throw: errors are logged
  with their stack and answered with no tokens.

Manifest: `contributes.semanticTokenModifiers` declares the custom `global`
modifier with a description localized in all 14 display languages
(machine-produced, as the other manifest strings). No `semanticTokenScopes`
fallback is contributed. The semantic highlight guide
(https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide)
predefines no scope for globals, VS Code's Lua grammar emits none, and LuaLS's
`variable.global.lua` is its own invention. Without a fallback, globals keep the
predefined fallback of their type (`variable` -> `variable.other.readwrite`),
and themes can still style `*.global`.

Tests: unit tests for the legend (standard types; `global` is the only
custom modifier and the manifest declares it), the encoding (UTF-16, ranges)
and builder deltas. Integration tests decode the tokens of new original
fixtures (`semantic.lua`, `SEMANTIC.MENU`) through
`vscode.provideDocumentSemanticTokens` and `...RangeSemanticTokens`. Both
changelogs have entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- README: semantic highlighting in the feature summary, and a feature entry
  with an `editor.semanticTokenColorCustomizations` example for the `global`
  modifier.
- Editor guide: the semanticTokens requests in the capability table, the
  token types and modifiers, and what `defaultLibrary` covers.
- CONTRIBUTING and CLAUDE.md: the new `src/server/semanticTokens/` module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Findings of the project review of this branch:

- The per-document bookkeeping for `/full/delta` (last full result, previous
  result id, drop on close) lived inside the handlers, untested: VS Code's
  `vscode.provideDocumentSemanticTokens` command never sends delta requests.
  It moves to `TokenResults`, LSP-free apart from the builder, with unit
  tests: edits against the last result, a full result for an unknown id, an
  unseen document or a closed one, and chained deltas.
- Legend lookups are typed records over `TokenType`/`TokenModifier`, so the
  compiler proves them; the `?? 0` fallbacks that would have turned a legend
  mismatch into a `namespace` token are gone.
- Each empty response is a fresh object, and a failed request drops the
  document's last result for all three requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@4Luke4

4Luke4 commented Oct 29, 2026

Copy link
Copy Markdown
Owner Author

CI results for 152b6b3: all checks pass. Durations against the #7 baseline:

Job #7 #8 Ratio
Detect changes 4 s 4 s 1.0×
Type-check, lint, unit tests, package 26 s 19 s 0.7×
Integration tests (VS Code minimum) 29 s 34 s 1.2×
Integration tests (VS Code stable) 35 s 45 s 1.3×
CodeQL: Analyze (javascript-typescript) 45 s 60 s 1.3×
CodeQL: Analyze (actions) 42 s 36 s 0.9×
Conventional Commits 16 s 14 s 0.9×

No job reached 2× the baseline. The two slowest were still investigated.

Integration tests (stable), +10 s. The VS Code cache hit in both runs (vscode-test-Linux-1.144.0), and no download happened. Timestamps from the logs:

Phase #7 #8
Found existing install → workbench#open() (Electron start under xvfb) 2.3 s 12.0 s
Test run (N passing (…)) 40 tests, 6 s 43 tests, 7 s

All of the extra time is spent before the workbench opens, so before any extension code loads. That points to runner variance, not to this change. The 3 new tests add about 1 s.

CodeQL JavaScript/TypeScript, +15 s. Initialize CodeQL went from 8 s to 13 s (runner variance). Perform CodeQL analysis went from 32 s to 41 s, in line with the ~400 lines of new source it analyzes.

The CodeQL results check reported no alerts.

@4Luke4
4Luke4 merged commit 1d63f02 into main Oct 29, 2026
11 checks passed
@4Luke4
4Luke4 deleted the feat/semantic-tokens branch October 29, 2026 18:50
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