From f99d5465f38ab5b8c4e1e217f6e67110f08995ab Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:01:16 +0100 Subject: [PATCH 1/8] refactor(server): share the cancellable index wait Move `untilCancelled` from the workspace symbols feature into `src/server/features/cancellation.ts`, so go to definition and find references can wait for the workspace index the same way. While moving it: resolve at once for a token that is already cancelled, and handle both outcomes of the promise with `then(done, done)` instead of `finally`, so a rejected promise can never surface as an unhandled rejection. `WorkspaceIndex.ready()` never rejects, so workspace symbols behave as before. Adds unit tests for the helper. Co-Authored-By: Claude Opus 5.5 --- src/server/features/cancellation.ts | 21 +++++++++++++ src/server/features/workspaceSymbols.ts | 17 ++--------- .../unit/server/features/cancellation.test.ts | 30 +++++++++++++++++++ 3 files changed, 53 insertions(+), 15 deletions(-) create mode 100644 src/server/features/cancellation.ts create mode 100644 test/unit/server/features/cancellation.test.ts diff --git a/src/server/features/cancellation.ts b/src/server/features/cancellation.ts new file mode 100644 index 0000000..f4ee67e --- /dev/null +++ b/src/server/features/cancellation.ts @@ -0,0 +1,21 @@ +import type { CancellationToken } from 'vscode-languageserver/node'; + +/** + * Resolves when `promise` settles or `token` is cancelled, whichever comes + * first. Never rejects: callers check `token.isCancellationRequested` afterwards. + */ +export function untilCancelled(promise: Promise, token: CancellationToken): Promise { + return new Promise((resolve) => { + if (token.isCancellationRequested) { + resolve(); + return; + } + const done = (): void => { + listener.dispose(); + resolve(); + }; + const listener = token.onCancellationRequested(done); + // Both outcomes are handled, so a rejected `promise` is never an unhandled rejection. + promise.then(done, done); + }); +} diff --git a/src/server/features/workspaceSymbols.ts b/src/server/features/workspaceSymbols.ts index 9718fb4..89136df 100644 --- a/src/server/features/workspaceSymbols.ts +++ b/src/server/features/workspaceSymbols.ts @@ -1,4 +1,4 @@ -import type { CancellationToken, Connection, SymbolInformation, TextDocuments } from 'vscode-languageserver/node'; +import type { Connection, SymbolInformation, TextDocuments } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; import type { ParsedDocumentCache } from '../documentCache.ts'; import { parseDocument } from '../syntax/document.ts'; @@ -6,6 +6,7 @@ import { documentSymbols } from '../syntax/symbols.ts'; import { matchesQuery } from '../syntax/workspaceSymbols.ts'; import { documentKind } from '../validation/validateText.ts'; import type { IndexedFile, WorkspaceIndex } from '../workspace/workspaceIndex.ts'; +import { untilCancelled } from './cancellation.ts'; import { flatSymbols } from './documentSymbols.ts'; export interface WorkspaceSymbolsDeps { @@ -53,20 +54,6 @@ export function collectWorkspaceSymbols( return result; } -/** Resolves when `promise` settles or `token` is cancelled, whichever comes first. */ -function untilCancelled(promise: Promise, token: CancellationToken): Promise { - return new Promise((resolve) => { - const listener = token.onCancellationRequested(() => { - listener.dispose(); - resolve(); - }); - void promise.finally(() => { - listener.dispose(); - resolve(); - }); - }); -} - /** * `workspace/symbol` ("Go to Symbol in Workspace"): the outline symbols (see * src/server/syntax/symbols.ts) of every Lua and .menu file in the workspace diff --git a/test/unit/server/features/cancellation.test.ts b/test/unit/server/features/cancellation.test.ts new file mode 100644 index 0000000..8ab177e --- /dev/null +++ b/test/unit/server/features/cancellation.test.ts @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict'; +import { CancellationTokenSource } from 'vscode-languageserver/node'; +import { untilCancelled } from '../../../../src/server/features/cancellation.ts'; + +describe('server/features/cancellation', () => { + it('resolves when the promise settles', async () => { + const source = new CancellationTokenSource(); + await untilCancelled(Promise.resolve(), source.token); + assert.equal(source.token.isCancellationRequested, false); + }); + + it('resolves when the token is cancelled before the promise settles', async () => { + const source = new CancellationTokenSource(); + const waiting = untilCancelled(new Promise(() => undefined), source.token); + source.cancel(); + await waiting; + assert.equal(source.token.isCancellationRequested, true); + }); + + it('resolves at once for a token that is already cancelled', async () => { + const source = new CancellationTokenSource(); + source.cancel(); + await untilCancelled(new Promise(() => undefined), source.token); + }); + + it('never rejects when the promise rejects', async () => { + const source = new CancellationTokenSource(); + await untilCancelled(Promise.reject(new Error('index failed')), source.token); + }); +}); From 07dd25238fef113ee388327a3098e8d34f6a4e9d Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:03:21 +0100 Subject: [PATCH 2/8] feat(server): index the globals of workspace files The workspace index now keeps, for every Lua and .menu file, both its outline (workspace symbols, unchanged) and where it names each global, with whether that use assigns it. Both come from one parse of the file (`analyzeFile` in `src/server/features/workspaceFiles.ts`). Per IESDP (Engine Lua globals), the Enhanced Editions run "in one global Lua state that is shared by the MENU file, the game's own Lua files and the engine", so a global is the same variable in every file. `_ENV` (one per chunk) and names resolved through a local `_ENV` are not globals and are left out (`globalOccurrences`, `sharedGlobalName` in syntax/navigation.ts). `fileSymbols(text, uri)` becomes `outlineSymbols(parsed, document)`, shared by open documents and indexed files; its tests move to workspaceFiles.test.ts. Nothing reads the new data yet. Co-Authored-By: Claude Opus 5.5 --- src/server/features/workspaceFiles.ts | 42 ++++++++++++++ src/server/features/workspaceSymbols.ts | 28 ++++------ src/server/server.ts | 8 +-- src/server/syntax/navigation.ts | 55 +++++++++++++++++++ .../server/features/workspaceFiles.test.ts | 46 ++++++++++++++++ .../server/features/workspaceSymbols.test.ts | 24 ++------ test/unit/server/syntax/navigation.test.ts | 32 ++++++++++- 7 files changed, 193 insertions(+), 42 deletions(-) create mode 100644 src/server/features/workspaceFiles.ts create mode 100644 test/unit/server/features/workspaceFiles.test.ts diff --git a/src/server/features/workspaceFiles.ts b/src/server/features/workspaceFiles.ts new file mode 100644 index 0000000..c4c6bb5 --- /dev/null +++ b/src/server/features/workspaceFiles.ts @@ -0,0 +1,42 @@ +// What the workspace index keeps for each Lua and .menu file, computed from one +// parse of its text: the outline for `workspace/symbol`, and where it names each +// global shared with other files, for go to definition and find references. +import type { Position, Range, SymbolInformation } from 'vscode-languageserver/node'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { parseDocument, type ParsedDocument } from '../syntax/document.ts'; +import { globalOccurrences } from '../syntax/navigation.ts'; +import { documentKind } from '../validation/validateText.ts'; +import { outlineSymbols } from './workspaceSymbols.ts'; + +/** Where a file names a global. */ +export interface GlobalLocation { + readonly range: Range; + /** Whether it assigns the global (`x = …`, `function x()`). */ + readonly isWrite: boolean; +} + +export interface IndexedFileFacts { + readonly symbols: readonly SymbolInformation[]; + /** The globals the file names, by name, each list in document order (see `globalOccurrences`). */ + readonly globals: ReadonlyMap; +} + +/** The shared globals of a parsed document, with LSP positions. */ +export function globalLocations(parsed: ParsedDocument, positionAt: (offset: number) => Position): Map { + const result = new Map(); + for (const [name, occurrences] of globalOccurrences(parsed)) { + result.set( + name, + occurrences.map(({ start, end, isWrite }) => ({ range: { start: positionAt(start), end: positionAt(end) }, isWrite })), + ); + } + return result; +} + +/** The facts of a file that is not open, for the workspace index. */ +export function analyzeFile(text: string, uri: string): IndexedFileFacts { + const document = TextDocument.create(uri, '', 0, text); + const parsed = parseDocument(text, documentKind(uri, '')); + const positionAt = (offset: number): Position => document.positionAt(offset); + return { symbols: outlineSymbols(parsed, { uri, positionAt }), globals: globalLocations(parsed, positionAt) }; +} diff --git a/src/server/features/workspaceSymbols.ts b/src/server/features/workspaceSymbols.ts index 89136df..67e7d60 100644 --- a/src/server/features/workspaceSymbols.ts +++ b/src/server/features/workspaceSymbols.ts @@ -1,24 +1,22 @@ -import type { Connection, SymbolInformation, TextDocuments } from 'vscode-languageserver/node'; -import { TextDocument } from 'vscode-languageserver-textdocument'; +import type { Connection, Position, SymbolInformation, TextDocuments } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; import type { ParsedDocumentCache } from '../documentCache.ts'; -import { parseDocument } from '../syntax/document.ts'; +import type { ParsedDocument } from '../syntax/document.ts'; import { documentSymbols } from '../syntax/symbols.ts'; import { matchesQuery } from '../syntax/workspaceSymbols.ts'; -import { documentKind } from '../validation/validateText.ts'; import type { IndexedFile, WorkspaceIndex } from '../workspace/workspaceIndex.ts'; import { untilCancelled } from './cancellation.ts'; import { flatSymbols } from './documentSymbols.ts'; +import type { IndexedFileFacts } from './workspaceFiles.ts'; export interface WorkspaceSymbolsDeps { readonly cache: ParsedDocumentCache; - readonly index: WorkspaceIndex; + readonly index: WorkspaceIndex; } -/** The flat outline of a file that is not open, for the workspace index. */ -export function fileSymbols(text: string, uri: string): SymbolInformation[] { - const document = TextDocument.create(uri, '', 0, text); - const outline = documentSymbols(parseDocument(text, documentKind(uri, '')), text.length); - return flatSymbols(outline, { uri, positionAt: (offset) => document.positionAt(offset) }); +/** The flat outline of a parsed document, as `workspace/symbol` lists it. */ +export function outlineSymbols(parsed: ParsedDocument, document: { readonly uri: string; positionAt(offset: number): Position }): SymbolInformation[] { + return flatSymbols(documentSymbols(parsed, parsed.text.length), document); } export interface SymbolSource { @@ -34,7 +32,7 @@ export interface SymbolSource { */ export function collectWorkspaceSymbols( open: readonly SymbolSource[], - indexed: Iterable>, + indexed: Iterable>>, query: string, isCancelled: () => boolean, ): SymbolInformation[] | undefined { @@ -49,7 +47,7 @@ export function collectWorkspaceSymbols( } for (const file of indexed) { if (isCancelled()) return undefined; - if (!openKeys.has(file.key)) add(file.value); + if (!openKeys.has(file.key)) add(file.value.symbols); } return result; } @@ -67,11 +65,7 @@ export function register(connection: Connection, documents: TextDocuments ({ key: deps.index.pathKey(document.uri) ?? document.uri, - symbols: () => - flatSymbols(documentSymbols(deps.cache.get(document), document.getText().length), { - uri: document.uri, - positionAt: (offset) => document.positionAt(offset), - }), + symbols: () => outlineSymbols(deps.cache.get(document), document), })); return collectWorkspaceSymbols(open, deps.index.entries(), query, () => token.isCancellationRequested) ?? null; } catch (error) { diff --git a/src/server/server.ts b/src/server/server.ts index f3f4ad5..ed08801 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -11,7 +11,6 @@ import { TextDocuments, TextDocumentSyncKind, WatchKind, - type SymbolInformation, } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { ParsedDocumentCache } from './documentCache.ts'; @@ -27,6 +26,7 @@ import { markupFormat } from './features/markup.ts'; import * as references from './features/references.ts'; import * as rename from './features/rename.ts'; import * as semanticTokens from './features/semanticTokens.ts'; +import { analyzeFile, type IndexedFileFacts } from './features/workspaceFiles.ts'; import * as workspaceSymbols from './features/workspaceSymbols.ts'; import { createMessages } from './l10n.ts'; import { SettingsStore } from './settingsStore.ts'; @@ -55,11 +55,11 @@ let formattingRegistration: formatting.FormattingRegistration = { document: fals /** Workspace folder URIs, kept up to date from `workspace/didChangeWorkspaceFolders`. */ let folders: string[] = []; -/** Lua and .menu files of the workspace folders, for workspace symbols. */ -const index = new WorkspaceIndex({ +/** Lua and .menu files of the workspace folders, for workspace symbols, definitions and references. */ +const index = new WorkspaceIndex({ fs: nodeFileSystem, path, - analyze: workspaceSymbols.fileSymbols, + analyze: analyzeFile, filesExclude: async (folderUri) => { if (!configurationPull) return undefined; try { diff --git a/src/server/syntax/navigation.ts b/src/server/syntax/navigation.ts index 8a2fd41..9f29736 100644 --- a/src/server/syntax/navigation.ts +++ b/src/server/syntax/navigation.ts @@ -129,3 +129,58 @@ export function references(document: ParsedDocument, target: NavigationTarget, i .filter((use) => includeDeclaration || !use.isWrite) .map((use) => use.identifier); } + +// ------------------------------------------------------------- across files +// +// The Enhanced Editions run all their Lua in one global state, "shared by the +// MENU file, the game's own Lua files and the engine" (IESDP, Engine Lua +// globals: https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm), +// so a global of one file is the same variable in every other file. `_ENV` is +// not: each chunk has its own (manual §2.2), and a name resolved through a local +// `_ENV` is a field of that table, not a global. + +/** One identifier naming a global, by offset in the document text. */ +export interface GlobalOccurrence { + readonly start: number; + readonly end: number; + /** Whether it assigns the global (`x = …`, `function x()`). */ + readonly isWrite: boolean; +} + +/** Whether `identifier` (of the chunk `scopes` belongs to) names a variable shared with other files. */ +function isSharedGlobal(scopes: ParsedDocument['chunks'][number]['scopes'], identifier: Ast.Identifier): boolean { + return identifier.name !== '_ENV' && !scopes.resolved.has(identifier) && !scopes.environmentFields.has(identifier); +} + +/** + * The identifiers of the document that name globals shared with other files, + * by name, each list in document order. `_ENV` and names resolved through a + * local `_ENV` are left out. + */ +export function globalOccurrences(document: ParsedDocument): Map { + const result = new Map(); + for (const { scopes } of document.chunks) { + for (const [name, identifiers] of scopes.globals) { + for (const identifier of identifiers) { + if (!isSharedGlobal(scopes, identifier)) continue; + let list = result.get(name); + if (!list) { + list = []; + result.set(name, list); + } + list.push({ start: identifier.start, end: identifier.end, isWrite: scopes.writes.has(identifier) }); + } + } + } + for (const list of result.values()) list.sort((a, b) => a.start - b.start); + return result; +} + +/** + * The name of the global shared with other files that `hit` is on, or + * `undefined` for locals, `_ENV` and names resolved through a local `_ENV`. + */ +export function sharedGlobalName(document: ParsedDocument, hit: TargetHit): string | undefined { + const scopes = document.chunks[hit.chunkIndex]?.scopes; + return hit.target.kind === 'global' && scopes && isSharedGlobal(scopes, hit.identifier) ? hit.target.name : undefined; +} diff --git a/test/unit/server/features/workspaceFiles.test.ts b/test/unit/server/features/workspaceFiles.test.ts new file mode 100644 index 0000000..1eb4f78 --- /dev/null +++ b/test/unit/server/features/workspaceFiles.test.ts @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import { analyzeFile, type GlobalLocation } from '../../../../src/server/features/workspaceFiles.ts'; + +/** `line:character` of each location, with `=` for assignments. */ +const where = (locations: readonly GlobalLocation[] | undefined): string[] | undefined => + locations?.map(({ range, isWrite }) => `${String(range.start.line)}:${String(range.start.character)}${isWrite ? '=' : ''}`); + +describe('server/features/workspaceFiles', () => { + describe('analyzeFile', () => { + it('lists the flat outline of a file with positions and containers', () => { + const { symbols } = analyzeFile('local M = {}\nfunction M.open()\nend\n', 'file:///w/a.lua'); + assert.deepEqual( + symbols.map((s) => [s.name, s.containerName ?? '', s.location.uri, s.location.range.start.line]), + [ + ['M', '', 'file:///w/a.lua', 0], + ['M.open', '', 'file:///w/a.lua', 1], + ], + ); + }); + + it('recognizes .menu files by their extension, in any letter case', () => { + const { symbols } = analyzeFile('menu\n{\n\tname "MAIN"\n\tonOpen "x = 1"\n}\n`\nfunction ready() end\n`\n', 'file:///w/UI.MENU'); + assert.deepEqual(symbols.map((s) => s.name), ['MAIN', 'ready']); + }); + + it('lists where a Lua file names each global, with its assignments', () => { + const { globals } = analyzeFile('local x = 1\nTotal = x\nfunction Add(n)\n\tTotal = Total + n\nend\nprint(Total)\n', 'file:///w/a.lua'); + assert.deepEqual([...globals.keys()].sort(), ['Add', 'Total', 'print']); + assert.deepEqual(where(globals.get('Total')), ['1:0=', '3:1=', '3:9', '5:6']); + assert.deepEqual(where(globals.get('Add')), ['2:9=']); + assert.equal(globals.get('x'), undefined); + }); + + it('collects the globals of every Lua chunk of a .menu file, in document order', () => { + const text = '`\nshown = 0\n`\nmenu\n{\n\tname "MAIN"\n\tonOpen "shown = shown + 1"\n\tlabel { enabled "shown > 0" }\n}\n'; + assert.deepEqual(where(analyzeFile(text, 'file:///w/UI.menu').globals.get('shown')), ['1:0=', '6:9=', '6:17', '7:18']); + }); + + it('leaves out _ENV and the names resolved through a local _ENV', () => { + const { globals } = analyzeFile('local _ENV = { y = 1 }\nz = y\n', 'file:///w/env.lua'); + assert.deepEqual([...globals.keys()], []); + const free = analyzeFile('_ENV.a = 1\nb = 2\n', 'file:///w/free.lua').globals; + assert.deepEqual([...free.keys()], ['b']); + }); + }); +}); diff --git a/test/unit/server/features/workspaceSymbols.test.ts b/test/unit/server/features/workspaceSymbols.test.ts index 18b2687..1473c79 100644 --- a/test/unit/server/features/workspaceSymbols.test.ts +++ b/test/unit/server/features/workspaceSymbols.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import type { SymbolInformation } from 'vscode-languageserver/node'; -import { collectWorkspaceSymbols, fileSymbols, type SymbolSource } from '../../../../src/server/features/workspaceSymbols.ts'; +import { collectWorkspaceSymbols, type SymbolSource } from '../../../../src/server/features/workspaceSymbols.ts'; const symbol = (name: string, uri: string): SymbolInformation => ({ name, @@ -9,27 +9,11 @@ const symbol = (name: string, uri: string): SymbolInformation => ({ }); describe('server/features/workspaceSymbols', () => { - it('lists the flat outline of a file with positions and containers', () => { - const symbols = fileSymbols('local M = {}\nfunction M.open()\nend\n', 'file:///w/a.lua'); - assert.deepEqual( - symbols.map((s) => [s.name, s.containerName ?? '', s.location.uri, s.location.range.start.line]), - [ - ['M', '', 'file:///w/a.lua', 0], - ['M.open', '', 'file:///w/a.lua', 1], - ], - ); - }); - - it('recognizes .menu files by their extension, in any letter case', () => { - const symbols = fileSymbols('menu\n{\n\tname "MAIN"\n\tonOpen "x = 1"\n}\n`\nfunction ready() end\n`\n', 'file:///w/UI.MENU'); - assert.deepEqual(symbols.map((s) => s.name), ['MAIN', 'ready']); - }); - it('returns the matching symbols of open documents and of indexed files that are not open', () => { const open: SymbolSource[] = [{ key: '/w/a.lua', symbols: () => [symbol('openVersion', 'file:///w/a.lua')] }]; const indexed = [ - { uri: 'file:///w/a.lua', key: '/w/a.lua', value: [symbol('savedVersion', 'file:///w/a.lua')] }, - { uri: 'file:///w/b.lua', key: '/w/b.lua', value: [symbol('other', 'file:///w/b.lua'), symbol('version', 'file:///w/b.lua')] }, + { uri: 'file:///w/a.lua', key: '/w/a.lua', value: { symbols: [symbol('savedVersion', 'file:///w/a.lua')] } }, + { uri: 'file:///w/b.lua', key: '/w/b.lua', value: { symbols: [symbol('other', 'file:///w/b.lua'), symbol('version', 'file:///w/b.lua')] } }, ]; const names = (query: string): string[] | undefined => collectWorkspaceSymbols(open, indexed, query, () => false)?.map((s) => s.name); assert.deepEqual(names(''), ['openVersion', 'other', 'version']); @@ -38,7 +22,7 @@ describe('server/features/workspaceSymbols', () => { it('stops when cancelled', () => { let calls = 0; - const result = collectWorkspaceSymbols([], [{ uri: 'file:///w/a.lua', key: '/w/a.lua', value: [] }], '', () => ++calls > 0); + const result = collectWorkspaceSymbols([], [{ uri: 'file:///w/a.lua', key: '/w/a.lua', value: { symbols: [] } }], '', () => ++calls > 0); assert.equal(result, undefined); }); }); diff --git a/test/unit/server/syntax/navigation.test.ts b/test/unit/server/syntax/navigation.test.ts index 17eae5f..c2af8db 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, identifierAt, references, targetAt } from '../../../../src/server/syntax/navigation.ts'; +import { definitions, globalOccurrences, identifierAt, references, sharedGlobalName, 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)}`); @@ -146,4 +146,34 @@ describe('server/syntax/navigation', () => { assert.deepEqual(referencesAt(text, 'own', 0, true, 'menu'), ['own@17']); }); }); + + describe('across files', () => { + it('lists each shared global by name in document order, with its assignments', () => { + const text = 'print(n)\nn = 1\nlocal m = n\n'; + assert.equal(text.slice(25, 26), 'n'); + const occurrences = globalOccurrences(parseDocument(text, 'lua')); + assert.deepEqual([...occurrences.keys()].sort(), ['n', 'print']); + // 0 1 2 + // 012345678 901234 56789012345 + assert.deepEqual(occurrences.get('n'), [ + { start: 6, end: 7, isWrite: false }, + { start: 9, end: 10, isWrite: true }, + { start: 25, end: 26, isWrite: false }, + ]); + }); + + it('names the shared global under the cursor, and nothing for locals or _ENV', () => { + const text = 'local l = g\n_ENV.x = l\ndo local _ENV = {} f = 1 end\n'; + const document = parseDocument(text, 'lua'); + const nameAt = (needle: string): string | undefined => { + const hit = targetAt(document, offsetOf(text, needle)); + assert.ok(hit, `no variable at "${needle}"`); + return sharedGlobalName(document, hit); + }; + assert.equal(nameAt('g'), 'g'); + assert.equal(nameAt('l = g'), undefined); + assert.equal(nameAt('_ENV.x'), undefined); + assert.equal(nameAt('f = 1'), undefined); + }); + }); }); From 4ef344d32c0a609185113299c34051585efbedc9 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:05:52 +0100 Subject: [PATCH 3/8] feat(server): find definitions and references of globals across the workspace Go to definition and find references on a global now also answer from the other Lua and .menu files: the open documents (their unsaved text wins over the saved file) and the indexed files of the workspace folders. Results of the current document come first, in document order, then the other files in URI order. Definition is still `null` when no file assigns the global (EEex, game and library functions). Locals, `_ENV` and names resolved through a local `_ENV` stay in their own document and are answered as before, synchronously. For globals the handler waits for the files queued for indexing, as workspace symbols does, honoring cancellation; if the document changed meanwhile it answers ContentModified (LSP 3.17), which vscode-languageclient turns into an empty result without logging. Rename stays within the document, as before. No new capability, setting, message or dependency. Co-Authored-By: Claude Opus 5.5 --- src/server/features/definition.ts | 36 +++--- src/server/features/references.ts | 36 ++++-- src/server/features/workspaceFiles.ts | 106 +++++++++++++++++- src/server/server.ts | 4 +- .../server/features/workspaceFiles.test.ts | 106 +++++++++++++++++- 5 files changed, 258 insertions(+), 30 deletions(-) diff --git a/src/server/features/definition.ts b/src/server/features/definition.ts index 367f547..a292967 100644 --- a/src/server/features/definition.ts +++ b/src/server/features/definition.ts @@ -1,34 +1,44 @@ -import type { Connection, Location, TextDocuments } from 'vscode-languageserver/node'; +import type { Connection, Location, ResponseError, 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'; +import { definitions, sharedGlobalName, targetAt } from '../syntax/navigation.ts'; +import { otherFileLocations, type CrossFileDeps } from './workspaceFiles.ts'; -export interface DefinitionDeps { - readonly cache: ParsedDocumentCache; -} +export type DefinitionDeps = CrossFileDeps; /** - * `textDocument/definition` within the document: the declaration of a local, or - * every assignment to a global (see src/server/syntax/navigation.ts). + * `textDocument/definition`: the declaration of a local, or every assignment + * to a global, first in the document (see src/server/syntax/navigation.ts), + * then in the other Lua and .menu files of the workspace, which share the + * engine's global state (see src/server/features/workspaceFiles.ts). */ export function register(connection: Connection, documents: TextDocuments, deps: DefinitionDeps): void { - connection.onDefinition(({ textDocument, position }, token): Location[] | null => { + connection.onDefinition(async ({ textDocument, position }, token): Promise => { 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) { + if (!hit) { return null; } - return found.map(({ start, end }) => ({ + const here: Location[] = definitions(parsed, hit.target).map(({ start, end }) => ({ uri: document.uri, range: { start: document.positionAt(start), end: document.positionAt(end) }, })); + const name = sharedGlobalName(parsed, hit); + // Locals, `_ENV` and fields of a local `_ENV` belong to this document alone. + if (name === undefined) { + return here.length > 0 ? here : null; + } + const elsewhere = await otherFileLocations(documents, document, name, (location) => location.isWrite, deps, token); + // Cancelled (`null`) or the document changed meanwhile (`ContentModified`). + if (!Array.isArray(elsewhere)) { + return elsewhere; + } + const all = [...here, ...elsewhere]; + return all.length > 0 ? all : null; } 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/features/references.ts b/src/server/features/references.ts index 66eb95f..7cb7448 100644 --- a/src/server/features/references.ts +++ b/src/server/features/references.ts @@ -1,34 +1,46 @@ -import type { Connection, Location, TextDocuments } from 'vscode-languageserver/node'; +import type { Connection, Location, ResponseError, 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'; +import { references, sharedGlobalName, targetAt } from '../syntax/navigation.ts'; +import { otherFileLocations, type CrossFileDeps } from './workspaceFiles.ts'; -export interface ReferencesDeps { - readonly cache: ParsedDocumentCache; -} +export type ReferencesDeps = CrossFileDeps; /** - * `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. + * `textDocument/references`: the uses of a local in the document, or of a + * global first in the document (see src/server/syntax/navigation.ts), then in + * the other Lua and .menu files of the workspace, which share the engine's + * global state (see src/server/features/workspaceFiles.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 => { + connection.onReferences(async ({ textDocument, position, context }, token): Promise => { 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 }) => ({ + const here: Location[] = references(parsed, hit.target, context.includeDeclaration).map(({ start, end }) => ({ uri: document.uri, range: { start: document.positionAt(start), end: document.positionAt(end) }, })); + const name = sharedGlobalName(parsed, hit); + // Locals, `_ENV` and fields of a local `_ENV` belong to this document alone. + if (name === undefined) { + return here; + } + const keep = context.includeDeclaration ? () => true : (location: { readonly isWrite: boolean }) => !location.isWrite; + const elsewhere = await otherFileLocations(documents, document, name, keep, deps, token); + // Cancelled (`null`) or the document changed meanwhile (`ContentModified`). + if (!Array.isArray(elsewhere)) { + return elsewhere; + } + return [...here, ...elsewhere]; } 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/features/workspaceFiles.ts b/src/server/features/workspaceFiles.ts index c4c6bb5..8fe039a 100644 --- a/src/server/features/workspaceFiles.ts +++ b/src/server/features/workspaceFiles.ts @@ -1,11 +1,24 @@ // What the workspace index keeps for each Lua and .menu file, computed from one // parse of its text: the outline for `workspace/symbol`, and where it names each -// global shared with other files, for go to definition and find references. -import type { Position, Range, SymbolInformation } from 'vscode-languageserver/node'; +// global shared with other files, for go to definition and find references, +// which look the globals up across files here. +import { + LSPErrorCodes, + ResponseError, + type CancellationToken, + type Location, + type Position, + type Range, + type SymbolInformation, + type TextDocuments, +} from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; +import type { ParsedDocumentCache } from '../documentCache.ts'; import { parseDocument, type ParsedDocument } from '../syntax/document.ts'; import { globalOccurrences } from '../syntax/navigation.ts'; import { documentKind } from '../validation/validateText.ts'; +import type { IndexedFile, WorkspaceIndex } from '../workspace/workspaceIndex.ts'; +import { untilCancelled } from './cancellation.ts'; import { outlineSymbols } from './workspaceSymbols.ts'; /** Where a file names a global. */ @@ -40,3 +53,92 @@ export function analyzeFile(text: string, uri: string): IndexedFileFacts { const positionAt = (offset: number): Position => document.positionAt(offset); return { symbols: outlineSymbols(parsed, { uri, positionAt }), globals: globalLocations(parsed, positionAt) }; } + +/** The globals of a file other than the one the request is for. */ +export interface GlobalSource { + readonly uri: string; + /** Index key (see `WorkspaceIndex.pathKey`), or the URI for a document that is not a local file. */ + readonly key: string; + readonly globals: () => ReadonlyMap; +} + +/** + * The locations in other files where `keep` accepts a use of the global `name`: + * first those of the open documents, then those of the indexed files that are + * not open (an open document wins over its saved version); `current` (the + * document the request is for, answered from its own text) is skipped. Files + * come in URI order, each file's locations in document order. Returns + * `undefined` once `isCancelled()` turns true. + */ +export function collectGlobalLocations( + name: string, + keep: (location: GlobalLocation) => boolean, + currentKey: string, + open: readonly GlobalSource[], + indexed: Iterable>>, + isCancelled: () => boolean, +): Location[] | undefined { + const files: { uri: string; locations: readonly GlobalLocation[] }[] = []; + const seen = new Set([currentKey]); + const add = (uri: string, globals: ReadonlyMap): void => { + const locations = globals.get(name)?.filter(keep); + if (locations && locations.length > 0) files.push({ uri, locations }); + }; + for (const source of open) { + if (isCancelled()) return undefined; + if (seen.has(source.key)) continue; + seen.add(source.key); + add(source.uri, source.globals()); + } + for (const file of indexed) { + if (isCancelled()) return undefined; + if (!seen.has(file.key)) add(file.uri, file.value.globals); + } + files.sort((a, b) => (a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0)); + return files.flatMap(({ uri, locations }) => locations.map(({ range }) => ({ uri, range }))); +} + +/** Globals of each open document version, dropped with it (see `ParsedDocumentCache`). */ +const openGlobals = new WeakMap>(); + +export interface CrossFileDeps { + readonly cache: ParsedDocumentCache; + readonly index: Pick, 'ready' | 'pathKey' | 'entries'>; +} + +/** + * Where other files use the global `name`, for a request on `document` + * (`keep` selects the uses). Waits for the files queued for indexing. Resolves + * to `null` when cancelled, and to a `ContentModified` error when `document` + * changed meanwhile (LSP 3.17: the result would be computed on a newer text). + */ +export async function otherFileLocations( + documents: Pick, 'get' | 'all'>, + document: TextDocument, + name: string, + keep: (location: GlobalLocation) => boolean, + deps: CrossFileDeps, + token: CancellationToken, +): Promise { + const { uri, version } = document; + await untilCancelled(deps.index.ready(), token); + if (token.isCancellationRequested) return null; + if (documents.get(uri)?.version !== version) { + return new ResponseError(LSPErrorCodes.ContentModified, `${uri} changed while the workspace was being indexed.`); + } + const open: GlobalSource[] = documents.all().map((other) => ({ + uri: other.uri, + key: deps.index.pathKey(other.uri) ?? other.uri, + globals: () => { + const parsed = deps.cache.get(other); + let globals = openGlobals.get(parsed); + if (!globals) { + globals = globalLocations(parsed, (offset) => other.positionAt(offset)); + openGlobals.set(parsed, globals); + } + return globals; + }, + })); + const currentKey = deps.index.pathKey(uri) ?? uri; + return collectGlobalLocations(name, keep, currentKey, open, deps.index.entries(), () => token.isCancellationRequested) ?? null; +} diff --git a/src/server/server.ts b/src/server/server.ts index ed08801..368fb67 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -106,8 +106,8 @@ connection.onInitialize((params) => { rangeLimit: folding?.rangeLimit, kinds: folding?.foldingRangeKind?.valueSet, }); - definition.register(connection, documents, { cache: parsed }); - references.register(connection, documents, { cache: parsed }); + definition.register(connection, documents, { cache: parsed, index }); + references.register(connection, documents, { cache: parsed, index }); const documentChanges = workspace?.workspaceEdit?.documentChanges === true; rename.register(connection, documents, { cache: parsed, documentChanges }); const codeActionLiterals = codeActions.supportsCodeActionLiterals(params.capabilities.textDocument?.codeAction?.codeActionLiteralSupport); diff --git a/test/unit/server/features/workspaceFiles.test.ts b/test/unit/server/features/workspaceFiles.test.ts index 1eb4f78..0e0ca9a 100644 --- a/test/unit/server/features/workspaceFiles.test.ts +++ b/test/unit/server/features/workspaceFiles.test.ts @@ -1,5 +1,16 @@ import assert from 'node:assert/strict'; -import { analyzeFile, type GlobalLocation } from '../../../../src/server/features/workspaceFiles.ts'; +import { CancellationTokenSource, LSPErrorCodes, ResponseError, type Location } from 'vscode-languageserver/node'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { ParsedDocumentCache } from '../../../../src/server/documentCache.ts'; +import { + analyzeFile, + collectGlobalLocations, + otherFileLocations, + type CrossFileDeps, + type GlobalLocation, + type IndexedFileFacts, +} from '../../../../src/server/features/workspaceFiles.ts'; +import type { IndexedFile } from '../../../../src/server/workspace/workspaceIndex.ts'; /** `line:character` of each location, with `=` for assignments. */ const where = (locations: readonly GlobalLocation[] | undefined): string[] | undefined => @@ -43,4 +54,97 @@ describe('server/features/workspaceFiles', () => { assert.deepEqual([...free.keys()], ['b']); }); }); + + describe('collectGlobalLocations', () => { + /** An indexed file analyzed from `text`, keyed by its path. */ + const indexed = (path: string, text: string): IndexedFile => ({ uri: `file://${path}`, key: path, value: analyzeFile(text, `file://${path}`) }); + const all = (): boolean => true; + const writes = (location: GlobalLocation): boolean => location.isWrite; + const show = (locations: Location[] | undefined): string[] | undefined => + locations?.map(({ uri, range }) => `${uri.slice('file:///w/'.length)} ${String(range.start.line)}:${String(range.start.character)}`); + + it('lists the uses in other files, in URI order, skipping the current document', () => { + const files = [indexed('/w/c.lua', 'print(G)\n'), indexed('/w/a.lua', 'G = 1\nG = G + 1\n'), indexed('/w/self.lua', 'G = 2\n'), indexed('/w/b.lua', 'local G = 0\n')]; + assert.deepEqual(show(collectGlobalLocations('G', all, '/w/self.lua', [], files, () => false)), ['a.lua 0:0', 'a.lua 1:0', 'a.lua 1:4', 'c.lua 0:6']); + assert.deepEqual(show(collectGlobalLocations('G', writes, '/w/self.lua', [], files, () => false)), ['a.lua 0:0', 'a.lua 1:0']); + assert.deepEqual(collectGlobalLocations('Missing', all, '/w/self.lua', [], files, () => false), []); + }); + + it('takes an open document over its saved version, once', () => { + const saved = indexed('/w/a.lua', 'G = 1\n'); + const reads: string[] = []; + const open = [ + { uri: 'file:///w/a.lua', key: '/w/a.lua', globals: () => (reads.push('a'), analyzeFile('\n\nG = 1\n', 'file:///w/a.lua').globals) }, + { uri: 'untitled:Untitled-1', key: 'untitled:Untitled-1', globals: () => (reads.push('untitled'), analyzeFile('x = G\n', 'untitled:Untitled-1').globals) }, + { uri: 'file:///w/a.lua', key: '/w/a.lua', globals: () => (reads.push('again'), new Map()) }, + ]; + const found = collectGlobalLocations('G', all, '/w/self.lua', open, [saved], () => false); + assert.deepEqual(found?.map(({ uri, range }) => `${uri} ${String(range.start.line)}`), ['file:///w/a.lua 2', 'untitled:Untitled-1 0']); + assert.deepEqual(reads, ['a', 'untitled']); + }); + + it('stops when cancelled', () => { + let calls = 0; + assert.equal(collectGlobalLocations('G', all, '/w/self.lua', [], [indexed('/w/a.lua', 'G = 1')], () => ++calls > 0), undefined); + }); + }); + + describe('otherFileLocations', () => { + /** Open documents as `TextDocuments` exposes them. */ + const openDocuments = (...open: TextDocument[]) => ({ + get: (uri: string) => open.find((document) => document.uri === uri), + all: () => open, + }); + const deps = (entries: IndexedFile[], ready: Promise = Promise.resolve()): CrossFileDeps => ({ + cache: new ParsedDocumentCache(), + index: { ready: () => ready, pathKey: (uri) => (uri.startsWith('file://') ? uri.slice('file://'.length) : undefined), entries: () => entries.values() }, + }); + const saved: IndexedFile = { uri: 'file:///w/b.lua', key: '/w/b.lua', value: analyzeFile('G = 1\n', 'file:///w/b.lua') }; + + it('finds the uses in the open documents and the indexed files', async () => { + const current = TextDocument.create('file:///w/a.lua', 'lua', 1, 'print(G)\n'); + const other = TextDocument.create('untitled:Untitled-1', 'lua', 1, 'G = 2\n'); + const found = await otherFileLocations(openDocuments(current, other), current, 'G', () => true, deps([saved]), new CancellationTokenSource().token); + assert.ok(Array.isArray(found)); + assert.deepEqual(found.map(({ uri }) => uri), ['file:///w/b.lua', 'untitled:Untitled-1']); + }); + + it('waits for the files queued for indexing', async () => { + const current = TextDocument.create('file:///w/a.lua', 'lua', 1, 'print(G)\n'); + const entries: IndexedFile[] = []; + let finish = (): void => undefined; + const ready = new Promise((resolve) => { + finish = () => { + entries.push(saved); + resolve(); + }; + }); + let settled = false; + const pending = otherFileLocations(openDocuments(current), current, 'G', () => true, deps(entries, ready), new CancellationTokenSource().token); + void pending.then(() => (settled = true)); + // Every pending callback runs before `setImmediate` fires: the request is still waiting. + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(settled, false); + finish(); + const found = await pending; + assert.ok(Array.isArray(found)); + assert.deepEqual(found.map(({ uri }) => uri), ['file:///w/b.lua']); + }); + + it('answers null when cancelled while waiting', async () => { + const current = TextDocument.create('file:///w/a.lua', 'lua', 1, 'print(G)\n'); + const source = new CancellationTokenSource(); + const pending = otherFileLocations(openDocuments(current), current, 'G', () => true, deps([saved], new Promise(() => undefined)), source.token); + source.cancel(); + assert.equal(await pending, null); + }); + + it('answers ContentModified when the document changed while waiting', async () => { + const current = TextDocument.create('file:///w/a.lua', 'lua', 1, 'print(G)\n'); + const newer = TextDocument.create('file:///w/a.lua', 'lua', 2, 'print(G, G)\n'); + const found = await otherFileLocations(openDocuments(newer), current, 'G', () => true, deps([saved]), new CancellationTokenSource().token); + assert.ok(found instanceof ResponseError); + assert.equal(found.code, LSPErrorCodes.ContentModified); + }); + }); }); From a9d8a3a88de4dabf520c0a6584388c440528dd5b Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:07:34 +0100 Subject: [PATCH 4/8] test: cover cross-file navigation in VS Code Original fixtures `crossfile/shared.lua` and `crossfile/CROSSFILE.MENU`, whose globals (`CrossFile_Total`, `CrossFile_Add`) occur in no other fixture, and four integration tests: definition from a .MENU file into a Lua file that is not open, definitions and references across both files, and an open document's unsaved text winning over its saved file. Locations of several files are compared sorted, since VS Code orders them itself; the server's order is covered by unit tests. Co-Authored-By: Claude Opus 5.5 --- .../workspace/crossfile/CROSSFILE.MENU | 14 +++ test/fixtures/workspace/crossfile/shared.lua | 6 ++ test/integration/crossFileNavigation.test.ts | 85 +++++++++++++++++++ 3 files changed, 105 insertions(+) create mode 100644 test/fixtures/workspace/crossfile/CROSSFILE.MENU create mode 100644 test/fixtures/workspace/crossfile/shared.lua create mode 100644 test/integration/crossFileNavigation.test.ts diff --git a/test/fixtures/workspace/crossfile/CROSSFILE.MENU b/test/fixtures/workspace/crossfile/CROSSFILE.MENU new file mode 100644 index 0000000..0f10a85 --- /dev/null +++ b/test/fixtures/workspace/crossfile/CROSSFILE.MENU @@ -0,0 +1,14 @@ +-- Original fixture: Lua that uses the globals of crossfile/shared.lua (cross-file navigation). +menu +{ + name 'CROSSFILE_MAIN' + button + { + enabled "CrossFile_Total > 0" + action + " + CrossFile_Add(1) + CrossFile_Total = 0 + " + } +} diff --git a/test/fixtures/workspace/crossfile/shared.lua b/test/fixtures/workspace/crossfile/shared.lua new file mode 100644 index 0000000..0919d7c --- /dev/null +++ b/test/fixtures/workspace/crossfile/shared.lua @@ -0,0 +1,6 @@ +-- Original fixture: globals that crossfile/CROSSFILE.MENU uses (cross-file navigation). +CrossFile_Total = 0 + +function CrossFile_Add(step) + CrossFile_Total = CrossFile_Total + step +end diff --git a/test/integration/crossFileNavigation.test.ts b/test/integration/crossFileNavigation.test.ts new file mode 100644 index 0000000..039560d --- /dev/null +++ b/test/integration/crossFileNavigation.test.ts @@ -0,0 +1,85 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, fixtureUri, openFixture } from './helpers.ts'; + +/** `file line:character` of each location's start, with the file relative to `crossfile/`, sorted. */ +function places(locations: readonly (vscode.Location | vscode.LocationLink)[]): string[] { + const folder = `${fixtureUri('crossfile').toString()}/`; + return locations + .map((location) => { + const [uri, range] = 'uri' in location ? [location.uri, location.range] : [location.targetUri, location.targetRange]; + const name = uri.toString().startsWith(folder) ? uri.toString().slice(folder.length) : uri.toString(); + return `${name} ${String(range.start.line)}:${String(range.start.character)}`; + }) + .sort(); +} + +async function definitionsAt(uri: vscode.Uri, line: number, character: number): Promise { + 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 places(found); +} + +/** References as VS Code requests them (declarations included). */ +async function referencesAt(uri: vscode.Uri, line: number, character: number): Promise { + const found = await vscode.commands.executeCommand( + 'vscode.executeReferenceProvider', + uri, + new vscode.Position(line, character), + ); + assert.ok(found, 'no reference provider answered'); + return places(found); +} + +// VS Code orders the locations of several files itself, so they are compared sorted; +// the server's own order is covered by the unit tests. +suite('Cross-file navigation', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('goes from a .MENU file to the definition of a global in a Lua file that is not open', async () => { + const menu = await openFixture('crossfile/CROSSFILE.MENU'); + assert.deepEqual(await definitionsAt(menu, 9, 3), ['shared.lua 3:9']); + }); + + test('lists the assignments to a global in this file and in the other files', async () => { + const lua = await openFixture('crossfile/shared.lua'); + assert.deepEqual(await definitionsAt(lua, 4, 19), ['CROSSFILE.MENU 10:3', 'shared.lua 1:0', 'shared.lua 4:1']); + }); + + test('finds the references of a global in every file of the workspace', async () => { + const menu = await openFixture('crossfile/CROSSFILE.MENU'); + assert.deepEqual(await referencesAt(menu, 6, 11), [ + 'CROSSFILE.MENU 10:3', + 'CROSSFILE.MENU 6:11', + 'shared.lua 1:0', + 'shared.lua 4:1', + 'shared.lua 4:19', + ]); + }); + + test('uses the unsaved text of open documents', async () => { + const lua = await openFixture('crossfile/shared.lua'); + const editor = vscode.window.activeTextEditor; + assert.ok(editor && editor.document.uri.toString() === lua.toString()); + await editor.edit((edit) => { + edit.insert(new vscode.Position(1, 0), '\n'); + }); + try { + const menu = await openFixture('crossfile/CROSSFILE.MENU'); + assert.deepEqual(await definitionsAt(menu, 9, 3), ['shared.lua 4:9']); + } finally { + await vscode.window.showTextDocument(lua); + await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor'); + } + }); +}); From b33c1d436914de6826c60755788cbb082faed28f Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:08:55 +0100 Subject: [PATCH 5/8] docs: document cross-file definition and references Both changelogs (the existing Unreleased entries, as nothing is released yet), the README (note banner and features; cross-file navigation is no longer "planned"), the editors guide (feature table, workspace folders requirement) and the CLAUDE.md overview. The changelog quotes the IESDP sentence the matching rests on. Rename stays within a file. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 26 ++++++++++++++++++-------- CLAUDE.md | 2 +- README.md | 16 ++++++++++------ docs/CHANGELOG.vsix.md | 6 ++++-- docs/editors/README.md | 11 ++++++----- 5 files changed, 39 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 751627e..d252efe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,14 +46,24 @@ 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. -- 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. +- Go to definition (`textDocument/definition`): from any use of a local to its declaration, and + from a global to every assignment to it (`x = …`, `function x()`), in the document and in + every other `.lua` and `.menu` file of the workspace. The engine runs "in one global Lua state + that is shared by the MENU file, the game's own Lua files and the engine" + ([IESDP](https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm)), so a + global is matched by name in every file; locals stay in their own chunk. No result for the + implicit `self`, for globals no file assigns (game, EEex and library functions), or for table + fields. +- Find references (`textDocument/references`), 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 in the + document and in the other files. `includeDeclaration` decides whether the local's + declaration, or the assignments to the global, are included. +- Across files, for go to definition and find references: the other files are the open + documents, whose unsaved text wins over the saved file, and the files of the workspace index + (the files of workspace symbols, `files.exclude` honored). The document's own results come + first, then the other files in URI order. A request waits for files still queued for + indexing, and answers `ContentModified` (LSP 3.17) if the document changed meanwhile. `_ENV`, + and names resolved through a local `_ENV`, are not globals and stay in their document. - 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 diff --git a/CLAUDE.md b/CLAUDE.md index addd8d0..84a5937 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, hover, completion, semantic tokens, formatting of `.lua` files, `.menu` quick fixes, document and workspace symbols, folding, LuaCATS doc comments in hover, completion and diagnostics, 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 | +| Purpose | Lua 5.2 language support (diagnostics, hover, completion, semantic tokens, formatting of `.lua` files, `.menu` quick fixes, document and workspace symbols, folding, LuaCATS doc comments in hover, completion and diagnostics, definition and references across workspace files, and same-file 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 2582f82..43e548d 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,8 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the > This is an early version. It currently provides **syntax diagnostics**, **hover**, > **completion**, **semantic highlighting**, **formatting** (Lua files), **document symbols**, > **workspace symbols**, **folding**, **quick fixes** (`.menu` files), **LuaCATS doc comments** -> in hover, completion and diagnostics, and **go to definition**, -> **find references** and **rename** within a file; cross-file navigation, formatting of `.menu` +> in hover, completion and diagnostics, **go to definition** and **find references** across +> the files of your workspace, and **rename** within a file; formatting of `.menu` > files and more are planned. ## Features @@ -68,10 +68,14 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the *Editor: Insert Spaces*). Turn on *Editor: Format On Type* to have `end`, `else` and closing brackets re-indented as you type them, or *Editor: Format On Save*. Files with a syntax error are left unchanged. `.menu` files are not formatted yet. -- **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. +- **Go to Definition and Find All References** for variables. Locals follow Lua's scoping rules. + Globals are followed across every Lua and `.menu` file of your workspace, even files you + haven't opened, because the game runs all of its Lua in + [one shared global state](https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm). + Files hidden with *Files: Exclude* are left out. +- **Rename Symbol** for variables within a 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. - **Quick fixes for `.menu` text the game misreads.** Put an unquoted name such as `My_Menu`, or a word too long for the game, in quotes, or add the space the game needs before the closing backtick of a Lua block, from the light bulb (Ctrl+.). *Fix all IE Lua auto-fixable problems* diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 57d5aed..61a7619 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -26,8 +26,10 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea - **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. -- **Find All References** lists every use of a variable in the same file. + gets its value: in the same file, including across the Lua of a `.menu` file, and in every + other Lua and `.menu` file of your workspace, even files you haven't opened. +- **Find All References** lists every use of a variable: of a local in its file, of a global in + every Lua and `.menu` file of your workspace. - **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. - **Go to Symbol in Workspace** (Ctrl+T) finds functions, variables and menus in every Lua and diff --git a/docs/editors/README.md b/docs/editors/README.md index 5989705..e360fc8 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -65,8 +65,8 @@ node /path/to/server.js --stdio | Syntax errors | `textDocument/publishDiagnostics` | When `validate.mode` says so (see above). In `.menu` files, also warnings for text the game misreads. Warnings for doc comments (see below). | | 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. | +| Go to definition | `textDocument/definition` | The declaration of a local, or every assignment to a global in the same file and in the other files of the workspace (as for workspace symbols, below). | +| Find references | `textDocument/references` | Every use of a local in its file, or of a global in the same file and in the other files of the workspace (as for workspace symbols, below). | | 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. | | Hover | `textDocument/hover` | Markdown or plain text, whichever the editor prefers (`hover.contentFormat`); the server's own words follow the editor's `locale`. See below. | | Completion | `textDocument/completion`, `completionItem/resolve` | Triggered by `.` and `:`. Documentation is sent on resolve (with the item, for names with a doc comment), in the editor's preferred `completionItem.documentationFormat`. See below. | @@ -75,9 +75,10 @@ node /path/to/server.js --stdio | Quick fixes | `textDocument/codeAction` | `.menu` files only: kinds `quickfix` and `source.fixAll.ieLua`. Needs `codeActionLiteralSupport`. See below. | | Workspace symbols | `workspace/symbol` | Every `*.lua` and `*.menu` file under the workspace folders, plus open files. See below. | -Workspace symbols need an editor that sends **workspace folders** when it starts the server; -otherwise only open files are searched. Files changed outside the editor are picked up when the -editor supports **dynamic registration of watched files** (`workspace/didChangeWatchedFiles`); +Workspace symbols, and go to definition and find references across files, need an editor that +sends **workspace folders** when it starts the server; otherwise only open files are searched. +Files changed outside the editor are picked up when the editor supports **dynamic registration +of watched files** (`workspace/didChangeWatchedFiles`); otherwise they are picked up when the server restarts or the file is opened and closed. Files are skipped as VS Code's `files.exclude` setting says, which the server reads with `workspace/configuration` (section `files.exclude`). If your editor passes server *settings* From 30869c026ec0ff1a3e82928f305ab89fb8800209 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:13:14 +0100 Subject: [PATCH 6/8] perf(server): keep the globals of indexed files in typed arrays Review finding: the index kept every use of a global as an LSP Range object (about 230 bytes each) for the life of the server. On a synthetic workspace of 2,000 files (12.1 MB of Lua, about 480,000 uses) the index took 128 MB of heap, against 15.9 MB for the outline alone (what `main` keeps). Each file now keeps its uses in `src/server/syntax/fileGlobals.ts` (pure): the line starts and one flat array of `start, end, isWrite` triples, with a name-to-slot map, so the number of typed arrays per file is fixed (each has a cost of its own; one array per name still took 65 MB). Positions are computed only for the uses a request returns, by binary search over the line starts, which split lines as vscode-languageserver-textdocument does (checked against `TextDocument.positionAt` at every offset of a test text). Same workspace now: 27.4 MB. A lookup returning 80,000 definitions takes 12 ms, 160,000 references 24 ms; indexing 0.4 ms per file (0.5 before). The `keep` predicates take `isWrite` directly (review nit on references.ts). Co-Authored-By: Claude Opus 5.5 --- src/server/features/definition.ts | 2 +- src/server/features/references.ts | 2 +- src/server/features/workspaceFiles.ts | 66 +++-------- src/server/syntax/fileGlobals.ts | 108 ++++++++++++++++++ .../server/features/workspaceFiles.test.ts | 30 ++--- test/unit/server/syntax/fileGlobals.test.ts | 35 ++++++ 6 files changed, 181 insertions(+), 62 deletions(-) create mode 100644 src/server/syntax/fileGlobals.ts create mode 100644 test/unit/server/syntax/fileGlobals.test.ts diff --git a/src/server/features/definition.ts b/src/server/features/definition.ts index a292967..588b338 100644 --- a/src/server/features/definition.ts +++ b/src/server/features/definition.ts @@ -32,7 +32,7 @@ export function register(connection: Connection, documents: TextDocuments 0 ? here : null; } - const elsewhere = await otherFileLocations(documents, document, name, (location) => location.isWrite, deps, token); + const elsewhere = await otherFileLocations(documents, document, name, (isWrite) => isWrite, deps, token); // Cancelled (`null`) or the document changed meanwhile (`ContentModified`). if (!Array.isArray(elsewhere)) { return elsewhere; diff --git a/src/server/features/references.ts b/src/server/features/references.ts index 7cb7448..e76c7b2 100644 --- a/src/server/features/references.ts +++ b/src/server/features/references.ts @@ -34,7 +34,7 @@ export function register(connection: Connection, documents: TextDocuments true : (location: { readonly isWrite: boolean }) => !location.isWrite; + const keep = context.includeDeclaration ? () => true : (isWrite: boolean) => !isWrite; const elsewhere = await otherFileLocations(documents, document, name, keep, deps, token); // Cancelled (`null`) or the document changed meanwhile (`ContentModified`). if (!Array.isArray(elsewhere)) { diff --git a/src/server/features/workspaceFiles.ts b/src/server/features/workspaceFiles.ts index 8fe039a..10253b8 100644 --- a/src/server/features/workspaceFiles.ts +++ b/src/server/features/workspaceFiles.ts @@ -2,56 +2,27 @@ // parse of its text: the outline for `workspace/symbol`, and where it names each // global shared with other files, for go to definition and find references, // which look the globals up across files here. -import { - LSPErrorCodes, - ResponseError, - type CancellationToken, - type Location, - type Position, - type Range, - type SymbolInformation, - type TextDocuments, -} from 'vscode-languageserver/node'; -import { TextDocument } from 'vscode-languageserver-textdocument'; +import { LSPErrorCodes, ResponseError, type CancellationToken, type Location, type SymbolInformation, type TextDocuments } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; import type { ParsedDocumentCache } from '../documentCache.ts'; import { parseDocument, type ParsedDocument } from '../syntax/document.ts'; -import { globalOccurrences } from '../syntax/navigation.ts'; +import { fileGlobals, globalRanges, positionAt, usesGlobal, type FileGlobals } from '../syntax/fileGlobals.ts'; import { documentKind } from '../validation/validateText.ts'; import type { IndexedFile, WorkspaceIndex } from '../workspace/workspaceIndex.ts'; import { untilCancelled } from './cancellation.ts'; import { outlineSymbols } from './workspaceSymbols.ts'; -/** Where a file names a global. */ -export interface GlobalLocation { - readonly range: Range; - /** Whether it assigns the global (`x = …`, `function x()`). */ - readonly isWrite: boolean; -} - export interface IndexedFileFacts { readonly symbols: readonly SymbolInformation[]; - /** The globals the file names, by name, each list in document order (see `globalOccurrences`). */ - readonly globals: ReadonlyMap; -} - -/** The shared globals of a parsed document, with LSP positions. */ -export function globalLocations(parsed: ParsedDocument, positionAt: (offset: number) => Position): Map { - const result = new Map(); - for (const [name, occurrences] of globalOccurrences(parsed)) { - result.set( - name, - occurrences.map(({ start, end, isWrite }) => ({ range: { start: positionAt(start), end: positionAt(end) }, isWrite })), - ); - } - return result; + /** Where the file names each global shared with other files, compactly (see syntax/fileGlobals.ts). */ + readonly globals: FileGlobals; } /** The facts of a file that is not open, for the workspace index. */ export function analyzeFile(text: string, uri: string): IndexedFileFacts { - const document = TextDocument.create(uri, '', 0, text); const parsed = parseDocument(text, documentKind(uri, '')); - const positionAt = (offset: number): Position => document.positionAt(offset); - return { symbols: outlineSymbols(parsed, { uri, positionAt }), globals: globalLocations(parsed, positionAt) }; + const globals = fileGlobals(parsed); + return { symbols: outlineSymbols(parsed, { uri, positionAt: (offset) => positionAt(globals.lineStarts, offset) }), globals }; } /** The globals of a file other than the one the request is for. */ @@ -59,11 +30,12 @@ export interface GlobalSource { readonly uri: string; /** Index key (see `WorkspaceIndex.pathKey`), or the URI for a document that is not a local file. */ readonly key: string; - readonly globals: () => ReadonlyMap; + readonly globals: () => FileGlobals; } /** - * The locations in other files where `keep` accepts a use of the global `name`: + * The locations in other files where `keep` accepts a use of the global `name` + * (by whether it assigns the global): * first those of the open documents, then those of the indexed files that are * not open (an open document wins over its saved version); `current` (the * document the request is for, answered from its own text) is skipped. Files @@ -72,17 +44,16 @@ export interface GlobalSource { */ export function collectGlobalLocations( name: string, - keep: (location: GlobalLocation) => boolean, + keep: (isWrite: boolean) => boolean, currentKey: string, open: readonly GlobalSource[], indexed: Iterable>>, isCancelled: () => boolean, ): Location[] | undefined { - const files: { uri: string; locations: readonly GlobalLocation[] }[] = []; + const files: { uri: string; globals: FileGlobals }[] = []; const seen = new Set([currentKey]); - const add = (uri: string, globals: ReadonlyMap): void => { - const locations = globals.get(name)?.filter(keep); - if (locations && locations.length > 0) files.push({ uri, locations }); + const add = (uri: string, globals: FileGlobals): void => { + if (usesGlobal(globals, name)) files.push({ uri, globals }); }; for (const source of open) { if (isCancelled()) return undefined; @@ -95,11 +66,12 @@ export function collectGlobalLocations( if (!seen.has(file.key)) add(file.uri, file.value.globals); } files.sort((a, b) => (a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0)); - return files.flatMap(({ uri, locations }) => locations.map(({ range }) => ({ uri, range }))); + // Positions are computed only here, for the files that use the name. + return files.flatMap(({ uri, globals }) => globalRanges(globals, name, keep).map((range) => ({ uri, range }))); } /** Globals of each open document version, dropped with it (see `ParsedDocumentCache`). */ -const openGlobals = new WeakMap>(); +const openGlobals = new WeakMap(); export interface CrossFileDeps { readonly cache: ParsedDocumentCache; @@ -116,7 +88,7 @@ export async function otherFileLocations( documents: Pick, 'get' | 'all'>, document: TextDocument, name: string, - keep: (location: GlobalLocation) => boolean, + keep: (isWrite: boolean) => boolean, deps: CrossFileDeps, token: CancellationToken, ): Promise { @@ -133,7 +105,7 @@ export async function otherFileLocations( const parsed = deps.cache.get(other); let globals = openGlobals.get(parsed); if (!globals) { - globals = globalLocations(parsed, (offset) => other.positionAt(offset)); + globals = fileGlobals(parsed); openGlobals.set(parsed, globals); } return globals; diff --git a/src/server/syntax/fileGlobals.ts b/src/server/syntax/fileGlobals.ts new file mode 100644 index 0000000..0dfb9da --- /dev/null +++ b/src/server/syntax/fileGlobals.ts @@ -0,0 +1,108 @@ +// A compact record of where a file names each global shared with other files +// (see `globalOccurrences` in navigation.ts), kept by the workspace index for +// every file for as long as the server runs. Offsets are stored in typed arrays +// and turned into line/character positions only for the uses a request returns. +// Pure: no LSP or `vscode` imports. + +import type { ParsedDocument } from './document.ts'; +import { globalOccurrences } from './navigation.ts'; + +/** A zero-based line and UTF-16 character, as LSP positions count them. */ +export interface LineCharacter { + readonly line: number; + readonly character: number; +} + +export interface FileGlobals { + /** The offset where each line starts (the first is 0). */ + readonly lineStarts: Uint32Array; + /** The slot of each global name the file uses. */ + readonly slots: ReadonlyMap; + /** Slot `s` owns the triples from `bounds[s]` to `bounds[s + 1]` (exclusive), counted in triples. */ + readonly bounds: Uint32Array; + /** `start, end, isWrite (0 or 1)` triples, by slot, each slot's in document order. */ + readonly uses: Uint32Array; +} + +/** Fields per use in `FileGlobals.uses`. */ +const FIELDS = 3; + +/** + * The offset where each line of `text` starts. A line ends at `\n`, `\r\n` or a + * lone `\r`, as in vscode-languageserver-textdocument, so positions match the + * ones `TextDocument.positionAt` gives for the same text. + */ +export function lineStarts(text: string): Uint32Array { + const starts = [0]; + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + if (code === 0x0d || code === 0x0a) { + if (code === 0x0d && text.charCodeAt(i + 1) === 0x0a) i++; + starts.push(i + 1); + } + } + return Uint32Array.from(starts); +} + +/** The position of `offset`, by binary search in `starts` (see `lineStarts`). */ +export function positionAt(starts: Uint32Array, offset: number): LineCharacter { + // The last line starting at or before `offset`; `starts[0]` is 0, so there is one. + let low = 0; + let high = starts.length - 1; + while (low < high) { + const middle = (low + high + 1) >> 1; + if ((starts[middle] ?? 0) <= offset) low = middle; + else high = middle - 1; + } + return { line: low, character: offset - (starts[low] ?? 0) }; +} + +/** + * The shared globals of a parsed document, compactly: three typed arrays and + * one map per file, whatever the number of names, as typed arrays have a fixed + * cost of their own each. + */ +export function fileGlobals(document: ParsedDocument): FileGlobals { + const occurrences = globalOccurrences(document); + const slots = new Map(); + const bounds = new Uint32Array(occurrences.size + 1); + let total = 0; + for (const list of occurrences.values()) total += list.length; + const uses = new Uint32Array(total * FIELDS); + let next = 0; + for (const [name, list] of occurrences) { + const slot = slots.size; + slots.set(name, slot); + bounds[slot] = next; + for (const { start, end, isWrite } of list) { + uses[next * FIELDS] = start; + uses[next * FIELDS + 1] = end; + uses[next * FIELDS + 2] = isWrite ? 1 : 0; + next++; + } + } + bounds[slots.size] = next; + return { lineStarts: lineStarts(document.text), slots, bounds, uses }; +} + +/** Whether the file uses the global `name`. */ +export function usesGlobal(globals: FileGlobals, name: string): boolean { + return globals.slots.has(name); +} + +/** The ranges of the uses of `name` that `keep` accepts (by whether they assign it), in document order. */ +export function globalRanges(globals: FileGlobals, name: string, keep: (isWrite: boolean) => boolean): { start: LineCharacter; end: LineCharacter }[] { + const ranges: { start: LineCharacter; end: LineCharacter }[] = []; + const slot = globals.slots.get(name); + if (slot === undefined) return ranges; + const { uses, lineStarts: starts } = globals; + const from = globals.bounds[slot] ?? 0; + const to = globals.bounds[slot + 1] ?? from; + for (let use = from; use < to; use++) { + // In bounds: `bounds` never exceeds the number of triples in `uses`. + const start = uses[use * FIELDS] ?? 0; + const end = uses[use * FIELDS + 1] ?? 0; + if (keep(uses[use * FIELDS + 2] === 1)) ranges.push({ start: positionAt(starts, start), end: positionAt(starts, end) }); + } + return ranges; +} diff --git a/test/unit/server/features/workspaceFiles.test.ts b/test/unit/server/features/workspaceFiles.test.ts index 0e0ca9a..042092f 100644 --- a/test/unit/server/features/workspaceFiles.test.ts +++ b/test/unit/server/features/workspaceFiles.test.ts @@ -7,14 +7,18 @@ import { collectGlobalLocations, otherFileLocations, type CrossFileDeps, - type GlobalLocation, type IndexedFileFacts, } from '../../../../src/server/features/workspaceFiles.ts'; +import { globalRanges, type FileGlobals } from '../../../../src/server/syntax/fileGlobals.ts'; import type { IndexedFile } from '../../../../src/server/workspace/workspaceIndex.ts'; -/** `line:character` of each location, with `=` for assignments. */ -const where = (locations: readonly GlobalLocation[] | undefined): string[] | undefined => - locations?.map(({ range, isWrite }) => `${String(range.start.line)}:${String(range.start.character)}${isWrite ? '=' : ''}`); +/** `line:character` of each use of `name`, with `=` for assignments; `undefined` when the file has none. */ +function where(globals: FileGlobals, name: string): string[] | undefined { + if (!globals.slots.has(name)) return undefined; + const at = ({ start }: { start: { line: number; character: number } }): string => `${String(start.line)}:${String(start.character)}`; + const writes = new Set(globalRanges(globals, name, (isWrite) => isWrite).map(at)); + return globalRanges(globals, name, () => true).map((range) => `${at(range)}${writes.has(at(range)) ? '=' : ''}`); +} describe('server/features/workspaceFiles', () => { describe('analyzeFile', () => { @@ -36,22 +40,22 @@ describe('server/features/workspaceFiles', () => { it('lists where a Lua file names each global, with its assignments', () => { const { globals } = analyzeFile('local x = 1\nTotal = x\nfunction Add(n)\n\tTotal = Total + n\nend\nprint(Total)\n', 'file:///w/a.lua'); - assert.deepEqual([...globals.keys()].sort(), ['Add', 'Total', 'print']); - assert.deepEqual(where(globals.get('Total')), ['1:0=', '3:1=', '3:9', '5:6']); - assert.deepEqual(where(globals.get('Add')), ['2:9=']); - assert.equal(globals.get('x'), undefined); + assert.deepEqual([...globals.slots.keys()].sort(), ['Add', 'Total', 'print']); + assert.deepEqual(where(globals, 'Total'), ['1:0=', '3:1=', '3:9', '5:6']); + assert.deepEqual(where(globals, 'Add'), ['2:9=']); + assert.equal(where(globals, 'x'), undefined); }); it('collects the globals of every Lua chunk of a .menu file, in document order', () => { const text = '`\nshown = 0\n`\nmenu\n{\n\tname "MAIN"\n\tonOpen "shown = shown + 1"\n\tlabel { enabled "shown > 0" }\n}\n'; - assert.deepEqual(where(analyzeFile(text, 'file:///w/UI.menu').globals.get('shown')), ['1:0=', '6:9=', '6:17', '7:18']); + assert.deepEqual(where(analyzeFile(text, 'file:///w/UI.menu').globals, 'shown'), ['1:0=', '6:9=', '6:17', '7:18']); }); it('leaves out _ENV and the names resolved through a local _ENV', () => { const { globals } = analyzeFile('local _ENV = { y = 1 }\nz = y\n', 'file:///w/env.lua'); - assert.deepEqual([...globals.keys()], []); + assert.deepEqual([...globals.slots.keys()], []); const free = analyzeFile('_ENV.a = 1\nb = 2\n', 'file:///w/free.lua').globals; - assert.deepEqual([...free.keys()], ['b']); + assert.deepEqual([...free.slots.keys()], ['b']); }); }); @@ -59,7 +63,7 @@ describe('server/features/workspaceFiles', () => { /** An indexed file analyzed from `text`, keyed by its path. */ const indexed = (path: string, text: string): IndexedFile => ({ uri: `file://${path}`, key: path, value: analyzeFile(text, `file://${path}`) }); const all = (): boolean => true; - const writes = (location: GlobalLocation): boolean => location.isWrite; + const writes = (isWrite: boolean): boolean => isWrite; const show = (locations: Location[] | undefined): string[] | undefined => locations?.map(({ uri, range }) => `${uri.slice('file:///w/'.length)} ${String(range.start.line)}:${String(range.start.character)}`); @@ -76,7 +80,7 @@ describe('server/features/workspaceFiles', () => { const open = [ { uri: 'file:///w/a.lua', key: '/w/a.lua', globals: () => (reads.push('a'), analyzeFile('\n\nG = 1\n', 'file:///w/a.lua').globals) }, { uri: 'untitled:Untitled-1', key: 'untitled:Untitled-1', globals: () => (reads.push('untitled'), analyzeFile('x = G\n', 'untitled:Untitled-1').globals) }, - { uri: 'file:///w/a.lua', key: '/w/a.lua', globals: () => (reads.push('again'), new Map()) }, + { uri: 'file:///w/a.lua', key: '/w/a.lua', globals: () => (reads.push('again'), analyzeFile('', 'file:///w/a.lua').globals) }, ]; const found = collectGlobalLocations('G', all, '/w/self.lua', open, [saved], () => false); assert.deepEqual(found?.map(({ uri, range }) => `${uri} ${String(range.start.line)}`), ['file:///w/a.lua 2', 'untitled:Untitled-1 0']); diff --git a/test/unit/server/syntax/fileGlobals.test.ts b/test/unit/server/syntax/fileGlobals.test.ts new file mode 100644 index 0000000..053c924 --- /dev/null +++ b/test/unit/server/syntax/fileGlobals.test.ts @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { fileGlobals, globalRanges, lineStarts, positionAt } from '../../../../src/server/syntax/fileGlobals.ts'; + +describe('server/syntax/fileGlobals', () => { + it('splits lines at \\n, \\r\\n and a lone \\r', () => { + assert.deepEqual([...lineStarts('a\nb\r\nc\rd')], [0, 2, 5, 7]); + assert.deepEqual([...lineStarts('')], [0]); + assert.deepEqual([...lineStarts('\n')], [0, 1]); + }); + + it('gives the positions TextDocument gives, for every offset', () => { + const text = 'x = 1\r\n\tlocal ü = "€"\rG = x\n\n-- 𝄞 end\n'; + const document = TextDocument.create('file:///w/a.lua', 'lua', 1, text); + const starts = lineStarts(text); + for (let offset = 0; offset <= text.length; offset++) { + // Inside \r\n TextDocument moves the offset before the line break; no identifier is ever there. + if (text[offset - 1] === '\r' && text[offset] === '\n') continue; + assert.deepEqual(positionAt(starts, offset), document.positionAt(offset), `offset ${String(offset)}`); + } + }); + + it('keeps the uses of each shared global and returns their ranges, filtered by assignment', () => { + const text = 'G = 1\nprint(G)\nlocal l = G\ndo local _ENV = {} G = 2 end\n'; + const globals = fileGlobals(parseDocument(text, 'lua')); + assert.deepEqual([...globals.slots.keys()].sort(), ['G', 'print']); + const lines = (keep: (isWrite: boolean) => boolean): string[] => + globalRanges(globals, 'G', keep).map(({ start, end }) => `${String(start.line)}:${String(start.character)}-${String(end.character)}`); + assert.deepEqual(lines(() => true), ['0:0-1', '1:6-7', '2:10-11']); + assert.deepEqual(lines((isWrite) => isWrite), ['0:0-1']); + assert.deepEqual(lines((isWrite) => !isWrite), ['1:6-7', '2:10-11']); + assert.deepEqual(globalRanges(globals, 'missing', () => true), []); + }); +}); From 6c6e7c07387f7c9bc8c98b559478cfdef986ee42 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:20:05 +0100 Subject: [PATCH 7/8] fix(server): keep _ENV and fields of a local _ENV out of same-file navigation `targetAt` returned a global target for a free `_ENV` and for names resolved while a local `_ENV` is visible, and `globalUses` matched every identifier of `scopes.globals` by name. Go to definition and find references therefore listed fields of a local `_ENV` table as uses of the global with the same name, and rename renamed them too, changing what the code does. Same-file navigation now uses `isSharedGlobal`, like the cross-file lookup, hover and semantic tokens already did: such names are no target (rename refuses them as `notAVariable`), and globals no longer match them. `sharedGlobalName` no longer needs the document. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +++--- src/server/features/definition.ts | 4 +-- src/server/features/references.ts | 4 +-- src/server/hover/resolve.ts | 8 ++--- src/server/syntax/navigation.ts | 36 +++++++++++++--------- src/server/syntax/rename.ts | 4 ++- test/unit/server/syntax/navigation.test.ts | 31 ++++++++++++++++--- test/unit/server/syntax/rename.test.ts | 11 +++++++ 8 files changed, 74 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d252efe..6dac662 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,12 +63,14 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). (the files of workspace symbols, `files.exclude` honored). The document's own results come first, then the other files in URI order. A request waits for files still queued for indexing, and answers `ContentModified` (LSP 3.17) if the document changed meanwhile. `_ENV`, - and names resolved through a local `_ENV`, are not globals and stay in their document. + and names resolved through a local `_ENV` (fields of that table, Lua 5.2 manual §2.2), are not + globals: they have no definition or references, in the document or elsewhere. - 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 + that is not a variable (including `_ENV` and names resolved through a local `_ENV`), 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`. - Workspace symbols (`workspace/symbol`; *Go to Symbol in Workspace*): the outline symbols of every diff --git a/src/server/features/definition.ts b/src/server/features/definition.ts index 588b338..e9a723c 100644 --- a/src/server/features/definition.ts +++ b/src/server/features/definition.ts @@ -27,8 +27,8 @@ export function register(connection: Connection, documents: TextDocuments 0 ? here : null; } diff --git a/src/server/features/references.ts b/src/server/features/references.ts index e76c7b2..b183593 100644 --- a/src/server/features/references.ts +++ b/src/server/features/references.ts @@ -29,8 +29,8 @@ export function register(connection: Connection, documents: TextDocuments(); -/** Every identifier that names a variable (local or global), sorted by offset. */ +/** + * Every identifier that names a variable (local or global), sorted by offset. + * Includes `_ENV` and names resolved through a local `_ENV`, which are not + * targets (see `targetAt`). + */ export function variableIndex(document: ParsedDocument): readonly VariableOccurrence[] { let index = indexes.get(document); if (!index) { @@ -87,17 +93,19 @@ export function targetAt(document: ParsedDocument, offset: number): TargetHit | return undefined; } const { identifier, chunkIndex } = found; - const declaration = document.chunks[chunkIndex]?.scopes.resolved.get(identifier); - return { - identifier, - chunkIndex, - target: declaration ? { kind: 'local', chunkIndex, declaration } : { kind: 'global', name: identifier.name }, - }; + const scopes = document.chunks[chunkIndex]?.scopes; + const declaration = scopes?.resolved.get(identifier); + if (declaration) { + return { identifier, chunkIndex, target: { kind: 'local', chunkIndex, declaration } }; + } + return scopes && isSharedGlobal(scopes, identifier) ? { identifier, chunkIndex, target: { kind: 'global', name: identifier.name } } : undefined; } /** 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) }))); + return document.chunks.flatMap(({ scopes }) => + (scopes.globals.get(name) ?? []).filter((identifier) => isSharedGlobal(scopes, identifier)).map((identifier) => ({ identifier, isWrite: scopes.writes.has(identifier) })), + ); } /** @@ -148,7 +156,7 @@ export interface GlobalOccurrence { } /** Whether `identifier` (of the chunk `scopes` belongs to) names a variable shared with other files. */ -function isSharedGlobal(scopes: ParsedDocument['chunks'][number]['scopes'], identifier: Ast.Identifier): boolean { +export function isSharedGlobal(scopes: ParsedDocument['chunks'][number]['scopes'], identifier: Ast.Identifier): boolean { return identifier.name !== '_ENV' && !scopes.resolved.has(identifier) && !scopes.environmentFields.has(identifier); } @@ -178,9 +186,9 @@ export function globalOccurrences(document: ParsedDocument): Map { assert.deepEqual(hit?.target, { kind: 'global', name: 'x' }); }); + it('finds nothing on _ENV or on names resolved through a local _ENV, which are fields of a table', () => { + const text = '_ENV.x = 1\ndo local _ENV = {} G = 2 print(_ENV) end\n'; + const document = parseDocument(text, 'lua'); + for (const needle of ['_ENV.x', 'G', 'print']) { + assert.equal(targetAt(document, offsetOf(text, needle)), undefined, needle); + } + assert.equal(targetAt(document, offsetOf(text, '_ENV', 1))?.target.kind, 'local'); + assert.equal(targetAt(document, offsetOf(text, '_ENV', 2))?.target.kind, 'local'); + }); + it('returns nothing for an empty document', () => { assert.equal(targetAt(parseDocument('', 'lua'), 0), undefined); }); @@ -100,6 +110,11 @@ describe('server/syntax/navigation', () => { assert.deepEqual(definitionsAt(document, offsetOf(text, 'shown', 1)), ['shown@2', `shown@${String(offsetOf(text, 'shown', 1))}`]); assert.deepEqual(definitionsAt(document, offsetOf(text, 'hidden', 1)), []); }); + + it('leaves out fields of a local _ENV with the name of a global', () => { + const text = 'G = 1\ndo local _ENV = {} G = 2 end\n'; + assert.deepEqual(definitionsAt(parseDocument(text, 'lua'), 0), ['G@0']); + }); }); describe('references', () => { @@ -140,6 +155,12 @@ describe('server/syntax/navigation', () => { assert.deepEqual(referencesAt(text, 'g', 2, false), ['g@29']); }); + it('leaves out fields of a local _ENV and _ENV itself', () => { + const text = 'print(G, _ENV)\ndo local _ENV = {} G = 2 print(G) end\n'; + assert.deepEqual(referencesAt(text, 'G', 0, true), ['G@6']); + assert.deepEqual(referencesAt(text, 'print', 0, true), ['print@0']); + }); + 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))}`]); @@ -162,18 +183,18 @@ describe('server/syntax/navigation', () => { ]); }); - it('names the shared global under the cursor, and nothing for locals or _ENV', () => { - const text = 'local l = g\n_ENV.x = l\ndo local _ENV = {} f = 1 end\n'; + it('names the shared global under the cursor, and nothing for locals', () => { + const text = 'local l = g\nprint(l)\n'; const document = parseDocument(text, 'lua'); const nameAt = (needle: string): string | undefined => { const hit = targetAt(document, offsetOf(text, needle)); assert.ok(hit, `no variable at "${needle}"`); - return sharedGlobalName(document, hit); + return sharedGlobalName(hit); }; assert.equal(nameAt('g'), 'g'); + assert.equal(nameAt('print'), 'print'); assert.equal(nameAt('l = g'), undefined); - assert.equal(nameAt('_ENV.x'), undefined); - assert.equal(nameAt('f = 1'), undefined); + assert.equal(nameAt('l)'), undefined); }); }); }); diff --git a/test/unit/server/syntax/rename.test.ts b/test/unit/server/syntax/rename.test.ts index 6070c7c..d2b62e4 100644 --- a/test/unit/server/syntax/rename.test.ts +++ b/test/unit/server/syntax/rename.test.ts @@ -109,6 +109,17 @@ describe('server/syntax/rename', () => { assert.deepEqual(renamed('g = 1 local h = 2 print(g)', 'g', 0, 'h'), { refusal: 'conflict' }); }); + it('leaves fields of a local _ENV with the same name alone when renaming a global', () => { + const text = 'G = 1\ndo local _ENV = {} G = 2 end\n'; + assert.equal(renamed(text, 'G', 0, 'H'), 'H = 1\ndo local _ENV = {} G = 2 end\n'); + }); + + it('refuses _ENV and names resolved through a local _ENV, which are fields of a table', () => { + const text = 'G = 1 _ENV.x = 1\ndo local _ENV = {} G = 2 end\n'; + assert.deepEqual(renamed(text, '_ENV', 0, 'e'), { refusal: 'notAVariable' }); + assert.deepEqual(renamed(text, 'G', 1, 'H'), { refusal: 'notAVariable' }); + }); + 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' }); From fc28a6fdaa39ba760e23bd219fe3e4e2772050c5 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:20:06 +0100 Subject: [PATCH 8/8] fix(server): refuse renames that move names into or out of a local _ENV The rename binding check keyed fields of a local `_ENV` and the chunk's own `_ENV` as globals, so it accepted renames that change what code does: renaming a local `_ENV` (its fields become globals), renaming a local to `_ENV` (later globals become its fields) and renaming a global to `_ENV` (assigning the chunk's environment). Each identifier is now keyed by what it resolves through: a field by its `_ENV` declaration and name, a free `_ENV` by its chunk. `ScopeAnalysis.environmentFields` becomes a map to that declaration, and the merge check ignores fields of a local `_ENV`, so a global may take the name of one. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- src/server/syntax/rename.ts | 27 +++++++++++++++++++------- src/server/syntax/scope.ts | 10 ++++++---- test/unit/server/syntax/rename.test.ts | 11 +++++++++++ test/unit/server/syntax/scope.test.ts | 2 +- 5 files changed, 40 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dac662..c05d2c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,7 +71,8 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). 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 + refers to, including moving a name into or out of a local `_ENV` (checked by re-analyzing the + renamed text). Edits are versioned when the client supports `documentChanges`. - Workspace symbols (`workspace/symbol`; *Go to Symbol in Workspace*): the outline symbols of every `.lua` and `.menu` file (any letter case) in the `file:` workspace folders, and of every open diff --git a/src/server/syntax/rename.ts b/src/server/syntax/rename.ts index f62d82a..49cb0da 100644 --- a/src/server/syntax/rename.ts +++ b/src/server/syntax/rename.ts @@ -14,14 +14,16 @@ // - 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, +// two globals merging, or a name moving into or out of a local `_ENV` (or +// the chunk's `_ENV` itself being assigned). 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 type { Declaration } from './scope.ts'; import { lex } from './lexer.ts'; -import { definitions, references, targetAt, variableIndex, type NavigationTarget, type VariableOccurrence } from './navigation.ts'; +import { definitions, isSharedGlobal, 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 }; @@ -69,15 +71,26 @@ function nameRefusal(name: string): RenameRefusal | undefined { return 'invalidName'; } -/** What an identifier refers to: a declaration (by chunk and position), or a global by name. */ +/** + * What an identifier refers to: a declaration (by chunk and position), a field + * of a local `_ENV` (by that declaration and name), the chunk's own `_ENV`, 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)}`); + const scopes = document.chunks[chunkIndex]?.scopes; + const declarationKey = (declaration: Declaration): string => `${String(chunkIndex)}:${String(declarationIndexes[chunkIndex]?.get(declaration))}`; + const declaration = scopes?.resolved.get(identifier); + const environment = scopes?.environmentFields.get(identifier); + let key: string; + if (declaration) key = `local ${declarationKey(declaration)}`; + else if (environment) key = `field ${declarationKey(environment)} ${identifier.name}`; + else if (identifier.name === '_ENV') key = `upvalue _ENV ${String(chunkIndex)}`; + else key = `global ${identifier.name}`; + keys.set(occurrence, key); } return keys; } @@ -130,7 +143,7 @@ export function rename(document: ParsedDocument, text: string, offset: number, n 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))) { + if (target.kind === 'global' && document.chunks.some(({ scopes }) => scopes.globals.get(newName)?.some((identifier) => isSharedGlobal(scopes, identifier)))) { return refuse('conflict'); } const edits = references(document, target, true).map(({ start, end }) => ({ start, end, newText: newName })); diff --git a/src/server/syntax/scope.ts b/src/server/syntax/scope.ts index 5b16d2a..5a6bfac 100644 --- a/src/server/syntax/scope.ts +++ b/src/server/syntax/scope.ts @@ -56,9 +56,10 @@ export interface ScopeAnalysis { /** * Global-looking identifiers resolved while a local, parameter or `for` * variable named `_ENV` was visible: fields of that table, not of the - * global environment. Also listed in `globals`. + * global environment. Also listed in `globals`. Mapped to the declaration + * of the `_ENV` they are resolved through. */ - readonly environmentFields: ReadonlySet; + readonly environmentFields: ReadonlyMap; } export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { @@ -66,7 +67,7 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { const resolved = new Map(); const globals = new Map(); const writes = new Set(); - const environmentFields = new Set(); + const environmentFields = new Map(); /** Open scopes, innermost last, each with the offset where it ends. */ const scopes: { readonly names: Map; readonly end: number }[] = []; const scopeEnd = (): number => scopes.at(-1)?.end ?? chunk.end; @@ -95,7 +96,8 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { return; } // The chunk's own _ENV is an upvalue, never in `scopes`: only a local one is found. - if (lookup('_ENV')) environmentFields.add(identifier); + const environment = lookup('_ENV'); + if (environment) environmentFields.set(identifier, environment); const uses = globals.get(identifier.name); if (uses) uses.push(identifier); else globals.set(identifier.name, [identifier]); diff --git a/test/unit/server/syntax/rename.test.ts b/test/unit/server/syntax/rename.test.ts index d2b62e4..c618eb5 100644 --- a/test/unit/server/syntax/rename.test.ts +++ b/test/unit/server/syntax/rename.test.ts @@ -120,6 +120,17 @@ describe('server/syntax/rename', () => { assert.deepEqual(renamed(text, 'G', 1, 'H'), { refusal: 'notAVariable' }); }); + it('refuses to change which names resolve through a local _ENV', () => { + assert.deepEqual(renamed('local _ENV = {} x = 1', '_ENV', 0, 'e'), { refusal: 'conflict' }); + assert.deepEqual(renamed('local t = {} x = 1', 't', 0, '_ENV'), { refusal: 'conflict' }); + assert.deepEqual(renamed('G = 1', 'G', 0, '_ENV'), { refusal: 'conflict' }); + }); + + it('allows a global to take the name of a field of a local _ENV', () => { + const text = 'G = 1 do local _ENV = {} x = 2 end'; + assert.equal(renamed(text, 'G', 0, 'x'), 'x = 1 do local _ENV = {} x = 2 end'); + }); + 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/server/syntax/scope.test.ts b/test/unit/server/syntax/scope.test.ts index a35aa0a..4d0fe53 100644 --- a/test/unit/server/syntax/scope.test.ts +++ b/test/unit/server/syntax/scope.test.ts @@ -91,7 +91,7 @@ describe('server/syntax/scope', () => { }); describe('environmentFields', () => { - const fields = (source: string): string[] => [...analyze(source).environmentFields].map((identifier) => `${identifier.name}@${String(identifier.start)}`); + const fields = (source: string): string[] => [...analyze(source).environmentFields.keys()].map((identifier) => `${identifier.name}@${String(identifier.start)}`); it('is empty while only the chunk\'s own _ENV is in effect', () => { assert.deepEqual(fields('print(x) _ENV.y = 1'), []);