Repository navigation
feat: add semantic tokens for the names in Lua and .menu files - #8
Merged
Merged
Conversation
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>
Owner
Author
|
CI results for 152b6b3: all checks pass. Durations against the #7 baseline:
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 (
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. |
6 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What and why
This is the next
plan.mdstep after #7: semantic tokens (textDocument/semanticTokens/full,/full/deltaand/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:
.menufiles only the embedded Lua. Keywords, literals, comments and.menusyntax stay with the TextMate grammars.globalmodifier, declared in the manifestdefaultLibraryprint, 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), plusglobal(custom).forvariablevariable;functionwhen declared with a function expression and never assigned againdeclarationon the declaring namelocal function ffunctiondeclarationonfself(manual §3.4.10: "an extra parameter calledself")parameterdeclarationon parameter namesfunctionorvariable, from its first assignmentglobal. No library modifier: the document's own definition wins, as in hover.namespacefor module tables,function,variablefor_G/_VERSION) or EEex-Docs (function);variableotherwiseglobal, plusdefaultLibraryas decided above_ENV, and names resolved through a local_ENVvariablet.x/t:m()property/method. Library and EEex-Docs members as documented (string.format→function,C:AddGold→method).defaultLibraryas above;globalonly for_G.xfunction a.b:m()names after the first; named table keysproperty…function/method;{ x = 1 }→propertymodification;declarationfor table keys::name::,goto namelabeldeclarationon::name::+ modificationio,os,requireandcoroutineare plain globals here. The engine doesn't provide them, so they never getdefaultLibrary.Deviation from the approved plan: no TextMate fallback scope for
globalThe plan proposed a
semanticTokenScopesfallback for*.global. I checked first, and no such scope exists to map to:LuaLS/vscode-lua) mapsvariable.globaltovariable.global.lua, a scope it invented. It doesn't declare aglobalmodifier at all. (The plan's claim that LuaLS declares aglobalmodifier was wrong.)So the manifest only declares the
globalmodifier, 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 witheditor.semanticTokenColorCustomizations.Commits (one concern each; please review them one by one)
refactor(server): resolve hover targets per occurrencevariableTarget/memberTargetfromhover/resolve.ts; hover is unchangedperf(server): index the first assignment to each global once per documentUI.MENUtook ~250 ms, mostly here. Hover benefits too.feat(server): classify the names of a document for semantic tokenssrc/server/semanticTokens/classify.ts(pure), with the rules above and 21 unit testsfeat(server): add semantic tokenspushTokens, manifest modifier + 15 nls files, fixtures, integration tests, both changelogsdocs: document semantic tokensrefactor(server): test the semantic token results kept for deltas/reviewfindings (below)Project
/reviewfindings and what was done/full/deltabookkeeping (last result per document, previous id, drop on close) lived inside the handlers and was untested. VS Code'svscode.provideDocumentSemanticTokenscommand never sends delta requests, so integration tests can't reach it.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.?? 0fallbacks in the legend lookups would turn a legend mismatch into anamespacetoken{ data: [] }response object.menufile: the existing shared parse plus classification can exceed 50 ms togetherThe review also checked:
vscodeimport insrc/serverorsrc/shared;engines.vscodechange, and no ID renamed;How it was tested
Locally (Linux/WSL2):
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 throughvscode.provideDocumentSemanticTokens/…RangeSemanticTokenson the new original fixturessemantic.luaandSEMANTIC.MENU. They cover locals, parameters, library and game functions, document globals,.menuglobals across chunks, and a range.package, thennotices -- --check, thenvsce package+vsce ls. The VSIX has 42 files, unchanged.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.UI.MENUbefore commit 2UI.MENUglobalUses, which hover'sfirstWritecalled once per member name across all chunks.UI.MENU, hover gives the same declaration site with and without the index (identity compared): 0 mismatches.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;
mainin a temporary worktree):maindist/server/server.jsdist/client/extension.jsscripts/release/vsix.mts)CI: results and timings against the #7 baseline will be added in a comment once the run finishes.
Limitations
variable;property..menufile. If semantic tokens are the first request on a new document version, they pay the existing parse (~35 ms onUI.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.editor.semanticHighlighting.enabled; VS Code's default theme enables it. Theglobalmodifier has no TextMate fallback (see above).Checklist
npm run check-types,npm run lintandnpm run test:unitpassnpm test(integration) passes, if activation, commands, settings or the LSP wiring changedvscode.l10n.t()/package.nls.json, andnpm run check-l10npasses (one new manifest string, in all 15 files)CHANGELOG.mdanddocs/CHANGELOG.vsix.mdhave entries under[Unreleased](if users notice the change)🤖 Generated with Claude Code