diff --git a/CHANGELOG.md b/CHANGELOG.md index 751627e..c05d2c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,20 +46,33 @@ 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` (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 - refers to (checked by re-analyzing the renamed text). Edits are versioned when the client + 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, 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/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* 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/definition.ts b/src/server/features/definition.ts index 367f547..e9a723c 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(hit); + // Locals belong to this document alone. + if (name === undefined) { + return here.length > 0 ? here : null; + } + 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; + } + 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..b183593 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(hit); + // Locals belong to this document alone. + if (name === undefined) { + return here; + } + 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)) { + 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 new file mode 100644 index 0000000..10253b8 --- /dev/null +++ b/src/server/features/workspaceFiles.ts @@ -0,0 +1,116 @@ +// 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, +// which look the globals up across files here. +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 { 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'; + +export interface IndexedFileFacts { + readonly symbols: readonly SymbolInformation[]; + /** 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 parsed = parseDocument(text, documentKind(uri, '')); + 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. */ +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: () => FileGlobals; +} + +/** + * 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 + * come in URI order, each file's locations in document order. Returns + * `undefined` once `isCancelled()` turns true. + */ +export function collectGlobalLocations( + name: string, + keep: (isWrite: boolean) => boolean, + currentKey: string, + open: readonly GlobalSource[], + indexed: Iterable>>, + isCancelled: () => boolean, +): Location[] | undefined { + const files: { uri: string; globals: FileGlobals }[] = []; + const seen = new Set([currentKey]); + const add = (uri: string, globals: FileGlobals): void => { + if (usesGlobal(globals, name)) files.push({ uri, globals }); + }; + 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)); + // 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(); + +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: (isWrite: boolean) => 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 = fileGlobals(parsed); + 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/features/workspaceSymbols.ts b/src/server/features/workspaceSymbols.ts index 9718fb4..67e7d60 100644 --- a/src/server/features/workspaceSymbols.ts +++ b/src/server/features/workspaceSymbols.ts @@ -1,23 +1,22 @@ -import type { CancellationToken, 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 { @@ -33,7 +32,7 @@ export interface SymbolSource { */ export function collectWorkspaceSymbols( open: readonly SymbolSource[], - indexed: Iterable>, + indexed: Iterable>>, query: string, isCancelled: () => boolean, ): SymbolInformation[] | undefined { @@ -48,25 +47,11 @@ 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; } -/** 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 @@ -80,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/hover/resolve.ts b/src/server/hover/resolve.ts index 6083781..8826d15 100644 --- a/src/server/hover/resolve.ts +++ b/src/server/hover/resolve.ts @@ -95,7 +95,7 @@ function globalTarget(document: ParsedDocument, name: string): HoverTarget { } /** What to describe for a variable occurrence (see `targetAt`), or `undefined` when there is nothing to say. */ -export function variableTarget(document: ParsedDocument, { target, identifier, chunkIndex }: TargetHit): HoverTarget | undefined { +export function variableTarget(document: ParsedDocument, { target }: TargetHit): HoverTarget | undefined { if (target.kind === 'local') { const declaring = target.declaration.identifier; return { @@ -106,11 +106,7 @@ export function variableTarget(document: ParsedDocument, { target, identifier, c param: declaring && target.declaration.kind === 'parameter' ? parameterDoc(document, declaring) : undefined, }; } - // A field of a local `_ENV` table, or `_ENV` itself (the chunk's upvalue, not a global). - const scopes = document.chunks[chunkIndex]?.scopes; - if (!scopes || scopes.environmentFields.has(identifier) || identifier.name === '_ENV') { - return undefined; - } + // `targetAt` never returns `_ENV` or a field of a local `_ENV` table. return globalTarget(document, target.name); } diff --git a/src/server/server.ts b/src/server/server.ts index f3f4ad5..368fb67 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 { @@ -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/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/src/server/syntax/navigation.ts b/src/server/syntax/navigation.ts index 8a2fd41..f24c15b 100644 --- a/src/server/syntax/navigation.ts +++ b/src/server/syntax/navigation.ts @@ -3,7 +3,9 @@ // // Locals belong to one chunk. Globals are shared by every chunk of a document: // the Lua of a .menu file runs in one global environment. Field names (`t.x`, -// `t:m()`, `{ x = 1 }`) are not variables and are never targets. +// `t:m()`, `{ x = 1 }`) are not variables and are never targets; neither are +// names resolved while a local `_ENV` is visible, which are fields of that +// table (manual §2.2), nor a free `_ENV`, the chunk's own upvalue. import type * as Ast from './ast.ts'; import type { ParsedDocument } from './document.ts'; @@ -35,7 +37,11 @@ export interface VariableOccurrence { /** Variable identifiers of each document, sorted by offset; dropped with the document. */ const indexes = new WeakMap(); -/** 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) })), + ); } /** @@ -129,3 +137,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. */ +export 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. (`targetAt` never returns `_ENV` or names resolved + * through a local `_ENV`.) + */ +export function sharedGlobalName(hit: TargetHit): string | undefined { + return hit.target.kind === 'global' ? hit.target.name : undefined; +} diff --git a/src/server/syntax/rename.ts b/src/server/syntax/rename.ts index a63459a..49cb0da 100644 --- a/src/server/syntax/rename.ts +++ b/src/server/syntax/rename.ts @@ -2,7 +2,9 @@ // // A rename is refused, rather than producing code that behaves differently, // when: -// - the cursor is not on a variable name, or is on the implicit `self`; +// - the cursor is not on a variable name (`_ENV` and names resolved through a +// local `_ENV`, which are fields of a table, are not), or is on the implicit +// `self`; // - the variable is a global the document never assigns: it is defined // elsewhere (another file, the game, EEex), which a same-file rename cannot // update; @@ -12,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 }; @@ -67,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; } @@ -128,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/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'); + } + }); +}); 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); + }); +}); diff --git a/test/unit/server/features/workspaceFiles.test.ts b/test/unit/server/features/workspaceFiles.test.ts new file mode 100644 index 0000000..042092f --- /dev/null +++ b/test/unit/server/features/workspaceFiles.test.ts @@ -0,0 +1,154 @@ +import assert from 'node:assert/strict'; +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 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 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', () => { + 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.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, '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.slots.keys()], []); + const free = analyzeFile('_ENV.a = 1\nb = 2\n', 'file:///w/free.lua').globals; + assert.deepEqual([...free.slots.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 = (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)}`); + + 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'), 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']); + 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); + }); + }); +}); 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/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), []); + }); +}); diff --git a/test/unit/server/syntax/navigation.test.ts b/test/unit/server/syntax/navigation.test.ts index 17eae5f..15cbed9 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)}`); @@ -58,6 +58,16 @@ describe('server/syntax/navigation', () => { 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,10 +155,46 @@ 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))}`]); 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', () => { + 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(hit); + }; + assert.equal(nameAt('g'), 'g'); + assert.equal(nameAt('print'), 'print'); + assert.equal(nameAt('l = g'), 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..c618eb5 100644 --- a/test/unit/server/syntax/rename.test.ts +++ b/test/unit/server/syntax/rename.test.ts @@ -109,6 +109,28 @@ 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 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'), []);