Skip to content
37 changes: 25 additions & 12 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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*
Expand Down
6 changes: 4 additions & 2 deletions docs/CHANGELOG.vsix.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 6 additions & 5 deletions docs/editors/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand All @@ -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*
Expand Down
21 changes: 21 additions & 0 deletions src/server/features/cancellation.ts
Original file line number Diff line number Diff line change
@@ -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<void>, token: CancellationToken): Promise<void> {
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);
});
}
36 changes: 23 additions & 13 deletions src/server/features/definition.ts
Original file line number Diff line number Diff line change
@@ -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<TextDocument>, deps: DefinitionDeps): void {
connection.onDefinition(({ textDocument, position }, token): Location[] | null => {
connection.onDefinition(async ({ textDocument, position }, token): Promise<Location[] | ResponseError | null> => {
try {
const document = documents.get(textDocument.uri);
if (!document || token.isCancellationRequested) {
return null;
}
// Synchronous from here on: a cancellation can only arrive after the response.
const 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;
Expand Down
36 changes: 24 additions & 12 deletions src/server/features/references.ts
Original file line number Diff line number Diff line change
@@ -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<TextDocument>, deps: ReferencesDeps): void {
connection.onReferences(({ textDocument, position, context }, token): Location[] | null => {
connection.onReferences(async ({ textDocument, position, context }, token): Promise<Location[] | ResponseError | null> => {
try {
const document = documents.get(textDocument.uri);
if (!document || token.isCancellationRequested) {
return null;
}
// Synchronous from here on: a cancellation can only arrive after the response.
const 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;
Expand Down
Loading