From 95ebc4cc9d8c1af1291ab69221ce232d398ecd21 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:48:31 +0100 Subject: [PATCH 1/9] feat(server): record assignments in the scope analysis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Go to definition and find references need to know where a global gets its value, and the scope analysis only recorded declarations and reads. ScopeAnalysis gains `writes`: identifiers assigned without being declared, that is the Identifier targets of `x = …` and the name of `function x()`. `function x.y()` and `function x:m()` only read `x`, so they are not writes; declaring identifiers stay in `declarations`. Co-Authored-By: Claude Opus 5.5 --- src/server/syntax/scope.ts | 18 ++++++++++++++++-- test/unit/server/syntax/scope.test.ts | 12 ++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/server/syntax/scope.ts b/src/server/syntax/scope.ts index a64af76..e8cf5cf 100644 --- a/src/server/syntax/scope.ts +++ b/src/server/syntax/scope.ts @@ -28,12 +28,19 @@ export interface ScopeAnalysis { readonly resolved: ReadonlyMap; /** Identifiers that name globals, by name, in source order. */ readonly globals: ReadonlyMap; + /** + * Identifiers that are assigned a value without being declared: the targets of + * `x = …` and the name of `function x()`. Local or global; declaring + * identifiers are not included (see `declarations`). + */ + readonly writes: ReadonlySet; } export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { const declarations: Declaration[] = []; const resolved = new Map(); const globals = new Map(); + const writes = new Set(); const scopes: Map[] = []; const declare = (kind: DeclarationKind, name: string, identifier: Ast.Identifier | undefined): void => { @@ -95,7 +102,11 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { case 'FunctionDeclaration': { // Only the first name is a variable; the rest are field names. const [first] = node.path; - if (first) use(first); + if (first) { + use(first); + // `function x()` assigns x; `function x.y()` and `function x:m()` only read it. + if (node.path.length === 1 && node.method === undefined) writes.add(first); + } func(node.func, node.method !== undefined); break; } @@ -103,6 +114,9 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { // No declaration happens in between, so visiting in source order is exact. expressions(node.targets); expressions(node.values); + for (const target of node.targets) { + if (target.kind === 'Identifier') writes.add(target); + } break; case 'CallStatement': visitExpression(node.call); @@ -206,5 +220,5 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { scoped(() => { block(chunk.body); }); - return { declarations, resolved, globals }; + return { declarations, resolved, globals, writes }; } diff --git a/test/unit/server/syntax/scope.test.ts b/test/unit/server/syntax/scope.test.ts index 3422a3a..b1c2430 100644 --- a/test/unit/server/syntax/scope.test.ts +++ b/test/unit/server/syntax/scope.test.ts @@ -81,4 +81,16 @@ describe('server/syntax/scope', () => { it('ignores field names in table constructors and member accesses', () => { assert.deepEqual(globalNames('t = { name = value, [key] = 1 } u = t.name'), ['t', 'value', 'key', 'u']); }); + + it('records assignment targets and `function x()` names as writes', () => { + // 0 1 2 3 4 + // 0123456789012345678901234567890123456789012345678 + const source = 'local a a, t.f, b = 1 function g() end a = b + g'; + const writes = [...analyze(source).writes].map((identifier) => `${identifier.name}@${String(identifier.start)}`); + assert.deepEqual(writes, ['a@8', 'b@16', 'g@31', 'a@39']); + }); + + it('does not record declarations, reads or function paths with fields or methods as writes', () => { + assert.deepEqual([...analyze('local x = y function t.f() end function t:m() end print(x)').writes], []); + }); }); From bb2d5298e6918e0afa873743f1730ccdc642fd49 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:50:21 +0100 Subject: [PATCH 2/9] feat(server): add go to definition textDocument/definition for .lua and .menu files, within the document. - src/server/syntax/navigation.ts (pure): targetAt() finds the variable under the cursor by binary search over the identifiers the scope analysis knows about, so keywords, field names and method names never match. The index is built once per parsed document and kept in a WeakMap, so it lives exactly as long as the parse cache entry. A cursor right after a name still selects it. - definitions(): a local goes to its declaring identifier; a global to every assignment to it in the document (the new scope `writes`), in document order. The Lua chunks of a .menu file share one global environment, so globals are matched across chunks; locals stay in their chunk. - No result (null) for the implicit `self` of `function a:m()`, for globals the document never assigns (standard library, game and EEex functions, other files) and for table fields, which would need type inference. - src/server/features/definition.ts follows the documentSymbols handler pattern; capability `definitionProvider`. Tests: unit tests for targetAt/definitions, two new original fixtures (navigation.lua, NAVIGATION.MENU) and an integration test through vscode.executeDefinitionProvider. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + docs/CHANGELOG.vsix.md | 2 + src/server/features/definition.ts | 37 +++++++ src/server/server.ts | 3 + src/server/syntax/navigation.ts | 118 +++++++++++++++++++++ test/fixtures/workspace/NAVIGATION.MENU | 21 ++++ test/fixtures/workspace/navigation.lua | 16 +++ test/integration/definition.test.ts | 40 +++++++ test/integration/helpers.ts | 15 +++ test/unit/server/syntax/navigation.test.ts | 93 ++++++++++++++++ 10 files changed, 349 insertions(+) create mode 100644 src/server/features/definition.ts create mode 100644 src/server/syntax/navigation.ts create mode 100644 test/fixtures/workspace/NAVIGATION.MENU create mode 100644 test/fixtures/workspace/navigation.lua create mode 100644 test/integration/definition.test.ts create mode 100644 test/unit/server/syntax/navigation.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1980a2e..fe57909 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,10 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). comments and runs of `--` lines; in `.menu` files every `{ … }` block, `` `…` `` blocks and `"…"` scripts, plus the Lua inside them. The closing line stays visible. Honors the client's `rangeLimit` and supported kinds. +- Go to definition (`textDocument/definition`) within the document: from any use of a local to + its declaration, and from a global to every assignment to it (`x = …`, `function x()`). In + `.menu` files globals are shared by all Lua chunks, locals stay in their own chunk. No result + for the implicit `self`, for globals the document never assigns, or for table fields. - Error-tolerant Lua 5.2 parser and scope analysis (`src/server/syntax/`), checked against the official compiler by a differential test; it publishes no diagnostics of its own. - Localization of the manifest and UI strings into all 14 VS Code display languages diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 93b229b..00c6ad9 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -22,6 +22,8 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea **Go to Symbol in Editor**. - **Code folding that follows the code.** Fold functions, loops, each branch of an `if`, tables, comments, and every block and script of a `.menu` file. +- **Go to Definition** jumps from a variable to where it is declared, or to where a global + gets its value in the same file, including across the Lua of a `.menu` file. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors too**: setup guides for Sublime Text, Neovim, Emacs, JetBrains IDEs, Helix, Zed, Kate, Notepad++ and Geany are on the project page. diff --git a/src/server/features/definition.ts b/src/server/features/definition.ts new file mode 100644 index 0000000..367f547 --- /dev/null +++ b/src/server/features/definition.ts @@ -0,0 +1,37 @@ +import type { Connection, Location, TextDocuments } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { definitions, targetAt } from '../syntax/navigation.ts'; + +export interface DefinitionDeps { + readonly cache: ParsedDocumentCache; +} + +/** + * `textDocument/definition` within the document: the declaration of a local, or + * every assignment to a global (see src/server/syntax/navigation.ts). + */ +export function register(connection: Connection, documents: TextDocuments, deps: DefinitionDeps): void { + connection.onDefinition(({ textDocument, position }, token): Location[] | null => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) { + return null; + } + // Synchronous from here on: a cancellation can only arrive after the response. + const parsed = deps.cache.get(document); + const hit = targetAt(parsed, document.offsetAt(position)); + const found = hit ? definitions(parsed, hit.target) : []; + if (found.length === 0) { + return null; + } + return found.map(({ start, end }) => ({ + uri: document.uri, + range: { start: document.positionAt(start), end: document.positionAt(end) }, + })); + } catch (error) { + connection.console.error(`Definition for ${textDocument.uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }); +} diff --git a/src/server/server.ts b/src/server/server.ts index c058144..5598ce7 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -10,6 +10,7 @@ import { } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { ParsedDocumentCache } from './documentCache.ts'; +import * as definition from './features/definition.ts'; import * as diagnostics from './features/diagnostics.ts'; import * as documentSymbols from './features/documentSymbols.ts'; import * as foldingRanges from './features/foldingRanges.ts'; @@ -49,6 +50,7 @@ connection.onInitialize((params) => { rangeLimit: folding?.rangeLimit, kinds: folding?.foldingRangeKind?.valueSet, }); + definition.register(connection, documents, { cache: parsed }); return { capabilities: { textDocumentSync: { @@ -58,6 +60,7 @@ connection.onInitialize((params) => { }, documentSymbolProvider: { label: 'IE Lua' }, foldingRangeProvider: true, + definitionProvider: true, }, serverInfo: { name: 'IE Lua Language Server' }, }; diff --git a/src/server/syntax/navigation.ts b/src/server/syntax/navigation.ts new file mode 100644 index 0000000..2d6994e --- /dev/null +++ b/src/server/syntax/navigation.ts @@ -0,0 +1,118 @@ +// Same-document navigation: the variable under the cursor, its definitions and +// its references. Pure: no LSP or `vscode` imports. +// +// Locals belong to one chunk. Globals are shared by every chunk of a document: +// the Lua of a .menu file runs in one global environment. Field names (`t.x`, +// `t:m()`, `{ x = 1 }`) are not variables and are never targets. + +import type * as Ast from './ast.ts'; +import type { ParsedDocument } from './document.ts'; +import type { Declaration } from './scope.ts'; + +export type NavigationTarget = + | { + readonly kind: 'local'; + /** Index in `ParsedDocument.chunks` of the chunk that declares the local. */ + readonly chunkIndex: number; + readonly declaration: Declaration; + } + | { readonly kind: 'global'; readonly name: string }; + +export interface TargetHit { + readonly target: NavigationTarget; + /** The identifier under the cursor. */ + readonly identifier: Ast.Identifier; +} + +interface IndexEntry { + readonly identifier: Ast.Identifier; + readonly chunkIndex: number; +} + +/** Variable identifiers of each document, sorted by offset; dropped with the document. */ +const indexes = new WeakMap(); + +function variableIndex(document: ParsedDocument): readonly IndexEntry[] { + let index = indexes.get(document); + if (!index) { + const entries: IndexEntry[] = []; + document.chunks.forEach(({ scopes }, chunkIndex) => { + for (const identifier of scopes.resolved.keys()) entries.push({ identifier, chunkIndex }); + for (const uses of scopes.globals.values()) { + for (const identifier of uses) entries.push({ identifier, chunkIndex }); + } + }); + index = entries.sort((a, b) => a.identifier.start - b.identifier.start); + indexes.set(document, index); + } + return index; +} + +/** + * The variable at `offset`, or `undefined` when there is none (keyword, field + * name, string, comment, menu syntax). A cursor just after a name still + * selects it, as editors place the cursor there after typing. + */ +export function targetAt(document: ParsedDocument, offset: number): TargetHit | undefined { + const index = variableIndex(document); + // Last identifier starting at or before `offset`. Identifiers never touch, so + // one starting exactly at `offset` wins over one ending there. + let low = 0; + let high = index.length - 1; + let found: IndexEntry | undefined; + while (low <= high) { + const middle = (low + high) >> 1; + const entry = index[middle]; + if (entry && entry.identifier.start <= offset) { + found = entry; + low = middle + 1; + } else { + high = middle - 1; + } + } + if (!found || offset > found.identifier.end) { + return undefined; + } + const { identifier, chunkIndex } = found; + const declaration = document.chunks[chunkIndex]?.scopes.resolved.get(identifier); + return { + identifier, + target: declaration ? { kind: 'local', chunkIndex, declaration } : { kind: 'global', name: identifier.name }, + }; +} + +/** Every identifier naming the global `name`, in document order. */ +function globalUses(document: ParsedDocument, name: string): Ast.Identifier[] { + return document.chunks.flatMap(({ scopes }) => scopes.globals.get(name) ?? []); +} + +function isGlobalWrite(document: ParsedDocument, identifier: Ast.Identifier): boolean { + return document.chunks.some(({ scopes }) => scopes.writes.has(identifier)); +} + +/** + * Where the target is defined, in document order: the declaring identifier of + * a local, or every assignment to a global in this document. Empty for the + * implicit `self` and for globals this document never assigns (standard + * library, game and EEex functions, globals of other files). + */ +export function definitions(document: ParsedDocument, target: NavigationTarget): Ast.Identifier[] { + if (target.kind === 'local') { + return target.declaration.identifier ? [target.declaration.identifier] : []; + } + return globalUses(document, target.name).filter((identifier) => isGlobalWrite(document, identifier)); +} + +/** + * Every identifier naming the target, in document order. Without + * `includeDeclaration`, the definitions (see `definitions`) are left out. + */ +export function references(document: ParsedDocument, target: NavigationTarget, includeDeclaration: boolean): Ast.Identifier[] { + if (target.kind === 'local') { + const { identifier, references: uses } = target.declaration; + const all = includeDeclaration && identifier ? [identifier, ...uses] : [...uses]; + return all.sort((a, b) => a.start - b.start); + } + const uses = globalUses(document, target.name); + return includeDeclaration ? uses : uses.filter((identifier) => !isGlobalWrite(document, identifier)); +} diff --git a/test/fixtures/workspace/NAVIGATION.MENU b/test/fixtures/workspace/NAVIGATION.MENU new file mode 100644 index 0000000..ba422a7 --- /dev/null +++ b/test/fixtures/workspace/NAVIGATION.MENU @@ -0,0 +1,21 @@ +-- Original fixture: navigation across the Lua chunks of a .menu file. +` +selected = 0 +` +menu +{ + name 'NAVIGATION_MAIN' + onOpen + " + selected = 1 + " + button + { + enabled "selected == 1" + action + " + local value = selected + selected = value + 1 + " + } +} diff --git a/test/fixtures/workspace/navigation.lua b/test/fixtures/workspace/navigation.lua new file mode 100644 index 0000000..d3b88ba --- /dev/null +++ b/test/fixtures/workspace/navigation.lua @@ -0,0 +1,16 @@ +-- Original fixture: go to definition, find references and rename. +local counter = 0 + +function increment(step) + counter = counter + step + return counter +end + +local Panel = {} + +function Panel:open() + return self +end + +increment(1) +print(counter) diff --git a/test/integration/definition.test.ts b/test/integration/definition.test.ts new file mode 100644 index 0000000..61fbc26 --- /dev/null +++ b/test/integration/definition.test.ts @@ -0,0 +1,40 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, openFixture, starts } from './helpers.ts'; + +async function definitionsAt(file: string, line: number, character: number): Promise { + const uri = await openFixture(file); + const found = await vscode.commands.executeCommand<(vscode.Location | vscode.LocationLink)[] | undefined>( + 'vscode.executeDefinitionProvider', + uri, + new vscode.Position(line, character), + ); + assert.ok(found, 'no definition provider answered'); + return starts(found); +} + +suite('Go to definition', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('goes from a use of a local to its declaration', async () => { + assert.deepEqual(await definitionsAt('navigation.lua', 15, 6), ['1:6']); + }); + + test('goes from a call of a global function to its definition', async () => { + assert.deepEqual(await definitionsAt('navigation.lua', 14, 0), ['3:9']); + }); + + test('has no definition for the implicit self', async () => { + assert.deepEqual(await definitionsAt('navigation.lua', 11, 8), []); + }); + + test('lists every assignment to a global across the Lua of a .menu file', async () => { + assert.deepEqual(await definitionsAt('NAVIGATION.MENU', 13, 11), ['2:0', '9:2', '17:3']); + }); +}); diff --git a/test/integration/helpers.ts b/test/integration/helpers.ts index 484eb2a..1ec1aa6 100644 --- a/test/integration/helpers.ts +++ b/test/integration/helpers.ts @@ -56,3 +56,18 @@ export async function withSetting(key: string, value: unknown): Promise<() => Th export async function closeAllEditors(): Promise { await vscode.commands.executeCommand('workbench.action.closeAllEditors'); } + +/** `line:character` of each location's start, for compact assertions. */ +export function starts(locations: readonly (vscode.Location | vscode.LocationLink)[]): string[] { + return locations.map((location) => { + const { start } = 'uri' in location ? location.range : location.targetRange; + return `${String(start.line)}:${String(start.character)}`; + }); +} + +/** Opens a fixture in an editor and returns its URI. */ +export async function openFixture(file: string): Promise { + const uri = fixtureUri(file); + await vscode.window.showTextDocument(await vscode.workspace.openTextDocument(uri)); + return uri; +} diff --git a/test/unit/server/syntax/navigation.test.ts b/test/unit/server/syntax/navigation.test.ts new file mode 100644 index 0000000..92c8dd3 --- /dev/null +++ b/test/unit/server/syntax/navigation.test.ts @@ -0,0 +1,93 @@ +import assert from 'node:assert/strict'; +import { parseDocument, type ParsedDocument } from '../../../../src/server/syntax/document.ts'; +import { definitions, targetAt } from '../../../../src/server/syntax/navigation.ts'; + +/** `name@offset` for each identifier. */ +const at = (identifiers: readonly { name: string; start: number }[]): string[] => identifiers.map((i) => `${i.name}@${String(i.start)}`); + +/** Offset of the `occurrence`-th (0-based) `needle` in `text`. */ +function offsetOf(text: string, needle: string, occurrence = 0): number { + let offset = -1; + for (let i = 0; i <= occurrence; i++) { + offset = text.indexOf(needle, offset + 1); + assert.ok(offset >= 0, `"${needle}" #${String(i)} not found`); + } + return offset; +} + +function definitionsAt(document: ParsedDocument, offset: number): string[] | undefined { + const hit = targetAt(document, offset); + return hit && at(definitions(document, hit.target)); +} + +describe('server/syntax/navigation', () => { + describe('targetAt', () => { + // 0 1 2 + // 0123456789012345678901234 + const text = 'local t = {} t.x = t:m()'; + const document = parseDocument(text, 'lua'); + + it('finds the variable under the cursor, also just after its last character', () => { + for (const offset of [6, 7]) { + const hit = targetAt(document, offset); + assert.equal(hit?.target.kind, 'local'); + assert.equal(hit.identifier.start, 6); + } + assert.deepEqual(targetAt(document, 13)?.identifier.start, 13); + }); + + it('ignores keywords, field and method names, and space between tokens', () => { + for (const offset of [0, 3, 9, 15, 21]) { + assert.equal(targetAt(document, offset), undefined, `offset ${String(offset)}`); + } + }); + + it('classifies names without a visible local as globals', () => { + const hit = targetAt(parseDocument('print(x)', 'lua'), 6); + assert.deepEqual(hit?.target, { kind: 'global', name: 'x' }); + }); + + it('returns nothing for an empty document', () => { + assert.equal(targetAt(parseDocument('', 'lua'), 0), undefined); + }); + }); + + describe('definitions', () => { + it('goes from any use of a local to its declaration', () => { + const text = 'local count = 0\ncount = count + 1\nprint(count)'; + const document = parseDocument(text, 'lua'); + for (const occurrence of [0, 1, 2, 3]) { + assert.deepEqual(definitionsAt(document, offsetOf(text, 'count', occurrence)), ['count@6']); + } + }); + + it('resolves shadowed names to the innermost declaration', () => { + const text = 'local x = 1\ndo local x = 2 print(x) end\nprint(x)'; + const document = parseDocument(text, 'lua'); + assert.deepEqual(definitionsAt(document, offsetOf(text, 'x', 2)), ['x@21']); + assert.deepEqual(definitionsAt(document, offsetOf(text, 'x', 3)), ['x@6']); + }); + + it('lists every assignment to a global, including `function g()`', () => { + const text = 'function g() end\nif ready then g = nil end\ng()'; + const document = parseDocument(text, 'lua'); + assert.deepEqual(definitionsAt(document, offsetOf(text, 'g', 2)), ['g@9', 'g@31']); + }); + + it('returns no definition for globals the document never assigns, nor for the implicit self', () => { + const text = 'function T:m() return self end\nprint(T)'; + const document = parseDocument(text, 'lua'); + assert.deepEqual(definitionsAt(document, offsetOf(text, 'print')), []); + assert.deepEqual(definitionsAt(document, offsetOf(text, 'T', 1)), []); + assert.deepEqual(definitionsAt(document, offsetOf(text, 'self')), []); + }); + + it('shares globals between the Lua chunks of a .menu file, but not locals', () => { + const text = "`\nshown = false\nlocal hidden = 1\n`\nmenu\n{\n\tname 'M'\n\tonOpen \"shown = true print(hidden)\"\n}\n"; + const document = parseDocument(text, 'menu'); + assert.equal(document.chunks.length, 2); + assert.deepEqual(definitionsAt(document, offsetOf(text, 'shown', 1)), ['shown@2', `shown@${String(offsetOf(text, 'shown', 1))}`]); + assert.deepEqual(definitionsAt(document, offsetOf(text, 'hidden', 1)), []); + }); + }); +}); From fec37c88fd7ac7cc77bda4e526c6f82e69daceaf Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:53:35 +0100 Subject: [PATCH 3/9] feat(server): add find references textDocument/references for .lua and .menu files, within the document, using the same matching as go to definition (navigation.ts): - a local: its declaring identifier and every use, in document order, including the implicit `self` of a method (which has no declaration); - a global: every use in every Lua chunk of the document. `context.includeDeclaration` is honored: for a local it adds the declaring identifier, for a global the assignments to it (the same locations go to definition returns). src/server/features/references.ts follows the existing handler pattern; capability `referencesProvider`. Unit tests cover shadowing, recursion, `self`, globals with and without declarations and .menu chunks; the integration test goes through vscode.executeReferenceProvider. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ docs/CHANGELOG.vsix.md | 1 + src/server/features/references.ts | 37 +++++++++++++++++ src/server/server.ts | 3 ++ test/integration/references.test.ts | 34 ++++++++++++++++ test/unit/server/syntax/navigation.test.ts | 47 +++++++++++++++++++++- 6 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 src/server/features/references.ts create mode 100644 test/integration/references.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fe57909..e08e6ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,10 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). its declaration, and from a global to every assignment to it (`x = …`, `function x()`). In `.menu` files globals are shared by all Lua chunks, locals stay in their own chunk. No result for the implicit `self`, for globals the document never assigns, or for table fields. +- Find references (`textDocument/references`) within the document, with the same matching as + go to definition: the uses of a local, including the implicit `self` of a method, or every use + of a global across the Lua chunks of the document. `includeDeclaration` decides whether the + local's declaration, or the assignments to the global, are included. - Error-tolerant Lua 5.2 parser and scope analysis (`src/server/syntax/`), checked against the official compiler by a differential test; it publishes no diagnostics of its own. - Localization of the manifest and UI strings into all 14 VS Code display languages diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 00c6ad9..fa0870a 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -24,6 +24,7 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea comments, and every block and script of a `.menu` file. - **Go to Definition** jumps from a variable to where it is declared, or to where a global gets its value in the same file, including across the Lua of a `.menu` file. +- **Find All References** lists every use of a variable in the same file. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors too**: setup guides for Sublime Text, Neovim, Emacs, JetBrains IDEs, Helix, Zed, Kate, Notepad++ and Geany are on the project page. diff --git a/src/server/features/references.ts b/src/server/features/references.ts new file mode 100644 index 0000000..66eb95f --- /dev/null +++ b/src/server/features/references.ts @@ -0,0 +1,37 @@ +import type { Connection, Location, TextDocuments } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { references, targetAt } from '../syntax/navigation.ts'; + +export interface ReferencesDeps { + readonly cache: ParsedDocumentCache; +} + +/** + * `textDocument/references` within the document (see + * src/server/syntax/navigation.ts). `context.includeDeclaration` decides whether + * the declaration of a local, or the assignments to a global, are included. + */ +export function register(connection: Connection, documents: TextDocuments, deps: ReferencesDeps): void { + connection.onReferences(({ textDocument, position, context }, token): Location[] | null => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) { + return null; + } + // Synchronous from here on: a cancellation can only arrive after the response. + const parsed = deps.cache.get(document); + const hit = targetAt(parsed, document.offsetAt(position)); + if (!hit) { + return null; + } + return references(parsed, hit.target, context.includeDeclaration).map(({ start, end }) => ({ + uri: document.uri, + range: { start: document.positionAt(start), end: document.positionAt(end) }, + })); + } catch (error) { + connection.console.error(`References for ${textDocument.uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }); +} diff --git a/src/server/server.ts b/src/server/server.ts index 5598ce7..3ba6c29 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -14,6 +14,7 @@ import * as definition from './features/definition.ts'; import * as diagnostics from './features/diagnostics.ts'; import * as documentSymbols from './features/documentSymbols.ts'; import * as foldingRanges from './features/foldingRanges.ts'; +import * as references from './features/references.ts'; import { SettingsStore } from './settingsStore.ts'; import { loadLua52 } from './validation/lua52.ts'; @@ -51,6 +52,7 @@ connection.onInitialize((params) => { kinds: folding?.foldingRangeKind?.valueSet, }); definition.register(connection, documents, { cache: parsed }); + references.register(connection, documents, { cache: parsed }); return { capabilities: { textDocumentSync: { @@ -61,6 +63,7 @@ connection.onInitialize((params) => { documentSymbolProvider: { label: 'IE Lua' }, foldingRangeProvider: true, definitionProvider: true, + referencesProvider: true, }, serverInfo: { name: 'IE Lua Language Server' }, }; diff --git a/test/integration/references.test.ts b/test/integration/references.test.ts new file mode 100644 index 0000000..12e508f --- /dev/null +++ b/test/integration/references.test.ts @@ -0,0 +1,34 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, openFixture, starts } from './helpers.ts'; + +/** References as VS Code requests them (declarations included). */ +async function referencesAt(file: string, line: number, character: number): Promise { + const uri = await openFixture(file); + const found = await vscode.commands.executeCommand( + 'vscode.executeReferenceProvider', + uri, + new vscode.Position(line, character), + ); + assert.ok(found, 'no reference provider answered'); + assert.ok(found.every((location) => location.uri.toString() === uri.toString())); + return starts(found); +} + +suite('Find references', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('finds the declaration and every use of a local', async () => { + assert.deepEqual(await referencesAt('navigation.lua', 1, 6), ['1:6', '4:1', '4:11', '5:8', '15:6']); + }); + + test('finds a global in every Lua chunk of a .menu file', async () => { + assert.deepEqual(await referencesAt('NAVIGATION.MENU', 2, 0), ['2:0', '9:2', '13:11', '16:17', '17:3']); + }); +}); diff --git a/test/unit/server/syntax/navigation.test.ts b/test/unit/server/syntax/navigation.test.ts index 92c8dd3..03ecdd3 100644 --- a/test/unit/server/syntax/navigation.test.ts +++ b/test/unit/server/syntax/navigation.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { parseDocument, type ParsedDocument } from '../../../../src/server/syntax/document.ts'; -import { definitions, targetAt } from '../../../../src/server/syntax/navigation.ts'; +import { definitions, references, targetAt } from '../../../../src/server/syntax/navigation.ts'; /** `name@offset` for each identifier. */ const at = (identifiers: readonly { name: string; start: number }[]): string[] => identifiers.map((i) => `${i.name}@${String(i.start)}`); @@ -90,4 +90,49 @@ describe('server/syntax/navigation', () => { assert.deepEqual(definitionsAt(document, offsetOf(text, 'hidden', 1)), []); }); }); + + describe('references', () => { + function referencesAt(text: string, needle: string, occurrence: number, includeDeclaration: boolean, kind: 'lua' | 'menu' = 'lua'): string[] { + const document = parseDocument(text, kind); + const hit = targetAt(document, offsetOf(text, needle, occurrence)); + assert.ok(hit, `no target at "${needle}" #${String(occurrence)}`); + return at(references(document, hit.target, includeDeclaration)); + } + + it('lists the uses of a local, with its declaration first when asked', () => { + // 0 1 2 3 + // 01234567890123456789012345678901234567 + const text = 'local n = 1 n = n + 1 do print(n) end'; + assert.deepEqual(referencesAt(text, 'n', 2, true), ['n@6', 'n@12', 'n@16', 'n@31']); + assert.deepEqual(referencesAt(text, 'n', 0, false), ['n@12', 'n@16', 'n@31']); + }); + + it('lists a local function before the recursive calls in its body', () => { + const text = 'local function f(n) return f(n - 1) end'; + assert.deepEqual(referencesAt(text, 'f', 1, true), ['f@15', 'f@27']); + }); + + it('keeps shadowing locals apart', () => { + const text = 'local x = 1 do local x = 2 print(x) end print(x)'; + assert.deepEqual(referencesAt(text, 'x', 0, true), ['x@6', 'x@46']); + assert.deepEqual(referencesAt(text, 'x', 1, true), ['x@21', 'x@33']); + }); + + it('lists the uses of the implicit self of a method', () => { + const text = 'function T:m() self.n = 1 return self end'; + assert.deepEqual(referencesAt(text, 'self', 1, true), ['self@15', 'self@33']); + }); + + it('treats every assignment to a global as a declaration', () => { + const text = 'g = 1 function g() end print(g)'; + assert.deepEqual(referencesAt(text, 'g', 2, true), ['g@0', 'g@15', 'g@29']); + assert.deepEqual(referencesAt(text, 'g', 2, false), ['g@29']); + }); + + it('finds globals in every Lua chunk of a .menu file, locals only in their own', () => { + const text = "`\nflag = 1\nlocal own = flag\n`\nmenu\n{\n\tname 'M'\n\tenabled \"flag == own\"\n}\n"; + assert.deepEqual(referencesAt(text, 'flag', 2, true, 'menu'), ['flag@2', 'flag@23', `flag@${String(offsetOf(text, 'flag', 2))}`]); + assert.deepEqual(referencesAt(text, 'own', 0, true, 'menu'), ['own@17']); + }); + }); }); From e09ed49df62c2df6e8a9aeb53988f1cbcb78efaa Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:59:17 +0100 Subject: [PATCH 4/9] feat: add same-file rename textDocument/prepareRename and textDocument/rename for .lua and .menu files, for locals and for globals the document assigns. src/server/syntax/rename.ts (pure) refuses, rather than producing code that behaves differently, when: - the cursor is not on a variable name, or is on the implicit `self`; - the variable is a global the document never assigns: it is defined in another file, the game or EEex, which a same-file rename cannot update; - the code where the variable can occur has syntax errors (its chunk for a local, any chunk for a global). Found while testing: error recovery drops the unfinished call in `print(a`, so that use of `a` is not in the tree and a rename would silently miss it; - the new name is not a Lua name or is a reserved word, decided by the lexer itself (`lex(newName)` must yield exactly one name token); - the rename would change what any name refers to. The renamed text is re-parsed and every identifier's binding (declaration, or global by name) is compared with the original: renamed uses must keep their declaration, every other identifier must be unchanged. This catches capture by an inner local and hiding an outer local or a global used in the renamed local's scope. Merging two globals is refused explicitly, since both sides keep a global binding. Refusals are ResponseError(RequestFailed) with a fixed English message per reason (src/shared/protocol.ts). LSP declares no error data for these requests, and vscode-languageclient 11 rethrows a failed prepareRename as `new Error(error.message)` (lib/common/rename.js), so the client middleware (src/client/renameRefusals.ts) recognizes a refusal by its exact message and rethrows it through vscode.l10n.t(). Other editors show the English message. The 7 strings are translated into all 14 locales (machine-produced, like the existing ones); a unit test checks that every server message has a client translation key. Capability: `renameProvider: { prepareProvider: true }` only when the client announces `rename.prepareSupport`, otherwise `true`. Edits are sent as versioned documentChanges when the client supports them, so a stale edit is rejected instead of applied. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++ docs/CHANGELOG.vsix.md | 2 + l10n/bundle.l10n.cs.json | 7 ++ l10n/bundle.l10n.de.json | 7 ++ l10n/bundle.l10n.es.json | 7 ++ l10n/bundle.l10n.fr.json | 7 ++ l10n/bundle.l10n.hu.json | 7 ++ l10n/bundle.l10n.it.json | 7 ++ l10n/bundle.l10n.ja.json | 7 ++ l10n/bundle.l10n.json | 7 ++ l10n/bundle.l10n.ko.json | 7 ++ l10n/bundle.l10n.pl.json | 7 ++ l10n/bundle.l10n.pt-br.json | 7 ++ l10n/bundle.l10n.ru.json | 7 ++ l10n/bundle.l10n.tr.json | 7 ++ l10n/bundle.l10n.zh-cn.json | 7 ++ l10n/bundle.l10n.zh-tw.json | 7 ++ src/client/lsp.ts | 2 + src/client/renameRefusals.ts | 59 ++++++++++ src/server/features/rename.ts | 74 ++++++++++++ src/server/server.ts | 5 + src/server/syntax/navigation.ts | 12 +- src/server/syntax/rename.ts | 144 +++++++++++++++++++++++ src/shared/protocol.ts | 28 +++++ test/integration/rename.test.ts | 77 ++++++++++++ test/unit/server/features/rename.test.ts | 31 +++++ test/unit/server/syntax/rename.test.ts | 117 ++++++++++++++++++ test/unit/shared/protocol.test.ts | 13 ++ 28 files changed, 671 insertions(+), 5 deletions(-) create mode 100644 src/client/renameRefusals.ts create mode 100644 src/server/features/rename.ts create mode 100644 src/server/syntax/rename.ts create mode 100644 test/integration/rename.test.ts create mode 100644 test/unit/server/features/rename.test.ts create mode 100644 test/unit/server/syntax/rename.test.ts create mode 100644 test/unit/shared/protocol.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e08e6ea..e7535cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,13 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). go to definition: the uses of a local, including the implicit `self` of a method, or every use of a global across the Lua chunks of the document. `includeDeclaration` decides whether the local's declaration, or the assignments to the global, are included. +- Rename (`textDocument/prepareRename`, `textDocument/rename`) within the document, for locals + and for globals the document assigns. Refused, with a reason localized in VS Code: anything + that is not a variable, the implicit `self`, globals the document never assigns (defined in + another file, the game or EEex), code with syntax errors where the variable can occur, new names + that are not Lua names or are reserved words, and any rename that would change what a name + refers to (checked by re-analyzing the renamed text). Edits are versioned when the client + supports `documentChanges`. - Error-tolerant Lua 5.2 parser and scope analysis (`src/server/syntax/`), checked against the official compiler by a differential test; it publishes no diagnostics of its own. - Localization of the manifest and UI strings into all 14 VS Code display languages diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index fa0870a..7d9b61f 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -25,6 +25,8 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea - **Go to Definition** jumps from a variable to where it is declared, or to where a global gets its value in the same file, including across the Lua of a `.menu` file. - **Find All References** lists every use of a variable in the same file. +- **Rename Symbol** renames a variable everywhere in the file. It refuses, and tells you why, + when the rename could break your code — for example when the new name is already used nearby. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors too**: setup guides for Sublime Text, Neovim, Emacs, JetBrains IDEs, Helix, Zed, Kate, Notepad++ and Geany are on the project page. diff --git a/l10n/bundle.l10n.cs.json b/l10n/bundle.l10n.cs.json index d94abfd..55d86fd 100644 --- a/l10n/bundle.l10n.cs.json +++ b/l10n/bundle.l10n.cs.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Přejmenovat lze pouze názvy lokálních a globálních proměnných.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "Implicitní \"self\" metody nemá deklaraci a nelze jej přejmenovat.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Tato globální proměnná se v tomto souboru nikdy nepřiřazuje. Je definována jinde (v jiném souboru, ve hře nebo v EEex), proto ji zde nelze přejmenovat.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Nejprve opravte syntaktické chyby: v kódu, který nelze analyzovat, nelze najít všechny názvy.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "Nový název není platný název jazyka Lua: použijte písmena, číslice a podtržítka a nezačínejte číslicí.", + "The new name is a reserved word in Lua.": "Nový název je v jazyce Lua rezervované slovo.", + "Renaming would change what another name in this file refers to.": "Přejmenováním by se změnilo, na co odkazuje jiný název v tomto souboru.", "Open a Lua or Infinity Engine menu file to validate it.": "Pokud chcete soubor ověřit, otevřete soubor Lua nebo soubor nabídky Infinity Engine.", "IE Lua: no problems found.": "IE Lua: Nenašly se žádné problémy.", "IE Lua: {0} problem(s) found.": "IE Lua: Počet nalezených problémů: {0}.", diff --git a/l10n/bundle.l10n.de.json b/l10n/bundle.l10n.de.json index 673072d..2bad2a2 100644 --- a/l10n/bundle.l10n.de.json +++ b/l10n/bundle.l10n.de.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Nur die Namen lokaler und globaler Variablen können umbenannt werden.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "Das implizite \"self\" einer Methode hat keine Deklaration und kann nicht umbenannt werden.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Diese globale Variable wird in dieser Datei nie zugewiesen. Sie ist an anderer Stelle definiert (in einer anderen Datei, im Spiel oder in EEex) und kann daher hier nicht umbenannt werden.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Beheben Sie zuerst die Syntaxfehler: In Code, der nicht geparst werden kann, lassen sich nicht alle Namen finden.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "Der neue Name ist kein gültiger Lua-Name: Verwenden Sie Buchstaben, Ziffern und Unterstriche, und beginnen Sie nicht mit einer Ziffer.", + "The new name is a reserved word in Lua.": "Der neue Name ist ein reserviertes Wort in Lua.", + "Renaming would change what another name in this file refers to.": "Durch die Umbenennung würde sich ändern, worauf sich ein anderer Name in dieser Datei bezieht.", "Open a Lua or Infinity Engine menu file to validate it.": "Öffnen Sie eine Lua- oder Infinity Engine-Menüdatei, um sie zu überprüfen.", "IE Lua: no problems found.": "IE Lua: Keine Probleme gefunden.", "IE Lua: {0} problem(s) found.": "IE Lua: {0} Problem(e) gefunden.", diff --git a/l10n/bundle.l10n.es.json b/l10n/bundle.l10n.es.json index 539286d..1b9b79d 100644 --- a/l10n/bundle.l10n.es.json +++ b/l10n/bundle.l10n.es.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Solo se puede cambiar el nombre de variables locales y globales.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "El \"self\" implícito de un método no tiene declaración y no se puede cambiar su nombre.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Esta variable global nunca se asigna en este archivo. Está definida en otro lugar (otro archivo, el juego o EEex), por lo que no se puede cambiar su nombre aquí.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Corrija primero los errores de sintaxis: en el código que no se puede analizar no se pueden encontrar todos los nombres.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "El nuevo nombre no es un nombre de Lua válido: use letras, dígitos y guiones bajos, y no empiece por un dígito.", + "The new name is a reserved word in Lua.": "El nuevo nombre es una palabra reservada de Lua.", + "Renaming would change what another name in this file refers to.": "El cambio de nombre modificaría a qué hace referencia otro nombre de este archivo.", "Open a Lua or Infinity Engine menu file to validate it.": "Abra un archivo Lua o un archivo de menú de Infinity Engine para validarlo.", "IE Lua: no problems found.": "IE Lua: no se encontraron problemas.", "IE Lua: {0} problem(s) found.": "IE Lua: se encontraron {0} problema(s).", diff --git a/l10n/bundle.l10n.fr.json b/l10n/bundle.l10n.fr.json index f4eaefa..9ddd033 100644 --- a/l10n/bundle.l10n.fr.json +++ b/l10n/bundle.l10n.fr.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Seuls les noms des variables locales et globales peuvent être renommés.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "Le \"self\" implicite d'une méthode n'a pas de déclaration et ne peut pas être renommé.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Cette variable globale n'est jamais affectée dans ce fichier. Elle est définie ailleurs (un autre fichier, le jeu ou EEex) et ne peut donc pas être renommée ici.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Corrigez d'abord les erreurs de syntaxe : dans du code qui ne peut pas être analysé, tous les noms ne peuvent pas être trouvés.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "Le nouveau nom n'est pas un nom Lua valide : utilisez des lettres, des chiffres et des traits de soulignement, et ne commencez pas par un chiffre.", + "The new name is a reserved word in Lua.": "Le nouveau nom est un mot réservé de Lua.", + "Renaming would change what another name in this file refers to.": "Le renommage changerait ce à quoi fait référence un autre nom de ce fichier.", "Open a Lua or Infinity Engine menu file to validate it.": "Ouvrez un fichier Lua ou un fichier de menu Infinity Engine pour le valider.", "IE Lua: no problems found.": "IE Lua : aucun problème détecté.", "IE Lua: {0} problem(s) found.": "IE Lua : {0} problème(s) détecté(s).", diff --git a/l10n/bundle.l10n.hu.json b/l10n/bundle.l10n.hu.json index b73e6f3..66f3db3 100644 --- a/l10n/bundle.l10n.hu.json +++ b/l10n/bundle.l10n.hu.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Csak helyi és globális változók neve nevezhető át.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "Egy metódus implicit \"self\" paraméterének nincs deklarációja, ezért nem nevezhető át.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Ez a globális változó ebben a fájlban sosem kap értéket. Máshol van definiálva (egy másik fájlban, a játékban vagy az EEex-ben), ezért itt nem nevezhető át.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Először javítsa ki a szintaktikai hibákat: a nem elemezhető kódban nem található meg minden név.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "Az új név nem érvényes Lua-név: használjon betűket, számjegyeket és aláhúzásjeleket, és ne kezdje számjeggyel.", + "The new name is a reserved word in Lua.": "Az új név foglalt szó a Lua nyelvben.", + "Renaming would change what another name in this file refers to.": "Az átnevezés megváltoztatná, hogy a fájl egy másik neve mire hivatkozik.", "Open a Lua or Infinity Engine menu file to validate it.": "Nyisson meg egy Lua-fájlt vagy Infinity Engine-menüfájlt az ellenőrzéshez.", "IE Lua: no problems found.": "IE Lua: Nem található probléma.", "IE Lua: {0} problem(s) found.": "IE Lua: Talált problémák száma: {0}.", diff --git a/l10n/bundle.l10n.it.json b/l10n/bundle.l10n.it.json index 1c39667..1dffc59 100644 --- a/l10n/bundle.l10n.it.json +++ b/l10n/bundle.l10n.it.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "È possibile rinominare solo i nomi di variabili locali e globali.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "Il \"self\" implicito di un metodo non ha una dichiarazione e non può essere rinominato.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Questa variabile globale non viene mai assegnata in questo file. È definita altrove (in un altro file, nel gioco o in EEex), quindi non può essere rinominata qui.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Correggere prima gli errori di sintassi: nel codice che non può essere analizzato non è possibile trovare tutti i nomi.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "Il nuovo nome non è un nome Lua valido: usare lettere, cifre e caratteri di sottolineatura e non iniziare con una cifra.", + "The new name is a reserved word in Lua.": "Il nuovo nome è una parola riservata di Lua.", + "Renaming would change what another name in this file refers to.": "La ridenominazione cambierebbe ciò a cui fa riferimento un altro nome in questo file.", "Open a Lua or Infinity Engine menu file to validate it.": "Aprire un file Lua o un file di menu di Infinity Engine per convalidarlo.", "IE Lua: no problems found.": "IE Lua: nessun problema rilevato.", "IE Lua: {0} problem(s) found.": "IE Lua: problemi rilevati: {0}.", diff --git a/l10n/bundle.l10n.ja.json b/l10n/bundle.l10n.ja.json index abf6d88..0934dbd 100644 --- a/l10n/bundle.l10n.ja.json +++ b/l10n/bundle.l10n.ja.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "名前を変更できるのは、ローカル変数とグローバル変数の名前だけです。", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "メソッドの暗黙の \"self\" には宣言がないため、名前を変更できません。", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "このグローバル変数はこのファイルで一度も代入されていません。別の場所 (別のファイル、ゲーム、または EEex) で定義されているため、ここでは名前を変更できません。", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "先に構文エラーを修正してください。解析できないコードでは、すべての名前を見つけることはできません。", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "新しい名前は有効な Lua の名前ではありません。英字、数字、アンダースコアを使用し、数字で始めないでください。", + "The new name is a reserved word in Lua.": "新しい名前は Lua の予約語です。", + "Renaming would change what another name in this file refers to.": "名前を変更すると、このファイル内の別の名前が参照する対象が変わります。", "Open a Lua or Infinity Engine menu file to validate it.": "検証するには、Lua ファイルまたは Infinity Engine のメニュー ファイルを開いてください。", "IE Lua: no problems found.": "IE Lua: 問題は見つかりませんでした。", "IE Lua: {0} problem(s) found.": "IE Lua: {0} 件の問題が見つかりました。", diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index ab5c074..774cbce 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Only the names of local and global variables can be renamed.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "The implicit \"self\" of a method has no declaration and cannot be renamed.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Fix the syntax errors first: names in code that does not parse cannot all be found.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.", + "The new name is a reserved word in Lua.": "The new name is a reserved word in Lua.", + "Renaming would change what another name in this file refers to.": "Renaming would change what another name in this file refers to.", "Open a Lua or Infinity Engine menu file to validate it.": "Open a Lua or Infinity Engine menu file to validate it.", "IE Lua: no problems found.": "IE Lua: no problems found.", "IE Lua: {0} problem(s) found.": "IE Lua: {0} problem(s) found.", diff --git a/l10n/bundle.l10n.ko.json b/l10n/bundle.l10n.ko.json index 9b7e9ba..9fed987 100644 --- a/l10n/bundle.l10n.ko.json +++ b/l10n/bundle.l10n.ko.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "로컬 및 전역 변수의 이름만 바꿀 수 있습니다.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "메서드의 암시적 \"self\"에는 선언이 없으므로 이름을 바꿀 수 없습니다.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "이 전역 변수는 이 파일에서 할당되지 않습니다. 다른 곳(다른 파일, 게임 또는 EEex)에 정의되어 있으므로 여기서 이름을 바꿀 수 없습니다.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "먼저 구문 오류를 수정하세요. 구문 분석할 수 없는 코드에서는 모든 이름을 찾을 수 없습니다.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "새 이름이 올바른 Lua 이름이 아닙니다. 문자, 숫자 및 밑줄을 사용하고 숫자로 시작하지 마세요.", + "The new name is a reserved word in Lua.": "새 이름은 Lua의 예약어입니다.", + "Renaming would change what another name in this file refers to.": "이름을 바꾸면 이 파일의 다른 이름이 참조하는 대상이 바뀝니다.", "Open a Lua or Infinity Engine menu file to validate it.": "유효성을 검사하려면 Lua 파일 또는 Infinity Engine 메뉴 파일을 여세요.", "IE Lua: no problems found.": "IE Lua: 문제가 없습니다.", "IE Lua: {0} problem(s) found.": "IE Lua: 문제 {0}개를 찾았습니다.", diff --git a/l10n/bundle.l10n.pl.json b/l10n/bundle.l10n.pl.json index f32d119..e1c158e 100644 --- a/l10n/bundle.l10n.pl.json +++ b/l10n/bundle.l10n.pl.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Można zmieniać nazwy tylko zmiennych lokalnych i globalnych.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "Niejawny parametr \"self\" metody nie ma deklaracji i nie można zmienić jego nazwy.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Ta zmienna globalna nigdy nie jest przypisywana w tym pliku. Jest zdefiniowana gdzie indziej (w innym pliku, w grze lub w EEex), więc nie można tutaj zmienić jej nazwy.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Najpierw popraw błędy składni: w kodzie, którego nie można przeanalizować, nie da się znaleźć wszystkich nazw.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "Nowa nazwa nie jest prawidłową nazwą Lua: użyj liter, cyfr i podkreśleń i nie zaczynaj od cyfry.", + "The new name is a reserved word in Lua.": "Nowa nazwa jest słowem zastrzeżonym w języku Lua.", + "Renaming would change what another name in this file refers to.": "Zmiana nazwy zmieniłaby to, do czego odwołuje się inna nazwa w tym pliku.", "Open a Lua or Infinity Engine menu file to validate it.": "Otwórz plik Lua lub plik menu Infinity Engine, aby sprawdzić jego poprawność.", "IE Lua: no problems found.": "IE Lua: nie znaleziono problemów.", "IE Lua: {0} problem(s) found.": "IE Lua: liczba znalezionych problemów: {0}.", diff --git a/l10n/bundle.l10n.pt-br.json b/l10n/bundle.l10n.pt-br.json index cd1b0c0..fd4e96d 100644 --- a/l10n/bundle.l10n.pt-br.json +++ b/l10n/bundle.l10n.pt-br.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Somente os nomes de variáveis locais e globais podem ser renomeados.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "O \"self\" implícito de um método não tem declaração e não pode ser renomeado.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Esta variável global nunca é atribuída neste arquivo. Ela está definida em outro lugar (outro arquivo, o jogo ou o EEex), portanto não pode ser renomeada aqui.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Corrija primeiro os erros de sintaxe: em um código que não pode ser analisado, nem todos os nomes podem ser encontrados.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "O novo nome não é um nome Lua válido: use letras, dígitos e sublinhados e não comece com um dígito.", + "The new name is a reserved word in Lua.": "O novo nome é uma palavra reservada em Lua.", + "Renaming would change what another name in this file refers to.": "A renomeação mudaria aquilo a que outro nome neste arquivo se refere.", "Open a Lua or Infinity Engine menu file to validate it.": "Abra um arquivo Lua ou um arquivo de menu do Infinity Engine para validá-lo.", "IE Lua: no problems found.": "IE Lua: nenhum problema encontrado.", "IE Lua: {0} problem(s) found.": "IE Lua: {0} problema(s) encontrado(s).", diff --git a/l10n/bundle.l10n.ru.json b/l10n/bundle.l10n.ru.json index 58d7a14..ac45376 100644 --- a/l10n/bundle.l10n.ru.json +++ b/l10n/bundle.l10n.ru.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Переименовывать можно только имена локальных и глобальных переменных.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "Неявный параметр \"self\" метода не имеет объявления, и его нельзя переименовать.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Этой глобальной переменной ничего не присваивается в этом файле. Она определена в другом месте (в другом файле, в игре или в EEex), поэтому переименовать ее здесь нельзя.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Сначала исправьте синтаксические ошибки: в коде, который не удается проанализировать, нельзя найти все имена.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "Новое имя не является допустимым именем Lua: используйте буквы, цифры и символы подчеркивания и не начинайте с цифры.", + "The new name is a reserved word in Lua.": "Новое имя является зарезервированным словом Lua.", + "Renaming would change what another name in this file refers to.": "Переименование изменит то, на что ссылается другое имя в этом файле.", "Open a Lua or Infinity Engine menu file to validate it.": "Откройте файл Lua или файл меню Infinity Engine, чтобы проверить его.", "IE Lua: no problems found.": "IE Lua: проблемы не найдены.", "IE Lua: {0} problem(s) found.": "IE Lua: найдено проблем: {0}.", diff --git a/l10n/bundle.l10n.tr.json b/l10n/bundle.l10n.tr.json index ef5e3c5..ee6ae3a 100644 --- a/l10n/bundle.l10n.tr.json +++ b/l10n/bundle.l10n.tr.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "Yalnızca yerel ve genel değişkenlerin adları yeniden adlandırılabilir.", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "Bir yöntemin örtük \"self\" parametresinin bildirimi yoktur ve yeniden adlandırılamaz.", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "Bu genel değişkene bu dosyada hiç değer atanmıyor. Başka bir yerde (başka bir dosyada, oyunda veya EEex'te) tanımlandığından burada yeniden adlandırılamaz.", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "Önce söz dizimi hatalarını düzeltin: ayrıştırılamayan kodda tüm adlar bulunamaz.", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "Yeni ad geçerli bir Lua adı değil: harf, rakam ve alt çizgi kullanın ve bir rakamla başlamayın.", + "The new name is a reserved word in Lua.": "Yeni ad, Lua'da ayrılmış bir sözcüktür.", + "Renaming would change what another name in this file refers to.": "Yeniden adlandırma, bu dosyadaki başka bir adın neye başvurduğunu değiştirir.", "Open a Lua or Infinity Engine menu file to validate it.": "Doğrulamak için bir Lua dosyası veya Infinity Engine menü dosyası açın.", "IE Lua: no problems found.": "IE Lua: Sorun bulunamadı.", "IE Lua: {0} problem(s) found.": "IE Lua: {0} sorun bulundu.", diff --git a/l10n/bundle.l10n.zh-cn.json b/l10n/bundle.l10n.zh-cn.json index 52e6aa4..622596a 100644 --- a/l10n/bundle.l10n.zh-cn.json +++ b/l10n/bundle.l10n.zh-cn.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "只能重命名局部变量和全局变量的名称。", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "方法的隐式 \"self\" 没有声明,无法重命名。", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "此全局变量在此文件中从未被赋值。它在其他位置定义(其他文件、游戏或 EEex),因此无法在此处重命名。", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "请先修复语法错误:在无法解析的代码中无法找到所有名称。", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "新名称不是有效的 Lua 名称:请使用字母、数字和下划线,并且不要以数字开头。", + "The new name is a reserved word in Lua.": "新名称是 Lua 的保留字。", + "Renaming would change what another name in this file refers to.": "重命名会改变此文件中另一个名称所引用的对象。", "Open a Lua or Infinity Engine menu file to validate it.": "请打开 Lua 文件或 Infinity Engine 菜单文件以进行验证。", "IE Lua: no problems found.": "IE Lua: 未发现问题。", "IE Lua: {0} problem(s) found.": "IE Lua: 发现 {0} 个问题。", diff --git a/l10n/bundle.l10n.zh-tw.json b/l10n/bundle.l10n.zh-tw.json index eff199d..2b67b60 100644 --- a/l10n/bundle.l10n.zh-tw.json +++ b/l10n/bundle.l10n.zh-tw.json @@ -1,4 +1,11 @@ { + "Only the names of local and global variables can be renamed.": "只能重新命名區域變數和全域變數的名稱。", + "The implicit \"self\" of a method has no declaration and cannot be renamed.": "方法的隱含 \"self\" 沒有宣告,無法重新命名。", + "This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.": "此全域變數在此檔案中從未被指派。它定義於其他位置(其他檔案、遊戲或 EEex),因此無法在此重新命名。", + "Fix the syntax errors first: names in code that does not parse cannot all be found.": "請先修正語法錯誤:在無法剖析的程式碼中,無法找到所有名稱。", + "The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.": "新名稱不是有效的 Lua 名稱:請使用字母、數字和底線,且不要以數字開頭。", + "The new name is a reserved word in Lua.": "新名稱是 Lua 的保留字。", + "Renaming would change what another name in this file refers to.": "重新命名會改變此檔案中另一個名稱所參考的對象。", "Open a Lua or Infinity Engine menu file to validate it.": "請開啟 Lua 檔案或 Infinity Engine 選單檔案以進行驗證。", "IE Lua: no problems found.": "IE Lua: 找不到任何問題。", "IE Lua: {0} problem(s) found.": "IE Lua: 找到 {0} 個問題。", diff --git a/src/client/lsp.ts b/src/client/lsp.ts index f4d4ea5..b1a6872 100644 --- a/src/client/lsp.ts +++ b/src/client/lsp.ts @@ -1,6 +1,7 @@ import type * as vscode from 'vscode'; import { LanguageClient, TransportKind, type LanguageClientOptions, type ServerOptions } from 'vscode-languageclient/node'; import { DOCUMENT_SCHEMES, LANGUAGE_IDS } from '../shared/protocol.ts'; +import { renameMiddleware } from './renameRefusals.ts'; export const CLIENT_ID = 'ieLua'; const CLIENT_NAME = 'IE Lua Language Server'; @@ -15,6 +16,7 @@ export async function startClient(context: vscode.ExtensionContext, outputChanne const clientOptions: LanguageClientOptions = { documentSelector: LANGUAGE_IDS.flatMap((language) => DOCUMENT_SCHEMES.map((scheme) => ({ language, scheme }))), outputChannel, + middleware: renameMiddleware, }; const client = new LanguageClient(CLIENT_ID, CLIENT_NAME, serverOptions, clientOptions); await client.start(); diff --git a/src/client/renameRefusals.ts b/src/client/renameRefusals.ts new file mode 100644 index 0000000..f8c624c --- /dev/null +++ b/src/client/renameRefusals.ts @@ -0,0 +1,59 @@ +import * as vscode from 'vscode'; +import type { Middleware } from 'vscode-languageclient/node'; +import { RENAME_REFUSAL_MESSAGES, type RenameRefusal } from '../shared/protocol.ts'; + +/** + * The display-language message of a refusal. The keys must equal + * RENAME_REFUSAL_MESSAGES: test/unit/shared/protocol.test.ts checks the exported + * l10n bundle, and `npm run check-l10n` that the bundle matches these calls. + */ +function localized(reason: RenameRefusal): string { + switch (reason) { + case 'notAVariable': + return vscode.l10n.t('Only the names of local and global variables can be renamed.'); + case 'implicitSelf': + return vscode.l10n.t('The implicit "self" of a method has no declaration and cannot be renamed.'); + case 'globalNotDefinedHere': + return vscode.l10n.t( + 'This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.', + ); + case 'syntaxErrors': + return vscode.l10n.t('Fix the syntax errors first: names in code that does not parse cannot all be found.'); + case 'invalidName': + return vscode.l10n.t('The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.'); + case 'reservedWord': + return vscode.l10n.t('The new name is a reserved word in Lua.'); + case 'conflict': + return vscode.l10n.t('Renaming would change what another name in this file refers to.'); + } +} + +const REASONS = new Map(Object.entries(RENAME_REFUSAL_MESSAGES).map(([reason, message]) => [message, reason as RenameRefusal])); + +/** + * The same error with a localized message when it is a rename refusal of the + * server (recognized by its exact English message, see src/shared/protocol.ts); + * any other error unchanged. + */ +function localizeRefusal(error: unknown): unknown { + const reason = error instanceof Error ? REASONS.get(error.message) : undefined; + return reason === undefined ? error : new Error(localized(reason)); +} + +/** Language client middleware showing the server's rename refusals in the display language. */ +export const renameMiddleware: Middleware = { + async prepareRename(document, position, token, next) { + try { + return await next(document, position, token); + } catch (error) { + throw localizeRefusal(error); + } + }, + async provideRenameEdits(document, position, newName, token, next) { + try { + return await next(document, position, newName, token); + } catch (error) { + throw localizeRefusal(error); + } + }, +}; diff --git a/src/server/features/rename.ts b/src/server/features/rename.ts new file mode 100644 index 0000000..469351c --- /dev/null +++ b/src/server/features/rename.ts @@ -0,0 +1,74 @@ +import type { Connection, PrepareRenameResult, TextDocuments, TextEdit, WorkspaceEdit } from 'vscode-languageserver/node'; +import { LSPErrorCodes, ResponseError } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import { RENAME_REFUSAL_MESSAGES, type RenameRefusal } from '../../shared/protocol.ts'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { prepareRename, rename } from '../syntax/rename.ts'; + +export interface RenameDeps { + readonly cache: ParsedDocumentCache; + /** `workspace.workspaceEdit.documentChanges` of the client: send versioned edits. */ + readonly documentChanges: boolean; +} + +/** A refusal as an LSP error (see RENAME_REFUSAL_MESSAGES). */ +export function refusalError(refusal: RenameRefusal): ResponseError { + return new ResponseError(LSPErrorCodes.RequestFailed, RENAME_REFUSAL_MESSAGES[refusal]); +} + +/** The edits of one document as a WorkspaceEdit, versioned when the client supports it. */ +export function toWorkspaceEdit(document: Pick, edits: TextEdit[], documentChanges: boolean): WorkspaceEdit { + return documentChanges + ? { documentChanges: [{ textDocument: { uri: document.uri, version: document.version }, edits }] } + : { changes: { [document.uri]: edits } }; +} + +/** + * `textDocument/prepareRename` and `textDocument/rename` within the document + * (see src/server/syntax/rename.ts for what is renamed and what is refused). + */ +export function register(connection: Connection, documents: TextDocuments, deps: RenameDeps): void { + const failed = (what: string, uri: string, error: unknown): null => { + connection.console.error(`${what} for ${uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + }; + + connection.onPrepareRename(({ textDocument, position }, token): PrepareRenameResult | ResponseError | null => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) { + return null; + } + // Synchronous from here on: a cancellation can only arrive after the response. + const result = prepareRename(deps.cache.get(document), document.offsetAt(position)); + if (!result.ok) { + return refusalError(result.refusal); + } + const { start, end, name } = result.value; + return { range: { start: document.positionAt(start), end: document.positionAt(end) }, placeholder: name }; + } catch (error) { + return failed('Prepare rename', textDocument.uri, error); + } + }); + + connection.onRenameRequest(({ textDocument, position, newName }, token): WorkspaceEdit | ResponseError | null => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) { + return null; + } + // Synchronous from here on: a cancellation can only arrive after the response. + const result = rename(deps.cache.get(document), document.getText(), document.offsetAt(position), newName); + if (!result.ok) { + return refusalError(result.refusal); + } + const edits = result.value.map(({ start, end, newText }) => ({ + range: { start: document.positionAt(start), end: document.positionAt(end) }, + newText, + })); + return toWorkspaceEdit(document, edits, deps.documentChanges); + } catch (error) { + return failed('Rename', textDocument.uri, error); + } + }); +} diff --git a/src/server/server.ts b/src/server/server.ts index 3ba6c29..35589fe 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -15,6 +15,7 @@ import * as diagnostics from './features/diagnostics.ts'; import * as documentSymbols from './features/documentSymbols.ts'; import * as foldingRanges from './features/foldingRanges.ts'; import * as references from './features/references.ts'; +import * as rename from './features/rename.ts'; import { SettingsStore } from './settingsStore.ts'; import { loadLua52 } from './validation/lua52.ts'; @@ -53,6 +54,8 @@ connection.onInitialize((params) => { }); definition.register(connection, documents, { cache: parsed }); references.register(connection, documents, { cache: parsed }); + rename.register(connection, documents, { cache: parsed, documentChanges: workspace?.workspaceEdit?.documentChanges === true }); + const prepareRename = params.capabilities.textDocument?.rename?.prepareSupport === true; return { capabilities: { textDocumentSync: { @@ -64,6 +67,8 @@ connection.onInitialize((params) => { foldingRangeProvider: true, definitionProvider: true, referencesProvider: true, + // Without prepareSupport the client must not be sent `prepareProvider` (LSP 3.17). + renameProvider: prepareRename ? { prepareProvider: true } : true, }, serverInfo: { name: 'IE Lua Language Server' }, }; diff --git a/src/server/syntax/navigation.ts b/src/server/syntax/navigation.ts index 2d6994e..ff8aa87 100644 --- a/src/server/syntax/navigation.ts +++ b/src/server/syntax/navigation.ts @@ -24,18 +24,20 @@ export interface TargetHit { readonly identifier: Ast.Identifier; } -interface IndexEntry { +export interface VariableOccurrence { readonly identifier: Ast.Identifier; + /** Index in `ParsedDocument.chunks` of the chunk the identifier is in. */ readonly chunkIndex: number; } /** Variable identifiers of each document, sorted by offset; dropped with the document. */ -const indexes = new WeakMap(); +const indexes = new WeakMap(); -function variableIndex(document: ParsedDocument): readonly IndexEntry[] { +/** Every identifier that names a variable (local or global), sorted by offset. */ +export function variableIndex(document: ParsedDocument): readonly VariableOccurrence[] { let index = indexes.get(document); if (!index) { - const entries: IndexEntry[] = []; + const entries: VariableOccurrence[] = []; document.chunks.forEach(({ scopes }, chunkIndex) => { for (const identifier of scopes.resolved.keys()) entries.push({ identifier, chunkIndex }); for (const uses of scopes.globals.values()) { @@ -59,7 +61,7 @@ export function targetAt(document: ParsedDocument, offset: number): TargetHit | // one starting exactly at `offset` wins over one ending there. let low = 0; let high = index.length - 1; - let found: IndexEntry | undefined; + let found: VariableOccurrence | undefined; while (low <= high) { const middle = (low + high) >> 1; const entry = index[middle]; diff --git a/src/server/syntax/rename.ts b/src/server/syntax/rename.ts new file mode 100644 index 0000000..a63459a --- /dev/null +++ b/src/server/syntax/rename.ts @@ -0,0 +1,144 @@ +// Same-document rename of a variable. Pure: no LSP or `vscode` imports. +// +// A rename is refused, rather than producing code that behaves differently, +// when: +// - the cursor is not on a variable name, or is on the implicit `self`; +// - the variable is a global the document never assigns: it is defined +// elsewhere (another file, the game, EEex), which a same-file rename cannot +// update; +// - the code where it can occur has syntax errors (its chunk for a local, any +// chunk for a global): error recovery skips tokens, so some uses would be +// missed; +// - the new name is not a Lua name, or is a reserved word; +// - the new name would change what any name refers to: an inner local capturing +// a renamed use, the renamed local hiding an outer variable used in its scope, +// or two globals merging. This is decided by re-analyzing the renamed text, +// not by heuristics (see `checkBindings`). + +import type { RenameRefusal } from '../../shared/protocol.ts'; +import type * as Ast from './ast.ts'; +import { parseDocument, type ParsedDocument } from './document.ts'; +import { lex } from './lexer.ts'; +import { definitions, references, targetAt, variableIndex, type NavigationTarget, type VariableOccurrence } from './navigation.ts'; + +export type RenameOutcome = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly refusal: RenameRefusal }; + +export interface RenameEdit { + readonly start: number; + readonly end: number; + readonly newText: string; +} + +const refuse = (refusal: RenameRefusal): { ok: false; refusal: RenameRefusal } => ({ ok: false, refusal }); + +/** The renameable variable at `offset`, as found by `targetAt`. */ +function renameTarget(document: ParsedDocument, offset: number): RenameOutcome<{ target: NavigationTarget; identifier: Ast.Identifier }> { + const hit = targetAt(document, offset); + if (!hit) { + return refuse('notAVariable'); + } + if (hit.target.kind === 'local' && hit.target.declaration.kind === 'self') { + return refuse('implicitSelf'); + } + if (hit.target.kind === 'global' && definitions(document, hit.target).length === 0) { + return refuse('globalNotDefinedHere'); + } + const searched = hit.target.kind === 'local' ? [document.chunks[hit.target.chunkIndex]] : document.chunks; + if (searched.some((chunk) => chunk && chunk.tree.errors.length > 0)) { + return refuse('syntaxErrors'); + } + return { ok: true, value: hit }; +} + +/** `textDocument/prepareRename`: the identifier that would be renamed. */ +export function prepareRename(document: ParsedDocument, offset: number): RenameOutcome { + const found = renameTarget(document, offset); + return found.ok ? { ok: true, value: found.value.identifier } : found; +} + +/** Whether `name` is a Lua 5.2 name, using the lexer's own rule. */ +function nameRefusal(name: string): RenameRefusal | undefined { + const { tokens, errors } = lex(name); + const [token, eof] = tokens; + if (errors.length === 0 && tokens.length === 2 && token?.start === 0 && token.end === name.length && eof?.type === 'eof') { + if (token.type === 'keyword') return 'reservedWord'; + if (token.type === 'name') return undefined; + } + return 'invalidName'; +} + +/** What an identifier refers to: a declaration (by chunk and position), or a global by name. */ +function bindingKeys(document: ParsedDocument): Map { + const keys = new Map(); + const declarationIndexes = document.chunks.map(({ scopes }) => new Map(scopes.declarations.map((d, i) => [d, i]))); + for (const occurrence of variableIndex(document)) { + const { identifier, chunkIndex } = occurrence; + const declaration = document.chunks[chunkIndex]?.scopes.resolved.get(identifier); + const index = declaration && declarationIndexes[chunkIndex]?.get(declaration); + keys.set(occurrence, index === undefined ? `global ${identifier.name}` : `local ${String(chunkIndex)}:${String(index)}`); + } + return keys; +} + +/** + * Whether every identifier of `renamed` refers to what it referred to in + * `original`: renamed identifiers to the same local, or to the global under its + * new name; every other identifier to exactly the same thing. + */ +function checkBindings(original: ParsedDocument, renamed: ParsedDocument, edits: readonly RenameEdit[], oldName: string, newName: string): boolean { + const before = bindingKeys(original); + const after = bindingKeys(renamed); + if (before.size !== after.size) { + return false; + } + const delta = newName.length - oldName.length; + const editStarts = new Set(edits.map((edit) => edit.start)); + const afterByOffset = new Map([...after].map(([occurrence, key]) => [occurrence.identifier.start, key])); + let shift = 0; + for (const [occurrence, key] of before) { + // Occurrences are in offset order, so `shift` counts the edits before this one. + const start = occurrence.identifier.start; + const isRenamed = editStarts.has(start); + const expected = isRenamed && key.startsWith('global ') ? `global ${newName}` : key; + if (afterByOffset.get(start + shift) !== expected) { + return false; + } + if (isRenamed) shift += delta; + } + return true; +} + +/** + * `textDocument/rename`: the edits renaming the variable at `offset` to + * `newName` everywhere in the document. `text` is the document text that + * `document` was parsed from. + */ +export function rename(document: ParsedDocument, text: string, offset: number, newName: string): RenameOutcome { + const found = renameTarget(document, offset); + if (!found.ok) { + return found; + } + const refusal = nameRefusal(newName); + if (refusal) { + return refuse(refusal); + } + const { target, identifier } = found.value; + const oldName = identifier.name; + if (newName === oldName) { + return { ok: true, value: [] }; + } + // Two globals would become one; the binding check cannot see that, since both keep a global binding. + if (target.kind === 'global' && document.chunks.some(({ scopes }) => scopes.globals.has(newName))) { + return refuse('conflict'); + } + const edits = references(document, target, true).map(({ start, end }) => ({ start, end, newText: newName })); + let renamedText = ''; + let last = 0; + for (const edit of edits) { + renamedText += text.slice(last, edit.start) + edit.newText; + last = edit.end; + } + renamedText += text.slice(last); + const renamed = parseDocument(renamedText, document.kind); + return checkBindings(document, renamed, edits, oldName, newName) ? { ok: true, value: edits } : refuse('conflict'); +} diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index 595cb5f..7ba280d 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -29,3 +29,31 @@ export interface ValidateDocumentResult { export const ValidateDocumentRequest = new RequestType( 'ieLua/validateDocument', ); + +/** Why the server refuses a `textDocument/prepareRename` or `textDocument/rename` request. */ +export type RenameRefusal = + | 'notAVariable' + | 'implicitSelf' + | 'globalNotDefinedHere' + | 'syntaxErrors' + | 'invalidName' + | 'reservedWord' + | 'conflict'; + +/** + * The `ResponseError.message` of each refusal (code `RequestFailed`), shown as + * is by other editors. LSP declares no error data for these requests, and + * vscode-languageclient passes only the message of a failed prepareRename on, + * so the VS Code client recognizes a refusal by its exact text to localize it. + * Hence no placeholders. + */ +export const RENAME_REFUSAL_MESSAGES: Readonly> = { + notAVariable: 'Only the names of local and global variables can be renamed.', + implicitSelf: 'The implicit "self" of a method has no declaration and cannot be renamed.', + globalNotDefinedHere: + 'This global is never assigned in this file. It is defined elsewhere (another file, the game or EEex), so it cannot be renamed here.', + syntaxErrors: 'Fix the syntax errors first: names in code that does not parse cannot all be found.', + invalidName: 'The new name is not a valid Lua name: use letters, digits and underscores, and do not start with a digit.', + reservedWord: 'The new name is a reserved word in Lua.', + conflict: 'Renaming would change what another name in this file refers to.', +}; diff --git a/test/integration/rename.test.ts b/test/integration/rename.test.ts new file mode 100644 index 0000000..17500f5 --- /dev/null +++ b/test/integration/rename.test.ts @@ -0,0 +1,77 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { RENAME_REFUSAL_MESSAGES } from '../../src/shared/protocol.ts'; +import { activateExtension, closeAllEditors, openFixture } from './helpers.ts'; + +/** `line:character newText` of each edit of `uri`, in document order. */ +function editsOf(edit: vscode.WorkspaceEdit, uri: vscode.Uri): string[] { + return edit + .get(uri) + .map(({ range, newText }) => `${String(range.start.line)}:${String(range.start.character)} ${newText}`) + .sort((a, b) => a.localeCompare(b, 'en', { numeric: true })); +} + +async function renameAt(file: string, line: number, character: number, newName: string): Promise<{ uri: vscode.Uri; edit: vscode.WorkspaceEdit }> { + const uri = await openFixture(file); + const edit = await vscode.commands.executeCommand( + 'vscode.executeDocumentRenameProvider', + uri, + new vscode.Position(line, character), + newName, + ); + assert.ok(edit, 'no rename provider answered'); + return { uri, edit }; +} + +/** The message a rejected command fails with. */ +async function rejection(command: Thenable): Promise { + try { + await command; + } catch (error) { + return error instanceof Error ? error.message : String(error); + } + assert.fail('the command did not fail'); +} + +suite('Rename', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('prepares the rename of a local with its range and name', async () => { + const uri = await openFixture('navigation.lua'); + const result = await vscode.commands.executeCommand<{ range: vscode.Range; placeholder: string } | undefined>( + 'vscode.prepareRename', + uri, + new vscode.Position(15, 8), + ); + assert.ok(result, 'no rename provider answered'); + assert.equal(result.placeholder, 'counter'); + assert.deepEqual([result.range.start.line, result.range.start.character, result.range.end.character], [15, 6, 13]); + }); + + test('renames the declaration and every use of a local', async () => { + const { uri, edit } = await renameAt('navigation.lua', 1, 6, 'total'); + assert.deepEqual(editsOf(edit, uri), ['1:6 total', '4:1 total', '4:11 total', '5:8 total', '15:6 total']); + }); + + test('renames a global in every Lua chunk of a .menu file', async () => { + const { uri, edit } = await renameAt('NAVIGATION.MENU', 9, 2, 'chosen'); + assert.deepEqual(editsOf(edit, uri), ['2:0 chosen', '9:2 chosen', '13:11 chosen', '16:17 chosen', '17:3 chosen']); + }); + + test('refuses globals defined outside the file, with the reason', async () => { + const uri = await openFixture('navigation.lua'); + const message = await rejection(vscode.commands.executeCommand('vscode.prepareRename', uri, new vscode.Position(15, 0))); + assert.equal(message, RENAME_REFUSAL_MESSAGES.globalNotDefinedHere); + }); + + test('refuses a new name that is a reserved word, with the reason', async () => { + const message = await rejection(renameAt('navigation.lua', 1, 6, 'end')); + assert.equal(message, RENAME_REFUSAL_MESSAGES.reservedWord); + }); +}); diff --git a/test/unit/server/features/rename.test.ts b/test/unit/server/features/rename.test.ts new file mode 100644 index 0000000..b86b5b3 --- /dev/null +++ b/test/unit/server/features/rename.test.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import { LSPErrorCodes } from 'vscode-languageserver/node'; +import { refusalError, toWorkspaceEdit } from '../../../../src/server/features/rename.ts'; +import { RENAME_REFUSAL_MESSAGES, type RenameRefusal } from '../../../../src/shared/protocol.ts'; + +describe('server/features/rename', () => { + const edits = [{ range: { start: { line: 0, character: 6 }, end: { line: 0, character: 7 } }, newText: 'b' }]; + + it('sends versioned document changes to clients that support them', () => { + assert.deepEqual(toWorkspaceEdit({ uri: 'file:///a.lua', version: 4 }, edits, true), { + documentChanges: [{ textDocument: { uri: 'file:///a.lua', version: 4 }, edits }], + }); + }); + + it('sends plain changes to other clients', () => { + assert.deepEqual(toWorkspaceEdit({ uri: 'file:///a.lua', version: 4 }, edits, false), { changes: { 'file:///a.lua': edits } }); + }); + + it('refuses with RequestFailed and the fixed English message of the reason', () => { + for (const reason of Object.keys(RENAME_REFUSAL_MESSAGES) as RenameRefusal[]) { + const error = refusalError(reason); + assert.equal(error.code, LSPErrorCodes.RequestFailed); + assert.equal(error.message, RENAME_REFUSAL_MESSAGES[reason]); + } + }); + + it('has a distinct message per reason, so the client can tell them apart', () => { + const messages = Object.values(RENAME_REFUSAL_MESSAGES); + assert.equal(new Set(messages).size, messages.length); + }); +}); diff --git a/test/unit/server/syntax/rename.test.ts b/test/unit/server/syntax/rename.test.ts new file mode 100644 index 0000000..6070c7c --- /dev/null +++ b/test/unit/server/syntax/rename.test.ts @@ -0,0 +1,117 @@ +import assert from 'node:assert/strict'; +import type { RenameRefusal } from '../../../../src/shared/protocol.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { prepareRename, rename } from '../../../../src/server/syntax/rename.ts'; + +/** Offset of the `occurrence`-th (0-based) whole-word `needle` in `text`. */ +function offsetOf(text: string, needle: string, occurrence = 0): number { + const match = [...text.matchAll(new RegExp(`\\b${needle}\\b`, 'g'))][occurrence]; + assert.ok(match, `"${needle}" #${String(occurrence)} not found`); + return match.index; +} + +/** The renamed text, or the refusal. */ +function renamed(text: string, needle: string, occurrence: number, newName: string, kind: 'lua' | 'menu' = 'lua'): string | { refusal: RenameRefusal } { + const result = rename(parseDocument(text, kind), text, offsetOf(text, needle, occurrence), newName); + if (!result.ok) { + return { refusal: result.refusal }; + } + let output = text; + for (const edit of [...result.value].reverse()) { + output = output.slice(0, edit.start) + edit.newText + output.slice(edit.end); + } + return output; +} + +describe('server/syntax/rename', () => { + describe('prepareRename', () => { + const text = 'local t = {} function t:m() return self end t.x = print(g) g = 1'; + const document = parseDocument(text, 'lua'); + const prepare = (needle: string, occurrence = 0) => prepareRename(document, offsetOf(text, needle, occurrence)); + + it('accepts locals and globals the document assigns, returning the name under the cursor', () => { + for (const [needle, occurrence] of [['t', 0], ['t', 1], ['g', 0], ['g', 1]] as const) { + const result = prepare(needle, occurrence); + assert.ok(result.ok, `${needle} #${String(occurrence)}`); + assert.equal(result.value.start, offsetOf(text, needle, occurrence)); + assert.equal(result.value.name, needle); + } + }); + + it('refuses keywords, field and method names', () => { + for (const needle of ['local', 'function', 'x', 'm']) { + assert.deepEqual(prepare(needle), { ok: false, refusal: 'notAVariable' }, needle); + } + }); + + it('refuses the implicit self and globals the document never assigns', () => { + assert.deepEqual(prepare('self'), { ok: false, refusal: 'implicitSelf' }); + assert.deepEqual(prepare('print'), { ok: false, refusal: 'globalNotDefinedHere' }); + }); + }); + + describe('rename', () => { + it('renames the declaration and every use of a local, and nothing else', () => { + const text = 'local n = 1 n = n + 1 local t = { n = n } print(t.n, n)'; + assert.equal(renamed(text, 'n', 0, 'count'), 'local count = 1 count = count + 1 local t = { n = count } print(t.n, count)'); + }); + + it('renames only the local the cursor is on when names are shadowed', () => { + const text = 'local x = 1 do local x = 2 print(x) end print(x)'; + assert.equal(renamed(text, 'x', 1, 'inner'), 'local x = 1 do local inner = 2 print(inner) end print(x)'); + }); + + it('renames a global everywhere in a .menu file, across its Lua chunks', () => { + const text = "`\nflag = 1\n`\nmenu\n{\n\tname 'flag'\n\tenabled \"flag\"\n}\n"; + assert.equal(renamed(text, 'flag', 0, 'ready', 'menu'), "`\nready = 1\n`\nmenu\n{\n\tname 'flag'\n\tenabled \"ready\"\n}\n"); + }); + + it('returns no edits for the same name', () => { + const text = 'local a = 1'; + const result = rename(parseDocument(text, 'lua'), text, 6, 'a'); + assert.deepEqual(result, { ok: true, value: [] }); + }); + + it('refuses when the code the variable can occur in has syntax errors, as uses may be missing', () => { + // Error recovery drops the unfinished call, and with it this use of `a`. + assert.deepEqual(renamed('local a = 1 print(a', 'a', 0, 'b'), { refusal: 'syntaxErrors' }); + const menu = "`\nlocal own = 1 g = own\n`\nmenu\n{\n\tname 'M'\n\tenabled \"g ==\"\n}\n"; + assert.deepEqual(renamed(menu, 'g', 0, 'h', 'menu'), { refusal: 'syntaxErrors' }); + assert.equal(renamed(menu, 'own', 0, 'mine', 'menu'), menu.replaceAll('own', 'mine')); + }); + + it('refuses names that are not Lua names, and reserved words', () => { + for (const name of ['', '1a', 'a-b', 'a b', ' a', 'a.b', 'é', '--a', '"a"']) { + assert.deepEqual(renamed('local a', 'a', 0, name), { refusal: 'invalidName' }, JSON.stringify(name)); + } + for (const name of ['end', 'nil', 'goto', 'and']) { + assert.deepEqual(renamed('local a', 'a', 0, name), { refusal: 'reservedWord' }, name); + } + assert.equal(renamed('local a', 'a', 0, '_Name2'), 'local _Name2'); + }); + + it('refuses to let an inner local capture a renamed use', () => { + assert.deepEqual(renamed('local a = 1 do local b = 2 print(a) end', 'a', 1, 'b'), { refusal: 'conflict' }); + }); + + it('refuses to hide an outer local or a global used in the renamed local\'s scope', () => { + assert.deepEqual(renamed('local b = 1 do local a = 2 print(b, a) end', 'a', 1, 'b'), { refusal: 'conflict' }); + assert.deepEqual(renamed('local a = 1 print(a, g)', 'a', 1, 'g'), { refusal: 'conflict' }); + }); + + it('allows a name used elsewhere when no reference changes', () => { + const text = 'do local a = 1 print(a) end print(b) local b = 2'; + assert.equal(renamed(text, 'a', 1, 'b'), 'do local b = 1 print(b) end print(b) local b = 2'); + }); + + it('refuses to merge two globals or to let a local capture a renamed global', () => { + assert.deepEqual(renamed('x = 1 y = 2', 'x', 0, 'y'), { refusal: 'conflict' }); + assert.deepEqual(renamed('g = 1 local h = 2 print(g)', 'g', 0, 'h'), { refusal: 'conflict' }); + }); + + it('refuses the same targets as prepareRename', () => { + assert.deepEqual(renamed('print(1)', 'print', 0, 'p'), { refusal: 'globalNotDefinedHere' }); + assert.deepEqual(renamed('local t = {} t.x = 1', 'x', 0, 'y'), { refusal: 'notAVariable' }); + }); + }); +}); diff --git a/test/unit/shared/protocol.test.ts b/test/unit/shared/protocol.test.ts new file mode 100644 index 0000000..e24e0b4 --- /dev/null +++ b/test/unit/shared/protocol.test.ts @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { RENAME_REFUSAL_MESSAGES } from '../../../src/shared/protocol.ts'; + +describe('shared/protocol', () => { + it('has a client translation key for every rename refusal message', () => { + // l10n/bundle.l10n.json is exported from the vscode.l10n.t() calls of src/client (npm run check-l10n). + const bundle = JSON.parse(readFileSync(new URL('../../../l10n/bundle.l10n.json', import.meta.url), 'utf8')) as Record; + for (const [reason, message] of Object.entries(RENAME_REFUSAL_MESSAGES)) { + assert.ok(message in bundle, `no vscode.l10n.t() call for the "${reason}" refusal message`); + } + }); +}); From 78a83986984594af0c2c99a0c05f75cddb1cc677 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:00:08 +0100 Subject: [PATCH 5/9] perf(server): find global assignments without scanning every chunk definitions() and references() asked, for each use of a global, whether any chunk of the document records it as a write: O(uses x chunks). On the game's UI.MENU (local only, never committed: 3,109 chunks, 12,542 variable identifiers) that made go to definition take 13-21 ms for a common global, and pushed rename of the most-used assigned global (`characters`, 364 uses) to 58 ms, above the ~50 ms event-loop budget of .claude/rules/language-server.md. Each use is now checked against the `writes` of its own chunk while the uses are collected. Medians of 15 runs on the same file: definition `characters` 21.34 ms -> 0.19 ms references `characters` 0.09 ms -> 0.14 ms (unchanged, noise) rename `characters` 57.92 ms -> 33.97 ms rename `currentID` 45.80 ms -> 32.22 ms Rename is now dominated by the re-parse of the renamed text (about 25 ms for this file), which the conflict check needs. Co-Authored-By: Claude Opus 5.5 --- src/server/syntax/navigation.ts | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/server/syntax/navigation.ts b/src/server/syntax/navigation.ts index ff8aa87..ae8078e 100644 --- a/src/server/syntax/navigation.ts +++ b/src/server/syntax/navigation.ts @@ -83,13 +83,9 @@ export function targetAt(document: ParsedDocument, offset: number): TargetHit | }; } -/** Every identifier naming the global `name`, in document order. */ -function globalUses(document: ParsedDocument, name: string): Ast.Identifier[] { - return document.chunks.flatMap(({ scopes }) => scopes.globals.get(name) ?? []); -} - -function isGlobalWrite(document: ParsedDocument, identifier: Ast.Identifier): boolean { - return document.chunks.some(({ scopes }) => scopes.writes.has(identifier)); +/** Every identifier naming the global `name`, in document order, with whether it assigns the global. */ +function globalUses(document: ParsedDocument, name: string): { identifier: Ast.Identifier; isWrite: boolean }[] { + return document.chunks.flatMap(({ scopes }) => (scopes.globals.get(name) ?? []).map((identifier) => ({ identifier, isWrite: scopes.writes.has(identifier) }))); } /** @@ -102,7 +98,9 @@ export function definitions(document: ParsedDocument, target: NavigationTarget): if (target.kind === 'local') { return target.declaration.identifier ? [target.declaration.identifier] : []; } - return globalUses(document, target.name).filter((identifier) => isGlobalWrite(document, identifier)); + return globalUses(document, target.name) + .filter((use) => use.isWrite) + .map((use) => use.identifier); } /** @@ -115,6 +113,7 @@ export function references(document: ParsedDocument, target: NavigationTarget, i const all = includeDeclaration && identifier ? [identifier, ...uses] : [...uses]; return all.sort((a, b) => a.start - b.start); } - const uses = globalUses(document, target.name); - return includeDeclaration ? uses : uses.filter((identifier) => !isGlobalWrite(document, identifier)); + return globalUses(document, target.name) + .filter((use) => includeDeclaration || !use.isWrite) + .map((use) => use.identifier); } From 267509c193326cfc386d209d790e88e8fcebf2f8 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:00:24 +0100 Subject: [PATCH 6/9] docs: document navigation - README: feature list and the early-version note now cover go to definition, find references and rename within a file. - docs/editors/README.md: three rows in "What you get" with the LSP requests, and the scope of navigation for other editors (variables only; no table fields or goto labels; .menu globals shared, locals per block or script). - CLAUDE.md: project purpose line. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- README.md | 9 +++++++-- docs/editors/README.md | 7 ++++++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2599049..d0e73db 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ |---|---| | Name | `IE Lua Language Server` | | Publisher | `infinity-engine-tools` | -| Purpose | Lua 5.2 language support (diagnostics, document symbols and folding now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | +| Purpose | Lua 5.2 language support (diagnostics, document symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | | Language | TypeScript (strict) | | Bundler | esbuild (two bundles: client + language server) | | Minimum VS Code | `^1.91.0` (see `engines.vscode` in `package.json`; required by `vscode-languageclient` ≥ 10) | diff --git a/README.md b/README.md index cd0f4d0..0be2ea1 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,9 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the `.menu` files such as `UI.MENU`. > [!NOTE] -> This is an early version. It currently provides **syntax diagnostics**, **document symbols** -> and **folding**; completion, hover, navigation, formatting and more are planned. +> This is an early version. It currently provides **syntax diagnostics**, **document symbols**, +> **folding**, **go to definition**, **find references** and **rename** within a file; completion, +> hover, workspace-wide navigation, formatting and more are planned. ## Features @@ -27,6 +28,10 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the **Go to Symbol in Editor**. Works while the file still has syntax errors. - **Folding that follows the code:** functions, loops, each `if`/`elseif`/`else` branch, tables, comments, and every `{ … }` block and Lua script of a `.menu` file. +- **Go to Definition, Find All References and Rename Symbol** for variables within a file. Locals + follow Lua's scoping rules; globals are followed across all the Lua of a `.menu` file. Rename + refuses, and says why, when it could change what the code does: a name already in use nearby, + a reserved word, or a global that is defined outside the file. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors** through the Language Server Protocol. diff --git a/docs/editors/README.md b/docs/editors/README.md index 30a511b..45a2a75 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -65,5 +65,10 @@ node /path/to/server.js --stdio | Syntax errors | `textDocument/publishDiagnostics` | When `validate.mode` says so (see above). | | Document symbols (outline) | `textDocument/documentSymbol` | Nested when the editor supports it, otherwise a flat list with container names. | | Folding | `textDocument/foldingRange` | Whole lines; the closing line of each construct stays visible. | +| Go to definition | `textDocument/definition` | The declaration of a local, or every assignment to a global, in the same file. | +| Find references | `textDocument/references` | Every use of a local or global in the same file. | +| Rename | `textDocument/prepareRename`, `textDocument/rename` | Same file only; refused, with the reason as the error message, when the rename could change what the code does. | -Symbols and folding always reflect the current text, whatever `validate.mode` is. +Symbols, folding and navigation always reflect the current text, whatever `validate.mode` is. +Navigation works on variables: table fields (`t.x`) and `goto` labels are not followed, and in a +`.menu` file globals are shared by all its Lua, while locals stay in their own block or script. From ceb162bb41a780ae06ce42b17e711215d207292f Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:00:46 +0100 Subject: [PATCH 7/9] ci(release): attach only the VSIX and give its SHA-256 in the release notes The downloads badge added later in this branch uses GitHub's total download count of all assets of all releases (the only figure the GitHub API offers; it is anonymous, so maintainers' own downloads cannot be told apart). Each release attached two assets, the VSIX and a `.vsix.sha256` file, so every checksum download would have counted as an extension download. The publish job now attaches the VSIX only and appends "**SHA-256** of ``: ``" to the release notes, and prints it in the job log. No release exists yet, so no earlier count is affected. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 12 ++++++++---- CHANGELOG.md | 2 ++ CONTRIBUTING.md | 3 ++- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index febcf7a..e246bfd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -129,9 +129,13 @@ jobs: run: | flags=() if [ "$CHANNEL" = "pre-release" ]; then flags+=(--pre-release); fi - npx vsce package --no-dependencies --changelog-path docs/CHANGELOG.vsix.md "${flags[@]}" \ - --out "ie-lua-language-server-$VERSION.vsix" - sha256sum "ie-lua-language-server-$VERSION.vsix" | tee "ie-lua-language-server-$VERSION.vsix.sha256" + vsix="ie-lua-language-server-$VERSION.vsix" + npx vsce package --no-dependencies --changelog-path docs/CHANGELOG.vsix.md "${flags[@]}" --out "$vsix" + # The checksum goes in the release notes, not in a second asset: the VSIX is then the + # only asset, so the downloads badge (all assets of all releases) counts VSIX downloads. + hash="$(sha256sum "$vsix" | cut -d ' ' -f 1)" + echo "SHA-256 of $vsix: $hash" + printf '\n**SHA-256** of `%s`: `%s`\n' "$vsix" "$hash" >> "$RUNNER_TEMP/notes.md" - name: Create GitHub release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -142,4 +146,4 @@ jobs: flags=() if [ "$CHANNEL" = "pre-release" ]; then flags+=(--prerelease); else flags+=(--latest); fi gh release create "$TAG" --target "$GITHUB_SHA" --title "$TAG" --notes-file "$RUNNER_TEMP/notes.md" "${flags[@]}" \ - "ie-lua-language-server-$VERSION.vsix" "ie-lua-language-server-$VERSION.vsix.sha256" + "ie-lua-language-server-$VERSION.vsix" diff --git a/CHANGELOG.md b/CHANGELOG.md index e7535cf..ee0a65f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,5 +65,7 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). committed `VERSION` as the first stable release (a pre-release before it would be 1.1.0). - The Release workflow publishes only for merged `chore(release): …` pull requests, not for any other push that changes `VERSION`. +- GitHub releases have the VSIX as their only asset; its SHA-256 moved from a separate + `.vsix.sha256` file into the release notes, so the download count covers VSIX downloads only. - CI integration jobs build the tests before running them, and a test run that finds no tests now fails. Until now the CI integration jobs ran 0 tests and passed. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c9f69ca..848021c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -123,7 +123,8 @@ Nothing is ever published to a marketplace (`"private": true`; `vsce publish` is `VERSION`, 1.0.0, and a pre-release before it would be 1.1.0), updates `VERSION`, `package.json`, `package-lock.json` and both changelogs, and opens a `chore(release): vX.Y.Z` pull request. 3. Review and merge that pull request. The workflow then verifies the version, runs the checks, - packages the VSIX and creates the tag and the GitHub release (environment `release`). + packages the VSIX and creates the tag and the GitHub release (environment `release`). The VSIX + is the release's only asset; its SHA-256 is at the end of the release notes. ## Repository settings (maintainers) From b1bcfba101ce4ae9036ad6e39805d40fcb20d0b1 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:07:43 +0100 Subject: [PATCH 8/9] ci(release): measure the installed size of the VSIX for the README badge No badge service reports an extension's installed size for a VSIX distributed through GitHub Releases, so the release tooling computes it and commits it as shields.io endpoint data, .github/badges/install-size.json (initially "no release yet"). What is measured is what VS Code shows as "Size" in the extension's details, derived from its source at tag 1.143.1 (references in scripts/release/vsix.mts): - installing extracts every ZIP entry matching the regular expression `^extension` (zip.ts:388, extensionManagementService.ts:649). The prefix has no slash, so `extension.vsixmanifest` is installed too, as `.vsixmanifest`; - `metadata.size = computeSize(folder)` right after extraction (:657), before VS Code adds `__metadata` to package.json; - the editor shows ByteSize.formatSize(size) (files.ts:1603), units of 1024, e.g. "933.08KB". Checked with a real install (VS Code 1.143.1, --extensions-dir in a scratch folder): the recorded `__metadata.size` was 955479 bytes, and installedSize() of the same VSIX gives 955479. scripts/release/vsix.mts reads the ZIP central directory itself (EOCD, then name and uncompressed size per entry), so no dependency is added; ZIP64 and corrupt archives are rejected with a clear error. New command `cli.mts install-size --vsix (--write | --check) [--notes ]`, used by: - release.yml `prepare`: after the bump, bundles and packages the VSIX as `publish` will (with --pre-release for that channel) and writes the JSON, which the release pull request commits; - release.yml `publish`: checks the JSON against the VSIX it publishes, and appends the exact byte count to the release notes; - ci.yml checks: on release/v* branches only, packages with the same flags (odd minor = pre-release) and checks. The ruleset requires branches to be up to date before merging, so the merged content is the checked content; if main moves, the error says how to regenerate. The check compares what the badge shows. shields.io rejects unknown keys in endpoint data (services/endpoint-common.js), so the exact byte count cannot live in the file; it is printed and put in the release notes. Dry run in a scratch clone (nothing pushed): stable 1.0.0 -> 955668 bytes "933.27KB", pre-release 1.1.0 -> 955737 bytes "933.34KB" (the pre-release flag is in the manifest, which is installed); --check passes for both with the CI packaging logic, and fails once the shown value changes (21 more README bytes). actionlint 1.7.12 passes. Co-Authored-By: Claude Opus 5.5 --- .github/badges/install-size.json | 6 ++ .github/workflows/ci.yml | 12 ++- .github/workflows/release.yml | 25 ++++- CHANGELOG.md | 5 + CONTRIBUTING.md | 9 +- scripts/release/cli.mts | 58 ++++++++++- scripts/release/vsix.mts | 115 ++++++++++++++++++++ test/unit/scripts/release/vsix.test.ts | 139 +++++++++++++++++++++++++ 8 files changed, 362 insertions(+), 7 deletions(-) create mode 100644 .github/badges/install-size.json create mode 100644 scripts/release/vsix.mts create mode 100644 test/unit/scripts/release/vsix.test.ts diff --git a/.github/badges/install-size.json b/.github/badges/install-size.json new file mode 100644 index 0000000..0cac652 --- /dev/null +++ b/.github/badges/install-size.json @@ -0,0 +1,6 @@ +{ + "schemaVersion": 1, + "label": "install size", + "message": "no release yet", + "color": "lightgrey" +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b4c264..4c4dd44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -94,7 +94,14 @@ jobs: - name: Third-party notices are current run: npm run notices -- --check - name: Package VSIX - run: npx vsce package --no-dependencies --changelog-path docs/CHANGELOG.vsix.md --out ie-lua-language-server.vsix + env: + BRANCH: ${{ github.head_ref || github.ref_name }} + run: | + flags=() + # Release branches are packaged exactly as the Release workflow will publish them + # (odd minor = pre-release), so that the install-size check below sees the same bytes. + if [[ "$BRANCH" == release/v* ]] && (( $(cut -d . -f 2 VERSION) % 2 == 1 )); then flags+=(--pre-release); fi + npx vsce package --no-dependencies --changelog-path docs/CHANGELOG.vsix.md "${flags[@]}" --out ie-lua-language-server.vsix - name: VSIX contents run: | npx vsce ls --no-dependencies | tee vsix-files.txt @@ -104,6 +111,9 @@ jobs: printf '::error title=VSIX contents::Unexpected files in the VSIX (update .vscodeignore):\n%s\n' "$unexpected" exit 1 fi + - name: Install-size badge matches the VSIX (release branches) + if: startsWith(github.head_ref || github.ref_name, 'release/v') + run: node scripts/release/cli.mts install-size --vsix ie-lua-language-server.vsix --check - name: Upload VSIX uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e246bfd..a41d1f7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,12 +4,15 @@ # 1. "Run workflow" (choose pre-release or stable) → job `prepare`: # computes the next version from git tags + Conventional Commits # (scripts/release/), updates VERSION, package.json, package-lock.json, -# CHANGELOG.md and docs/CHANGELOG.vsix.md, and opens a release pull request. +# CHANGELOG.md and docs/CHANGELOG.vsix.md, packages the VSIX to record its +# installed size for the README badge (.github/badges/install-size.json), +# and opens a release pull request. # 2. Merging that pull request changes VERSION on main → job `publish` # (environment `release`): verifies the version, runs the checks, packages the # VSIX and creates the tag and the GitHub (pre-)release. Other pushes that # touch VERSION (for example a manual version reset) skip `publish`: it runs -# only for the squash commit of a `chore(release): …` pull request. +# only for the squash commit of a `chore(release): …` pull request. It also +# checks that the committed install-size badge matches the VSIX it publishes. # # Version rules (VS Code): plain major.minor.patch; even minor = stable, # odd minor = pre-release (packaged with `vsce package --pre-release`). @@ -60,6 +63,18 @@ jobs: env: CHANNEL: ${{ inputs.channel }} run: node scripts/release/cli.mts prepare --channel "$CHANNEL" + - name: Production bundle + run: npm run package + - name: Record the installed size of the VSIX + env: + VERSION: ${{ steps.version.outputs.version }} + CHANNEL: ${{ steps.version.outputs.channel }} + run: | + flags=() + if [ "$CHANNEL" = "pre-release" ]; then flags+=(--pre-release); fi + vsix="$RUNNER_TEMP/ie-lua-language-server-$VERSION.vsix" + npx vsce package --no-dependencies --changelog-path docs/CHANGELOG.vsix.md "${flags[@]}" --out "$vsix" + node scripts/release/cli.mts install-size --vsix "$vsix" --write - name: Open release pull request env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -75,7 +90,7 @@ jobs: git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git switch -c "$branch" - git add VERSION package.json package-lock.json CHANGELOG.md docs/CHANGELOG.vsix.md + git add VERSION package.json package-lock.json CHANGELOG.md docs/CHANGELOG.vsix.md .github/badges/install-size.json git commit -m "chore(release): $TAG" git push origin "$branch" gh pr create --base main --head "$branch" --title "chore(release): $TAG" --body \ @@ -136,6 +151,10 @@ jobs: hash="$(sha256sum "$vsix" | cut -d ' ' -f 1)" echo "SHA-256 of $vsix: $hash" printf '\n**SHA-256** of `%s`: `%s`\n' "$vsix" "$hash" >> "$RUNNER_TEMP/notes.md" + - name: Install-size badge matches the VSIX + env: + VERSION: ${{ steps.version.outputs.version }} + run: node scripts/release/cli.mts install-size --vsix "ie-lua-language-server-$VERSION.vsix" --check --notes "$RUNNER_TEMP/notes.md" - name: Create GitHub release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index ee0a65f..52c7a1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,11 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). committed `VERSION` as the first stable release (a pre-release before it would be 1.1.0). - The Release workflow publishes only for merged `chore(release): …` pull requests, not for any other push that changes `VERSION`. +- The Release workflow records the installed size of each release for the README's install-size + badge (`.github/badges/install-size.json`, a shields.io endpoint): the size VS Code shows in the + extension's details, computed from the VSIX exactly as VS Code installs it + (`scripts/release/vsix.mts`). CI checks it on release branches and the publish job against the + VSIX it publishes; the exact byte count goes in the release notes. - GitHub releases have the VSIX as their only asset; its SHA-256 moved from a separate `.vsix.sha256` file into the release notes, so the download count covers VSIX downloads only. - CI integration jobs build the tests before running them, and a test run that finds no tests now diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 848021c..37ad3f3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -121,10 +121,15 @@ Nothing is ever published to a marketplace (`"private": true`; `vsce publish` is **stable**. It computes the next version (odd minor for pre-releases, even minor for stable, always higher than every earlier release; the very first stable release is the committed `VERSION`, 1.0.0, and a pre-release before it would be 1.1.0), updates `VERSION`, `package.json`, `package-lock.json` - and both changelogs, and opens a `chore(release): vX.Y.Z` pull request. + and both changelogs, records the size VS Code will show for the installed VSIX in + `.github/badges/install-size.json` (the README's install-size badge), and opens a + `chore(release): vX.Y.Z` pull request. CI checks that size on every `release/v*` branch: if `main` moves + and you update the branch, re-run `node scripts/release/cli.mts install-size --vsix --write` on + a VSIX packaged as the error message describes, and commit the file. 3. Review and merge that pull request. The workflow then verifies the version, runs the checks, packages the VSIX and creates the tag and the GitHub release (environment `release`). The VSIX - is the release's only asset; its SHA-256 is at the end of the release notes. + is the release's only asset; its SHA-256 and exact installed size are at the end of the release + notes. Publishing fails if the committed install-size badge does not match the VSIX. ## Repository settings (maintainers) diff --git a/scripts/release/cli.mts b/scripts/release/cli.mts index 29093ab..fd18a21 100644 --- a/scripts/release/cli.mts +++ b/scripts/release/cli.mts @@ -7,6 +7,13 @@ // node scripts/release/cli.mts verify [--notes ] // Checks that the committed version is consistent and not yet released, and // optionally writes the CHANGELOG.md section of that version to . +// node scripts/release/cli.mts install-size --vsix (--write | --check) [--notes ] +// Computes the size VS Code shows for the extension once is installed +// (scripts/release/vsix.mts) and writes it to, or checks it against, the +// README badge data in .github/badges/install-size.json. The check compares +// what the badge shows (VS Code's rounding to 0.01 KB): shields.io rejects +// extra keys, so the exact byte count is printed, and appended to the +// release notes file given with --notes. // // On GitHub Actions both commands append `version`, `tag` and `channel` to $GITHUB_OUTPUT. import { execFileSync } from 'node:child_process'; @@ -25,10 +32,13 @@ import { type Channel, type Version, } from './version.mts'; +import { formatSize, installedSize, installSizeBadge, zipEntries } from './vsix.mts'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'); const REPOSITORY_URL = 'https://github.com/4Luke4/IE-Lua-Language-Server'; const CHANGELOGS = ['CHANGELOG.md', join('docs', 'CHANGELOG.vsix.md')]; +/** shields.io endpoint data of the README's install-size badge, for the latest release. */ +const INSTALL_SIZE_BADGE = join('.github', 'badges', 'install-size.json'); function fail(message: string): never { console.error(`::error title=Release::${message}`); @@ -149,6 +159,43 @@ function verify(notesFile: string | undefined): void { output({ version: text, tag, channel: channelOf(version) }); } +function installSize(vsixFile: string | undefined, mode: 'write' | 'check', notesFile: string | undefined): void { + if (!vsixFile) { + fail('install-size needs --vsix .'); + } + let size: number; + try { + size = installedSize(zipEntries(readFileSync(vsixFile))); + } catch (error) { + fail(`Cannot read the VSIX ${vsixFile}: ${error instanceof Error ? error.message : String(error)}`); + } + const badge = `${JSON.stringify(installSizeBadge(size), null, 2)}\n`; + console.log(`${vsixFile} installs ${String(size)} bytes, shown by VS Code as ${formatSize(size)}.`); + if (mode === 'write') { + writeFileSync(join(root, INSTALL_SIZE_BADGE), badge); + console.log(`Wrote ${INSTALL_SIZE_BADGE}.`); + return; + } + let committed: string; + try { + committed = read(INSTALL_SIZE_BADGE); + } catch (error) { + fail(`Cannot read ${INSTALL_SIZE_BADGE}: ${error instanceof Error ? error.message : String(error)}`); + } + if (committed !== badge) { + fail( + `${INSTALL_SIZE_BADGE} does not match ${vsixFile}, which installs ${formatSize(size)} (${String(size)} bytes). ` + + 'The badge must describe the VSIX this commit releases. On the release branch, run `npm run package`, package the VSIX ' + + 'as the Release workflow does (with --pre-release for an odd minor version), run ' + + '`node scripts/release/cli.mts install-size --vsix --write` and commit the file.', + ); + } + console.log(`${INSTALL_SIZE_BADGE} matches.`); + if (notesFile) { + appendFileSync(notesFile, `\n**Installed size:** ${String(size)} bytes (${formatSize(size)} in VS Code).\n`); + } +} + const [command, ...args] = process.argv.slice(2); const option = (name: string): string | undefined => { const index = args.indexOf(name); @@ -163,6 +210,15 @@ if (command === 'prepare') { prepare(channel); } else if (command === 'verify') { verify(option('--notes')); +} else if (command === 'install-size') { + const write = args.includes('--write'); + if (write === args.includes('--check')) { + fail('install-size needs exactly one of --write and --check.'); + } + installSize(option('--vsix'), write ? 'write' : 'check', option('--notes')); } else { - fail(`Unknown command "${String(command)}". Use "prepare --channel " or "verify [--notes ]".`); + fail( + `Unknown command "${String(command)}". Use "prepare --channel ", "verify [--notes ]" ` + + 'or "install-size --vsix (--write | --check) [--notes ]".', + ); } diff --git a/scripts/release/vsix.mts b/scripts/release/vsix.mts new file mode 100644 index 0000000..35a6c86 --- /dev/null +++ b/scripts/release/vsix.mts @@ -0,0 +1,115 @@ +// Installed size of a VSIX, computed exactly as VS Code computes and shows it, +// for the README's install-size badge. Pure: reads bytes, no file system access. +// +// VS Code (references at tag 1.143.1, https://github.com/microsoft/vscode/tree/1.143.1): +// - Installing a VSIX extracts it with `extract(zipPath, …, { sourcePath: 'extension' })` +// (src/vs/platform/extensionManagement/node/extensionManagementService.ts:649). +// `extract` matches entries with the regular expression `^extension` and strips +// that prefix (src/vs/base/node/zip.ts:388 and :149). The prefix has no slash, +// so `extension.vsixmanifest` is installed too, as `.vsixmanifest`. Entries +// whose names end in `/` only create directories. +// - Right after extracting, `metadata.size = await computeSize(tempLocation, …)` +// (extensionManagementService.ts:657): the sum of the sizes of all files. +// VS Code adds `__metadata` to package.json only after that, so it is not counted. +// - The extension editor shows `ByteSize.formatSize(extension.size)` +// (src/vs/workbench/contrib/extensions/browser/extensionEditor.ts:1186; +// src/vs/platform/files/common/files.ts:1603), in units of 1024. +// +// Checked against a real install with VS Code 1.143.1: the recorded +// `__metadata.size` equals `installedSize()` of the same VSIX. + +export interface ZipEntry { + /** Name as stored in the archive, `/`-separated; directories end in `/`. */ + readonly name: string; + readonly uncompressedSize: number; +} + +const END_OF_CENTRAL_DIRECTORY = 0x06054b50; +const ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR = 0x07064b50; +const CENTRAL_DIRECTORY_HEADER = 0x02014b50; +/** Fixed part of the end of central directory record; a comment of up to 65,535 bytes may follow. */ +const END_RECORD_SIZE = 22; +/** General purpose bit 11: the file name is UTF-8 (APPNOTE.TXT 4.4.4). */ +const UTF8_FLAG = 0x0800; + +/** + * The entries of a ZIP archive, read from its central directory + * (PKWARE APPNOTE.TXT 4.3.12 and 4.3.16). Throws on anything that is not a + * plain ZIP: a VSIX never needs ZIP64, so its markers are rejected. + */ +export function zipEntries(zip: Uint8Array): ZipEntry[] { + const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength); + let end = -1; + for (let offset = zip.length - END_RECORD_SIZE; offset >= Math.max(0, zip.length - END_RECORD_SIZE - 0xffff); offset--) { + if (view.getUint32(offset, true) === END_OF_CENTRAL_DIRECTORY && offset + END_RECORD_SIZE + view.getUint16(offset + 20, true) === zip.length) { + end = offset; + break; + } + } + if (end < 0) { + throw new Error('Not a ZIP archive: no end of central directory record.'); + } + if (end >= 20 && view.getUint32(end - 20, true) === ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR) { + throw new Error('ZIP64 archives are not supported.'); + } + const count = view.getUint16(end + 10, true); + const directorySize = view.getUint32(end + 12, true); + const directoryOffset = view.getUint32(end + 16, true); + if (directoryOffset + directorySize > end) { + throw new Error('Corrupt ZIP archive: the central directory overlaps its end record.'); + } + const entries: ZipEntry[] = []; + let offset = directoryOffset; + for (let i = 0; i < count; i++) { + if (offset + 46 > end || view.getUint32(offset, true) !== CENTRAL_DIRECTORY_HEADER) { + throw new Error(`Corrupt ZIP archive: central directory entry ${String(i + 1)} of ${String(count)} is missing.`); + } + const flags = view.getUint16(offset + 8, true); + const uncompressedSize = view.getUint32(offset + 24, true); + const nameLength = view.getUint16(offset + 28, true); + const extraLength = view.getUint16(offset + 30, true); + const commentLength = view.getUint16(offset + 32, true); + if (uncompressedSize === 0xffffffff) { + throw new Error('ZIP64 archives are not supported.'); + } + const nameBytes = zip.subarray(offset + 46, offset + 46 + nameLength); + // Without the UTF-8 flag names are CP437; VSIX names are ASCII, which both encodings share. + const name = new TextDecoder(flags & UTF8_FLAG ? 'utf-8' : 'latin1').decode(nameBytes); + entries.push({ name, uncompressedSize }); + offset += 46 + nameLength + extraLength + commentLength; + } + return entries; +} + +/** Bytes VS Code installs from a VSIX with these entries (see the file header). */ +export function installedSize(entries: readonly ZipEntry[]): number { + return entries + .filter(({ name }) => name.startsWith('extension') && !name.endsWith('/')) + .reduce((total, { uncompressedSize }) => total + uncompressedSize, 0); +} + +/** `ByteSize.formatSize` of VS Code with its English messages, e.g. `933.08KB`. */ +export function formatSize(size: number): string { + const units = ['KB', 'MB', 'GB', 'TB'] as const; + if (size < 1024) { + return `${size.toFixed(0)}B`; + } + let unit = 0; + while (unit < units.length - 1 && size >= 1024 ** (unit + 2)) { + unit++; + } + return `${(size / 1024 ** (unit + 1)).toFixed(2)}${units[unit] ?? ''}`; +} + +/** A shields.io endpoint badge (https://shields.io/badges/endpoint-badge), schema version 1. */ +export interface EndpointBadge { + readonly schemaVersion: 1; + readonly label: string; + readonly message: string; + readonly color: string; +} + +/** The install-size badge for a VSIX of `size` installed bytes. */ +export function installSizeBadge(size: number): EndpointBadge { + return { schemaVersion: 1, label: 'install size', message: formatSize(size), color: 'informational' }; +} diff --git a/test/unit/scripts/release/vsix.test.ts b/test/unit/scripts/release/vsix.test.ts new file mode 100644 index 0000000..764f375 --- /dev/null +++ b/test/unit/scripts/release/vsix.test.ts @@ -0,0 +1,139 @@ +import assert from 'node:assert/strict'; +import { formatSize, installedSize, installSizeBadge, zipEntries } from '../../../../scripts/release/vsix.mts'; + +interface TestFile { + readonly name: string; + readonly content: string; + readonly utf8?: boolean; +} + +/** A ZIP archive of stored (uncompressed) files, built per PKWARE APPNOTE.TXT. CRCs are left 0: the reader does not check them. */ +function buildZip(files: readonly TestFile[], comment = ''): Uint8Array { + const encoder = new TextEncoder(); + const locals: Uint8Array[] = []; + const centrals: Uint8Array[] = []; + let offset = 0; + for (const file of files) { + const name = file.utf8 ? encoder.encode(file.name) : Uint8Array.from(file.name, (c) => c.charCodeAt(0)); + const data = encoder.encode(file.content); + const flags = file.utf8 ? 0x0800 : 0; + const local = new DataView(new ArrayBuffer(30)); + local.setUint32(0, 0x04034b50, true); + local.setUint16(6, flags, true); + local.setUint32(18, data.length, true); + local.setUint32(22, data.length, true); + local.setUint16(26, name.length, true); + locals.push(new Uint8Array(local.buffer), name, data); + const central = new DataView(new ArrayBuffer(46)); + central.setUint32(0, 0x02014b50, true); + central.setUint16(8, flags, true); + central.setUint32(20, data.length, true); + central.setUint32(24, data.length, true); + central.setUint16(28, name.length, true); + central.setUint32(42, offset, true); + centrals.push(new Uint8Array(central.buffer), name); + offset += 30 + name.length + data.length; + } + const directorySize = centrals.reduce((total, part) => total + part.length, 0); + const commentBytes = encoder.encode(comment); + const end = new DataView(new ArrayBuffer(22)); + end.setUint32(0, 0x06054b50, true); + end.setUint16(8, files.length, true); + end.setUint16(10, files.length, true); + end.setUint32(12, directorySize, true); + end.setUint32(16, offset, true); + end.setUint16(20, commentBytes.length, true); + return concat([...locals, ...centrals, new Uint8Array(end.buffer), commentBytes]); +} + +function concat(parts: readonly Uint8Array[]): Uint8Array { + const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0)); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.length; + } + return out; +} + +/** The layout `vsce package` produces. */ +const VSIX: TestFile[] = [ + { name: 'extension.vsixmanifest', content: '' }, + { name: '[Content_Types].xml', content: '' }, + { name: 'extension/', content: '' }, + { name: 'extension/package.json', content: '{"name":"x"}' }, + { name: 'extension/dist/server/server.js', content: 'console.log(1);' }, +]; + +describe('scripts/release/vsix', () => { + describe('zipEntries', () => { + it('reads the name and uncompressed size of every entry, in order', () => { + assert.deepEqual( + zipEntries(buildZip(VSIX)), + VSIX.map(({ name, content }) => ({ name, uncompressedSize: content.length })), + ); + }); + + it('decodes UTF-8 names when the archive says so', () => { + assert.deepEqual(zipEntries(buildZip([{ name: 'extension/né.md', content: 'x', utf8: true }])), [{ name: 'extension/né.md', uncompressedSize: 1 }]); + }); + + it('finds the end record behind an archive comment', () => { + assert.equal(zipEntries(buildZip(VSIX, 'comment with PK\x05\x06 inside')).length, VSIX.length); + }); + + it('rejects data that is not a ZIP archive', () => { + assert.throws(() => zipEntries(new TextEncoder().encode('not a zip archive, just text')), /no end of central directory/); + assert.throws(() => zipEntries(new Uint8Array(0)), /no end of central directory/); + }); + + it('rejects ZIP64 archives and truncated central directories', () => { + const zip = buildZip(VSIX); + const locator = new DataView(new ArrayBuffer(20)); + locator.setUint32(0, 0x07064b50, true); + const end = zip.subarray(zip.length - 22); + const withLocator = concat([zip.subarray(0, zip.length - 22), new Uint8Array(locator.buffer), end]); + // Keep the central directory offset valid: it is before the inserted locator. + assert.throws(() => zipEntries(withLocator), /ZIP64/); + + const truncated = buildZip(VSIX); + new DataView(truncated.buffer).setUint16(truncated.length - 22 + 10, VSIX.length + 1, true); + assert.throws(() => zipEntries(truncated), /entry 6 of 6 is missing/); + }); + }); + + describe('installedSize', () => { + it('counts the files VS Code extracts: names starting with "extension", the manifest included', () => { + const sizes = Object.fromEntries(VSIX.map(({ name, content }) => [name, content.length])); + const expected = (sizes['extension.vsixmanifest'] ?? 0) + (sizes['extension/package.json'] ?? 0) + (sizes['extension/dist/server/server.js'] ?? 0); + assert.equal(installedSize(zipEntries(buildZip(VSIX))), expected); + }); + + it('is 0 for an archive without extension files', () => { + assert.equal(installedSize([{ name: '[Content_Types].xml', uncompressedSize: 9 }]), 0); + }); + }); + + describe('formatSize', () => { + it('formats like VS Code\'s ByteSize.formatSize, in units of 1024', () => { + const cases: [number, string][] = [ + [0, '0B'], + [1023, '1023B'], + [1024, '1.00KB'], + [955_479, '933.08KB'], + [1024 ** 2 - 1, '1024.00KB'], + [1024 ** 2, '1.00MB'], + [5.5 * 1024 ** 3, '5.50GB'], + [2 * 1024 ** 4, '2.00TB'], + [3 * 1024 ** 5, '3072.00TB'], + ]; + for (const [size, text] of cases) { + assert.equal(formatSize(size), text, String(size)); + } + }); + }); + + it('builds a shields.io endpoint badge', () => { + assert.deepEqual(installSizeBadge(955_479), { schemaVersion: 1, label: 'install size', message: '933.08KB', color: 'informational' }); + }); +}); From 222e4fc2d580f15e64c337b9a8de20c95b970d61 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:08:39 +0100 Subject: [PATCH 9/9] docs(readme): add downloads and install-size badges - Downloads: shields.io `github/downloads//total`, the sum of the download counts of all assets of all releases. Since the VSIX is now the only asset of a release, that is the number of VSIX downloads. GitHub's API only offers anonymous per-asset counts, so maintainers' and collaborators' own downloads cannot be excluded; the README says so next to the installation steps. - Install size: shields.io endpoint badge reading .github/badges/install-size.json from main, which the Release workflow keeps equal to the size VS Code shows for the latest release. It reads "no release yet" until the first release. `vsce package` accepts both badges (img.shields.io is a trusted badge source for the README shipped in the VSIX). Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 0be2ea1..f0a2079 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ [![CI](https://img.shields.io/github/actions/workflow/status/4Luke4/IE-Lua-Language-Server/ci.yml?branch=main&label=CI&logo=github)](https://github.com/4Luke4/IE-Lua-Language-Server/actions/workflows/ci.yml) [![CodeQL](https://img.shields.io/github/actions/workflow/status/4Luke4/IE-Lua-Language-Server/codeql.yml?branch=main&label=CodeQL&logo=github)](https://github.com/4Luke4/IE-Lua-Language-Server/actions/workflows/codeql.yml) [![Release](https://img.shields.io/github/v/release/4Luke4/IE-Lua-Language-Server?include_prereleases&sort=semver&label=release)](https://github.com/4Luke4/IE-Lua-Language-Server/releases) +[![Downloads](https://img.shields.io/github/downloads/4Luke4/IE-Lua-Language-Server/total?label=downloads&logo=github)](https://github.com/4Luke4/IE-Lua-Language-Server/releases) +[![Install size](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F4Luke4%2FIE-Lua-Language-Server%2Fmain%2F.github%2Fbadges%2Finstall-size.json)](#installation) [![License: proprietary](https://img.shields.io/badge/license-proprietary-informational)](LICENSE.md) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-fe5196?logo=conventionalcommits&logoColor=white)](https://www.conventionalcommits.org/en/v1.0.0/) @@ -49,6 +51,10 @@ This extension is distributed privately as a `.vsix` file. Requires VS Code **1.91** or later. +The *downloads* badge counts downloads of the `.vsix` files of all releases, as reported by +GitHub; GitHub does not say who downloads, so maintainers' own downloads are included. The +*install size* badge shows the size VS Code reports for the latest release once installed. + ## Settings | Setting | Default | Description |