diff --git a/CHANGELOG.md b/CHANGELOG.md index 52c7a1b..f140d17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,8 +19,21 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). syntax diagnostics from the official Lua 5.2.4 compiler, built to WebAssembly from the checksum-verified lua.org tarball (`third_party/lua52/`, reproducible build checked in CI). - `.menu` support: new `ie-menu` language (case-insensitive `.menu` extension), TextMate grammar - with embedded Lua highlighting, and validation of `` `…` `` blocks, `action*`/`onOpen`/`onClose` - scripts, `enabled "…"` and ` lua "…"` expressions. + that highlights the engine's keywords and embeds Lua where validation finds it, and validation of the Lua the engine compiles, found with a lexer + that follows the engine's (per [IESDP](https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm)): + `` `…` `` blocks; `onOpen`, `onClose` and `action*` scripts; and the expressions of `enabled`, + `actionDrag`, `table`, `seperator`, `useOverlayTint`, `bitmap res` and every `lua` value. A value + can be `"…"`, `'…'` or an unquoted word that is not a keyword, anywhere on a line. Each is + compiled in the shape the engine compiles it: property code as the body of + `function f () … end` (so `...` and a trailing `--` comment are errors), expressions as its + `return` value, and `` `…` `` blocks without their last character, which the engine drops. + `slotinfo`, `spellInfo` and `memorizedSpellInfo` strings are checked in every expression and + statement the engine generates from them (`T.item.icon`, `Infinity_SwapSlot(T.id)`, …). +- `.menu` diagnostics for text the engine misreads (codes are stable): `menu-unterminated-string` + for `"` and `'` strings, `menu-unterminated-block`, and the new `menu-word-too-long` (error: an + unquoted word of 64 or more characters aborts the game), `menu-inline-lua-last-character` + (warning: the character before a closing backtick is dropped) and `menu-unquoted-underscore` + (warning: unquoted `My_Menu` is read as `My` and `Menu`). - Settings `ieLua.validate.mode` (`manual`, `save` (default), `type`, `saveAndType`) and `ieLua.validate.debounce` (default 300 ms). - Command **IE Lua: Validate Current File** (`ieLua.validateDocument`). @@ -48,6 +61,14 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). that are not Lua names or are reserved words, and any rename that would change what a name refers to (checked by re-analyzing the renamed text). Edits are versioned when the client supports `documentChanges`. +- Workspace symbols (`workspace/symbol`; *Go to Symbol in Workspace*): the outline symbols of every + `.lua` and `.menu` file (any letter case) in the `file:` workspace folders, and of every open + document, whose unsaved text wins over the file. The query matches loosely (its characters in + order, case-insensitively), as LSP recommends. Files are indexed in the background, one per + event-loop turn, and kept current through watched-file events (`**/*.[lL][uU][aA]`, + `**/*.[mM][eE][nN][uU]`, and creates and deletes of folders), workspace folder changes and + document closes. `files.exclude` is honored as VS Code's explorer applies it, with an original + matcher checked against VS Code's own; changing it rescans. - Error-tolerant Lua 5.2 parser and scope analysis (`src/server/syntax/`), checked against the official compiler by a differential test; it publishes no diagnostics of its own. - Localization of the manifest and UI strings into all 14 VS Code display languages @@ -60,6 +81,9 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). ### Changed +- The extension also activates in workspaces that contain `.lua` or `.menu` files, in any letter + case (`workspaceContains:**/*.[lL][uU][aA]`, `workspaceContains:**/*.[mM][eE][nN][uU]`), so + *Go to Symbol in Workspace* works before any file is opened. - Minimum VS Code version is 1.91.0 (required by `vscode-languageclient` 10 and later). - Versioning starts at 1.0.0: when no release exists yet, the Release workflow ships the committed `VERSION` as the first stable release (a pre-release before it would be 1.1.0). diff --git a/CLAUDE.md b/CLAUDE.md index d0e73db..98992de 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ |---|---| | Name | `IE Lua Language Server` | | Publisher | `infinity-engine-tools` | -| Purpose | Lua 5.2 language support (diagnostics, document symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | +| Purpose | Lua 5.2 language support (diagnostics, document and workspace symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | | Language | TypeScript (strict) | | Bundler | esbuild (two bundles: client + language server) | | Minimum VS Code | `^1.91.0` (see `engines.vscode` in `package.json`; required by `vscode-languageclient` ≥ 10) | @@ -33,7 +33,8 @@ │ │ ├── server.ts # Connection, capabilities, handlers │ │ ├── features/ # completion.ts, diagnostics.ts, hover.ts, ... │ │ ├── syntax/ # Lua 5.2 lexer, parser, scopes, symbols, folding (pure, no LSP imports) -│ │ └── validation/ # Pure analysis logic (no LSP imports) — unit-tested directly +│ │ ├── validation/ # Pure analysis logic (no LSP imports) — unit-tested directly +│ │ └── workspace/ # Workspace index, files.exclude glob matching (fs injected; no LSP) │ └── shared/ # Types/constants used by BOTH sides — no vscode imports ├── test/ │ ├── unit/ # Pure logic, runs in plain Node (no VS Code) @@ -131,6 +132,12 @@ esbuild does **not** type-check. Always run `npm run check-types` — a green bu - Only advertise capabilities that are actually implemented. - Debug the server with `--inspect=6009` via the `debug` server options. - Full details: `.claude/rules/language-server.md`. +- **Engine facts come from IESDP** (checked against the 2.6.6.0 and 2.7.3.0 executables), never from guesses: + [MENU format](https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm) (lexer, grammar, + which properties are Lua and the exact text compiled for them: see `src/server/validation/menu*.ts`) and + [Engine Lua globals](https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm). The engine's + Lua state opens only `_G`, `table`, `string`, `bit32`, `math` and `debug` and replaces `print`; `io`, `os` and + `package` (hence `require`) exist only as test-automation stubs. Hover/completion must not offer them. --- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 37ad3f3..4987248 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,6 +30,7 @@ server (port 6009). | `src/server/` | Language server (separate Node process; no `vscode` import) | | `src/server/validation/` | Pure validation logic, unit-tested without LSP or VS Code | | `src/server/syntax/` | Error-tolerant Lua 5.2 parser, scope analysis, document symbols and folding (pure; checked against the official compiler by `test/unit/server/syntax/differential.test.ts`) | +| `src/server/workspace/` | Index of the workspace's Lua and `.menu` files, and `files.exclude` matching as VS Code applies it (file system injected, unit-tested with an in-memory one) | | `src/shared/` | Types and constants used by both sides | | `third_party/lua52/` | Reproducible build of the official Lua 5.2.4 compiler to WebAssembly | | `data/eeex/` | Generated EEex documentation index (names and links) | diff --git a/README.md b/README.md index f0a2079..c08e741 100644 --- a/README.md +++ b/README.md @@ -14,20 +14,26 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the > [!NOTE] > This is an early version. It currently provides **syntax diagnostics**, **document symbols**, -> **folding**, **go to definition**, **find references** and **rename** within a file; completion, -> hover, workspace-wide navigation, formatting and more are planned. +> **workspace symbols**, **folding**, and **go to definition**, **find references** and **rename** +> within a file; completion, hover, cross-file navigation, formatting and more are planned. ## Features - **Syntax errors from the official Lua 5.2 compiler.** The real Lua 5.2.4 front end, built to WebAssembly, checks your code — nothing to install, and no code is ever run. -- **`.menu` files understood.** Lua inside `` `…` `` blocks, `action`/`onOpen`/`onClose` scripts, - `enabled "…"` and ` lua "…"` expressions is checked, and errors point to the right line - of the `.menu` file. Upper-case names like `UI.MENU` are recognized, with Lua highlighting. +- **`.menu` files understood as the game reads them.** All the Lua the game compiles is checked, + in the exact form it compiles it: `` `…` `` blocks, `onOpen`/`onClose`/`action…` scripts, and + `enabled`, `table`, `lua "…"` and other expressions, in `"…"` or `'…'`, plus the Lua the game + generates from `slotinfo` and `spellInfo`. Errors point to the right line of the `.menu` file, + and warnings flag text the game reads differently than it looks, such as `My_Menu` unquoted. + Upper-case names like `UI.MENU` are recognized, with Lua highlighting. The rules come from the + [IESDP description of the format](https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm). - **You decide when files are checked:** on save (default), while typing, both, or only on request. - **Outline and breadcrumbs.** Functions, methods, top-level variables and table fields of Lua files, and each menu of a `.menu` file by its `name`, in the Outline view, the breadcrumbs and **Go to Symbol in Editor**. Works while the file still has syntax errors. +- **Go to Symbol in Workspace** across every Lua and `.menu` file of your workspace, including files + you haven't opened; files hidden with *Files: Exclude* are left out. - **Folding that follows the code:** functions, loops, each `if`/`elseif`/`else` branch, tables, comments, and every `{ … }` block and Lua script of a `.menu` file. - **Go to Definition, Find All References and Rename Symbol** for variables within a file. Locals diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 7d9b61f..5f6fb78 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -14,6 +14,9 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea with the official Lua 5.2 compiler, and errors appear in the Problems panel. - **`.menu` files are recognized**, including upper-case names such as `UI.MENU`, with Lua highlighting inside them. +- **Warnings for `.menu` text the game reads differently than it looks**: an underscore in + unquoted text (`My_Menu` is read as two words), a Lua block whose last character the game + drops, and unquoted words long enough to make the game abort. - **Choose when files are checked** with the *IE Lua › Validate: Mode* setting: on save (the default), while typing, both, or only on request. - **Check a file on request** with the **IE Lua: Validate Current File** command. @@ -27,6 +30,9 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea - **Find All References** lists every use of a variable in the same file. - **Rename Symbol** renames a variable everywhere in the file. It refuses, and tells you why, when the rename could break your code — for example when the new name is already used nearby. +- **Go to Symbol in Workspace** (Ctrl+T) finds functions, variables and menus in every Lua and + `.menu` file of your workspace, even files you haven't opened. Files hidden with + *Files: Exclude* are left out. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors too**: setup guides for Sublime Text, Neovim, Emacs, JetBrains IDEs, Helix, Zed, Kate, Notepad++ and Geany are on the project page. diff --git a/docs/editors/README.md b/docs/editors/README.md index 45a2a75..078c4c4 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -62,12 +62,23 @@ node /path/to/server.js --stdio | Feature | LSP request | Notes | | --- | --- | --- | -| Syntax errors | `textDocument/publishDiagnostics` | When `validate.mode` says so (see above). | +| Syntax errors | `textDocument/publishDiagnostics` | When `validate.mode` says so (see above). In `.menu` files, also warnings for text the game misreads. | | Document symbols (outline) | `textDocument/documentSymbol` | Nested when the editor supports it, otherwise a flat list with container names. | | Folding | `textDocument/foldingRange` | Whole lines; the closing line of each construct stays visible. | | Go to definition | `textDocument/definition` | The declaration of a local, or every assignment to a global, in the same file. | | Find references | `textDocument/references` | Every use of a local or global in the same file. | | Rename | `textDocument/prepareRename`, `textDocument/rename` | Same file only; refused, with the reason as the error message, when the rename could change what the code does. | +| 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`); +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* +through `workspace/configuration` (your guide says whether it does), you can add one next to +`ieLua`, for example `{ "files": { "exclude": { "**/backup": true } } }`. +Only folders on the local disk are scanned. Symbols, folding and navigation always reflect the current text, whatever `validate.mode` is. Navigation works on variables: table fields (`t.x`) and `goto` labels are not followed, and in a diff --git a/package.json b/package.json index 3e0f850..f5474e7 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,9 @@ "l10n": "./l10n", "main": "./dist/client/extension.js", "activationEvents": [ - "onLanguage:lua" + "onLanguage:lua", + "workspaceContains:**/*.[lL][uU][aA]", + "workspaceContains:**/*.[mM][eE][nN][uU]" ], "contributes": { "languages": [ diff --git a/src/server/features/diagnostics.ts b/src/server/features/diagnostics.ts index 2e27b76..362029b 100644 --- a/src/server/features/diagnostics.ts +++ b/src/server/features/diagnostics.ts @@ -24,7 +24,12 @@ export interface DiagnosticsDeps { * | `type` | ✓ | | ✓ | * | `saveAndType` | ✓ | ✓ | ✓ | */ -export function register(connection: Connection, documents: TextDocuments, deps: DiagnosticsDeps): void { +export interface DiagnosticsFeature { + /** Handles `workspace/didChangeConfiguration` (the server owns the single handler). */ + configurationChanged(settings: unknown): void; +} + +export function register(connection: Connection, documents: TextDocuments, deps: DiagnosticsDeps): DiagnosticsFeature { const debouncer = new Debouncer(deps.timers); /** Document version whose diagnostics were last published, per URI. */ const published = new Map(); @@ -37,7 +42,7 @@ export function register(connection: Connection, documents: TextDocuments ({ range: { start: document.positionAt(problem.start), end: document.positionAt(problem.end) }, - severity: DiagnosticSeverity.Error, + severity: problem.severity === 'warning' ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error, source: DIAGNOSTIC_SOURCE, code: problem.code, message: problem.message, @@ -100,7 +105,7 @@ export function register(connection: Connection, documents: TextDocuments { + const configurationChanged = (settings: unknown): void => { deps.settings.changed(settings); // A switch to a `type` mode should take effect without waiting for the next edit. for (const document of documents.all()) { @@ -116,9 +121,11 @@ export function register(connection: Connection, documents: TextDocuments { debouncer.dispose(); }); + + return { configurationChanged }; } diff --git a/src/server/features/documentSymbols.ts b/src/server/features/documentSymbols.ts index a642ad7..815aa98 100644 --- a/src/server/features/documentSymbols.ts +++ b/src/server/features/documentSymbols.ts @@ -41,6 +41,12 @@ export function toLspSymbols(symbols: readonly OutlineSymbol[], options: SymbolC }); return symbols.map(convert); } + return flatSymbols(symbols, options); +} + +/** Flat `SymbolInformation[]` in document order, each with the name of its parent as container. */ +export function flatSymbols(symbols: readonly OutlineSymbol[], options: Omit): SymbolInformation[] { + const range = (start: number, end: number) => ({ start: options.positionAt(start), end: options.positionAt(end) }); const flat: SymbolInformation[] = []; const flatten = (symbol: OutlineSymbol, container: string | undefined): void => { flat.push({ diff --git a/src/server/features/workspaceSymbols.ts b/src/server/features/workspaceSymbols.ts new file mode 100644 index 0000000..9718fb4 --- /dev/null +++ b/src/server/features/workspaceSymbols.ts @@ -0,0 +1,95 @@ +import type { CancellationToken, Connection, SymbolInformation, TextDocuments } from 'vscode-languageserver/node'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { parseDocument } from '../syntax/document.ts'; +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 { flatSymbols } from './documentSymbols.ts'; + +export interface WorkspaceSymbolsDeps { + readonly cache: ParsedDocumentCache; + 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) }); +} + +export interface SymbolSource { + /** Index key (see `WorkspaceIndex.pathKey`), or the URI for a document that is not a local file. */ + readonly key: string; + readonly symbols: () => readonly SymbolInformation[]; +} + +/** + * The symbols matching `query`: those of the open documents, then those of the + * indexed files that are not open (an open document wins over its saved version). + * Returns `undefined` once `isCancelled()` turns true. + */ +export function collectWorkspaceSymbols( + open: readonly SymbolSource[], + indexed: Iterable>, + query: string, + isCancelled: () => boolean, +): SymbolInformation[] | undefined { + const result: SymbolInformation[] = []; + const openKeys = new Set(open.map((source) => source.key)); + const add = (symbols: readonly SymbolInformation[]): void => { + for (const symbol of symbols) if (matchesQuery(symbol.name, query)) result.push(symbol); + }; + for (const source of open) { + if (isCancelled()) return undefined; + add(source.symbols()); + } + for (const file of indexed) { + if (isCancelled()) return undefined; + if (!openKeys.has(file.key)) add(file.value); + } + 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 + * folders, and of every open document. + */ +export function register(connection: Connection, documents: TextDocuments, deps: WorkspaceSymbolsDeps): void { + connection.onWorkspaceSymbol(async ({ query }, token): Promise => { + try { + // Files queued for indexing are part of the answer. + await untilCancelled(deps.index.ready(), token); + if (token.isCancellationRequested) return null; + const open: SymbolSource[] = documents.all().map((document) => ({ + 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), + }), + })); + return collectWorkspaceSymbols(open, deps.index.entries(), query, () => token.isCancellationRequested) ?? null; + } catch (error) { + connection.console.error(`Workspace symbols for "${query}" failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }); +} diff --git a/src/server/server.ts b/src/server/server.ts index 35589fe..9a5baff 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -1,12 +1,17 @@ // IE Lua language server. Runs as its own Node process: VS Code starts it over // IPC (`--node-ipc`); other editors start it with `--stdio` (see docs/editors/). // `createConnection` picks the transport from those command-line flags. +import * as path from 'node:path'; import { createConnection, DidChangeConfigurationNotification, + DidChangeWatchedFilesNotification, + FileChangeType, ProposedFeatures, TextDocuments, TextDocumentSyncKind, + WatchKind, + type SymbolInformation, } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { ParsedDocumentCache } from './documentCache.ts'; @@ -16,8 +21,11 @@ import * as documentSymbols from './features/documentSymbols.ts'; import * as foldingRanges from './features/foldingRanges.ts'; import * as references from './features/references.ts'; import * as rename from './features/rename.ts'; +import * as workspaceSymbols from './features/workspaceSymbols.ts'; import { SettingsStore } from './settingsStore.ts'; import { loadLua52 } from './validation/lua52.ts'; +import { nodeFileSystem } from './workspace/nodeFileSystem.ts'; +import { WorkspaceIndex } from './workspace/workspaceIndex.ts'; const connection = createConnection(ProposedFeatures.all); const documents = new TextDocuments(TextDocument); @@ -33,11 +41,44 @@ lua.catch((error: unknown) => { }); let configurationPull = false; +let watchedFilesRegistration = false; +let workspaceFolderChanges = false; +/** 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({ + fs: nodeFileSystem, + path, + analyze: workspaceSymbols.fileSymbols, + filesExclude: async (folderUri) => { + if (!configurationPull) return undefined; + try { + return (await connection.workspace.getConfiguration({ scopeUri: folderUri, section: 'files.exclude' })) as unknown; + } catch (error) { + connection.console.error(`Reading "files.exclude" for ${folderUri} failed: ${String(error)}`); + return undefined; + } + }, + yieldToEventLoop: () => new Promise((resolve) => setImmediate(resolve)), + log: (message) => { + connection.console.log(message); + }, +}); +// A closed document may have unsaved changes the disk version lacks: index the saved file again. +documents.onDidClose(({ document }) => { + index.fileChanged(document.uri); +}); connection.onInitialize((params) => { const workspace = params.capabilities.workspace; configurationPull = workspace?.configuration === true; - diagnostics.register(connection, documents, { + watchedFilesRegistration = workspace?.didChangeWatchedFiles?.dynamicRegistration === true; + workspaceFolderChanges = workspace?.workspaceFolders === true; + // Null or absent when no folder is open or the client does not support workspace folders + // (the deprecated rootUri is not used): then only open documents are searched. + folders = params.workspaceFolders?.map((folder) => folder.uri) ?? []; + const diagnosticsFeature = diagnostics.register(connection, documents, { lua, settings: new SettingsStore(connection, configurationPull, params.initializationOptions), timers: { setTimeout, clearTimeout: (handle) => { clearTimeout(handle as NodeJS.Timeout); } }, @@ -55,6 +96,12 @@ connection.onInitialize((params) => { definition.register(connection, documents, { cache: parsed }); references.register(connection, documents, { cache: parsed }); rename.register(connection, documents, { cache: parsed, documentChanges: workspace?.workspaceEdit?.documentChanges === true }); + workspaceSymbols.register(connection, documents, { cache: parsed, index }); + // One handler per notification: settings changes go to every feature that needs them. + connection.onDidChangeConfiguration(({ settings }) => { + diagnosticsFeature.configurationChanged(settings); + index.settingsChanged(); + }); const prepareRename = params.capabilities.textDocument?.rename?.prepareSupport === true; return { capabilities: { @@ -69,6 +116,8 @@ connection.onInitialize((params) => { referencesProvider: true, // Without prepareSupport the client must not be sent `prepareProvider` (LSP 3.17). renameProvider: prepareRename ? { prepareProvider: true } : true, + workspaceSymbolProvider: true, + ...(workspaceFolderChanges ? { workspace: { workspaceFolders: { supported: true, changeNotifications: true } } } : {}), }, serverInfo: { name: 'IE Lua Language Server' }, }; @@ -81,6 +130,36 @@ connection.onInitialized(() => { connection.console.warn(`Could not register for configuration changes: ${String(error)}`); }); } + if (watchedFilesRegistration) { + // LSP glob patterns are case-sensitive; `[]` ranges match the extensions in any letter case. + // `**/*` (create and delete only) reports folders moved in or deleted, whose files get no events. + const watchers = [ + { globPattern: '**/*.[lL][uU][aA]' }, + { globPattern: '**/*.[mM][eE][nN][uU]' }, + { globPattern: '**/*', kind: WatchKind.Create | WatchKind.Delete }, + ]; + connection.client.register(DidChangeWatchedFilesNotification.type, { watchers }).catch((error: unknown) => { + connection.console.warn(`Could not register file watchers; files changed outside the editor are indexed again only on restart: ${String(error)}`); + }); + } + if (workspaceFolderChanges) { + connection.workspace.onDidChangeWorkspaceFolders(({ added, removed }) => { + const gone = new Set(removed.map((folder) => folder.uri)); + folders = [...folders.filter((uri) => !gone.has(uri)), ...added.map((folder) => folder.uri)]; + index.setFolders(folders); + }); + } + // Requests to the client (files.exclude) are allowed only after `initialized`. + index.setFolders(folders); +}); + +connection.onDidChangeWatchedFiles(({ changes }) => { + // Both watchers can report the same file: handle each URI once, with its last change. + const latest = new Map(changes.map((change) => [change.uri, change.type])); + for (const [uri, type] of latest) { + if (type === FileChangeType.Deleted) index.fileDeleted(uri); + else index.fileChanged(uri); + } }); documents.listen(connection); diff --git a/src/server/syntax/document.ts b/src/server/syntax/document.ts index b062436..55b366d 100644 --- a/src/server/syntax/document.ts +++ b/src/server/syntax/document.ts @@ -1,7 +1,7 @@ // Syntax trees of a whole document: one chunk for a .lua file, one per embedded // chunk for a .menu file. Pure: no LSP or `vscode` imports. import { extractMenuLua, type MenuBlock } from '../validation/menuExtractor.ts'; -import type { LuaChunk } from '../validation/types.ts'; +import { CHUNK_FORM, type LuaChunk } from '../validation/types.ts'; import type { DocumentKind } from '../validation/validateText.ts'; import type { Chunk } from './ast.ts'; import { parseChunk } from './parser.ts'; @@ -24,11 +24,17 @@ export interface ParsedDocument { /** Parses every Lua chunk of a document. Never throws. */ export function parseDocument(text: string, kind: DocumentKind): ParsedDocument { const parse = (chunk: LuaChunk): ParsedChunk => { - const tree = parseChunk(text, { from: chunk.offset, to: chunk.offset + chunk.text.length, mode: chunk.kind }); + const tree = parseChunk(text, { + from: chunk.offset, + to: chunk.offset + chunk.text.length, + mode: chunk.kind, + // The engine compiles property code as the body of a function (see CompiledForm). + functionBody: chunk.origin === 'property', + }); return { chunk, tree, scopes: analyzeScopes(tree) }; }; if (kind === 'lua') { - return { kind, chunks: [parse({ kind: 'statements', origin: 'file', offset: 0, text })], blocks: [] }; + return { kind, chunks: [parse({ kind: 'statements', origin: 'file', offset: 0, region: { start: 0, end: text.length }, text, forms: [CHUNK_FORM] })], blocks: [] }; } const { chunks, blocks } = extractMenuLua(text); return { kind, chunks: chunks.map(parse), blocks }; diff --git a/src/server/syntax/folding.ts b/src/server/syntax/folding.ts index 8168b79..f466c7b 100644 --- a/src/server/syntax/folding.ts +++ b/src/server/syntax/folding.ts @@ -161,9 +161,10 @@ export function foldingRanges(document: ParsedDocument, text: string, lineAt: (o } for (const { chunk, tree } of document.chunks) { - if (chunk.origin !== 'file') { - // The delimiters of the chunk: a backtick or a double quote on each side. - fold(chunk.offset - 1, chunk.offset + chunk.text.length, chunk.offset + chunk.text.length); + const { region } = chunk; + if (region.start < chunk.offset) { + // From the opening backtick or quote to the closing one. + fold(region.start, region.end - 1, region.end - 1); } block(tree.body); // Runs of `--` comments that each start their own, consecutive line. diff --git a/src/server/syntax/parser.ts b/src/server/syntax/parser.ts index ebc81e8..ee0434f 100644 --- a/src/server/syntax/parser.ts +++ b/src/server/syntax/parser.ts @@ -24,10 +24,16 @@ export interface ParseOptions { readonly to?: number; /** * `statements` (default): a chunk. `expression`: a value the engine evaluates - * (`enabled "…"` in .menu files), parsed as if preceded by `return `, which is - * how the validator compiles it. + * (`enabled "…"` in .menu files), parsed as if preceded by `return `. */ readonly mode?: 'statements' | 'expression'; + /** + * Parse the code as the body of `function f () end`, the shape in which + * the engine compiles .menu property code: `...` is not allowed (the function + * is not vararg), and every statement is one level deeper (`enterlevel` of the + * enclosing `function` statement). Default `false`: a top-level chunk. + */ + readonly functionBody?: boolean; } /** lparser.c `priority`: [left, right]; right < left means right-associative. */ @@ -69,9 +75,12 @@ class Parser { private previousEnd: number; private level = 0; private readonly functions: FunctionState[] = []; + /** `ParseOptions.functionBody`. */ + private readonly insideFunction: boolean; - constructor(source: string, tokens: readonly Token[], from: number, to: number) { + constructor(source: string, tokens: readonly Token[], from: number, to: number, functionBody: boolean) { this.source = source; + this.insideFunction = functionBody; this.tokens = tokens; this.eof = tokens.at(-1) ?? { type: 'eof', value: '', start: to, end: to }; this.previousEnd = from; @@ -177,8 +186,14 @@ class Parser { // --------------------------------------------------------------- chunks + /** Enters the function the chunk is compiled as (see `ParseOptions.functionBody`). */ + private enterChunk(): void { + this.functions.push({ isVararg: !this.insideFunction, loopDepth: 0 }); + if (this.insideFunction) this.enterLevel(); + } + chunk(from: number): Ast.Block { - this.functions.push({ isVararg: true, loopDepth: 0 }); + this.enterChunk(); const body: Ast.Statement[] = []; for (;;) { body.push(...this.statementList()); @@ -192,9 +207,11 @@ class Parser { /** `return [;]` followed by the end of the chunk. */ expressionChunk(from: number): Ast.Block { - this.functions.push({ isVararg: true, loopDepth: 0 }); + this.enterChunk(); const body: Ast.Statement[] = []; try { + // The implied `return` is a statement: lparser.c `statement` enters a level. + this.enterLevel(); const values = this.token.type === 'eof' || this.check(';') ? [] : this.expressionList(); this.accept(';'); body.push({ kind: 'ReturnStatement', values, start: from, end: this.previousEnd }); @@ -609,7 +626,7 @@ export function parseChunk(source: string, options: ParseOptions = {}): Ast.Chun const from = options.from ?? 0; const to = options.to ?? source.length; const { tokens, comments, errors: lexErrors } = lex(source, from, to); - const parser = new Parser(source, tokens, from, to); + const parser = new Parser(source, tokens, from, to, options.functionBody ?? false); const body = options.mode === 'expression' ? parser.expressionChunk(from) : parser.chunk(from); const errors = [...lexErrors, ...parser.errors].sort((a, b) => a.start - b.start); return { kind: 'Chunk', body, comments, errors, start: from, end: to }; diff --git a/src/server/syntax/workspaceSymbols.ts b/src/server/syntax/workspaceSymbols.ts new file mode 100644 index 0000000..08b9d5e --- /dev/null +++ b/src/server/syntax/workspaceSymbols.ts @@ -0,0 +1,20 @@ +// Query matching for workspace symbols. Pure: no LSP or `vscode` imports. + +/** + * Whether `name` matches a `workspace/symbol` query. LSP 3.17 asks servers to + * interpret the query "in a relaxed way as editors will apply their own + * highlighting and scoring on the results", and gives the rule of thumb used here: + * match case-insensitively, and check that the characters of the query appear in + * their order in the name. An empty query matches everything. + */ +export function matchesQuery(name: string, query: string): boolean { + if (query === '') return true; + const haystack = name.toLowerCase(); + let from = 0; + for (const c of query.toLowerCase()) { + const at = haystack.indexOf(c, from); + if (at < 0) return false; + from = at + c.length; + } + return true; +} diff --git a/src/server/validation/menuExtractor.ts b/src/server/validation/menuExtractor.ts index 78b2151..d851076 100644 --- a/src/server/validation/menuExtractor.ts +++ b/src/server/validation/menuExtractor.ts @@ -1,31 +1,96 @@ -import { DiagnosticCode, type LuaChunk, type Problem } from './types.ts'; +import { lexMenu, type MenuToken } from './menuLexer.ts'; +import { CHUNK_FORM, EXPRESSION_FORM, STATEMENT_FORM, type CompiledForm, type LuaChunk, type Problem } from './types.ts'; -/** - * Properties whose `"…"` value is a Lua script (one or more statements), - * compared case-insensitively. Every entry was observed with Lua statements in - * the game's own UI.MENU; properties not listed here are never validated. - */ -const STATEMENT_PROPERTIES: ReadonlySet = new Set([ +// Which property values are Lua, from IESDP, "MENU file format", section "How a +// menu becomes Lua" (https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm, +// commit 38e7532). Keywords in lower case, as `menuKeyword` returns them. The tables +// are exported only so that test/unit/syntaxes/ieMenuGrammar.test.ts can check the +// TextMate grammar against them. + +/** Properties whose STRING is compiled as a function body (one or more statements). */ +export const STATEMENT_PROPERTIES: ReadonlySet = new Set([ + 'onopen', + 'onclose', 'action', 'actionalt', 'actiondbl', - 'actiondrag', 'actionenter', 'actionexit', - 'actionhold', - 'actionscroll', + 'actionupdate', 'actionsimpledrag', 'actionsimpledrop', - 'actionupdate', - 'onclose', - 'onopen', + 'actionhold', + 'actionscroll', ]); /** - * Properties whose `"…"` value is a Lua expression without the `lua` keyword - * (e.g. `enabled "bookMode == 1"`), compared case-insensitively. + * Properties whose STRING is compiled as `return `. `bitmap res` and + * every `lua STRING` value are expressions too; they are recognized separately. */ -const EXPRESSION_PROPERTIES: ReadonlySet = new Set(['enabled']); +export const EXPRESSION_PROPERTIES: ReadonlySet = new Set([ + 'enabled', + 'actiondrag', + 'table', + 'seperator', + 'useoverlaytint', +]); + +/** An expression the engine generates from a shorthand STRING `T`: `T`. */ +function generatedExpression(before: string, after: string): CompiledForm { + return { prefix: EXPRESSION_FORM.prefix + before, suffix: after + EXPRESSION_FORM.suffix }; +} + +/** A statement the engine generates from a shorthand STRING `T`: `T`. */ +function generatedStatement(before: string, after: string): CompiledForm { + return { prefix: STATEMENT_FORM.prefix + before, suffix: after + STATEMENT_FORM.suffix }; +} + +const SPELL_INFO_COMMON: readonly CompiledForm[] = [ + generatedExpression('', ' ~= nil'), // enabled + generatedExpression('', '.icon'), // icon lua + generatedExpression('Infinity_FetchString(', '.name)'), // tooltip lua + generatedExpression('', '.castable == 0'), // greyscale lua + // bam lua "'IVSLOT'" does not contain T, so it cannot fail. +]; + +/** + * Shorthand properties whose STRING `T` the engine pastes into generated Lua + * (IESDP, MENU file format, Item properties › Slots). Each STRING is validated + * in every generated form, and parsed as an expression for navigation. + */ +export const SHORTHAND_FORMS: ReadonlyMap = new Map([ + [ + 'slotinfo', + [ + generatedExpression('', '.item.icon'), // icon lua + generatedExpression('', '.item.count'), // count lua + generatedExpression('', '.item.usages'), // usages lua + generatedExpression('', '.highlight'), // highlight lua + generatedExpression('', '.item.tint'), // tint lua + generatedExpression('', '.tooltip'), // tooltip lua + generatedExpression('', '.valid'), // enabled + generatedExpression('Infinity_SwapSlot(', '.id)'), // action (expression) + generatedStatement('showItemDescriptionInventory(', '.slotName)'), // actionalt + generatedStatement('slotDoubleClick(', '.slotName)'), // actiondbl + ], + ], + [ + 'spellinfo', + [ + ...SPELL_INFO_COMMON, + generatedExpression('memorizeSpell(', ')'), // action (expression) + generatedStatement('showSpellDetails(', ', false)'), // actionalt + ], + ], + [ + 'memorizedspellinfo', + [ + ...SPELL_INFO_COMMON, + generatedExpression('unmemorizeSpell(', ')'), // action (expression) + generatedStatement('showSpellDetails(', ', true)'), // actionalt + ], + ], +]); /** A word of a .menu file, as half-open document offsets. */ export interface MenuWord { @@ -37,15 +102,18 @@ export interface MenuWord { /** A `{ … }` block of a .menu file (`menu`, `button`, `label`, …). */ export interface MenuBlock { /** - * The first word of the line holding `{`, or of the last non-empty line before - * it when `{` is alone on its line: `menu`, `button`, … `undefined` if none. + * The keyword just before `{`, as written: `menu`, `button`, `column`, … + * `undefined` when `{` follows anything else. */ readonly keyword: MenuWord | undefined; /** Offset of `{`. */ readonly open: number; /** Offset of the matching `}`; `undefined` when the block is never closed. */ readonly close: number | undefined; - /** Text of the first `name '…'` / `name "…"` property directly inside the block (offsets exclude the quotes). */ + /** + * The STRING of the first `name` property directly inside the block: `name "…"`, + * `name '…'` (offsets exclude the quotes) or an unquoted `name WORD`. + */ readonly name: MenuWord | undefined; readonly children: readonly MenuBlock[]; } @@ -65,131 +133,92 @@ interface OpenBlock { children: OpenBlock[]; } -function isWordChar(c: string | undefined): boolean { - return c !== undefined && /[A-Za-z0-9_.+-]/.test(c); -} - /** - * Finds the Lua embedded in an Infinity Engine `.menu` file: + * Finds the Lua embedded in an Infinity Engine `.menu` file, from the tokens of + * `lexMenu` (which follows the engine's lexer): * - * - `` `…` `` blocks: Lua statements. - * - ` lua "…"`: a Lua expression. - * - `"…"` after a property in STATEMENT_PROPERTIES / EXPRESSION_PROPERTIES. - * The property may be on the same line as the string or on the previous - * non-empty line (`action` followed by `"` on the next line). + * - `` `…` `` blocks: a Lua chunk, without the last character before the + * closing backtick, which the engine drops. + * - a STRING after a property in STATEMENT_PROPERTIES: Lua statements. + * - a STRING after a property in EXPRESSION_PROPERTIES, after `bitmap res`, or + * after `lua`: a Lua expression. + * - a STRING after `slotinfo`, `spellInfo` or `memorizedSpellInfo`: an + * expression the engine pastes into the Lua of SHORTHAND_FORMS. * - * `--` starts a comment that runs to the end of the line, `'…'` is a plain menu - * string, and a `"` string ends at the next `"` (the format has no escapes). + * A STRING is a `"…"` or `'…'` string, or a word that is not a keyword (the + * engine treats both alike: `enabled currentSave` is the expression + * `currentSave`). The engine's grammar is token based, so line breaks don't + * matter. An unterminated string is reported by the lexer and is not Lua. * - * The same scan also records the nesting of `{ … }` blocks and their `name`. + * The same pass records the nesting of `{ … }` blocks and their `name`. */ export function extractMenuLua(text: string): MenuExtraction { - const chunks: LuaChunk[] = []; - const problems: Problem[] = []; + const { tokens, inline, problems } = lexMenu(text); + const chunks: LuaChunk[] = inline.map((block) => ({ + kind: 'statements', + origin: 'block', + offset: block.start + 1, + region: { start: block.start, end: block.close + 1 }, + // The engine drops the last character before the closing backtick (IESDP, + // Lexical structure); the chunk is the text it actually runs. + text: text.slice(block.start + 1, Math.max(block.start + 1, block.close - 1)), + forms: [CHUNK_FORM], + })); const blocks: OpenBlock[] = []; /** Blocks whose `}` has not been seen yet, innermost last. */ const open: OpenBlock[] = []; - // Words on the current line, and the words of the last line that had any. - let lineWords: MenuWord[] = []; - let previousLineWords: MenuWord[] = []; - let i = 0; + const word = (token: MenuToken): MenuWord => ({ + text: text.slice(token.valueStart, token.valueEnd), + start: token.valueStart, + end: token.valueEnd, + }); - const endLine = (): void => { - if (lineWords.length > 0) { - previousLineWords = lineWords; - lineWords = []; - } - }; - - while (i < text.length) { - const c = text[i]; - if (c === '\n' || c === '\r') { - endLine(); - i++; - } else if (c === '-' && text[i + 1] === '-') { - while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i++; - } else if (c === '`') { - const close = text.indexOf('`', i + 1); - if (close < 0) { - problems.push({ - start: i, - end: i + 1, - message: 'Unterminated Lua block: missing closing "`".', - code: DiagnosticCode.MenuUnterminatedBlock, + tokens.forEach((token, index) => { + const previous = tokens[index - 1]; + if (token.type === '{') { + const block: OpenBlock = { + keyword: previous?.type === 'keyword' ? word(previous) : undefined, + open: token.start, + close: undefined, + name: undefined, + children: [], + }; + (open.at(-1)?.children ?? blocks).push(block); + open.push(block); + } else if (token.type === '}') { + const block = open.pop(); + if (block) block.close = token.start; + } else if (token.type === 'string' && previous?.type === 'keyword') { + const kind = classify(previous, tokens[index - 2]); + const shorthand = previous.keyword === undefined ? undefined : SHORTHAND_FORMS.get(previous.keyword); + // An unterminated string runs to the end of the file; it is reported, not validated. + const terminated = token.quote === undefined || token.end > token.valueEnd; + if ((kind || shorthand) && terminated) { + chunks.push({ + kind: kind ?? 'expression', + origin: 'property', + offset: token.valueStart, + region: { start: token.start, end: token.end }, + text: text.slice(token.valueStart, token.valueEnd), + forms: shorthand ?? [kind === 'statements' ? STATEMENT_FORM : EXPRESSION_FORM], }); - break; - } - chunks.push({ kind: 'statements', origin: 'block', offset: i + 1, text: text.slice(i + 1, close) }); - lineWords = []; - previousLineWords = []; - i = close + 1; - } else if (c === '"' || c === "'") { - const close = text.indexOf(c, i + 1); - if (close < 0) { - if (c === '"') { - problems.push({ - start: i, - end: i + 1, - message: 'Unterminated string: missing closing \'"\'.', - code: DiagnosticCode.MenuUnterminatedString, - }); - } - break; - } - const words = lineWords.length > 0 ? lineWords : previousLineWords; - if (c === '"') { - const kind = classify(lineWords, previousLineWords); - if (kind) { - chunks.push({ kind, origin: 'property', offset: i + 1, text: text.slice(i + 1, close) }); - } } const block = open.at(-1); - if (block && block.name === undefined && words.length === 1 && words[0]?.text.toLowerCase() === 'name') { - block.name = { text: text.slice(i + 1, close), start: i + 1, end: close }; + if (block && block.name === undefined && previous.keyword === 'name') { + block.name = word(token); } - // A string completes a property; the next string needs its own keyword. - lineWords = []; - previousLineWords = []; - i = close + 1; - } else if (c === '{') { - const words = lineWords.length > 0 ? lineWords : previousLineWords; - const block: OpenBlock = { keyword: words[0], open: i, close: undefined, name: undefined, children: [] }; - (open.at(-1)?.children ?? blocks).push(block); - open.push(block); - lineWords = []; - previousLineWords = []; - i++; - } else if (c === '}') { - const block = open.pop(); - if (block) block.close = i; - lineWords = []; - previousLineWords = []; - i++; - } else if (isWordChar(c)) { - const start = i; - while (isWordChar(text[i])) i++; - lineWords.push({ text: text.slice(start, i), start, end: i }); - } else { - i++; } - } + }); + chunks.sort((a, b) => a.offset - b.offset); return { chunks, problems, blocks }; } -function classify(lineWords: readonly MenuWord[], previousLineWords: readonly MenuWord[]): LuaChunk['kind'] | undefined { - if (lineWords.at(-1)?.text.toLowerCase() === 'lua') { - return 'expression'; - } - const words = lineWords.length > 0 ? lineWords : previousLineWords; - const property = words[0]?.text.toLowerCase(); - if (property === undefined || words.length !== 1) { - return undefined; - } - if (STATEMENT_PROPERTIES.has(property)) { - return 'statements'; - } - if (EXPRESSION_PROPERTIES.has(property)) { - return 'expression'; - } +/** Whether a STRING after `property` (preceded by `before`) is Lua, and of which kind. */ +function classify(property: MenuToken, before: MenuToken | undefined): LuaChunk['kind'] | undefined { + const keyword = property.keyword; + if (keyword === undefined) return undefined; + if (STATEMENT_PROPERTIES.has(keyword)) return 'statements'; + if (EXPRESSION_PROPERTIES.has(keyword) || keyword === 'lua') return 'expression'; + if (keyword === 'res' && before?.keyword === 'bitmap') return 'expression'; return undefined; } diff --git a/src/server/validation/menuKeywords.ts b/src/server/validation/menuKeywords.ts new file mode 100644 index 0000000..1a193be --- /dev/null +++ b/src/server/validation/menuKeywords.ts @@ -0,0 +1,35 @@ +// Keywords of the Infinity Engine MENU format. Pure data: no LSP or `vscode` imports. +// +// Source: IESDP, "MENU file format", section Keywords +// (https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm, commit 38e7532), +// which was checked against the executables of BGEE, BG2EE and IWDEE 2.6.6.0 and 2.7.3.0. +// The engine's table has 124 entries for these 122 distinct words; the spelling is the engine's. + +/** Every MENU keyword, spelled as in the engine. */ +export const MENU_KEYWORDS: readonly string[] = [ + 'action', 'actionalt', 'actionbar', 'actiondbl', 'actiondrag', 'actionenter', 'actionexit', 'actionHold', + 'actionScroll', 'actionsimpledrag', 'actionsimpledrop', 'actionUpdate', 'align', 'area', 'areamap', + 'background', 'bam', 'bitmap', 'bottom', 'button', 'center', 'clickable', 'clunkyScroll', 'color', + 'colordisplay', 'column', 'count', 'dynamic', 'edit', 'enabled', 'encumbrance', 'fill', 'font', 'force', + 'frame', 'frameTimes', 'full', 'func', 'glow', 'greyscale', 'handle', 'hide', 'hidehighlight', 'highlight', + 'highlightgroup', 'icon', 'ignoreEsc', 'ignoreEvents', 'label', 'left', 'list', 'loop', 'lower', 'lua', + 'map', 'maxchars', 'maxlines', 'memorizedSpellInfo', 'menu', 'modal', 'mosaic', 'movie', 'name', 'offset', + 'on', 'onclose', 'onopen', 'opacity', 'overlayTint', 'pad', 'palette', 'panel', 'paperdoll', 'placeholder', + 'point', 'portrait', 'position', 'progressbar', 'pulse', 'queuedMovie', 'rectangle', 'res', + 'respectClipping', 'respectConstraints', 'right', 'rowbackground', 'rowheight', 'rowwidth', 'scaleToClip', + 'scrollbar', 'seperator', 'sequence', 'sequenceonce', 'settings', 'shadow', 'size', 'skipReset', 'slider', + 'sliderBackground', 'slot', 'slotinfo', 'sound', 'spellInfo', 'state', 'style', 'subtitle', 'table', + 'template', 'text', 'tint', 'toggle', 'tooltip', 'top', 'transparent', 'upper', 'usages', 'usealpha', + 'useFontZoom', 'useOverlayTint', 'var', 'width', 'worldmap', +]; + +const LOWER_CASE: ReadonlySet = new Set(MENU_KEYWORDS.map((keyword) => keyword.toLowerCase())); + +/** + * The keyword `word` stands for, in lower case, or `undefined` if it is not a + * keyword. The engine compares keywords case-insensitively. + */ +export function menuKeyword(word: string): string | undefined { + const lower = word.toLowerCase(); + return LOWER_CASE.has(lower) ? lower : undefined; +} diff --git a/src/server/validation/menuLexer.ts b/src/server/validation/menuLexer.ts new file mode 100644 index 0000000..79f2cb9 --- /dev/null +++ b/src/server/validation/menuLexer.ts @@ -0,0 +1,189 @@ +// Lexer for Infinity Engine MENU files. Pure: no LSP or `vscode` imports. +// +// Follows IESDP, "MENU file format", section Lexical structure +// (https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm, commit 38e7532), +// which describes the lexer of BGEE, BG2EE and IWDEE 2.6.6.0 and 2.7.3.0: +// +// - white space is any character C `isspace` accepts (space, tab, CR, LF, VT, FF); +// - `--` starts a comment that runs to the end of the line; a single `-` is a minus sign; +// - `{` and `}` open and close a block; +// - a string runs from `"` or `'` to the next occurrence of the same quote, with no +// escape sequences, across lines; an unterminated string runs to the end of the file; +// - a number is a run of decimal digits; +// - a word is a run of ASCII letters and digits that does not start with a digit. A +// keyword (compared case-insensitively) is that keyword; any other word is a string; +// - text between two backticks is inline Lua, which produces no token; +// - any other character (`,` `;` `=` `(` `.` `_` …) is skipped. + +import { menuKeyword } from './menuKeywords.ts'; +import { DiagnosticCode, type Problem } from './types.ts'; + +export interface MenuToken { + /** + * `string` covers both quoted strings and words that are not keywords, which + * the engine treats exactly like strings. + */ + readonly type: 'keyword' | 'string' | 'number' | '{' | '}' | '-'; + /** Half-open offsets of the whole token, quotes included. */ + readonly start: number; + readonly end: number; + /** Half-open offsets of the value: a string without its quotes, or the word or number itself. */ + readonly valueStart: number; + readonly valueEnd: number; + /** The keyword in lower case (`keyword` tokens only). */ + readonly keyword?: string; + /** The quote character of a quoted string; `undefined` for words and other tokens. */ + readonly quote?: '"' | "'"; +} + +/** A `` `…` `` block of inline Lua. */ +export interface MenuInlineLua { + /** Offset of the opening backtick. */ + readonly start: number; + /** Offset of the closing backtick. */ + readonly close: number; +} + +export interface MenuLexResult { + /** Tokens in document order. Inline Lua blocks produce none. */ + readonly tokens: MenuToken[]; + readonly inline: MenuInlineLua[]; + readonly problems: Problem[]; +} + +/** C `isspace` in the "C" locale. */ +export function isMenuSpace(c: string | undefined): boolean { + return c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\v' || c === '\f'; +} + +function isLetter(c: string | undefined): boolean { + if (c === undefined) return false; + const code = c.charCodeAt(0) | 0x20; // ASCII upper case to lower case + return code >= 0x61 && code <= 0x7a; +} + +function isDigit(c: string | undefined): boolean { + return c !== undefined && c >= '0' && c <= '9'; +} + +const LINE_END = /[\n\r]/g; + +/** IESDP, Limits: "A longer unquoted word [than 63 characters] aborts the game." */ +export const MAX_WORD_LENGTH = 64; + +function isWordOrUnderscore(c: string | undefined): boolean { + return c === '_' || isLetter(c) || isDigit(c); +} + +/** + * The run of letters, digits and `_` around the `_` at `at`, and the words and + * numbers the engine reads from it (none when the run is only underscores). + */ +function underscoreRun(text: string, at: number): { start: number; end: number; parts: string[] } { + let start = at; + while (start > 0 && isWordOrUnderscore(text[start - 1])) start--; + let end = at; + while (isWordOrUnderscore(text[end])) end++; + return { start, end, parts: text.slice(start, end).match(/[A-Za-z][A-Za-z0-9]*|[0-9]+/g) ?? [] }; +} + +/** Splits a MENU file into tokens. Never throws. */ +export function lexMenu(text: string): MenuLexResult { + const tokens: MenuToken[] = []; + const inline: MenuInlineLua[] = []; + const problems: Problem[] = []; + const simple = (type: '{' | '}' | '-', start: number): void => { + tokens.push({ type, start, end: start + 1, valueStart: start, valueEnd: start + 1 }); + }; + /** End of the last run reported by the underscore check, so each run is reported once. */ + let underscoreRunEnd = 0; + let i = 0; + while (i < text.length) { + const c = text[i]; + if (c === '-' && text[i + 1] === '-') { + LINE_END.lastIndex = i + 2; + i = LINE_END.exec(text)?.index ?? text.length; + } else if (c === '-' || c === '{' || c === '}') { + simple(c, i); + i++; + } else if (c === '`') { + const close = text.indexOf('`', i + 1); + if (close < 0) { + problems.push({ + start: i, + end: i + 1, + message: 'Unterminated Lua block: missing closing "`".', + code: DiagnosticCode.MenuUnterminatedBlock, + severity: 'error', + }); + break; + } + inline.push({ start: i, close }); + const last = close - 1; + if (last > i && !isMenuSpace(text[last])) { + problems.push({ + start: last, + end: close, + message: `The engine drops the last character before the closing "\`", so ${JSON.stringify(text[last])} is not run. End the block with a line break or a space.`, + code: DiagnosticCode.MenuInlineLuaLastCharacter, + severity: 'warning', + }); + } + i = close + 1; + } else if (c === '"' || c === "'") { + const close = text.indexOf(c, i + 1); + if (close < 0) { + problems.push({ + start: i, + end: i + 1, + message: c === '"' ? 'Unterminated string: missing closing \'"\'.' : 'Unterminated string: missing closing "\'".', + code: DiagnosticCode.MenuUnterminatedString, + severity: 'error', + }); + tokens.push({ type: 'string', start: i, end: text.length, valueStart: i + 1, valueEnd: text.length, quote: c }); + break; + } + tokens.push({ type: 'string', start: i, end: close + 1, valueStart: i + 1, valueEnd: close, quote: c }); + i = close + 1; + } else if (isDigit(c)) { + const start = i; + while (isDigit(text[i])) i++; + tokens.push({ type: 'number', start, end: i, valueStart: start, valueEnd: i }); + } else if (isLetter(c)) { + const start = i; + while (isLetter(text[i]) || isDigit(text[i])) i++; + if (i - start >= MAX_WORD_LENGTH) { + problems.push({ + start, + end: i, + message: `This unquoted word has ${i - start} characters; the engine aborts on words of ${MAX_WORD_LENGTH} or more. Quote it.`, + code: DiagnosticCode.MenuWordTooLong, + severity: 'error', + }); + } + const keyword = menuKeyword(text.slice(start, i)); + tokens.push( + keyword === undefined + ? { type: 'string', start, end: i, valueStart: start, valueEnd: i } + : { type: 'keyword', start, end: i, valueStart: start, valueEnd: i, keyword }, + ); + } else { + if (c === '_' && i >= underscoreRunEnd) { + const run = underscoreRun(text, i); + underscoreRunEnd = run.end; + if (run.parts.length > 0) { + const written = text.slice(run.start, run.end); + problems.push({ + start: run.start, + end: run.end, + message: `The engine skips "_" in unquoted text, so ${written} is read as ${run.parts.join(' ')}. Quote it: "${written}".`, + code: DiagnosticCode.MenuUnquotedUnderscore, + severity: 'warning', + }); + } + } + i++; + } + } + return { tokens, inline, problems }; +} diff --git a/src/server/validation/types.ts b/src/server/validation/types.ts index 3abfa94..4eac506 100644 --- a/src/server/validation/types.ts +++ b/src/server/validation/types.ts @@ -5,8 +5,7 @@ export interface LuaChunk { /** * `statements`: a full chunk (a `.lua` file, a `` `…` `` block, an `action "…"` script). - * `expression`: a value the engine evaluates (`enabled "…"`, ` lua "…"`); - * validated as `return `. + * `expression`: a value the engine evaluates (`enabled "…"`, ` lua "…"`). */ readonly kind: 'statements' | 'expression'; /** @@ -16,18 +15,58 @@ export interface LuaChunk { readonly origin: 'file' | 'block' | 'property'; /** Offset of the first character of the Lua text in the document. */ readonly offset: number; + /** + * Half-open document range the chunk comes from, delimiters included (the + * backticks of a block, the quotes of a string). Equal to the text's range for + * a file or an unquoted word, which have none. + */ + readonly region: { readonly start: number; readonly end: number }; /** The Lua text exactly as it appears in the document. */ readonly text: string; + /** + * How the engine compiles the text: once per form, as `prefix + text + suffix`. + * Neither part contains a line break, so compiler line numbers are chunk lines. + */ + readonly forms: readonly CompiledForm[]; } +/** Text the engine puts around a chunk before compiling it. */ +export interface CompiledForm { + readonly prefix: string; + readonly suffix: string; +} + +// The shapes in which the engine compiles .menu property code, from IESDP, "MENU +// file format", section "How a menu becomes Lua" +// (https://gibberlings3.github.io/iesdp/file_formats/ie_formats/menu_v1.htm, commit 38e7532): +// +// function
() end -- statement form +// function
() return end -- expression form +// +// The engine's function name is a property-specific prefix followed by a memory +// address; any Lua name gives the same syntax, so `f` stands in for it. + +/** A whole `.lua` file or a `` `…` `` block, compiled as it is. */ +export const CHUNK_FORM: CompiledForm = { prefix: '', suffix: '' }; +/** Property code compiled as a function body (`action "…"`, `onOpen "…"`, …). */ +export const STATEMENT_FORM: CompiledForm = { prefix: 'function f () ', suffix: ' end' }; +/** Property code compiled as a returned expression (`enabled "…"`, `lua "…"`, …). */ +export const EXPRESSION_FORM: CompiledForm = { prefix: 'function f () return ', suffix: ' end' }; + /** Stable diagnostic codes. Never rename one: users may filter or suppress them. */ export const DiagnosticCode = { /** Reported by the official Lua 5.2.4 compiler. */ LuaSyntax: 'lua-syntax', /** A `` ` `` Lua block in a .menu file is never closed. */ MenuUnterminatedBlock: 'menu-unterminated-block', - /** A `"` string in a .menu file is never closed. */ + /** A `"` or `'` string in a .menu file is never closed. */ MenuUnterminatedString: 'menu-unterminated-string', + /** The character before the closing `` ` `` of a .menu Lua block is not white space; the engine drops it. */ + MenuInlineLuaLastCharacter: 'menu-inline-lua-last-character', + /** An unquoted word of 64 or more characters in a .menu file; the engine aborts. */ + MenuWordTooLong: 'menu-word-too-long', + /** `_` joined to unquoted text in a .menu file; the engine skips it and splits the text. */ + MenuUnquotedUnderscore: 'menu-unquoted-underscore', } as const; export type DiagnosticCode = (typeof DiagnosticCode)[keyof typeof DiagnosticCode]; @@ -37,4 +76,5 @@ export interface Problem { readonly end: number; readonly message: string; readonly code: DiagnosticCode; + readonly severity: 'error' | 'warning'; } diff --git a/src/server/validation/validateText.ts b/src/server/validation/validateText.ts index 67ccf48..8397ef3 100644 --- a/src/server/validation/validateText.ts +++ b/src/server/validation/validateText.ts @@ -1,12 +1,9 @@ import { luaLineRanges } from './luaLines.ts'; import { parseLuaError } from './luaError.ts'; import { extractMenuLua } from './menuExtractor.ts'; -import { DiagnosticCode, type LuaChunk, type Problem } from './types.ts'; +import { CHUNK_FORM, DiagnosticCode, type CompiledForm, type LuaChunk, type Problem } from './types.ts'; import type { Lua52Checker } from './lua52.ts'; -/** Prepended to `expression` chunks; contains no line break so line numbers are unchanged. */ -export const EXPRESSION_PREFIX = 'return '; - export type DocumentKind = 'lua' | 'menu'; /** @@ -28,44 +25,62 @@ export function documentKind(uri: string, languageId: string): DocumentKind { */ export function validateText(text: string, kind: DocumentKind, lua: Lua52Checker): Problem[] { if (kind === 'lua') { - return validateChunk({ kind: 'statements', origin: 'file', offset: 0, text }, lua); + return validateChunk({ kind: 'statements', origin: 'file', offset: 0, region: { start: 0, end: text.length }, text, forms: [CHUNK_FORM] }, lua); } const { chunks, problems } = extractMenuLua(text); return [...problems, ...chunks.flatMap((chunk) => validateChunk(chunk, lua))]; } +/** + * Compiles the chunk in each of its forms, as the engine does, and reports the + * first form that fails: one problem per chunk at most. + */ export function validateChunk(chunk: LuaChunk, lua: Lua52Checker): Problem[] { - const source = chunk.kind === 'expression' ? EXPRESSION_PREFIX + chunk.text : chunk.text; + for (const form of chunk.forms) { + const found = validateForm(chunk, form, lua); + if (found) return [found]; + } + return []; +} + +function validateForm(chunk: LuaChunk, form: CompiledForm, lua: Lua52Checker): Problem | undefined { + const source = form.prefix + chunk.text + form.suffix; const raw = lua.check(source); if (raw === undefined) { - return []; + return undefined; } + // Offsets in `source` → offsets in the chunk text, clamped into it. + const textStart = form.prefix.length; + const textEnd = textStart + chunk.text.length; + const toChunk = (offset: number): number => Math.min(Math.max(offset, textStart), textEnd) - textStart; const error = parseLuaError(raw); - const lines = luaLineRanges(chunk.text); if (!error) { // Unexpected message shape: report it verbatim on the first line of the chunk. - const first = lines[0] ?? { start: 0, end: 0 }; - return [problem(chunk, first.start, first.end, raw)]; + const first = luaLineRanges(chunk.text)[0] ?? { start: 0, end: 0 }; + return problem(chunk, first.start, first.end, raw); } - // `` errors may name the line after the last one; clamp into the chunk. - const index = Math.min(Math.max(error.line, 1), lines.length) - 1; - const line = lines[index] ?? { start: 0, end: chunk.text.length }; - const lineText = chunk.text.slice(line.start, line.end); - if (error.atEof) { - const end = chunk.text.length; - return [problem(chunk, end, end, error.message)]; + return problem(chunk, chunk.text.length, chunk.text.length, error.message); } + // `` errors may name the line after the last one; clamp into the source. + const lines = luaLineRanges(source); + const index = Math.min(Math.max(error.line, 1), lines.length) - 1; + const line = lines[index] ?? { start: 0, end: source.length }; if (error.nearToken) { // Lua reports only a line. Point at the token when it occurs exactly once on // that line; otherwise the location is ambiguous and the whole line is used. + // A token in the text the engine adds (`end`, …) maps to the edge of the chunk. + const lineText = source.slice(line.start, line.end); const first = lineText.indexOf(error.nearToken); if (first >= 0 && lineText.indexOf(error.nearToken, first + 1) < 0) { const start = line.start + first; - return [problem(chunk, start, start + error.nearToken.length, error.message)]; + const end = start + error.nearToken.length; + if (end <= textStart) return problem(chunk, 0, 0, error.message); + if (start >= textEnd) return problem(chunk, chunk.text.length, chunk.text.length, error.message); + return problem(chunk, toChunk(start), toChunk(end), error.message); } } - return [problem(chunk, line.start, line.end, error.message)]; + return problem(chunk, toChunk(line.start), toChunk(line.end), error.message); } function problem(chunk: LuaChunk, start: number, end: number, message: string): Problem { @@ -74,5 +89,6 @@ function problem(chunk: LuaChunk, start: number, end: number, message: string): end: chunk.offset + end, message, code: DiagnosticCode.LuaSyntax, + severity: 'error', }; } diff --git a/src/server/workspace/filesExclude.ts b/src/server/workspace/filesExclude.ts new file mode 100644 index 0000000..30b9146 --- /dev/null +++ b/src/server/workspace/filesExclude.ts @@ -0,0 +1,57 @@ +// The `files.exclude` setting as a predicate. Pure: no LSP or `vscode` imports. +// +// Follows how VS Code's explorer applies `files.exclude` +// (`src/vs/workbench/contrib/files/browser/views/explorerViewer.ts`, class +// FilesFilter, and `parseExpressionPattern` in `src/vs/base/common/glob.ts`, at +// tags 1.91.0 and 1.144.0): +// +// - each key is a glob pattern (see glob.ts), matched against the path relative to +// the workspace folder, with `/` separators; +// - the value `false` disables the pattern; `{ "when": "…" }` excludes a match only +// if a sibling named by `when` exists, where the first `$(basename)` stands for +// the file name without its extension; any other value enables the pattern; +// - the children of an excluded folder are excluded too (the caller does not +// descend into it). + +import { posix } from 'node:path'; +import { compileGlob } from './glob.ts'; + +/** + * `true` when `relativePath` (relative to the workspace folder, `/`-separated) is + * excluded. `hasSibling(name)` tells whether its folder contains an entry `name`. + */ +export type ExcludeFilter = (relativePath: string, hasSibling: (name: string) => boolean) => boolean; + +interface ExcludePattern { + readonly glob: RegExp; + /** The sibling clause, if any. */ + readonly when: string | undefined; +} + +/** Turns a `files.exclude` value into a filter. Anything that is not an object excludes nothing. */ +export function filesExcludeFilter(value: unknown): ExcludeFilter { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return () => false; + } + const patterns: ExcludePattern[] = []; + for (const [pattern, setting] of Object.entries(value)) { + if (setting === false) continue; + const glob = compileGlob(pattern); + if (!glob) continue; + const when: unknown = typeof setting === 'object' && setting !== null ? (setting as { when?: unknown }).when : undefined; + patterns.push({ glob, when: typeof when === 'string' ? when : undefined }); + } + if (patterns.length === 0) { + return () => false; + } + return (relativePath, hasSibling) => { + for (const { glob, when } of patterns) { + if (!glob.test(relativePath)) continue; + if (when === undefined) return true; + const base = posix.basename(relativePath); + const name = base.slice(0, base.length - posix.extname(base).length); + if (hasSibling(when.replace('$(basename)', () => name))) return true; + } + return false; + }; +} diff --git a/src/server/workspace/glob.ts b/src/server/workspace/glob.ts new file mode 100644 index 0000000..9b22393 --- /dev/null +++ b/src/server/workspace/glob.ts @@ -0,0 +1,133 @@ +// Glob patterns as VS Code matches `files.exclude`. Pure: no LSP or `vscode` imports. +// +// The semantics follow VS Code's `src/vs/base/common/glob.ts` (function +// `parseRegExp`, identical at tags 1.91.0 and 1.144.0), which also implements the +// syntax of LSP 3.17's `GlobPattern`: +// +// - the pattern is split into segments at `/` (not inside `{…}` or `[…]`); +// - a `**` segment matches any number of path segments, including none; +// - `*` matches any run of characters except a path separator, `?` exactly one; +// - `{a,b}` matches either choice; each choice is itself a pattern, and braces do not nest; +// - `[…]` matches one character of a set, `-` gives a range, `!` or `^` first negates, +// `]` first is literal and `/` is dropped; +// - `/` and `\` both separate path segments in the matched path; +// - an unterminated `{` or `[` drops the rest of its segment; a stray `}` is dropped +// and a stray `]` makes the pattern match nothing; +// - matching is case-sensitive (the explorer parses `files.exclude` without `ignoreCase`). + +const SEPARATOR = '[/\\\\]'; +const NOT_SEPARATOR = '[^/\\\\]'; + +/** Escapes what VS Code's `escapeRegExpCharacters` escapes. */ +function escape(text: string): string { + return text.replace(/[\\{}*+?|^$.[\]()]/g, '\\$&'); +} + +/** Splits at `separator` except inside `{…}` and `[…]` (which do not nest). */ +function split(pattern: string, separator: string): string[] { + const parts: string[] = []; + let inBraces = false; + let inBrackets = false; + let current = ''; + for (const c of pattern) { + if (c === separator && !inBraces && !inBrackets) { + parts.push(current); + current = ''; + continue; + } + if (c === '{') inBraces = true; + else if (c === '}') inBraces = false; + else if (c === '[') inBrackets = true; + else if (c === ']') inBrackets = false; + current += c; + } + if (current !== '') parts.push(current); + return parts; +} + +/** `**`: any number of whole segments; as the last segment also `/`. */ +function globstar(last: boolean): string { + return `(?:${SEPARATOR}|${NOT_SEPARATOR}+${SEPARATOR}${last ? `|${SEPARATOR}${NOT_SEPARATOR}+` : ''})*?`; +} + +/** One segment without `/` (except inside braces, whose choices are whole patterns). */ +function segmentSource(segment: string): string { + let source = ''; + let braces: string | undefined; + let brackets: string | undefined; + for (const c of segment) { + if (braces !== undefined) { + if (c === '}') { + source += `(?:${split(braces, ',').map(patternSource).join('|')})`; + braces = undefined; + } else { + braces += c; + } + } else if (brackets !== undefined) { + if (c === ']' && brackets !== '') { + source += `[${brackets}]`; + brackets = undefined; + } else if (c === '-') { + brackets += c; + } else if ((c === '!' || c === '^') && brackets === '') { + brackets = '^'; + } else if (c !== '/') { + brackets += escape(c); + } + } else if (c === '{') { + braces = ''; + } else if (c === '[') { + brackets = ''; + } else if (c === '}') { + // A `}` outside braces closes an empty choice list: it matches the empty string. + source += '(?:)'; + } else if (c === ']') { + // A `]` outside brackets closes an empty set, which matches nothing. + source += '[]'; + } else if (c === '?') { + source += NOT_SEPARATOR; + } else if (c === '*') { + source += `${NOT_SEPARATOR}*?`; + } else { + source += escape(c); + } + } + return source; +} + +function patternSource(pattern: string): string { + const segments = split(pattern, '/'); + if (segments.length > 0 && segments.every((segment) => segment === '**')) { + return '.*'; + } + let source = ''; + segments.forEach((segment, index) => { + if (segment === '**') { + // Consecutive globstars act as one. + if (segments[index - 1] !== '**') source += globstar(index === segments.length - 1); + return; + } + source += segmentSource(segment); + // A separator follows unless the rest of the pattern is a single trailing `**`. + const next = segments[index + 1]; + if (next !== undefined && (next !== '**' || index + 2 < segments.length)) { + source += SEPARATOR; + } + }); + return source; +} + +/** + * Compiles a glob pattern. Returns `undefined` for a pattern that matches + * nothing: empty after trimming, or not a valid regular expression once + * translated (VS Code treats both the same way). + */ +export function compileGlob(pattern: string): RegExp | undefined { + const trimmed = pattern.trim(); + if (trimmed === '') return undefined; + try { + return new RegExp(`^${patternSource(trimmed)}$`); + } catch { + return undefined; + } +} diff --git a/src/server/workspace/nodeFileSystem.ts b/src/server/workspace/nodeFileSystem.ts new file mode 100644 index 0000000..06790c0 --- /dev/null +++ b/src/server/workspace/nodeFileSystem.ts @@ -0,0 +1,17 @@ +// The real file system for the workspace index (Node `fs`). +import { readdir, readFile } from 'node:fs/promises'; +import type { DirectoryEntry, WorkspaceFileSystem } from './workspaceIndex.ts'; + +export const nodeFileSystem: WorkspaceFileSystem = { + async readDirectory(path: string): Promise { + // `withFileTypes` reports a symbolic link as such (lstat semantics), without following it. + const entries = await readdir(path, { withFileTypes: true }); + return entries.map((entry) => ({ + name: entry.name, + kind: entry.isSymbolicLink() ? 'symlink' : entry.isDirectory() ? 'directory' : entry.isFile() ? 'file' : 'other', + })); + }, + readFile(path: string): Promise { + return readFile(path); + }, +}; diff --git a/src/server/workspace/workspaceIndex.ts b/src/server/workspace/workspaceIndex.ts new file mode 100644 index 0000000..a355705 --- /dev/null +++ b/src/server/workspace/workspaceIndex.ts @@ -0,0 +1,299 @@ +// Index of the Lua and .menu files in the workspace folders, for workspace-wide +// features. No LSP connection: the file system, the per-file analysis, the +// `files.exclude` lookup and the event-loop yield are injected, so the index can be +// unit-tested with an in-memory file system. + +import { fileURLToPath } from 'node:url'; +import { filesExcludeFilter, type ExcludeFilter } from './filesExclude.ts'; + +/** An entry of a directory listing. Symbolic links are reported as such, not followed. */ +export interface DirectoryEntry { + readonly name: string; + readonly kind: 'file' | 'directory' | 'symlink' | 'other'; +} + +/** The file system, by native path. */ +export interface WorkspaceFileSystem { + readDirectory(path: string): Promise; + readFile(path: string): Promise; +} + +export interface WorkspaceIndexDeps { + readonly fs: WorkspaceFileSystem; + /** Native path functions (`node:path` in the server; `posix` in tests). */ + readonly path: { + readonly sep: string; + join(...parts: string[]): string; + dirname(path: string): string; + basename(path: string): string; + relative(from: string, to: string): string; + }; + /** `fileURLToPath` for `file:` URIs (injectable for tests of other platforms). */ + readonly toPath?: (uri: string) => string; + /** What the index keeps for one file, from its text. */ + analyze(text: string, uri: string): T; + /** The `files.exclude` value for a workspace folder (`undefined` when the client has none). */ + filesExclude(folderUri: string): Promise; + /** Lets other events run between files, so a large workspace never blocks the server. */ + yieldToEventLoop(): Promise; + log(message: string): void; +} + +export interface IndexedFile { + readonly uri: string; + /** The normalized native path (see `pathKey`). */ + readonly key: string; + readonly value: T; +} + +/** Lua files and .menu files, in any letter case, as `documentKind` recognizes them. */ +export function isIndexedFileName(name: string): boolean { + return /\.(?:lua|menu)$/i.test(name); +} + +interface Folder { + readonly uri: string; + readonly path: string; + readonly key: string; + excluded: ExcludeFilter; + /** The `files.exclude` value `excluded` was built from, as JSON. */ + excludeJson: string | undefined; +} + +const decoder = new TextDecoder('utf-8'); + +/** + * The index. Scans happen in the background, one file per macrotask; `ready()` + * resolves once the work queued so far is done. Never rejects: failures are + * logged and the file is left out. + */ +export class WorkspaceIndex { + private readonly deps: WorkspaceIndexDeps; + private readonly toPath: (uri: string) => string; + private folders: Folder[] = []; + private readonly files = new Map>(); + /** Incremented by every full rescan; a scan of an older generation stops. */ + private generation = 0; + private tail: Promise = Promise.resolve(); + + constructor(deps: WorkspaceIndexDeps) { + this.deps = deps; + this.toPath = deps.toPath ?? ((uri) => fileURLToPath(uri)); + } + + /** The key of a `file:` URI: its native path, with a Windows drive letter in lower case. */ + pathKey(uri: string): string | undefined { + if (!uri.startsWith('file:')) return undefined; + try { + return normalizeKey(this.toPath(uri)); + } catch { + return undefined; + } + } + + /** Replaces the workspace folders and rescans them. Only `file:` folders are scanned. */ + setFolders(folderUris: readonly string[]): void { + const folders: Folder[] = []; + for (const uri of folderUris) { + const key = this.pathKey(uri); + if (key === undefined) { + this.deps.log(`Workspace folder ${uri} is not on the local file system; only its open documents are indexed.`); + continue; + } + folders.push({ uri: uri.replace(/\/+$/, ''), path: this.toPath(uri), key, excluded: () => false, excludeJson: undefined }); + } + this.folders = folders; + this.rescan(); + } + + /** Rescans every folder, re-reading `files.exclude` (call when it changes). */ + rescan(): void { + const generation = ++this.generation; + this.enqueue(() => this.scan(generation)); + } + + /** Walks every folder and indexes what it finds, unless a newer scan starts meanwhile. */ + private async scan(generation: number): Promise { + const started = Date.now(); + const found: { folder: Folder; path: string }[] = []; + for (const folder of this.folders) { + const value = await this.deps.filesExclude(folder.uri); + folder.excluded = filesExcludeFilter(value); + folder.excludeJson = JSON.stringify(value ?? null); + await this.walk(folder, folder.path, found, generation); + if (generation !== this.generation) return; + } + this.files.clear(); + for (const { folder, path } of found) { + await this.deps.yieldToEventLoop(); + if (generation !== this.generation) return; + await this.indexFile(folder, path); + } + this.deps.log(`Indexed ${this.files.size} Lua and .menu files in ${Date.now() - started} ms.`); + } + + /** + * Settings changed: re-reads `files.exclude` and rescans if it changed for any + * folder. Clients notify every settings change, so this avoids needless rescans. + */ + settingsChanged(): void { + this.enqueue(async () => { + let changed = false; + for (const folder of this.folders) { + if (JSON.stringify((await this.deps.filesExclude(folder.uri)) ?? null) !== folder.excludeJson) changed = true; + } + // Scan within this job, so that `ready()` callers waiting for it see the result. + if (changed) await this.scan(++this.generation); + }); + } + + /** + * A file was created or changed on disk, or closed in the editor: index it + * again. A created folder (for example one moved into the workspace) has its + * files indexed. + */ + fileChanged(uri: string): void { + this.enqueue(async () => { + const key = this.pathKey(uri); + const folder = key === undefined ? undefined : this.folderOf(key); + if (key === undefined || !folder) return; + const path = this.toPath(uri); + if (isIndexedFileName(this.deps.path.basename(path))) { + // The previous entry stays until the new one is ready, so the file never drops out meanwhile. + if ((await this.isExcluded(folder, path)) || !(await this.indexFile(folder, path))) this.files.delete(key); + return; + } + if (!(await this.isDirectory(path)) || (await this.isExcluded(folder, path))) return; + const generation = this.generation; + const found: { folder: Folder; path: string }[] = []; + await this.walk(folder, path, found, generation); + for (const file of found) { + await this.deps.yieldToEventLoop(); + if (generation !== this.generation) return; + await this.indexFile(file.folder, file.path); + } + }); + } + + /** A file or folder was deleted: drop it and everything under it. */ + fileDeleted(uri: string): void { + this.enqueue(() => { + const key = this.pathKey(uri); + if (key === undefined) return Promise.resolve(); + const prefix = key.endsWith(this.deps.path.sep) ? key : key + this.deps.path.sep; + for (const indexed of [...this.files.keys()]) { + if (indexed === key || indexed.startsWith(prefix)) this.files.delete(indexed); + } + return Promise.resolve(); + }); + } + + /** + * Resolves when the work queued before the call is done. Work queued later is + * not waited for, so a stream of file events cannot hold a request up. + */ + ready(): Promise { + return this.tail; + } + + /** The indexed files, in no particular order. */ + entries(): IterableIterator> { + return this.files.values(); + } + + private enqueue(work: () => Promise): void { + this.tail = this.tail.then(work).catch((error: unknown) => { + this.deps.log(`Workspace indexing failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + }); + } + + /** The innermost workspace folder containing `key`. */ + private folderOf(key: string): Folder | undefined { + let best: Folder | undefined; + for (const folder of this.folders) { + const prefix = folder.key.endsWith(this.deps.path.sep) ? folder.key : folder.key + this.deps.path.sep; + if (key.startsWith(prefix) && (!best || folder.key.length > best.key.length)) best = folder; + } + return best; + } + + private relative(folder: Folder, path: string): string { + return this.deps.path.relative(folder.path, path).split(this.deps.path.sep).join('/'); + } + + private async listing(directory: string): Promise { + try { + return await this.deps.fs.readDirectory(directory); + } catch (error) { + this.deps.log(`Cannot list ${directory}: ${error instanceof Error ? error.message : String(error)}`); + return undefined; + } + } + + /** Collects the files to index under `directory`, depth first, in listing order. */ + private async walk(folder: Folder, directory: string, found: { folder: Folder; path: string }[], generation: number): Promise { + const entries = await this.listing(directory); + if (!entries || generation !== this.generation) return; + const names = new Set(entries.map((entry) => entry.name)); + const hasSibling = (name: string): boolean => names.has(name); + for (const entry of entries) { + const path = this.deps.path.join(directory, entry.name); + if (folder.excluded(this.relative(folder, path), hasSibling)) continue; + if (entry.kind === 'directory') { + await this.walk(folder, path, found, generation); + if (generation !== this.generation) return; + } else if ((entry.kind === 'file' || entry.kind === 'symlink') && isIndexedFileName(entry.name)) { + // A symbolic link is read (which follows it) but never descended into, so links cannot loop. + found.push({ folder, path }); + } + } + } + + private async isDirectory(path: string): Promise { + try { + await this.deps.fs.readDirectory(path); + return true; + } catch { + // Not a directory (or gone): nothing to index. + return false; + } + } + + /** Whether `path` or one of its folders below the workspace folder is excluded. */ + private async isExcluded(folder: Folder, path: string): Promise { + let current = path; + while (current !== folder.path && current.length > folder.path.length) { + const parent = this.deps.path.dirname(current); + const names = new Set((await this.listing(parent))?.map((entry) => entry.name)); + if (folder.excluded(this.relative(folder, current), (name) => names.has(name))) return true; + current = parent; + } + return false; + } + + /** Reads and analyzes a file; `false` when it cannot be read. */ + private async indexFile(folder: Folder, path: string): Promise { + let bytes: Uint8Array; + try { + bytes = await this.deps.fs.readFile(path); + } catch (error) { + // A file deleted meanwhile (or a closed document whose file is gone) is simply not indexed. + if (!isNotFound(error)) this.deps.log(`Cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`); + return false; + } + const relative = this.relative(folder, path); + const uri = `${folder.uri}/${relative.split('/').map(encodeURIComponent).join('/')}`; + // UTF-8, with a byte order mark removed and invalid bytes replaced, as VS Code opens files by default. + const value = this.deps.analyze(decoder.decode(bytes), uri); + this.files.set(normalizeKey(path), { uri, key: normalizeKey(path), value }); + return true; + } +} + +function isNotFound(error: unknown): boolean { + return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'ENOENT'; +} + +function normalizeKey(path: string): string { + return path.replace(/^([A-Z]):/, (_, drive: string) => `${drive.toLowerCase()}:`); +} diff --git a/syntaxes/ie-menu.tmLanguage.json b/syntaxes/ie-menu.tmLanguage.json index 788fbf9..5921a56 100644 --- a/syntaxes/ie-menu.tmLanguage.json +++ b/syntaxes/ie-menu.tmLanguage.json @@ -2,17 +2,16 @@ "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", "name": "Infinity Engine Menu", "scopeName": "source.ie-menu", - "comment": "Lua regions mirror src/server/validation/menuExtractor.ts: `…` blocks, lua \"…\", and the action*/onOpen/onClose/enabled properties. Element keywords are those used in the game's UI.MENU.", + "comment": "Approximates src/server/validation/menuLexer.ts and menuExtractor.ts, which follow the engine's lexer and its list of Lua properties as described by IESDP (menu_v1.htm). TextMate matches regular expressions rather than the engine's tokens, so a Lua property is only recognized when white space and comments alone separate it from its string, and unquoted Lua words are not highlighted as Lua. test/unit/syntaxes/ieMenuGrammar.test.ts checks the keyword, element and Lua property lists against the TypeScript sources.", "patterns": [ { "include": "#comment" }, { "include": "#lua-block" }, { "include": "#lua-property" }, - { "include": "#lua-expression" }, { "include": "#element" }, + { "include": "#keyword" }, { "include": "#string-double" }, { "include": "#string-single" }, - { "include": "#number" }, - { "include": "#property" } + { "include": "#number" } ], "repository": { "comment": { @@ -28,21 +27,22 @@ "patterns": [{ "include": "source.lua" }] }, "lua-property": { - "begin": "(?i)^\\s*(action(?:alt|dbl|drag|enter|exit|hold|scroll|simpledrag|simpledrop|update)?|onopen|onclose|enabled)\\b", - "beginCaptures": { "1": { "name": "keyword.other.property.ie-menu" } }, - "end": "(?<=\")", + "comment": "Statement properties, expression properties, the slot shorthands, bitmap res and lua, up to the string that follows them.", + "begin": "(?i)\\b(?:(bitmap)\\s+(res)|(onopen|onclose|action|actionalt|actiondbl|actionenter|actionexit|actionUpdate|actionsimpledrag|actionsimpledrop|actionHold|actionScroll|enabled|actiondrag|table|seperator|useOverlayTint|slotinfo|spellInfo|memorizedSpellInfo)|(lua))\\b", + "beginCaptures": { + "1": { "name": "variable.other.property.ie-menu" }, + "2": { "name": "keyword.other.property.ie-menu" }, + "3": { "name": "keyword.other.property.ie-menu" }, + "4": { "name": "storage.modifier.lua.ie-menu" } + }, + "end": "(?<=[\"'])|(?=[^\\s\"'-]|-(?!-))", "patterns": [ { "include": "#comment" }, - { "include": "#lua-string" } + { "include": "#lua-string-double" }, + { "include": "#lua-string-single" } ] }, - "lua-expression": { - "begin": "\\b(lua)\\s*(?=\")", - "beginCaptures": { "1": { "name": "storage.modifier.lua.ie-menu" } }, - "end": "(?<=\")", - "patterns": [{ "include": "#lua-string" }] - }, - "lua-string": { + "lua-string-double": { "begin": "\"", "end": "\"", "beginCaptures": { "0": { "name": "punctuation.section.embedded.begin.ie-menu" } }, @@ -50,10 +50,24 @@ "contentName": "meta.embedded.inline.lua", "patterns": [{ "include": "source.lua" }] }, + "lua-string-single": { + "begin": "'", + "end": "'", + "beginCaptures": { "0": { "name": "punctuation.section.embedded.begin.ie-menu" } }, + "endCaptures": { "0": { "name": "punctuation.section.embedded.end.ie-menu" } }, + "contentName": "meta.embedded.inline.lua", + "patterns": [{ "include": "source.lua" }] + }, "element": { - "match": "^\\s*(button|column|edit|handle|label|list|map|menu|movie|slider|template|text)\\s*$", + "comment": "Item types and menu/column, when a block follows.", + "match": "(?i)\\b(menu|label|text|button|list|edit|movie|slider|handle|slot|map|template|column)\\b(?=\\s*(?:\\{|$))", "captures": { "1": { "name": "storage.type.element.ie-menu" } } }, + "keyword": { + "comment": "The 122 keywords of the engine (src/server/validation/menuKeywords.ts).", + "match": "(?i)\\b(?:action|actionalt|actionbar|actiondbl|actiondrag|actionenter|actionexit|actionHold|actionScroll|actionsimpledrag|actionsimpledrop|actionUpdate|align|area|areamap|background|bam|bitmap|bottom|button|center|clickable|clunkyScroll|color|colordisplay|column|count|dynamic|edit|enabled|encumbrance|fill|font|force|frame|frameTimes|full|func|glow|greyscale|handle|hide|hidehighlight|highlight|highlightgroup|icon|ignoreEsc|ignoreEvents|label|left|list|loop|lower|lua|map|maxchars|maxlines|memorizedSpellInfo|menu|modal|mosaic|movie|name|offset|on|onclose|onopen|opacity|overlayTint|pad|palette|panel|paperdoll|placeholder|point|portrait|position|progressbar|pulse|queuedMovie|rectangle|res|respectClipping|respectConstraints|right|rowbackground|rowheight|rowwidth|scaleToClip|scrollbar|seperator|sequence|sequenceonce|settings|shadow|size|skipReset|slider|sliderBackground|slot|slotinfo|sound|spellInfo|state|style|subtitle|table|template|text|tint|toggle|tooltip|top|transparent|upper|usages|usealpha|useFontZoom|useOverlayTint|var|width|worldmap)\\b", + "name": "variable.other.property.ie-menu" + }, "string-double": { "begin": "\"", "end": "\"", @@ -65,12 +79,8 @@ "name": "string.quoted.single.ie-menu" }, "number": { - "match": "(? { assert.equal(diagnostics[0]?.range.start.line, 6); }); + test('validateDocument checks .menu Lua as the engine compiles and reads it', async () => { + const uri = fixtureUri('MISREAD.MENU'); + await vscode.window.showTextDocument(await vscode.workspace.openTextDocument(uri)); + await vscode.commands.executeCommand('ieLua.validateDocument', uri); + const diagnostics = await waitForDiagnostics(uri, (found) => found.length === 2); + assert.deepEqual( + diagnostics + .map((d) => [d.code, d.severity, d.range.start.line, d.range.start.character]) + .sort((a, b) => Number(a[2]) - Number(b[2])), + [ + // The engine drops the `e` before the closing backtick. + ['menu-inline-lua-last-character', vscode.DiagnosticSeverity.Warning, 2, 18], + // `action` code is compiled as the body of a function that is not vararg. + ['lua-syntax', vscode.DiagnosticSeverity.Error, 8, 31], + ], + ); + }); + test('"type" mode validates while editing', async () => { const restore = await withSetting('validate.mode', 'type'); try { diff --git a/test/integration/helpers.ts b/test/integration/helpers.ts index 1ec1aa6..4c9d065 100644 --- a/test/integration/helpers.ts +++ b/test/integration/helpers.ts @@ -71,3 +71,21 @@ export async function openFixture(file: string): Promise { await vscode.window.showTextDocument(await vscode.workspace.openTextDocument(uri)); return uri; } + +/** + * Resolves with the workspace symbols for `query` as soon as `predicate` accepts + * them. The server answers only after the file events it has received are indexed, + * so this asks again until the client has delivered them; the Mocha test timeout + * bounds the wait instead of a fixed sleep. + */ +export async function waitForWorkspaceSymbols( + query: string, + predicate: (symbols: vscode.SymbolInformation[]) => boolean, +): Promise { + for (;;) { + const symbols = await vscode.commands.executeCommand('vscode.executeWorkspaceSymbolProvider', query); + if (predicate(symbols)) return symbols; + // Let pending events (the client's file-event batch) run before asking again. + await new Promise((resolve) => setImmediate(resolve)); + } +} diff --git a/test/integration/workspaceSymbols.test.ts b/test/integration/workspaceSymbols.test.ts new file mode 100644 index 0000000..b206b42 --- /dev/null +++ b/test/integration/workspaceSymbols.test.ts @@ -0,0 +1,84 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, fixtureUri, openFixture, waitForWorkspaceSymbols } from './helpers.ts'; + +const encoder = new TextEncoder(); +const names = (symbols: readonly vscode.SymbolInformation[]): string[] => symbols.map((s) => s.name); +const has = (name: string) => (symbols: readonly vscode.SymbolInformation[]): boolean => names(symbols).includes(name); +const lacks = (name: string) => (symbols: readonly vscode.SymbolInformation[]): boolean => !names(symbols).includes(name); + +suite('Workspace symbols', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('finds symbols in files that were never opened', async () => { + const symbols = await waitForWorkspaceSymbols('fixtureNeverOpened', has('fixtureNeverOpened')); + const found = symbols.find((s) => s.name === 'fixtureNeverOpened'); + assert.ok(found); + assert.equal(found.location.uri.toString(), fixtureUri('symbols', 'never-opened.lua').toString()); + assert.equal(found.location.range.start.line, 1); + assert.equal(found.kind, vscode.SymbolKind.Function); + }); + + test('finds the menus of .MENU files by name, and the Lua symbols in them', async () => { + const menu = fixtureUri('OUTLINE.MENU').toString(); + const inMenu = (found: readonly vscode.SymbolInformation[]): string[] => + found.filter((s) => s.location.uri.toString() === menu).map((s) => `${vscode.SymbolKind[s.kind]} ${s.name}`); + const symbols = await waitForWorkspaceSymbols('', (found) => inMenu(found).length > 0); + // VS Code orders workspace symbols itself, so compare them sorted. + assert.deepEqual(inMenu(symbols).sort(), ['Function helper', 'Namespace OUTLINE_MAIN']); + }); + + test('matches the query loosely: its characters in order, in any case', async () => { + const symbols = await waitForWorkspaceSymbols('fxnvropnd', has('fixtureNeverOpened')); + assert.ok(!names(symbols).includes('fixtureExcludedSymbol')); + }); + + test('uses the unsaved text of open documents', async () => { + const uri = await openFixture('symbols/never-opened.lua'); + const editor = vscode.window.activeTextEditor; + assert.ok(editor && editor.document.uri.toString() === uri.toString()); + await editor.edit((edit) => { + edit.insert(new vscode.Position(3, 0), 'function fixtureUnsavedEdit()\nend\n'); + }); + await waitForWorkspaceSymbols('fixtureUnsavedEdit', has('fixtureUnsavedEdit')); + await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor'); + // Closing re-reads the saved file, which never had the edit. + await waitForWorkspaceSymbols('fixtureUnsavedEdit', lacks('fixtureUnsavedEdit')); + }); + + test('indexes .lua and .MENU files created and deleted outside the editor', async () => { + const folder = fixtureUri('.tmp'); + const lua = vscode.Uri.joinPath(folder, 'created.lua'); + const menu = vscode.Uri.joinPath(folder, 'CREATED.MENU'); + await vscode.workspace.fs.createDirectory(folder); + try { + await vscode.workspace.fs.writeFile(lua, encoder.encode('function fixtureCreatedLua()\nend\n')); + await vscode.workspace.fs.writeFile(menu, encoder.encode('`\nfunction fixtureCreatedMenu() end\n`\n')); + await waitForWorkspaceSymbols('fixtureCreated', (found) => has('fixtureCreatedLua')(found) && has('fixtureCreatedMenu')(found)); + await vscode.workspace.fs.delete(lua); + await waitForWorkspaceSymbols('fixtureCreated', lacks('fixtureCreatedLua')); + } finally { + await vscode.workspace.fs.delete(folder, { recursive: true }); + } + await waitForWorkspaceSymbols('fixtureCreated', lacks('fixtureCreatedMenu')); + }); + + test('honors files.exclude, and follows changes to it', async () => { + await waitForWorkspaceSymbols('fixtureExcludedSymbol', has('fixtureExcludedSymbol')); + const files = vscode.workspace.getConfiguration('files'); + const previous = files.inspect('exclude')?.workspaceValue; + await files.update('exclude', { '**/excluded': true }, vscode.ConfigurationTarget.Workspace); + try { + await waitForWorkspaceSymbols('fixtureExcludedSymbol', lacks('fixtureExcludedSymbol')); + } finally { + await vscode.workspace.getConfiguration('files').update('exclude', previous, vscode.ConfigurationTarget.Workspace); + } + await waitForWorkspaceSymbols('fixtureExcludedSymbol', has('fixtureExcludedSymbol')); + }); +}); diff --git a/test/unit/server/features/workspaceSymbols.test.ts b/test/unit/server/features/workspaceSymbols.test.ts new file mode 100644 index 0000000..18b2687 --- /dev/null +++ b/test/unit/server/features/workspaceSymbols.test.ts @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import type { SymbolInformation } from 'vscode-languageserver/node'; +import { collectWorkspaceSymbols, fileSymbols, type SymbolSource } from '../../../../src/server/features/workspaceSymbols.ts'; + +const symbol = (name: string, uri: string): SymbolInformation => ({ + name, + kind: 12, + location: { uri, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 1 } } }, +}); + +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')] }, + ]; + const names = (query: string): string[] | undefined => collectWorkspaceSymbols(open, indexed, query, () => false)?.map((s) => s.name); + assert.deepEqual(names(''), ['openVersion', 'other', 'version']); + assert.deepEqual(names('ver'), ['openVersion', 'version']); + }); + + it('stops when cancelled', () => { + let calls = 0; + const result = collectWorkspaceSymbols([], [{ uri: 'file:///w/a.lua', key: '/w/a.lua', value: [] }], '', () => ++calls > 0); + assert.equal(result, undefined); + }); +}); diff --git a/test/unit/server/syntax/differential.test.ts b/test/unit/server/syntax/differential.test.ts index 0ae3a00..cb4231e 100644 --- a/test/unit/server/syntax/differential.test.ts +++ b/test/unit/server/syntax/differential.test.ts @@ -117,4 +117,46 @@ describe('server/syntax/parser agrees with the official Lua 5.2.4 compiler', () // The mutations must exercise both outcomes to be meaningful. assert.ok(rejected > 400, `only ${rejected} mutants were invalid`); }); + + it('on expression chunks at the nesting limit, where the implied return is a statement level', () => { + for (let depth = 196; depth <= 200; depth++) { + const code = `${'('.repeat(depth)}1${')'.repeat(depth)}`; + const official = lua.check(`return ${code}`); + assert.equal(parseChunk(code, { mode: 'expression' }).errors.length === 0, official === undefined, `depth ${depth}: ${official ?? 'accepted'}`); + } + }); + + // .menu property code: the engine compiles `function f () end` (statements) + // or `function f () return end` (expressions); see CompiledForm. + describe('on .menu property code, against the form the engine compiles', () => { + const agreeAsBody = (code: string, mode: 'statements' | 'expression'): void => { + const official = lua.check(`function f () ${mode === 'expression' ? 'return ' : ''}${code} end`); + const ours = parseChunk(code, { mode, functionBody: true }).errors; + assert.equal(ours.length === 0, official === undefined, `${mode} ${JSON.stringify(code)}\n official: ${official ?? 'accepted'}\n parser: ${JSON.stringify(ours)}`); + }; + + it('on the fixed corpus and the seeds, as statements', () => { + for (const code of [...CORPUS, ...SEEDS]) agreeAsBody(code, 'statements'); + }); + + it('on expressions', () => { + for (const code of ['a', 'a, b', 'f(...)', '...', 'a; b', 'a = 1', 'function() end', '(a)', 'a b', '', 'x == 1 and not y']) { + agreeAsBody(code, 'expression'); + } + }); + + it('on 1,600 deterministic token mutations of the seeds, as statements', () => { + SEEDS.forEach((seed, index) => { + for (const mutant of mutations(seed, 400, index + 1)) agreeAsBody(mutant, 'statements'); + }); + }); + + it('at the nesting limit, which the enclosing function statement lowers by one level', () => { + for (let depth = 196; depth <= 200; depth++) { + agreeAsBody(`${'do '.repeat(depth)}${'end '.repeat(depth)}`, 'statements'); + agreeAsBody(`${'('.repeat(depth)}1${')'.repeat(depth)}`, 'expression'); + agreeAsBody(`x = ${'('.repeat(depth)}1${')'.repeat(depth)}`, 'statements'); + } + }); + }); }); diff --git a/test/unit/server/syntax/workspaceSymbols.test.ts b/test/unit/server/syntax/workspaceSymbols.test.ts new file mode 100644 index 0000000..aeaecf8 --- /dev/null +++ b/test/unit/server/syntax/workspaceSymbols.test.ts @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict'; +import { matchesQuery } from '../../../../src/server/syntax/workspaceSymbols.ts'; + +describe('server/syntax/workspaceSymbols matchesQuery', () => { + it('matches everything for an empty query', () => { + assert.equal(matchesQuery('anything', ''), true); + }); + + it('matches the characters of the query in order, case-insensitively', () => { + assert.equal(matchesQuery('Infinity_PushMenu', 'ipm'), true); + assert.equal(matchesQuery('Infinity_PushMenu', 'PUSH'), true); + assert.equal(matchesQuery('Infinity_PushMenu', 'mpi'), false); + assert.equal(matchesQuery('abc', 'abcd'), false); + }); + + it('does not reuse a character of the name for two characters of the query', () => { + assert.equal(matchesQuery('ab', 'aa'), false); + assert.equal(matchesQuery('aab', 'aa'), true); + }); +}); diff --git a/test/unit/server/validation/menuExtractor.test.ts b/test/unit/server/validation/menuExtractor.test.ts index b8ca0ca..c6456d2 100644 --- a/test/unit/server/validation/menuExtractor.test.ts +++ b/test/unit/server/validation/menuExtractor.test.ts @@ -11,10 +11,10 @@ function chunksOf(menu: string): [string, string][] { } describe('server/validation/menuExtractor', () => { - it('extracts top-level backtick blocks as statements', () => { + it('extracts backtick blocks without their last character, which the engine drops', () => { assert.deepEqual(chunksOf('`\nlocal x = 1\n`\nmenu\n{\n}\n`y = 2`'), [ - ['statements', '\nlocal x = 1\n'], - ['statements', 'y = 2'], + ['statements', '\nlocal x = 1'], + ['statements', 'y = '], ]); }); @@ -60,6 +60,59 @@ describe('server/validation/menuExtractor', () => { assert.deepEqual(chunksOf('action\r\n"\r\n\tx()\r\n"'), [['statements', '\r\n\tx()\r\n']]); }); + it('extracts Lua from single-quoted strings like double-quoted ones', () => { + assert.deepEqual(chunksOf("action 'Close()'\nbam lua 'getBam()'\nenabled 'a == 1'"), [ + ['statements', 'Close()'], + ['expression', 'getBam()'], + ['expression', 'a == 1'], + ]); + }); + + it('extracts unquoted words that are not keywords, which the engine reads as strings', () => { + assert.deepEqual(chunksOf('table characterDetails\nenabled\tcurrentSave\ntext lua someName'), [ + ['expression', 'characterDetails'], + ['expression', 'currentSave'], + ['expression', 'someName'], + ]); + }); + + it('extracts table, seperator, useOverlayTint, actiondrag and bitmap res as expressions', () => { + assert.deepEqual( + chunksOf('table "rows"\nseperator "sep()"\nuseOverlayTint "tint"\nactionDrag "drag()"\nbitmap res "resName()"'), + [ + ['expression', 'rows'], + ['expression', 'sep()'], + ['expression', 'tint'], + ['expression', 'drag()'], + ['expression', 'resName()'], + ], + ); + }); + + it('extracts res only after bitmap', () => { + assert.deepEqual(chunksOf('res "x"\nbitmap "y"'), []); + }); + + it('finds properties anywhere on a line, since the grammar ignores line breaks', () => { + assert.deepEqual(chunksOf('button { name "B" area 0 0 10 10 action "f()" enabled "g()" }'), [ + ['statements', 'f()'], + ['expression', 'g()'], + ]); + }); + + it('keeps a property and its string together across inline Lua, which produces no token', () => { + assert.deepEqual(chunksOf('action `x = 1\n` "f()"'), [ + ['statements', 'x = 1'], + ['statements', 'f()'], + ]); + }); + + it('does not validate an unterminated string, which runs to the end of the file', () => { + const { chunks, problems } = extractMenuLua("action 'f()\n"); + assert.deepEqual(chunks, []); + assert.deepEqual(problems.map((p) => p.code), ['menu-unterminated-string']); + }); + it('reports an unterminated backtick block', () => { const { chunks, problems } = extractMenuLua('menu\n{\n}\n`\nlocal x = 1\n'); assert.deepEqual(chunks, []); @@ -84,6 +137,10 @@ describe('server/validation/menuExtractor', () => { assert.equal(outline(extractMenuLua(menu).blocks), 'menu(MAIN)[button label] menu'); }); + it('names blocks written on one line, and takes unquoted names', () => { + assert.equal(outline(extractMenuLua('menu { name MAIN button { name "B" area 0 0 1 1 } }').blocks), 'menu(MAIN)[button(B)]'); + }); + it('records the offsets of the keyword, the braces and the name', () => { const menu = 'menu\n{\n\tname "M"\n}'; const [block] = extractMenuLua(menu).blocks; @@ -109,6 +166,41 @@ describe('server/validation/menuExtractor', () => { }); }); + it('keeps an empty backtick block empty', () => { + assert.deepEqual(chunksOf('``'), [['statements', '']]); + }); + + it('records the region of each chunk, delimiters included', () => { + const menu = '`a()\n` action "b()" table rows'; + assert.deepEqual(extractMenuLua(menu).chunks.map((c) => menu.slice(c.region.start, c.region.end)), ['`a()\n`', '"b()"', 'rows']); + }); + + it('compiles statement properties as a function body and expressions as its return value', () => { + assert.deepEqual(extractMenuLua('`x` action "a()" enabled "b"').chunks.map((c) => c.forms), [ + [{ prefix: '', suffix: '' }], + [{ prefix: 'function f () ', suffix: ' end' }], + [{ prefix: 'function f () return ', suffix: ' end' }], + ]); + }); + + it('extracts slotinfo, spellInfo and memorizedSpellInfo strings as expressions with the forms the engine generates', () => { + const { chunks } = extractMenuLua('slotinfo "T" spellInfo "T" memorizedSpellInfo "T"'); + assert.deepEqual(chunks.map((c) => [c.kind, c.text, c.forms.length]), [ + ['expression', 'T', 10], + ['expression', 'T', 6], + ['expression', 'T', 6], + ]); + assert.deepEqual(chunks[0]?.forms.map((f) => `${f.prefix}T${f.suffix}`).slice(-3), [ + 'function f () return Infinity_SwapSlot(T.id) end', + 'function f () showItemDescriptionInventory(T.slotName) end', + 'function f () slotDoubleClick(T.slotName) end', + ]); + assert.deepEqual(chunks[2]?.forms.map((f) => `${f.prefix}T${f.suffix}`).slice(-2), [ + 'function f () return unmemorizeSpell(T) end', + 'function f () showSpellDetails(T, true) end', + ]); + }); + it('tells backtick blocks from property values', () => { assert.deepEqual(extractMenuLua('`a()`\naction "b()"').chunks.map((c) => c.origin), ['block', 'property']); }); diff --git a/test/unit/server/validation/menuLexer.test.ts b/test/unit/server/validation/menuLexer.test.ts new file mode 100644 index 0000000..450159d --- /dev/null +++ b/test/unit/server/validation/menuLexer.test.ts @@ -0,0 +1,101 @@ +import assert from 'node:assert/strict'; +import { menuKeyword, MENU_KEYWORDS } from '../../../../src/server/validation/menuKeywords.ts'; +import { lexMenu } from '../../../../src/server/validation/menuLexer.ts'; + +/** `type:value` per token, where value is the token's value text. */ +function tokens(text: string): string[] { + return lexMenu(text).tokens.map((t) => `${t.keyword === undefined ? t.type : `kw`}:${text.slice(t.valueStart, t.valueEnd)}`); +} + +describe('server/validation/menuKeywords', () => { + it('has the 122 distinct keywords of the engine table', () => { + assert.equal(MENU_KEYWORDS.length, 122); + assert.equal(new Set(MENU_KEYWORDS.map((k) => k.toLowerCase())).size, 122); + }); + + it('matches keywords case-insensitively and returns them in lower case', () => { + assert.equal(menuKeyword('ActionUpdate'), 'actionupdate'); + assert.equal(menuKeyword('MENU'), 'menu'); + assert.equal(menuKeyword('characterDetails'), undefined); + }); +}); + +describe('server/validation/menuLexer', () => { + it('reads keywords, words, numbers and braces', () => { + assert.deepEqual(tokens('menu { name MAIN area 0 10 -5 }'), [ + 'kw:menu', '{:{', 'kw:name', 'string:MAIN', 'kw:area', 'number:0', 'number:10', '-:-', 'number:5', '}:}', + ]); + }); + + it('treats both quote characters alike, with no escapes, across lines', () => { + assert.deepEqual(tokens(`"it's" 'say "hi"' "a\\" 'x\ny'`), [ + "string:it's", 'string:say "hi"', 'string:a\\', 'string:x\ny', + ]); + const [quoted, word] = lexMenu(`'q' w`).tokens; + assert.equal(quoted?.quote, "'"); + assert.equal(word?.quote, undefined); + }); + + it('splits words at characters that are not ASCII letters or digits, such as "_"', () => { + assert.deepEqual(tokens('My_Menu a.b 1x'), ['string:My', 'kw:Menu', 'string:a', 'string:b', 'number:1', 'string:x']); + }); + + it('skips punctuation, so commas between values are ignored', () => { + assert.deepEqual(tokens('area 0, 0, 10, 10;'), ['kw:area', 'number:0', 'number:0', 'number:10', 'number:10']); + }); + + it('skips -- comments to the end of the line, but keeps a single minus', () => { + assert.deepEqual(tokens('a -- "b\n- 1 --c\r\nd'), ['string:a', '-:-', 'number:1', 'string:d']); + }); + + it('records inline Lua without producing a token', () => { + const text = 'action `x = 1\n` "f()"'; + const { tokens: found, inline } = lexMenu(text); + assert.deepEqual(found.map((t) => t.keyword ?? text.slice(t.valueStart, t.valueEnd)), ['action', 'f()']); + assert.deepEqual(inline, [{ start: 7, close: 14 }]); + }); + + it('does not start inline Lua inside strings or comments', () => { + assert.deepEqual(lexMenu('"`" -- `\n\'`\'').inline, []); + }); + + it('runs an unterminated string to the end of the file and reports it', () => { + const text = "a 'b\nc"; + const { tokens: found, problems } = lexMenu(text); + assert.equal(found.at(-1)?.end, text.length); + assert.deepEqual(problems.map((p) => [p.code, p.start, p.message]), [ + ['menu-unterminated-string', 2, 'Unterminated string: missing closing "\'".'], + ]); + }); + + it('warns when the character before a closing backtick is not white space, since the engine drops it', () => { + const text = '`a()`\n`b()\n`\n`c() `\n``'; + const { problems } = lexMenu(text); + assert.deepEqual(problems.map((p) => [p.code, p.severity, text.slice(p.start, p.end)]), [ + ['menu-inline-lua-last-character', 'warning', ')'], + ]); + assert.match(problems[0]?.message ?? '', /drops the last character before the closing "`", so "\)" is not run/); + }); + + it('reports unquoted words of 64 or more characters, which abort the engine', () => { + const text = `name ${'a'.repeat(63)} name ${'b'.repeat(64)} name "${'c'.repeat(100)}"`; + const { problems } = lexMenu(text); + assert.deepEqual(problems.map((p) => [p.code, p.severity, p.end - p.start]), [['menu-word-too-long', 'error', 64]]); + }); + + it('warns once per run about "_" joined to unquoted text, naming what the engine reads', () => { + const text = 'name My_Menu_1 name "Quoted_Name" -- a_b\n`x_y = 1\n` _ __ v_'; + const { problems } = lexMenu(text); + assert.deepEqual(problems.map((p) => [p.code, p.severity, text.slice(p.start, p.end)]), [ + ['menu-unquoted-underscore', 'warning', 'My_Menu_1'], + ['menu-unquoted-underscore', 'warning', 'v_'], + ]); + assert.equal(problems[0]?.message, 'The engine skips "_" in unquoted text, so My_Menu_1 is read as My Menu 1. Quote it: "My_Menu_1".'); + }); + + it('reports an unterminated inline Lua block and stops', () => { + const { tokens: found, problems } = lexMenu('a `b c'); + assert.equal(found.length, 1); + assert.deepEqual(problems.map((p) => [p.code, p.start, p.end]), [['menu-unterminated-block', 2, 3]]); + }); +}); diff --git a/test/unit/server/validation/validateText.test.ts b/test/unit/server/validation/validateText.test.ts index 9074119..793fe5f 100644 --- a/test/unit/server/validation/validateText.test.ts +++ b/test/unit/server/validation/validateText.test.ts @@ -51,12 +51,52 @@ describe('server/validation/validateText (official Lua 5.2.4 compiler)', () => { describe('.menu documents', () => { it('validates each embedded chunk and maps problems back into the document', () => { const text = '`\nfunction ok() return 1 end\n`\nmenu\n{\n\tbutton\n\t{\n\t\tenabled "a =="\n\t\taction\n\t\t"\n\t\t\tfoo(\n\t\t"\n\t}\n}\n'; - const found = problems(text, 'menu', lua); - assert.equal(found.length, 2); - assert.deepEqual(found.map(([code]) => code), ['lua-syntax', 'lua-syntax']); - for (const [, , message] of found) { - assert.match(message, /near /); - } + const found = validateText(text, 'menu', lua); + // The `end` the engine appends is what the compiler stumbles on: an empty range at the end of each chunk. + assert.deepEqual(found.map((p) => [p.code, text[p.start], p.start === p.end, p.message]), [ + ['lua-syntax', '"', true, "unexpected symbol near 'end'"], + ['lua-syntax', '"', true, "unexpected symbol near 'end'"], + ]); + }); + + it('rejects ... in property code, which the engine compiles into a function that is not vararg', () => { + assert.deepEqual(problems('action "print(...)"', 'menu', lua), [ + ['lua-syntax', '...', "cannot use '...' outside a vararg function near '...'"], + ]); + assert.deepEqual(problems('`print(...) `', 'menu', lua), []); + }); + + it('rejects a trailing -- comment in property code, which comments out the end the engine appends', () => { + const [problem] = problems('action "f() -- note"', 'menu', lua); + assert.match(problem?.[2] ?? '', /'end' expected near /); + assert.deepEqual(problems('action "f() -- note\n"', 'menu', lua), []); + }); + + it('compiles a backtick block without its last character, as the engine does', () => { + assert.deepEqual(problems('`x = 1`', 'menu', lua).map(([code, found]) => [code, found]), [ + ['menu-inline-lua-last-character', '1'], + ['lua-syntax', ''], + ]); + assert.deepEqual(problems('`x = 1\n`', 'menu', lua), []); + }); + + it('points at a token of the property code when it occurs once on the line', () => { + assert.deepEqual(problems('action "a b"', 'menu', lua), [['lua-syntax', 'b', "syntax error near 'b'"]]); + }); + + it('validates slotinfo, spellInfo and memorizedSpellInfo in every form the engine generates', () => { + const valid = 'slot { slotinfo "characters[id].equipment.weapon0" spellInfo \'t[1]\' memorizedSpellInfo "s" }'; + assert.deepEqual(problems(valid, 'menu', lua), []); + // `return 1` compiles, but the engine generates `return 1.item.icon`: `1.` is a number, then `item` + // (generated text) is unexpected, so the problem is an empty range at the end of the string. + assert.deepEqual(problems('slotinfo "1"', 'menu', lua), [['lua-syntax', '', "'end' expected near 'item'"]]); + assert.equal(validateText('spellInfo "\'s\'"', 'menu', lua).length, 1); + assert.equal(validateText('memorizedSpellInfo "a b"', 'menu', lua).length, 1); + }); + + it('rejects code that only parses as a chunk, not as a function body or return value', () => { + assert.equal(validateText('enabled "a; b"', 'menu', lua).length, 1); + assert.equal(validateText('enabled "a return b"', 'menu', lua).length, 1); }); it('accepts valid expressions and statements', () => { @@ -68,6 +108,14 @@ describe('server/validation/validateText (official Lua 5.2.4 compiler)', () => { assert.equal(validateText('enabled "x = 1"', 'menu', lua).length, 1); }); + it('reports Lua syntax errors as errors and misread menu text as warnings', () => { + const found = validateText('a_b action "f("', 'menu', lua); + assert.deepEqual(found.map((p) => [p.code, p.severity]), [ + ['menu-unquoted-underscore', 'warning'], + ['lua-syntax', 'error'], + ]); + }); + it('includes extractor problems', () => { assert.deepEqual(problems('action "x()', 'menu', lua).map(([code]) => code), ['menu-unterminated-string']); }); diff --git a/test/unit/server/workspace/filesExclude.test.ts b/test/unit/server/workspace/filesExclude.test.ts new file mode 100644 index 0000000..5f9c016 --- /dev/null +++ b/test/unit/server/workspace/filesExclude.test.ts @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import { filesExcludeFilter } from '../../../../src/server/workspace/filesExclude.ts'; + +const noSiblings = (): boolean => false; + +describe('server/workspace/filesExclude', () => { + it('excludes paths matching an enabled pattern, relative to the folder', () => { + const excluded = filesExcludeFilter({ '**/.git': true, 'out/**': true }); + assert.equal(excluded('.git', noSiblings), true); + assert.equal(excluded('a/.git', noSiblings), true); + assert.equal(excluded('out/x.lua', noSiblings), true); + assert.equal(excluded('src/out/x.lua', noSiblings), false); + }); + + it('ignores patterns whose value is false', () => { + assert.equal(filesExcludeFilter({ '**/*.lua': false })('a.lua', noSiblings), false); + }); + + it('excludes a match with a when clause only if the named sibling exists', () => { + const excluded = filesExcludeFilter({ '**/*.js': { when: '$(basename).ts' } }); + const siblings = new Set(['a.ts']); + const has = (name: string): boolean => siblings.has(name); + assert.equal(excluded('src/a.js', has), true); + assert.equal(excluded('src/b.js', has), false); + }); + + it('replaces only the first $(basename), with the name without its last extension', () => { + const asked: string[] = []; + filesExcludeFilter({ '**/*.lua': { when: '$(basename).$(basename)' } })('a.b.lua', (name) => { + asked.push(name); + return false; + }); + assert.deepEqual(asked, ['a.b.$(basename)']); + }); + + it('treats any other value, such as an object without when, as enabled', () => { + const excluded = filesExcludeFilter({ 'a.lua': { other: true }, 'b.lua': { when: 1 }, 'c.lua': 'yes' }); + for (const path of ['a.lua', 'b.lua', 'c.lua']) assert.equal(excluded(path, noSiblings), true, path); + }); + + it('excludes nothing for a value that is not an object', () => { + for (const value of [undefined, null, true, 'x', ['**']]) { + assert.equal(filesExcludeFilter(value)('a.lua', noSiblings), false, String(value)); + } + }); +}); diff --git a/test/unit/server/workspace/glob.test.ts b/test/unit/server/workspace/glob.test.ts new file mode 100644 index 0000000..a0e1de2 --- /dev/null +++ b/test/unit/server/workspace/glob.test.ts @@ -0,0 +1,65 @@ +import assert from 'node:assert/strict'; +import { compileGlob } from '../../../../src/server/workspace/glob.ts'; + +/** The paths among `paths` that `pattern` matches. */ +function matching(pattern: string, paths: string[]): string[] { + const glob = compileGlob(pattern); + return paths.filter((path) => glob?.test(path) === true); +} + +describe('server/workspace/glob (VS Code files.exclude semantics)', () => { + it('matches * and ? within one path segment only', () => { + assert.deepEqual(matching('*.lua', ['a.lua', '.lua', 'dir/a.lua', 'a.luac']), ['a.lua', '.lua']); + assert.deepEqual(matching('a?c', ['abc', 'ac', 'a/c', 'abbc']), ['abc']); + }); + + it('matches ** across any number of segments, including none', () => { + const paths = ['.git', 'a/.git', 'a/b/.git', 'a.git', 'a/.git/x']; + assert.deepEqual(matching('**/.git', paths), ['.git', 'a/.git', 'a/b/.git']); + assert.deepEqual(matching('a/**/b', ['a/b', 'a/x/b', 'a/x/y/b', 'ab', 'a/xb']), ['a/b', 'a/x/b', 'a/x/y/b']); + assert.deepEqual(matching('**', ['a', 'a/b']), ['a', 'a/b']); + }); + + it('matches a folder and everything under it with a trailing /**', () => { + assert.deepEqual(matching('out/**', ['out', 'out/a', 'out/a/b', 'outside', 'x/out']), ['out', 'out/a', 'out/a/b']); + }); + + it('expands {a,b} choices, which may contain slashes and globs', () => { + assert.deepEqual(matching('*.{lua,menu}', ['a.lua', 'a.menu', 'a.MENU', 'a.txt']), ['a.lua', 'a.menu']); + assert.deepEqual(matching('{a/b,x*}', ['a/b', 'xyz', 'a']), ['a/b', 'xyz']); + }); + + it('matches character sets, ranges and negated sets', () => { + assert.deepEqual(matching('[a-c].lua', ['a.lua', 'c.lua', 'd.lua']), ['a.lua', 'c.lua']); + assert.deepEqual(matching('[!a]x', ['ax', 'bx', '/x']), ['bx', '/x']); + assert.deepEqual(matching('[^a]x', ['ax', 'bx']), ['bx']); + assert.deepEqual(matching('[]]', [']', 'a']), [']']); + }); + + it('is case-sensitive, like the explorer', () => { + assert.deepEqual(matching('**/*.menu', ['UI.MENU', 'ui.menu']), ['ui.menu']); + }); + + it('accepts backslashes as separators in the matched path', () => { + assert.deepEqual(matching('**/.git', ['a\\.git']), ['a\\.git']); + }); + + it('treats regular-expression characters literally', () => { + assert.deepEqual(matching('a+(b).$', ['a+(b).$', 'aa(b)x$']), ['a+(b).$']); + }); + + it('trims the pattern and matches nothing when it is empty', () => { + assert.deepEqual(matching(' *.lua ', ['a.lua']), ['a.lua']); + assert.equal(compileGlob(' '), undefined); + }); + + it('drops an unterminated { or [ with the rest of its segment, and a stray }', () => { + assert.deepEqual(matching('a{b', ['a', 'ab']), ['a']); + assert.deepEqual(matching('a[b', ['a', 'ab']), ['a']); + assert.deepEqual(matching('a}b', ['ab', 'a}b']), ['ab']); + }); + + it('matches nothing when a stray ] closes an empty set', () => { + assert.deepEqual(matching('a]', ['a', 'a]']), []); + }); +}); diff --git a/test/unit/server/workspace/nodeFileSystem.test.ts b/test/unit/server/workspace/nodeFileSystem.test.ts new file mode 100644 index 0000000..2ce917f --- /dev/null +++ b/test/unit/server/workspace/nodeFileSystem.test.ts @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { nodeFileSystem } from '../../../../src/server/workspace/nodeFileSystem.ts'; + +describe('server/workspace/nodeFileSystem', () => { + let root: string; + before(async () => { + root = await mkdtemp(join(tmpdir(), 'ie-lua-fs-')); + await mkdir(join(root, 'dir')); + await writeFile(join(root, 'a.lua'), 'x = 1'); + await symlink(join(root, 'dir'), join(root, 'dir-link')); + await symlink(join(root, 'a.lua'), join(root, 'link.lua')); + }); + after(async () => { + await rm(root, { recursive: true, force: true }); + }); + + it('lists files, directories and symbolic links without following links', async () => { + const entries = (await nodeFileSystem.readDirectory(root)).sort((a, b) => a.name.localeCompare(b.name)); + assert.deepEqual(entries, [ + { name: 'a.lua', kind: 'file' }, + { name: 'dir', kind: 'directory' }, + { name: 'dir-link', kind: 'symlink' }, + { name: 'link.lua', kind: 'symlink' }, + ]); + }); + + it('reads a file, following a link to it', async () => { + assert.equal(new TextDecoder().decode(await nodeFileSystem.readFile(join(root, 'link.lua'))), 'x = 1'); + }); + + it('rejects with the Node error code for a missing path', async () => { + await assert.rejects(nodeFileSystem.readFile(join(root, 'missing.lua')), { code: 'ENOENT' }); + }); +}); diff --git a/test/unit/server/workspace/workspaceIndex.test.ts b/test/unit/server/workspace/workspaceIndex.test.ts new file mode 100644 index 0000000..fbfd5f8 --- /dev/null +++ b/test/unit/server/workspace/workspaceIndex.test.ts @@ -0,0 +1,281 @@ +import assert from 'node:assert/strict'; +import { posix, win32 } from 'node:path'; +import { isIndexedFileName, WorkspaceIndex, type DirectoryEntry, type WorkspaceFileSystem } from '../../../../src/server/workspace/workspaceIndex.ts'; + +/** An in-memory file system keyed by full path; `links` marks symbolic links. */ +class MemoryFileSystem implements WorkspaceFileSystem { + readonly files = new Map(); + readonly links = new Set(); + readonly reads: string[] = []; + /** Paths whose read never completes, to hold the index's queue. */ + readonly hanging = new Set(); + private readonly sep: string; + + constructor(sep = '/') { + this.sep = sep; + } + + add(path: string, text = ''): this { + this.files.set(path, text); + return this; + } + + readDirectory(path: string): Promise { + const prefix = path.endsWith(this.sep) ? path : `${path}${this.sep}`; + const entries = new Map(); + for (const file of [...this.files.keys(), ...this.links]) { + if (!file.startsWith(prefix)) continue; + const [name, ...rest] = file.slice(prefix.length).split(this.sep); + if (!name) continue; + const kind = this.links.has(prefix + name) ? 'symlink' : rest.length > 0 ? 'directory' : 'file'; + entries.set(name, kind); + } + if (entries.size === 0 && ![...this.files.keys()].some((file) => file.startsWith(prefix))) { + return Promise.reject(new Error(`ENOENT: ${path}`)); + } + return Promise.resolve([...entries].map(([name, kind]) => ({ name, kind }))); + } + + readFile(path: string): Promise { + this.reads.push(path); + if (this.hanging.has(path)) return new Promise(() => undefined); + const text = this.files.get(path); + return text === undefined + ? Promise.reject(Object.assign(new Error(`ENOENT: no such file, open '${path}'`), { code: 'ENOENT' })) + : Promise.resolve(new TextEncoder().encode(text)); + } +} + +function setup(fs: MemoryFileSystem, excludes: Record = {}) { + const log: string[] = []; + let yields = 0; + const index = new WorkspaceIndex({ + fs, + path: posix, + toPath: (uri) => decodeURIComponent(new URL(uri).pathname), + analyze: (text) => text, + filesExclude: (folder) => Promise.resolve(excludes[folder]), + yieldToEventLoop: () => { + yields++; + return Promise.resolve(); + }, + log: (message) => log.push(message), + }); + const indexed = (): string[] => [...index.entries()].map((e) => `${e.uri}=${e.value}`).sort(); + return { index, log, indexed, yields: () => yields }; +} + +describe('server/workspace/workspaceIndex', () => { + it('recognizes Lua and .menu files in any letter case', () => { + assert.deepEqual(['a.lua', 'UI.MENU', 'b.Lua', 'c.luac', 'menu', 'x.txt'].filter(isIndexedFileName), ['a.lua', 'UI.MENU', 'b.Lua']); + }); + + it('indexes every Lua and .menu file of every folder, one file per yield', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A').add('/w/sub/UI.MENU', 'M').add('/w/notes.txt', 'N').add('/v/b.lua', 'B'); + const { index, indexed, yields, log } = setup(fs); + index.setFolders(['file:///w', 'file:///v/']); + await index.ready(); + assert.deepEqual(indexed(), ['file:///v/b.lua=B', 'file:///w/a.lua=A', 'file:///w/sub/UI.MENU=M']); + assert.equal(yields(), 3); + assert.match(log.at(-1) ?? '', /^Indexed 3 Lua and \.menu files in \d+ ms\.$/); + }); + + it('percent-encodes path segments in the URIs it builds', async () => { + const { index, indexed } = setup(new MemoryFileSystem().add('/w/my mod/a#1.lua', 'x')); + index.setFolders(['file:///w']); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/my%20mod/a%231.lua=x']); + }); + + it('skips files.exclude matches, including whole folders, relative to each folder', async () => { + const fs = new MemoryFileSystem().add('/w/keep.lua').add('/w/out/gen.lua').add('/w/a.lua').add('/w/a.menu').add('/w/x/.git/h.lua'); + const { index, indexed } = setup(fs, { 'file:///w': { 'out': true, '**/.git': true, '*.lua': { when: '$(basename).menu' } } }); + index.setFolders(['file:///w']); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/a.menu=', 'file:///w/keep.lua=']); + assert.ok(!fs.reads.some((path) => path.startsWith('/w/out/')), 'an excluded folder is not read'); + }); + + it('reads symbolic links to files but never descends into linked folders', async () => { + const fs = new MemoryFileSystem().add('/w/real/a.lua', 'A').add('/w/linked.lua', 'L'); + fs.links.add('/w/linked.lua'); + fs.links.add('/w/loop'); + const { index, indexed } = setup(fs); + index.setFolders(['file:///w']); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/linked.lua=L', 'file:///w/real/a.lua=A']); + }); + + it('logs and skips what it cannot read, but not files that are gone', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A').add('/w/locked.lua'); + fs.readFile = (path) => (path === '/w/locked.lua' ? Promise.reject(new Error('EACCES: permission denied')) : MemoryFileSystem.prototype.readFile.call(fs, path)); + fs.links.add('/w/broken.lua'); + const { index, indexed, log } = setup(fs); + index.setFolders(['file:///w', 'file:///missing']); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/a.lua=A']); + assert.ok(log.some((line) => line === 'Cannot read /w/locked.lua: EACCES: permission denied')); + assert.ok(!log.some((line) => line.includes('broken.lua')), 'a dangling link is a file that is gone, not an error'); + assert.ok(log.some((line) => line.startsWith('Cannot list /missing'))); + }); + + it('does not log when the file of a closed document no longer exists', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A').add('/w/notes.txt'); + const { index, indexed, log } = setup(fs); + index.setFolders(['file:///w']); + await index.ready(); + const lines = log.length; + fs.files.delete('/w/a.lua'); + index.fileChanged('file:///w/a.lua'); + await index.ready(); + assert.deepEqual(indexed(), []); + assert.equal(log.length, lines); + }); + + it('answers ready() for the work queued before the call, even while more keeps arriving', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A').add('/w/slow.lua', 'S'); + const { index, indexed } = setup(fs); + index.setFolders(['file:///w']); + await index.ready(); + fs.add('/w/a.lua', 'A2'); + index.fileChanged('file:///w/a.lua'); + const ready = index.ready(); + // Work queued after the call never finishes; the call must not wait for it. + fs.hanging.add('/w/slow.lua'); + index.fileChanged('file:///w/slow.lua'); + await ready; + // slow.lua is being read again: its previous entry stays meanwhile. + assert.deepEqual(indexed(), ['file:///w/a.lua=A2', 'file:///w/slow.lua=S']); + }); + + it('waits in ready() for the rescan a files.exclude change starts', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A').add('/w/b.lua', 'B'); + const excludes: Record = {}; + const { index, indexed } = setup(fs, excludes); + index.setFolders(['file:///w']); + await index.ready(); + excludes['file:///w'] = { 'b.lua': true }; + index.settingsChanged(); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/a.lua=A']); + }); + + it('handles Windows paths: separators, drive letters and URIs', async () => { + const fs = new MemoryFileSystem('\\').add('c:\\Mods\\My Mod\\a.lua', 'A').add('c:\\Mods\\out\\b.lua', 'B'); + const log: string[] = []; + const index = new WorkspaceIndex({ + fs, + path: win32, + // fileURLToPath as on Windows, for the two URI spellings clients use. + toPath: (uri) => decodeURIComponent(new URL(uri).pathname).replace(/^\/([A-Za-z]):/, '$1:').replaceAll('/', '\\'), + analyze: (text) => text, + filesExclude: () => Promise.resolve({ out: true }), + yieldToEventLoop: () => Promise.resolve(), + log: (message) => log.push(message), + }); + index.setFolders(['file:///c%3A/Mods']); + await index.ready(); + assert.deepEqual([...index.entries()].map((e) => [e.uri, e.key, e.value]), [ + ['file:///c%3A/Mods/My%20Mod/a.lua', 'c:\\Mods\\My Mod\\a.lua', 'A'], + ]); + // An open document spelled with an upper-case drive letter is the same file. + assert.equal(index.pathKey('file:///C:/Mods/My%20Mod/a.lua'), 'c:\\Mods\\My Mod\\a.lua'); + index.fileDeleted('file:///C:/Mods/My%20Mod'); + await index.ready(); + assert.deepEqual([...index.entries()], []); + }); + + it('scans only file: folders and says so for the others', async () => { + const { index, log } = setup(new MemoryFileSystem()); + index.setFolders(['vscode-vfs://github/x/y']); + await index.ready(); + assert.ok(log.some((line) => line.includes('vscode-vfs://github/x/y is not on the local file system'))); + }); + + it('reindexes changed files and drops deleted files and folders', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'old').add('/w/d/b.lua', 'B').add('/w/d/c.lua', 'C'); + const { index, indexed } = setup(fs); + index.setFolders(['file:///w']); + fs.add('/w/a.lua', 'new').add('/w/n.lua', 'N'); + index.fileChanged('file:///w/a.lua'); + index.fileChanged('file:///w/n.lua'); + index.fileDeleted('file:///w/d'); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/a.lua=new', 'file:///w/n.lua=N']); + }); + + it('indexes the files of a created folder, except excluded ones', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A'); + const { index, indexed } = setup(fs, { 'file:///w': { '**/skip.lua': true } }); + index.setFolders(['file:///w']); + fs.add('/w/moved/sub/b.lua', 'B').add('/w/moved/skip.lua', 'S').add('/w/moved/readme.txt'); + index.fileChanged('file:///w/moved'); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/a.lua=A', 'file:///w/moved/sub/b.lua=B']); + }); + + it('rescans when files.exclude changes, and only then', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A').add('/w/b.lua', 'B'); + const excludes: Record = { 'file:///w': { 'x.lua': true } }; + const { index, indexed } = setup(fs, excludes); + index.setFolders(['file:///w']); + await index.ready(); + const reads = fs.reads.length; + index.settingsChanged(); + await index.ready(); + assert.equal(fs.reads.length, reads, 'an unrelated settings change rescans nothing'); + excludes['file:///w'] = { 'b.lua': true }; + index.settingsChanged(); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/a.lua=A']); + }); + + it('ignores changes outside the folders, to other file types, and to excluded files', async () => { + const fs = new MemoryFileSystem().add('/w/out/x.lua', 'X').add('/w/t.txt', 'T').add('/elsewhere/e.lua', 'E'); + const { index, indexed } = setup(fs, { 'file:///w': { out: true } }); + index.setFolders(['file:///w']); + index.fileChanged('file:///w/out/x.lua'); + index.fileChanged('file:///w/t.txt'); + index.fileChanged('file:///elsewhere/e.lua'); + index.fileChanged('untitled:Untitled-1'); + await index.ready(); + assert.deepEqual(indexed(), []); + }); + + it('rescans with the new files.exclude value', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A').add('/w/b.lua', 'B'); + const excludes: Record = {}; + const { index, indexed } = setup(fs, excludes); + index.setFolders(['file:///w']); + await index.ready(); + excludes['file:///w'] = { 'b.lua': true }; + index.rescan(); + await index.ready(); + assert.deepEqual(indexed(), ['file:///w/a.lua=A']); + }); + + it('abandons a scan that a newer one supersedes', async () => { + const fs = new MemoryFileSystem().add('/w/a.lua', 'A').add('/v/b.lua', 'B'); + const { index, indexed } = setup(fs); + index.setFolders(['file:///w']); + index.setFolders(['file:///v']); + await index.ready(); + assert.deepEqual(indexed(), ['file:///v/b.lua=B']); + assert.ok(!fs.reads.includes('/w/a.lua')); + }); + + it('keys files by native path, with the Windows drive letter in lower case', () => { + const { index } = setup(new MemoryFileSystem()); + const windows = new WorkspaceIndex({ + fs: new MemoryFileSystem(), + path: posix, + toPath: () => 'C:\\mods\\a.lua', + analyze: (text) => text, + filesExclude: () => Promise.resolve(undefined), + yieldToEventLoop: () => Promise.resolve(), + log: () => undefined, + }); + assert.equal(windows.pathKey('file:///C:/mods/a.lua'), 'c:\\mods\\a.lua'); + assert.equal(index.pathKey('untitled:Untitled-1'), undefined); + }); +}); diff --git a/test/unit/syntaxes/ieMenuGrammar.test.ts b/test/unit/syntaxes/ieMenuGrammar.test.ts new file mode 100644 index 0000000..2f8943c --- /dev/null +++ b/test/unit/syntaxes/ieMenuGrammar.test.ts @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { EXPRESSION_PROPERTIES, SHORTHAND_FORMS, STATEMENT_PROPERTIES } from '../../../src/server/validation/menuExtractor.ts'; +import { MENU_KEYWORDS } from '../../../src/server/validation/menuKeywords.ts'; + +interface Rule { + readonly match?: string; + readonly begin?: string; +} + +const grammar = JSON.parse(readFileSync(new URL('../../../syntaxes/ie-menu.tmLanguage.json', import.meta.url), 'utf8')) as { + readonly repository: Readonly>; +}; + +/** The words of every `(…|…)` / `(?:…|…)` alternation in a pattern, in lower case. */ +function alternatives(pattern: string | undefined): Set { + const words = new Set(); + for (const group of (pattern ?? '').matchAll(/\((?:\?:)?([A-Za-z|]+)\)/g)) { + for (const word of group[1]?.split('|') ?? []) words.add(word.toLowerCase()); + } + return words; +} + +const sorted = (words: Iterable): string[] => [...words].sort(); + +// The grammar is static JSON; these checks keep it in step with the extractor, +// which is the source of truth for what is Lua in a .menu file. +describe('syntaxes/ie-menu.tmLanguage.json', () => { + it('highlights exactly the engine keywords', () => { + assert.deepEqual(sorted(alternatives(grammar.repository['keyword']?.match)), sorted(MENU_KEYWORDS.map((k) => k.toLowerCase()))); + }); + + it('embeds Lua after exactly the properties the extractor treats as Lua', () => { + const expected = [...STATEMENT_PROPERTIES, ...EXPRESSION_PROPERTIES, ...SHORTHAND_FORMS.keys(), 'lua', 'bitmap', 'res']; + assert.deepEqual(sorted(alternatives(grammar.repository['lua-property']?.begin)), sorted(expected)); + }); + + it('marks the item types and menu/column as elements, all of them keywords', () => { + const elements = alternatives(grammar.repository['element']?.match); + assert.deepEqual(sorted(elements), sorted(['menu', 'label', 'text', 'button', 'list', 'edit', 'movie', 'slider', 'handle', 'slot', 'map', 'template', 'column'])); + const keywords = new Set(MENU_KEYWORDS.map((k) => k.toLowerCase())); + for (const element of elements) assert.ok(keywords.has(element), element); + }); +});