diff --git a/.github/CLAUDE.md b/.github/CLAUDE.md index d44c050..3f34991 100644 --- a/.github/CLAUDE.md +++ b/.github/CLAUDE.md @@ -29,7 +29,7 @@ Scoped notes for workflows, Dependabot and templates. The root `CLAUDE.md` still | `ci.yml` | PR, push to main, dispatch | checks, VSIX artifact, integration tests (min + stable VS Code), WASM reproducibility | | `commitlint.yml` | PR, dispatch | Conventional Commits for commits and PR title (Dependabot exempt) | | `codeql.yml` | PR, push, weekly | code scanning (`actions`, `javascript-typescript`) | -| `release.yml` | dispatch → PR; push of `VERSION` | prepare release PR; publish GitHub release (environment `release`) | +| `release.yml` | dispatch → PR; push of `VERSION` by a `chore(release):` merge | prepare release PR; publish GitHub release (environment `release`) | | `dependabot-automerge.yml` | Dependabot PR | auto-merge low-risk updates after required checks | | `eeex-docs-sync*.yml` | weekly, staggered | refresh `data/eeex/*.json` from the published EEex docs | | `stale.yml` | weekly | stale issues/PRs | diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 5f3219c..983d9d4 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -28,7 +28,7 @@ body: attributes: label: Extension version description: "VS Code: Extensions view › IE Lua Language Server. Other editors: the version of the release you downloaded." - placeholder: "0.1.0" + placeholder: "1.0.0" validations: required: true - type: dropdown diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4533c28..0b4c264 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -151,6 +151,11 @@ jobs: with: path: .vscode-test key: vscode-test-${{ runner.os }}-${{ steps.vscode.outputs.version }} + # `npm test` runs this as its `pretest` script; calling vscode-test directly + # (to pick one label) skips it, and without the bundled tests in + # out/test/integration/ the run would find no test files. + - name: Build extension and integration tests + run: npm run pretest - name: Run integration tests run: xvfb-run -a npx vscode-test --label "${{ matrix.label }}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 708580c..febcf7a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,7 +7,9 @@ # CHANGELOG.md and docs/CHANGELOG.vsix.md, and opens a release pull request. # 2. Merging that pull request changes VERSION on main → job `publish` # (environment `release`): verifies the version, runs the checks, packages the -# VSIX and creates the tag and the GitHub (pre-)release. +# VSIX and creates the tag and the GitHub (pre-)release. Other pushes that +# touch VERSION (for example a manual version reset) skip `publish`: it runs +# only for the squash commit of a `chore(release): …` pull request. # # Version rules (VS Code): plain major.minor.patch; even minor = stable, # odd minor = pre-release (packaged with `vsce package --pre-release`). @@ -85,7 +87,12 @@ jobs: publish: name: Publish GitHub release - if: github.event_name == 'push' + # `prepare` opens release pull requests with one commit and a title that are + # both `chore(release): vX.Y.Z`; the squash merge (title: COMMIT_OR_PR_TITLE) + # therefore starts with that prefix. Any other push touching VERSION is skipped. + if: >- + github.event_name == 'push' && + startsWith(github.event.head_commit.message, 'chore(release): ') runs-on: ubuntu-latest timeout-minutes: 15 environment: release diff --git a/.mocharc.json b/.mocharc.json index b63a4e1..8bf4d32 100644 --- a/.mocharc.json +++ b/.mocharc.json @@ -4,5 +4,6 @@ "extension": ["ts"], "reporter": "spec", "forbidOnly": true, + "fail-zero": true, "timeout": 5000 } diff --git a/.vscode-test.mjs b/.vscode-test.mjs index d44e11b..1d9e36c 100644 --- a/.vscode-test.mjs +++ b/.vscode-test.mjs @@ -10,7 +10,8 @@ const config = (label, version) => ({ workspaceFolder: 'test/fixtures/workspace', // Isolated user data and extensions: never depend on the developer's own setup. launchArgs: ['--disable-extensions', '--disable-workspace-trust'], - mocha: { ui: 'tdd', timeout: 20000, forbidOnly: true }, + // failZero: a run that finds no tests (e.g. tests not built) fails instead of passing. + mocha: { ui: 'tdd', timeout: 20000, forbidOnly: true, failZero: true }, }); export default defineConfig([ diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c258b1..1980a2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,17 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). - Settings `ieLua.validate.mode` (`manual`, `save` (default), `type`, `saveAndType`) and `ieLua.validate.debounce` (default 300 ms). - Command **IE Lua: Validate Current File** (`ieLua.validateDocument`). +- Document symbols (`textDocument/documentSymbol`; outline, breadcrumbs, *Go to Symbol in + Editor*): functions and methods at any depth, top-level locals, the first assignment to each + global, and named table fields; in `.menu` files, each `menu` block by its `name`, holding the + Lua symbols inside it. Flat `SymbolInformation` for clients without hierarchical support. +- Folding ranges (`textDocument/foldingRange`): function bodies, `do`/`while`/`for`/`repeat`, + each `if`/`elseif`/`else` clause, multi-line tables, call arguments and long strings, long + comments and runs of `--` lines; in `.menu` files every `{ … }` block, `` `…` `` blocks and + `"…"` scripts, plus the Lua inside them. The closing line stays visible. Honors the client's + `rangeLimit` and supported kinds. +- 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 (machine-produced; review welcome). - Setup guides for Sublime Text, Neovim, Emacs, JetBrains IDEs, Helix, Zed, Kate, Notepad++ and Geany. @@ -35,3 +46,9 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). ### Changed - 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). +- The Release workflow publishes only for merged `chore(release): …` pull requests, not for any + other push that changes `VERSION`. +- CI integration jobs build the tests before running them, and a test run that finds no tests now + fails. Until now the CI integration jobs ran 0 tests and passed. diff --git a/CLAUDE.md b/CLAUDE.md index 072f232..2599049 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 now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | +| Purpose | Lua 5.2 language support (diagnostics, document symbols and folding now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | | 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) | @@ -32,6 +32,7 @@ │ ├── server/ # Language server (separate Node process) │ │ ├── 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 │ └── shared/ # Types/constants used by BOTH sides — no vscode imports ├── test/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9279dc9..c9f69ca 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,6 +29,7 @@ server (port 6009). | `src/client/` | VS Code extension host code: activation, command, settings, language client | | `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/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) | @@ -118,7 +119,8 @@ Nothing is ever published to a marketplace (`"private": true`; `vsce publish` is 1. Make sure both changelogs describe the changes under `## [Unreleased]`. 2. Run the **Release** workflow (*Actions › Release › Run workflow*) and choose **pre-release** or **stable**. It computes the next version (odd minor for pre-releases, even minor for stable, - always higher than every earlier release), updates `VERSION`, `package.json`, `package-lock.json` + always higher than every earlier release; the very first stable release is the committed + `VERSION`, 1.0.0, and a pre-release before it would be 1.1.0), updates `VERSION`, `package.json`, `package-lock.json` and both changelogs, and opens a `chore(release): vX.Y.Z` pull request. 3. Review and merge that pull request. The workflow then verifies the version, runs the checks, packages the VSIX and creates the tag and the GitHub release (environment `release`). diff --git a/README.md b/README.md index 0ac9c75..cd0f4d0 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the `.menu` files such as `UI.MENU`. > [!NOTE] -> This is an early version. It currently provides **syntax diagnostics**; completion, hover, -> navigation, formatting and more are planned. +> This is an early version. It currently provides **syntax diagnostics**, **document symbols** +> and **folding**; completion, hover, navigation, formatting and more are planned. ## Features @@ -22,6 +22,11 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the `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. - **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. +- **Folding that follows the code:** functions, loops, each `if`/`elseif`/`else` branch, tables, + comments, and every `{ … }` block and Lua script of a `.menu` file. - **Available in 14 languages**, following your VS Code display language. - **Works in other editors** through the Language Server Protocol. @@ -70,8 +75,9 @@ Start with the [common steps](docs/editors/README.md). ## Release channels -Versions follow VS Code's convention: an **even** middle number (0.**2**.0) is a stable release, -an **odd** one (0.**1**.0) is a pre-release. See [CHANGELOG.md](CHANGELOG.md). +Versions follow VS Code's convention: an **even** middle number (1.**2**.0) is a stable release, +an **odd** one (1.**1**.0) is a pre-release. The first stable release is 1.0.0. +See [CHANGELOG.md](CHANGELOG.md). ## Contributing and support diff --git a/VERSION b/VERSION index 77d6f4c..3eefcb9 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.0 +1.0.0 diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 2aa90f9..93b229b 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -3,8 +3,8 @@ All notable changes for users of the extension. The format is based on [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.1.0/). -Versions with an **odd** middle number (for example 0.**1**.0) are pre-releases; -versions with an **even** middle number (for example 0.**2**.0) are stable releases. +Versions with an **odd** middle number (for example 1.**1**.0) are pre-releases; +versions with an **even** middle number (for example 1.**2**.0) are stable releases. ## [Unreleased] @@ -17,6 +17,11 @@ versions with an **even** middle number (for example 0.**2**.0) are stable relea - **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. +- **Outline and breadcrumbs.** Functions, variables and table fields of Lua files, and each menu + of a `.menu` file by name, appear in the Outline view, the breadcrumbs and + **Go to Symbol in Editor**. +- **Code folding that follows the code.** Fold functions, loops, each branch of an `if`, tables, + comments, and every block and script of a `.menu` file. - **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 669b843..30a511b 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -57,3 +57,13 @@ node /path/to/server.js --stdio | `saveAndType` | both | Outside VS Code there is no "Validate Current File" command, so prefer `type` or `saveAndType`. + +## 4. What you get + +| Feature | LSP request | Notes | +| --- | --- | --- | +| Syntax errors | `textDocument/publishDiagnostics` | When `validate.mode` says so (see above). | +| Document symbols (outline) | `textDocument/documentSymbol` | Nested when the editor supports it, otherwise a flat list with container names. | +| Folding | `textDocument/foldingRange` | Whole lines; the closing line of each construct stays visible. | + +Symbols and folding always reflect the current text, whatever `validate.mode` is. diff --git a/package-lock.json b/package-lock.json index 8e73ef8..b0a5ff4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ie-lua-language-server", - "version": "0.0.0", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ie-lua-language-server", - "version": "0.0.0", + "version": "1.0.0", "license": "SEE LICENSE IN LICENSE.md", "dependencies": { "vscode-languageclient": "11.0.0", diff --git a/package.json b/package.json index 3dc1171..3e0f850 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "ie-lua-language-server", "displayName": "%displayName%", "description": "%description%", - "version": "0.0.0", + "version": "1.0.0", "private": true, "publisher": "infinity-engine-tools", "author": "4Luke4", diff --git a/scripts/release/cli.mts b/scripts/release/cli.mts index 63d630a..29093ab 100644 --- a/scripts/release/cli.mts +++ b/scripts/release/cli.mts @@ -1,8 +1,9 @@ // Release automation used by .github/workflows/release.yml (also runnable locally). // // node scripts/release/cli.mts prepare --channel -// Computes the next version from git tags + Conventional Commits, then updates -// VERSION, package.json, package-lock.json, CHANGELOG.md and docs/CHANGELOG.vsix.md. +// Computes the next version from git tags + Conventional Commits (the first +// stable release is VERSION itself), then updates VERSION, package.json, +// package-lock.json, CHANGELOG.md and docs/CHANGELOG.vsix.md. // node scripts/release/cli.mts verify [--notes ] // Checks that the committed version is consistent and not yet released, and // optionally writes the CHANGELOG.md section of that version to . @@ -19,8 +20,8 @@ import { compareVersions, formatVersion, latestTaggedVersion, - nextVersion, parseVersion, + releaseVersion, type Channel, type Version, } from './version.mts'; @@ -87,7 +88,6 @@ function prepare(channel: Channel): void { const current = committedVersion(); const allTags = tags(); const latest = latestTaggedVersion(allTags); - const baseline = latest ?? current; if (latest && compareVersions(current, latest) !== 0) { fail(`VERSION is ${formatVersion(current)} but the latest tag is v${formatVersion(latest)}. Run prepare only from a commit where they match.`); } @@ -106,7 +106,12 @@ function prepare(channel: Channel): void { if (!bump) { fail(`No feat/fix/perf/revert or breaking commit since ${latest ? `v${formatVersion(latest)}` : 'the first commit'}; there is nothing to release.`); } - const next = formatVersion(nextVersion(baseline, bump, channel)); + let next: string; + try { + next = formatVersion(releaseVersion(latest, current, bump, channel)); + } catch (error) { + fail(error instanceof Error ? error.message : String(error)); + } const date = new Date().toISOString().slice(0, 10); const previousTag = latest ? `v${formatVersion(latest)}` : undefined; diff --git a/scripts/release/version.mts b/scripts/release/version.mts index 2a19be7..8248267 100644 --- a/scripts/release/version.mts +++ b/scripts/release/version.mts @@ -108,3 +108,31 @@ export function nextVersion(latest: Version, bump: Bump, channel: Channel): Vers } return { ...latest, patch: latest.patch + 1 }; } + +/** + * Version of the next release. + * + * - First release (no `vX.Y.Z` tag yet), stable: the committed version itself, so + * the first stable release is whatever VERSION says (1.0.0). It must already + * have an even minor; the bump only proves that there is something to release. + * - First release, pre-release: the next odd line above the committed version + * (1.0.0 → 1.1.0), so a later stable release can never be lower than it. + * - Otherwise: `nextVersion` from the highest tag. + * + * Throws a `RangeError` with an actionable message when the committed version + * cannot be released on the stable channel as is. + */ +export function releaseVersion(latestTag: Version | undefined, committed: Version, bump: Bump, channel: Channel): Version { + if (latestTag !== undefined) { + return nextVersion(latestTag, bump, channel); + } + if (channel === 'pre-release') { + return nextVersion(committed, bump, channel); + } + if (channelOf(committed) !== 'stable') { + throw new RangeError( + `The first stable release uses VERSION as is, but ${formatVersion(committed)} has an odd minor (pre-release). Set VERSION to a version with an even minor, for example ${formatVersion({ major: committed.major, minor: committed.minor + 1, patch: 0 })}.`, + ); + } + return committed; +} diff --git a/src/server/documentCache.ts b/src/server/documentCache.ts new file mode 100644 index 0000000..c25bd97 --- /dev/null +++ b/src/server/documentCache.ts @@ -0,0 +1,38 @@ +import { parseDocument, type ParsedDocument } from './syntax/document.ts'; +import { documentKind } from './validation/validateText.ts'; + +/** The parts of an LSP `TextDocument` the cache needs. */ +export interface VersionedDocument { + readonly uri: string; + readonly languageId: string; + readonly version: number; + getText(): string; +} + +/** + * Parse results per document, keyed by URI and reused while the version is + * unchanged, so that every feature parses a document version at most once. + * Call `delete` when the document is closed. + */ +export class ParsedDocumentCache { + private readonly entries = new Map(); + + get(document: VersionedDocument): ParsedDocument { + const cached = this.entries.get(document.uri); + if (cached?.version === document.version) { + return cached.parsed; + } + const parsed = parseDocument(document.getText(), documentKind(document.uri, document.languageId)); + this.entries.set(document.uri, { version: document.version, parsed }); + return parsed; + } + + delete(uri: string): void { + this.entries.delete(uri); + } + + /** Number of cached documents (for logging and tests). */ + get size(): number { + return this.entries.size; + } +} diff --git a/src/server/features/documentSymbols.ts b/src/server/features/documentSymbols.ts new file mode 100644 index 0000000..a642ad7 --- /dev/null +++ b/src/server/features/documentSymbols.ts @@ -0,0 +1,81 @@ +import type { Connection, DocumentSymbol, Position, SymbolInformation, TextDocuments } from 'vscode-languageserver/node'; +import { SymbolKind } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { documentSymbols, type OutlineKind, type OutlineSymbol } from '../syntax/symbols.ts'; + +export interface DocumentSymbolsDeps { + readonly cache: ParsedDocumentCache; + /** `textDocument.documentSymbol.hierarchicalDocumentSymbolSupport` of the client. */ + readonly hierarchical: boolean; +} + +const KIND: Readonly> = { + function: SymbolKind.Function, + method: SymbolKind.Method, + variable: SymbolKind.Variable, + field: SymbolKind.Field, + namespace: SymbolKind.Namespace, +}; + +export interface SymbolConversion { + readonly hierarchical: boolean; + readonly uri: string; + readonly positionAt: (offset: number) => Position; +} + +/** + * Hierarchical `DocumentSymbol[]`, or for clients without hierarchical support a + * flat `SymbolInformation[]` in document order with container names. + */ +export function toLspSymbols(symbols: readonly OutlineSymbol[], options: SymbolConversion): DocumentSymbol[] | SymbolInformation[] { + const range = (start: number, end: number) => ({ start: options.positionAt(start), end: options.positionAt(end) }); + if (options.hierarchical) { + const convert = (symbol: OutlineSymbol): DocumentSymbol => ({ + name: symbol.name, + kind: KIND[symbol.kind], + ...(symbol.detail === undefined ? {} : { detail: symbol.detail }), + range: range(symbol.start, symbol.end), + selectionRange: range(symbol.selectionStart, symbol.selectionEnd), + children: symbol.children.map(convert), + }); + return symbols.map(convert); + } + const flat: SymbolInformation[] = []; + const flatten = (symbol: OutlineSymbol, container: string | undefined): void => { + flat.push({ + name: symbol.name, + kind: KIND[symbol.kind], + location: { uri: options.uri, range: range(symbol.start, symbol.end) }, + ...(container === undefined ? {} : { containerName: container }), + }); + for (const child of symbol.children) flatten(child, symbol.name); + }; + for (const symbol of symbols) flatten(symbol, undefined); + return flat; +} + +/** + * `textDocument/documentSymbol`: the outline, breadcrumbs and "Go to Symbol in + * Editor" (see src/server/syntax/symbols.ts for what is listed). + */ +export function register(connection: Connection, documents: TextDocuments, deps: DocumentSymbolsDeps): void { + connection.onDocumentSymbol(({ textDocument }, token): DocumentSymbol[] | SymbolInformation[] | null => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) { + return null; + } + // Synchronous from here on: a cancellation can only arrive after the response. + const symbols = documentSymbols(deps.cache.get(document), document.getText().length); + return toLspSymbols(symbols, { + hierarchical: deps.hierarchical, + uri: document.uri, + positionAt: (offset) => document.positionAt(offset), + }); + } catch (error) { + connection.console.error(`Document symbols for ${textDocument.uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }); +} diff --git a/src/server/features/foldingRanges.ts b/src/server/features/foldingRanges.ts new file mode 100644 index 0000000..3d3f7f3 --- /dev/null +++ b/src/server/features/foldingRanges.ts @@ -0,0 +1,45 @@ +import type { Connection, FoldingRange, TextDocuments } from 'vscode-languageserver/node'; +import { FoldingRangeKind } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { foldingRanges, type Fold } from '../syntax/folding.ts'; + +export interface FoldingClientOptions { + /** `textDocument.foldingRange.rangeLimit` of the client: a hint, honored by keeping the first ranges. */ + readonly rangeLimit: number | undefined; + /** `textDocument.foldingRange.foldingRangeKind.valueSet`; kinds outside it are omitted. */ + readonly kinds: readonly string[] | undefined; +} + +export interface FoldingRangesDeps extends FoldingClientOptions { + readonly cache: ParsedDocumentCache; +} + +/** LSP folding ranges for a client. Ranges are whole lines, so `lineFoldingOnly` clients are served as is. */ +export function toLspFoldingRanges(folds: readonly Fold[], options: FoldingClientOptions): FoldingRange[] { + const commentKind = options.kinds === undefined || options.kinds.includes(FoldingRangeKind.Comment); + const limited = options.rangeLimit === undefined ? folds : folds.slice(0, Math.max(0, options.rangeLimit)); + return limited.map(({ startLine, endLine, kind }) => ({ + startLine, + endLine, + ...(kind === 'comment' && commentKind ? { kind: FoldingRangeKind.Comment } : {}), + })); +} + +/** `textDocument/foldingRange` (see src/server/syntax/folding.ts). */ +export function register(connection: Connection, documents: TextDocuments, deps: FoldingRangesDeps): void { + connection.onFoldingRanges(({ textDocument }, token): FoldingRange[] | null => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) { + return null; + } + // Synchronous from here on: a cancellation can only arrive after the response. + const folds = foldingRanges(deps.cache.get(document), document.getText(), (offset) => document.positionAt(offset).line); + return toLspFoldingRanges(folds, deps); + } catch (error) { + connection.console.error(`Folding ranges for ${textDocument.uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }); +} diff --git a/src/server/server.ts b/src/server/server.ts index e5c65ac..c058144 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -9,12 +9,20 @@ import { TextDocumentSyncKind, } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; +import { ParsedDocumentCache } from './documentCache.ts'; import * as diagnostics from './features/diagnostics.ts'; +import * as documentSymbols from './features/documentSymbols.ts'; +import * as foldingRanges from './features/foldingRanges.ts'; import { SettingsStore } from './settingsStore.ts'; import { loadLua52 } from './validation/lua52.ts'; const connection = createConnection(ProposedFeatures.all); const documents = new TextDocuments(TextDocument); +/** Syntax trees shared by the features, one per open document version. */ +const parsed = new ParsedDocumentCache(); +documents.onDidClose(({ document }) => { + parsed.delete(document.uri); +}); const lua = loadLua52(); lua.catch((error: unknown) => { @@ -31,6 +39,16 @@ connection.onInitialize((params) => { settings: new SettingsStore(connection, configurationPull, params.initializationOptions), timers: { setTimeout, clearTimeout: (handle) => { clearTimeout(handle as NodeJS.Timeout); } }, }); + documentSymbols.register(connection, documents, { + cache: parsed, + hierarchical: params.capabilities.textDocument?.documentSymbol?.hierarchicalDocumentSymbolSupport === true, + }); + const folding = params.capabilities.textDocument?.foldingRange; + foldingRanges.register(connection, documents, { + cache: parsed, + rangeLimit: folding?.rangeLimit, + kinds: folding?.foldingRangeKind?.valueSet, + }); return { capabilities: { textDocumentSync: { @@ -38,6 +56,8 @@ connection.onInitialize((params) => { change: TextDocumentSyncKind.Incremental, save: { includeText: false }, }, + documentSymbolProvider: { label: 'IE Lua' }, + foldingRangeProvider: true, }, serverInfo: { name: 'IE Lua Language Server' }, }; diff --git a/src/server/syntax/ast.ts b/src/server/syntax/ast.ts new file mode 100644 index 0000000..d80a150 --- /dev/null +++ b/src/server/syntax/ast.ts @@ -0,0 +1,296 @@ +// Syntax tree of a Lua 5.2 chunk (grammar: Lua 5.2 manual §9). Pure data: no +// LSP or `vscode` imports. Every node spans the half-open offsets `[start, end)` +// of the source it was parsed from (document offsets, see lexer.ts). +// +// Closing keywords (`end`, `until`, `)`, `]`, `}`) are recorded as `closeStart`, +// the offset of the keyword. It is `undefined` when the keyword is missing; the +// node then ends where parsing stopped. + +import type { Comment, ParseError } from './lexer.ts'; + +interface Node { + readonly start: number; + readonly end: number; +} + +export interface Chunk extends Node { + readonly kind: 'Chunk'; + readonly body: Block; + readonly comments: readonly Comment[]; + /** Lexical and syntax errors, in source order. Empty when the chunk is valid Lua 5.2 (see parser.ts for the checks that are not done). */ + readonly errors: readonly ParseError[]; +} + +export interface Block extends Node { + readonly kind: 'Block'; + readonly body: readonly Statement[]; +} + +export interface Identifier extends Node { + readonly kind: 'Identifier'; + readonly name: string; +} + +// ---------------------------------------------------------------- statements + +export interface LocalStatement extends Node { + readonly kind: 'LocalStatement'; + readonly names: readonly Identifier[]; + readonly values: readonly Expression[]; +} + +export interface AssignmentStatement extends Node { + readonly kind: 'AssignmentStatement'; + /** Each target is an `Identifier`, `MemberExpression` (`.` only) or `IndexExpression`. */ + readonly targets: readonly Expression[]; + readonly values: readonly Expression[]; +} + +export interface CallStatement extends Node { + readonly kind: 'CallStatement'; + readonly call: CallExpression | MethodCallExpression; +} + +export interface DoStatement extends Node { + readonly kind: 'DoStatement'; + readonly body: Block; + readonly closeStart: number | undefined; +} + +export interface WhileStatement extends Node { + readonly kind: 'WhileStatement'; + readonly condition: Expression; + readonly body: Block; + readonly closeStart: number | undefined; +} + +export interface RepeatStatement extends Node { + readonly kind: 'RepeatStatement'; + readonly body: Block; + /** `undefined` when `until` is missing. */ + readonly condition: Expression | undefined; + /** Offset of `until`. */ + readonly closeStart: number | undefined; +} + +export interface IfClause extends Node { + readonly kind: 'IfClause'; + /** `if`, `elseif` or `else`; `start` is the offset of that keyword. */ + readonly keyword: 'if' | 'elseif' | 'else'; + /** `undefined` for `else`. */ + readonly condition: Expression | undefined; + readonly body: Block; +} + +export interface IfStatement extends Node { + readonly kind: 'IfStatement'; + readonly clauses: readonly IfClause[]; + readonly closeStart: number | undefined; +} + +export interface NumericForStatement extends Node { + readonly kind: 'NumericForStatement'; + readonly variable: Identifier; + readonly initial: Expression; + readonly limit: Expression; + readonly step: Expression | undefined; + readonly body: Block; + readonly closeStart: number | undefined; +} + +export interface GenericForStatement extends Node { + readonly kind: 'GenericForStatement'; + readonly variables: readonly Identifier[]; + readonly iterators: readonly Expression[]; + readonly body: Block; + readonly closeStart: number | undefined; +} + +/** `function a.b.c:m() … end`. */ +export interface FunctionDeclaration extends Node { + readonly kind: 'FunctionDeclaration'; + /** `a`, `b`, `c` in `function a.b.c:m()`; at least one. */ + readonly path: readonly Identifier[]; + /** `m` in `function a.b.c:m()`. */ + readonly method: Identifier | undefined; + readonly func: FunctionExpression; +} + +/** `local function f() … end`. */ +export interface LocalFunctionStatement extends Node { + readonly kind: 'LocalFunctionStatement'; + readonly name: Identifier; + readonly func: FunctionExpression; +} + +export interface ReturnStatement extends Node { + readonly kind: 'ReturnStatement'; + readonly values: readonly Expression[]; +} + +export interface BreakStatement extends Node { + readonly kind: 'BreakStatement'; +} + +export interface GotoStatement extends Node { + readonly kind: 'GotoStatement'; + readonly label: Identifier; +} + +export interface LabelStatement extends Node { + readonly kind: 'LabelStatement'; + readonly label: Identifier; +} + +export type Statement = + | LocalStatement + | AssignmentStatement + | CallStatement + | DoStatement + | WhileStatement + | RepeatStatement + | IfStatement + | NumericForStatement + | GenericForStatement + | FunctionDeclaration + | LocalFunctionStatement + | ReturnStatement + | BreakStatement + | GotoStatement + | LabelStatement; + +// --------------------------------------------------------------- expressions + +export interface NilLiteral extends Node { + readonly kind: 'NilLiteral'; +} + +export interface BooleanLiteral extends Node { + readonly kind: 'BooleanLiteral'; + readonly value: boolean; +} + +export interface NumberLiteral extends Node { + readonly kind: 'NumberLiteral'; + /** The numeral exactly as written. */ + readonly raw: string; +} + +export interface StringLiteral extends Node { + readonly kind: 'StringLiteral'; + /** The literal exactly as written, quotes or long brackets included. */ + readonly raw: string; +} + +export interface VarargLiteral extends Node { + readonly kind: 'VarargLiteral'; +} + +/** `function (params) … end`; also the body of declarations and local functions. */ +export interface FunctionExpression extends Node { + readonly kind: 'FunctionExpression'; + readonly parameters: readonly Identifier[]; + /** The parameter list ends with `...`. */ + readonly isVararg: boolean; + readonly body: Block; + readonly closeStart: number | undefined; +} + +export interface TableField extends Node { + readonly kind: 'TableField'; + /** `[k] = v` (`keyed`), `name = v` (`named`), or a positional `v` (`item`). */ + readonly form: 'keyed' | 'named' | 'item'; + /** Expression for `keyed`, `Identifier` for `named`, `undefined` for `item`. */ + readonly key: Expression | undefined; + readonly value: Expression; +} + +export interface TableConstructor extends Node { + readonly kind: 'TableConstructor'; + readonly fields: readonly TableField[]; + readonly closeStart: number | undefined; +} + +/** Binary operators of Lua 5.2 (manual §3.4). */ +export type BinaryOperator = + | 'or' | 'and' + | '<' | '>' | '<=' | '>=' | '~=' | '==' + | '..' + | '+' | '-' | '*' | '/' | '%' + | '^'; + +export type UnaryOperator = 'not' | '#' | '-'; + +export interface BinaryExpression extends Node { + readonly kind: 'BinaryExpression'; + readonly operator: BinaryOperator; + readonly left: Expression; + readonly right: Expression; +} + +export interface UnaryExpression extends Node { + readonly kind: 'UnaryExpression'; + readonly operator: UnaryOperator; + readonly argument: Expression; +} + +export interface ParenthesizedExpression extends Node { + readonly kind: 'ParenthesizedExpression'; + readonly expression: Expression; +} + +/** `base.name`. */ +export interface MemberExpression extends Node { + readonly kind: 'MemberExpression'; + readonly base: Expression; + readonly member: Identifier; +} + +/** `base[index]`. */ +export interface IndexExpression extends Node { + readonly kind: 'IndexExpression'; + readonly base: Expression; + readonly index: Expression; +} + +/** Arguments of a call: `( … )`, a table constructor or a string literal. */ +export interface CallArguments { + readonly form: 'parentheses' | 'table' | 'string'; + readonly values: readonly Expression[]; + /** Offset of `(` (or of the table / string). */ + readonly start: number; + /** Offset of `)`; `undefined` for the other forms or when `)` is missing. */ + readonly closeStart: number | undefined; +} + +/** `base(args)`. */ +export interface CallExpression extends Node { + readonly kind: 'CallExpression'; + readonly base: Expression; + readonly arguments: CallArguments; +} + +/** `base:method(args)`. */ +export interface MethodCallExpression extends Node { + readonly kind: 'MethodCallExpression'; + readonly base: Expression; + readonly method: Identifier; + readonly arguments: CallArguments; +} + +export type Expression = + | NilLiteral + | BooleanLiteral + | NumberLiteral + | StringLiteral + | VarargLiteral + | FunctionExpression + | TableConstructor + | BinaryExpression + | UnaryExpression + | ParenthesizedExpression + | Identifier + | MemberExpression + | IndexExpression + | CallExpression + | MethodCallExpression; diff --git a/src/server/syntax/document.ts b/src/server/syntax/document.ts new file mode 100644 index 0000000..b062436 --- /dev/null +++ b/src/server/syntax/document.ts @@ -0,0 +1,35 @@ +// 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 type { DocumentKind } from '../validation/validateText.ts'; +import type { Chunk } from './ast.ts'; +import { parseChunk } from './parser.ts'; +import { analyzeScopes, type ScopeAnalysis } from './scope.ts'; + +export interface ParsedChunk { + readonly chunk: LuaChunk; + readonly tree: Chunk; + readonly scopes: ScopeAnalysis; +} + +export interface ParsedDocument { + readonly kind: DocumentKind; + /** Lua chunks in document order. */ + readonly chunks: readonly ParsedChunk[]; + /** `{ … }` blocks of a .menu file; empty for Lua. */ + readonly blocks: readonly MenuBlock[]; +} + +/** 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 }); + return { chunk, tree, scopes: analyzeScopes(tree) }; + }; + if (kind === 'lua') { + return { kind, chunks: [parse({ kind: 'statements', origin: 'file', offset: 0, text })], 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 new file mode 100644 index 0000000..8168b79 --- /dev/null +++ b/src/server/syntax/folding.ts @@ -0,0 +1,209 @@ +// Folding ranges (LSP `textDocument/foldingRange`). Pure: no LSP or `vscode` +// imports; src/server/features/foldingRanges.ts converts the result. +// +// Once a language server provides folding ranges, VS Code uses them instead of +// indentation and of the `folding.markers` of language-configuration/ie-menu.json, +// so every construct those covered is covered here too. +// +// Constructs fold from their first line to the line before their closing +// keyword, which stays visible (`end`, `until`, `}`, `)`, the next `elseif` / +// `else`, a closing `]]`, backtick or quote). A construct whose closing keyword +// is missing folds to its last line. Comments fold entirely. +// +// Lua: function bodies, `do`, `while`, `for`, `repeat`, each `if` / `elseif` / +// `else` clause, table constructors, parenthesized call arguments, long strings, +// long comments and runs of two or more `--` lines. +// .menu: every `{ … }` block, `` `…` `` blocks and `"…"` scripts, and the Lua +// constructs inside them. +// VS Code's built-in Lua configuration defines no region markers, so none are +// recognized here. + +import type * as Ast from './ast.ts'; +import type { ParsedDocument } from './document.ts'; + +export interface Fold { + /** Zero-based lines, `startLine < endLine`. */ + readonly startLine: number; + readonly endLine: number; + readonly kind: 'comment' | undefined; +} + +export function foldingRanges(document: ParsedDocument, text: string, lineAt: (offset: number) => number): Fold[] { + const folds: Fold[] = []; + + /** From `start` to the line before `closeStart`; to the line of `end` when the closer is missing. */ + const fold = (start: number, closeStart: number | undefined, end: number): void => { + const startLine = lineAt(start); + const endLine = closeStart === undefined ? lineAt(end) : lineAt(closeStart) - 1; + if (endLine > startLine) folds.push({ startLine, endLine, kind: undefined }); + }; + + const comment = (start: number, end: number): void => { + const startLine = lineAt(start); + const endLine = lineAt(end); + if (endLine > startLine) folds.push({ startLine, endLine, kind: 'comment' }); + }; + + /** Only blanks between the start of its line and `offset`. */ + const startsLine = (offset: number): boolean => { + let i = offset - 1; + while (i >= 0 && (text[i] === ' ' || text[i] === '\t')) i--; + return i < 0 || text[i] === '\n' || text[i] === '\r'; + }; + + const block = (node: Ast.Block): void => { + for (const statement of node.body) visitStatement(statement); + }; + + const expressions = (nodes: readonly (Ast.Expression | undefined)[]): void => { + for (const node of nodes) if (node) visitExpression(node); + }; + + function func(node: Ast.FunctionExpression): void { + fold(node.start, node.closeStart, node.end); + block(node.body); + } + + function visitStatement(node: Ast.Statement): void { + switch (node.kind) { + case 'LocalStatement': + expressions(node.values); + break; + case 'AssignmentStatement': + expressions(node.targets); + expressions(node.values); + break; + case 'CallStatement': + visitExpression(node.call); + break; + case 'DoStatement': + fold(node.start, node.closeStart, node.end); + block(node.body); + break; + case 'WhileStatement': + fold(node.start, node.closeStart, node.end); + visitExpression(node.condition); + block(node.body); + break; + case 'RepeatStatement': + fold(node.start, node.closeStart, node.end); + block(node.body); + expressions([node.condition]); + break; + case 'IfStatement': + node.clauses.forEach((clause, index) => { + fold(clause.start, node.clauses[index + 1]?.start ?? node.closeStart, clause.end); + expressions([clause.condition]); + block(clause.body); + }); + break; + case 'NumericForStatement': + fold(node.start, node.closeStart, node.end); + expressions([node.initial, node.limit, node.step]); + block(node.body); + break; + case 'GenericForStatement': + fold(node.start, node.closeStart, node.end); + expressions(node.iterators); + block(node.body); + break; + case 'FunctionDeclaration': + case 'LocalFunctionStatement': + func(node.func); + break; + case 'ReturnStatement': + expressions(node.values); + break; + case 'BreakStatement': + case 'GotoStatement': + case 'LabelStatement': + break; + } + } + + function visitExpression(node: Ast.Expression): void { + switch (node.kind) { + case 'FunctionExpression': + func(node); + break; + case 'TableConstructor': + fold(node.start, node.closeStart, node.end); + for (const field of node.fields) expressions([field.form === 'keyed' ? field.key : undefined, field.value]); + break; + case 'StringLiteral': + // A long string keeps its closing bracket line visible. + if (node.raw.startsWith('[')) fold(node.start, node.end, node.end); + break; + case 'BinaryExpression': + expressions([node.left, node.right]); + break; + case 'UnaryExpression': + visitExpression(node.argument); + break; + case 'ParenthesizedExpression': + visitExpression(node.expression); + break; + case 'MemberExpression': + visitExpression(node.base); + break; + case 'IndexExpression': + expressions([node.base, node.index]); + break; + case 'CallExpression': + case 'MethodCallExpression': + visitExpression(node.base); + if (node.arguments.form === 'parentheses') fold(node.arguments.start, node.arguments.closeStart, node.end); + expressions(node.arguments.values); + break; + default: + break; + } + } + + 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); + } + block(tree.body); + // Runs of `--` comments that each start their own, consecutive line. + let run: { startLine: number; endLine: number } | undefined; + const endRun = (): void => { + if (run && run.endLine > run.startLine) folds.push({ ...run, kind: 'comment' }); + run = undefined; + }; + for (const c of tree.comments) { + if (c.long) { + endRun(); + comment(c.start, c.end); + } else if (startsLine(c.start)) { + const line = lineAt(c.start); + if (run?.endLine === line - 1) { + run.endLine = line; + } else { + endRun(); + run = { startLine: line, endLine: line }; + } + } else { + endRun(); + } + } + endRun(); + } + + const menuBlocks = (blocks: ParsedDocument['blocks']): void => { + for (const b of blocks) { + fold(b.keyword?.start ?? b.open, b.close, text.length); + menuBlocks(b.children); + } + }; + menuBlocks(document.blocks); + + // A line has one fold toggle, so keep one range per start line: the outermost. + const byStart = new Map(); + for (const f of folds) { + const existing = byStart.get(f.startLine); + if (!existing || f.endLine > existing.endLine) byStart.set(f.startLine, f); + } + return [...byStart.values()].sort((a, b) => a.startLine - b.startLine); +} diff --git a/src/server/syntax/lexer.ts b/src/server/syntax/lexer.ts new file mode 100644 index 0000000..c50f351 --- /dev/null +++ b/src/server/syntax/lexer.ts @@ -0,0 +1,250 @@ +// Lua 5.2 lexer, following the official lexer (lua-5.2.4/src/llex.c). Pure: no +// LSP or `vscode` imports. Offsets are positions in the JavaScript string (UTF-16 +// code units), the same unit `TextDocument.positionAt` uses, so tokens of a +// chunk embedded in a .menu file carry document offsets directly. + +export type TokenType = 'name' | 'keyword' | 'number' | 'string' | 'symbol' | 'eof'; + +export interface Token { + readonly type: TokenType; + /** Keyword or symbol text; the identifier for names; the source text for numbers and strings. */ + readonly value: string; + readonly start: number; + readonly end: number; +} + +export interface Comment { + readonly start: number; + readonly end: number; + /** `--[[ … ]]` (any level) rather than `-- …` to the end of the line. */ + readonly long: boolean; +} + +/** A lexical or syntax error as half-open offsets `[start, end)`. */ +export interface ParseError { + readonly start: number; + readonly end: number; + readonly message: string; +} + +export interface LexResult { + /** Always ends with one `eof` token. */ + readonly tokens: Token[]; + readonly comments: Comment[]; + readonly errors: ParseError[]; +} + +/** The 22 reserved words of Lua 5.2 (manual §3.1). */ +export const KEYWORDS: ReadonlySet = new Set([ + 'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', + 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while', +]); + +const isNewline = (c: string | undefined): boolean => c === '\n' || c === '\r'; +// llex.c uses lctype.c with LUA_UCID undefined: identifiers are ASCII only. +const isAlpha = (c: string | undefined): boolean => c !== undefined && /[A-Za-z_]/.test(c); +const isAlnum = (c: string | undefined): boolean => c !== undefined && /[A-Za-z0-9_]/.test(c); +const isDigit = (c: string | undefined): boolean => c !== undefined && c >= '0' && c <= '9'; +const isHexDigit = (c: string | undefined): boolean => c !== undefined && /[0-9A-Fa-f]/.test(c); +// lisspace: ' ', \t, \n, \v, \f, \r. +const isSpace = (c: string | undefined): boolean => c !== undefined && /[ \t\n\v\f\r]/.test(c); + +// luaO_str2d: decimal numbers go through strtod (but `inf`/`nan` are refused, +// and the lexer never reads letters other than hex digits and the exponent); +// hexadecimal ones through lua_strx2number, which needs at least one digit and +// a decimal exponent after `p`. +const DECIMAL = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/; +const HEXADECIMAL = /^0[xX](?:[0-9A-Fa-f]+\.?[0-9A-Fa-f]*|\.[0-9A-Fa-f]+)(?:[pP][+-]?\d+)?$/; + +/** Symbols of more than one character, longest first. */ +const LONG_SYMBOLS = ['...', '..', '==', '~=', '<=', '>=', '::']; + +/** + * Splits `source[from, to)` into tokens. Never throws: every problem is + * recorded in `errors` and lexing goes on, so that a tree can still be built. + */ +export function lex(source: string, from = 0, to = source.length): LexResult { + const tokens: Token[] = []; + const comments: Comment[] = []; + const errors: ParseError[] = []; + let i = from; + + const at = (index: number): string | undefined => (index < to ? source[index] : undefined); + const error = (start: number, end: number, message: string): void => { + errors.push({ start, end, message }); + }; + + /** + * llex.c `skip_sep`: at `[` or `]`, counts the `=` that follow. Returns the + * level when the same bracket follows them, otherwise `-1 - count`. + */ + const separator = (index: number): number => { + const bracket = at(index); + let j = index + 1; + while (at(j) === '=') j++; + return at(j) === bracket ? j - index - 1 : -1 - (j - index - 1); + }; + + /** Reads `[==[ … ]==]` starting at `i`; returns the end offset (or `to` when unfinished). */ + const longBracket = (level: number, what: 'string' | 'comment'): number => { + const start = i; + let j = i + level + 2; + while (j < to) { + if (source[j] === ']' && separator(j) === level) { + return j + level + 2; + } + j++; + } + error(start, to, `unfinished long ${what}`); + return to; + }; + + /** Reads a `'…'` or `"…"` string starting at `i`; returns its end offset. */ + const shortString = (): number => { + const start = i; + const quote = source[i]; + let j = i + 1; + for (;;) { + const c = at(j); + if (c === undefined || isNewline(c)) { + error(start, j, 'unfinished string'); + return j; + } + if (c === quote) { + return j + 1; + } + if (c !== '\\') { + j++; + continue; + } + // llex.c `read_string`, escape sequences. + const escapeStart = j; + const e = at(j + 1); + j += 2; + if (e === undefined) { + continue; // reported as an unfinished string on the next iteration + } + if ('abfnrtv\\"\''.includes(e)) { + continue; + } + if (isNewline(e)) { + // `\` followed by a line break: \n, \r, \r\n and \n\r count as one. + const next = at(j); + if (isNewline(next) && next !== e) j++; + continue; + } + if (e === 'x') { + if (isHexDigit(at(j)) && isHexDigit(at(j + 1))) { + j += 2; + } else { + error(escapeStart, Math.min(j + 2, to), 'hexadecimal digit expected'); + } + continue; + } + if (e === 'z') { + while (isSpace(at(j))) j++; + continue; + } + if (isDigit(e)) { + let k = j; + while (k < j + 2 && isDigit(at(k))) k++; + if (Number(source.slice(j - 1, k)) > 255) { + error(escapeStart, k, 'decimal escape too large'); + } + j = k; + continue; + } + error(escapeStart, j, 'invalid escape sequence'); + } + }; + + /** llex.c `read_numeral`: reads digits, hex digits, `.` and signed exponents. */ + const numeral = (): number => { + const start = i; + let exponent = 'Ee'; + let j = i + 1; + if (source[i] === '0' && (at(j) === 'x' || at(j) === 'X')) { + exponent = 'Pp'; + j++; + } + for (;;) { + const c = at(j); + if (c !== undefined && exponent.includes(c)) { + j++; + if (at(j) === '+' || at(j) === '-') j++; + } else if (isHexDigit(c) || c === '.') { + j++; + } else { + break; + } + } + const text = source.slice(start, j); + if (!(exponent === 'Pp' ? HEXADECIMAL : DECIMAL).test(text)) { + error(start, j, 'malformed number'); + } + return j; + }; + + const push = (type: TokenType, start: number, end: number, value = source.slice(start, end)): void => { + tokens.push({ type, value, start, end }); + }; + + while (i < to) { + const c = source[i]; + if (isSpace(c)) { + i++; + } else if (c === '-' && at(i + 1) === '-') { + const start = i; + i += 2; + if (at(i) === '[') { + const level = separator(i); + if (level >= 0) { + i = longBracket(level, 'comment'); + comments.push({ start, end: i, long: true }); + continue; + } + } + while (i < to && !isNewline(source[i])) i++; + comments.push({ start, end: i, long: false }); + } else if (c === '[') { + const level = separator(i); + if (level >= 0) { + const start = i; + i = longBracket(level, 'string'); + push('string', start, i); + } else { + if (level !== -1) { + error(i, i + 1 - level - 1, 'invalid long string delimiter'); + } + push('symbol', i, i + 1); + i++; + } + } else if (c === '"' || c === "'") { + const start = i; + i = shortString(); + push('string', start, i); + } else if (c === '.' && isDigit(at(i + 1))) { + const start = i; + i = numeral(); + push('number', start, i); + } else if (isDigit(c)) { + const start = i; + i = numeral(); + push('number', start, i); + } else if (isAlpha(c)) { + const start = i; + while (isAlnum(at(i))) i++; + const word = source.slice(start, i); + push(KEYWORDS.has(word) ? 'keyword' : 'name', start, i, word); + } else { + const symbol = LONG_SYMBOLS.find((s) => source.startsWith(s, i) && i + s.length <= to); + const length = symbol?.length ?? 1; + // Any other character becomes a one-character token (llex.c `default:`); + // the parser then reports it as an unexpected symbol. + push('symbol', i, i + length); + i += length; + } + } + tokens.push({ type: 'eof', value: '', start: to, end: to }); + return { tokens, comments, errors }; +} diff --git a/src/server/syntax/parser.ts b/src/server/syntax/parser.ts new file mode 100644 index 0000000..ebc81e8 --- /dev/null +++ b/src/server/syntax/parser.ts @@ -0,0 +1,616 @@ +// Error-tolerant Lua 5.2 parser: recursive descent over the grammar of the Lua +// 5.2 manual (§9), mirroring the official parser (lua-5.2.4/src/lparser.c) for +// what it accepts. Pure: no LSP or `vscode` imports. +// +// The tree feeds editor features (symbols, folding, …). Diagnostics still come +// only from the official compiler (src/server/validation/), so this parser +// publishes nothing; `Chunk.errors` only tells callers whether the tree is +// complete. Never throws: after an error it skips to the next statement and +// keeps going, so features keep working while the user types. +// +// Checks of lparser.c that are done: the grammar, operator precedence, `...` +// outside a vararg function, `break` outside a loop, and the nesting limit +// (LUAI_MAXCCALLS). Checks that are NOT done (code-generation limits and goto +// semantics): labels (duplicates, visibility, jumps into the scope of a local), +// and the limits on locals (200), upvalues (255), registers and constants. + +import type * as Ast from './ast.ts'; +import { lex, type ParseError, type Token } from './lexer.ts'; + +export interface ParseOptions { + /** First offset of the chunk in `source` (default 0). */ + readonly from?: number; + /** End offset of the chunk in `source` (default `source.length`). */ + 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. + */ + readonly mode?: 'statements' | 'expression'; +} + +/** lparser.c `priority`: [left, right]; right < left means right-associative. */ +const BINARY_PRIORITY: Readonly> = { + '+': [6, 6], '-': [6, 6], + '*': [7, 7], '/': [7, 7], '%': [7, 7], + '^': [10, 9], + '..': [5, 4], + '==': [3, 3], '<': [3, 3], '<=': [3, 3], '~=': [3, 3], '>': [3, 3], '>=': [3, 3], + 'and': [2, 2], + 'or': [1, 1], +}; +const UNARY_PRIORITY = 8; +/** luaconf.h LUAI_MAXCCALLS: nesting limit enforced by lparser.c `enterlevel`. */ +export const MAX_SYNTAX_LEVELS = 200; + +const STATEMENT_KEYWORDS: ReadonlySet = new Set([ + 'break', 'do', 'for', 'function', 'goto', 'if', 'local', 'repeat', 'return', 'while', +]); + +/** + * Thrown to abandon the statement being parsed; the error is already recorded. + * One shared instance: it is always caught inside this module, so no stack is needed. + */ +const ABORT = new Error('Lua parse aborted'); + +interface FunctionState { + readonly isVararg: boolean; + loopDepth: number; +} + +class Parser { + readonly errors: ParseError[] = []; + private readonly tokens: readonly Token[]; + private readonly eof: Token; + private readonly source: string; + private p = 0; + /** End offset of the last consumed token. */ + private previousEnd: number; + private level = 0; + private readonly functions: FunctionState[] = []; + + constructor(source: string, tokens: readonly Token[], from: number, to: number) { + this.source = source; + this.tokens = tokens; + this.eof = tokens.at(-1) ?? { type: 'eof', value: '', start: to, end: to }; + this.previousEnd = from; + } + + // ------------------------------------------------------------- token stream + + private get token(): Token { + return this.tokens[this.p] ?? this.eof; + } + + private lookahead(): Token { + return this.tokens[this.p + 1] ?? this.eof; + } + + private advance(): Token { + const token = this.token; + if (token.type !== 'eof') { + this.p++; + this.previousEnd = token.end; + } + return token; + } + + /** Current token is the keyword or symbol `value`. */ + private check(value: string): boolean { + const { type } = this.token; + return (type === 'keyword' || type === 'symbol') && this.token.value === value; + } + + private accept(value: string): Token | undefined { + return this.check(value) ? this.advance() : undefined; + } + + private near(token: Token = this.token): string { + return token.type === 'eof' ? 'near ' : `near '${token.value}'`; + } + + private record(message: string, token: Token = this.token): void { + this.errors.push({ start: token.start, end: token.end, message: `${message} ${this.near(token)}` }); + } + + private fail(message: string, token: Token = this.token): never { + this.record(message, token); + throw ABORT; + } + + private expect(value: string): Token { + return this.accept(value) ?? this.fail(`'${value}' expected`); + } + + /** Closing keyword of a construct. A missing one is recorded but does not abandon the construct. */ + private close(value: string, opener: string): number | undefined { + const token = this.accept(value); + if (!token) { + this.record(`'${value}' expected (to close '${opener}')`); + } + return token?.start; + } + + private name(): Ast.Identifier { + const token = this.token; + if (token.type !== 'name') { + this.fail(' expected'); + } + this.advance(); + return { kind: 'Identifier', name: token.value, start: token.start, end: token.end }; + } + + private enterLevel(): void { + if (++this.level > MAX_SYNTAX_LEVELS) { + this.fail(`too many C levels (limit is ${MAX_SYNTAX_LEVELS})`); + } + } + + private get currentFunction(): FunctionState { + // The chunk's own state is pushed before parsing starts and never popped. + return this.functions.at(-1) ?? { isVararg: true, loopDepth: 0 }; + } + + private blockFollow(withUntil: boolean): boolean { + const { type, value } = this.token; + if (type === 'eof') return true; + if (type !== 'keyword') return false; + return value === 'else' || value === 'elseif' || value === 'end' || (withUntil && value === 'until'); + } + + /** Skips to a token that can plausibly start a statement or end a block. */ + private synchronize(startIndex: number): void { + if (this.p === startIndex) { + this.advance(); + } + while (this.token.type !== 'eof') { + const token = this.token; + if (token.type === 'keyword' && (STATEMENT_KEYWORDS.has(token.value) || this.blockFollow(true))) return; + if (this.check(';') || this.check('::')) return; + // A name or `(` that starts a line probably starts a new statement. + const previous = this.tokens[this.p - 1]; + if ((token.type === 'name' || this.check('(')) && previous && /[\n\r]/.test(this.source.slice(previous.end, token.start))) return; + this.advance(); + } + } + + // --------------------------------------------------------------- chunks + + chunk(from: number): Ast.Block { + this.functions.push({ isVararg: true, loopDepth: 0 }); + const body: Ast.Statement[] = []; + for (;;) { + body.push(...this.statementList()); + if (this.token.type === 'eof') break; + // A stray `end`, `until`, … at the top level, or code after `return`. + this.record("'' expected"); + this.advance(); + } + return { kind: 'Block', body, start: from, end: this.previousEnd }; + } + + /** `return [;]` followed by the end of the chunk. */ + expressionChunk(from: number): Ast.Block { + this.functions.push({ isVararg: true, loopDepth: 0 }); + const body: Ast.Statement[] = []; + try { + const values = this.token.type === 'eof' || this.check(';') ? [] : this.expressionList(); + this.accept(';'); + body.push({ kind: 'ReturnStatement', values, start: from, end: this.previousEnd }); + if (this.token.type !== 'eof') { + this.record("'' expected"); + } + } catch (error) { + if (error !== ABORT) throw error; + } + return { kind: 'Block', body, start: from, end: this.previousEnd }; + } + + // ----------------------------------------------------------- statements + + private block(): Ast.Block { + const start = this.token.start; + const body = this.statementList(); + return { kind: 'Block', body, start, end: Math.max(start, this.previousEnd) }; + } + + /** lparser.c `statlist`: statements up to a block end; `return` must be last. */ + private statementList(): Ast.Statement[] { + const body: Ast.Statement[] = []; + while (!this.blockFollow(true)) { + const isReturn = this.check('return'); + const startIndex = this.p; + try { + const statement = this.statement(); + if (statement) body.push(statement); + } catch (error) { + if (error !== ABORT) throw error; + this.synchronize(startIndex); + continue; + } + if (isReturn) break; + } + return body; + } + + private loopBody(): Ast.Block { + const fn = this.currentFunction; + fn.loopDepth++; + try { + return this.block(); + } finally { + fn.loopDepth--; + } + } + + private statement(): Ast.Statement | undefined { + const level = this.level; + try { + this.enterLevel(); + return this.statementBody(); + } finally { + this.level = level; + } + } + + private statementBody(): Ast.Statement | undefined { + const token = this.token; + const start = token.start; + if (token.type === 'keyword') { + switch (token.value) { + case 'if': + return this.ifStatement(); + case 'while': { + this.advance(); + const condition = this.expression(); + this.expect('do'); + const body = this.loopBody(); + const closeStart = this.close('end', 'while'); + return { kind: 'WhileStatement', condition, body, closeStart, start, end: this.previousEnd }; + } + case 'do': { + this.advance(); + const body = this.block(); + const closeStart = this.close('end', 'do'); + return { kind: 'DoStatement', body, closeStart, start, end: this.previousEnd }; + } + case 'for': + return this.forStatement(); + case 'repeat': { + this.advance(); + const body = this.loopBody(); + const closeStart = this.close('until', 'repeat'); + const condition = closeStart === undefined ? undefined : this.expression(); + return { kind: 'RepeatStatement', body, condition, closeStart, start, end: this.previousEnd }; + } + case 'function': { + this.advance(); + const path = [this.name()]; + while (this.accept('.')) path.push(this.name()); + const method = this.accept(':') ? this.name() : undefined; + const func = this.functionBody(start); + return { kind: 'FunctionDeclaration', path, method, func, start, end: this.previousEnd }; + } + case 'local': { + this.advance(); + if (this.accept('function')) { + const name = this.name(); + const func = this.functionBody(start); + return { kind: 'LocalFunctionStatement', name, func, start, end: this.previousEnd }; + } + const names = [this.name()]; + while (this.accept(',')) names.push(this.name()); + const values = this.accept('=') ? this.expressionList() : []; + return { kind: 'LocalStatement', names, values, start, end: this.previousEnd }; + } + case 'return': { + this.advance(); + const values = this.blockFollow(true) || this.check(';') ? [] : this.expressionList(); + this.accept(';'); + return { kind: 'ReturnStatement', values, start, end: this.previousEnd }; + } + case 'break': + this.advance(); + if (this.currentFunction.loopDepth === 0) { + this.errors.push({ start, end: token.end, message: "'break' not inside a loop" }); + } + return { kind: 'BreakStatement', start, end: this.previousEnd }; + case 'goto': { + this.advance(); + const label = this.name(); + return { kind: 'GotoStatement', label, start, end: this.previousEnd }; + } + default: + break; + } + } + if (this.accept(';')) { + return undefined; + } + if (this.accept('::')) { + const label = this.name(); + this.expect('::'); + return { kind: 'LabelStatement', label, start, end: this.previousEnd }; + } + return this.expressionStatement(); + } + + private ifStatement(): Ast.IfStatement { + const start = this.token.start; + const clauses: Ast.IfClause[] = []; + const conditional = (keyword: 'if' | 'elseif'): void => { + const clauseStart = this.advance().start; + const condition = this.expression(); + this.expect('then'); + const body = this.block(); + clauses.push({ kind: 'IfClause', keyword, condition, body, start: clauseStart, end: this.previousEnd }); + }; + conditional('if'); + while (this.check('elseif')) conditional('elseif'); + if (this.check('else')) { + const clauseStart = this.advance().start; + const body = this.block(); + clauses.push({ kind: 'IfClause', keyword: 'else', condition: undefined, body, start: clauseStart, end: this.previousEnd }); + } + const closeStart = this.close('end', 'if'); + return { kind: 'IfStatement', clauses, closeStart, start, end: this.previousEnd }; + } + + private forStatement(): Ast.NumericForStatement | Ast.GenericForStatement { + const start = this.advance().start; + const first = this.name(); + if (this.accept('=')) { + const initial = this.expression(); + this.expect(','); + const limit = this.expression(); + const step = this.accept(',') ? this.expression() : undefined; + this.expect('do'); + const body = this.loopBody(); + const closeStart = this.close('end', 'for'); + return { kind: 'NumericForStatement', variable: first, initial, limit, step, body, closeStart, start, end: this.previousEnd }; + } + if (!this.check(',') && !this.check('in')) { + this.fail("'=' or 'in' expected"); + } + const variables = [first]; + while (this.accept(',')) variables.push(this.name()); + this.expect('in'); + const iterators = this.expressionList(); + this.expect('do'); + const body = this.loopBody(); + const closeStart = this.close('end', 'for'); + return { kind: 'GenericForStatement', variables, iterators, body, closeStart, start, end: this.previousEnd }; + } + + /** lparser.c `exprstat`: an assignment or a function call. */ + private expressionStatement(): Ast.AssignmentStatement | Ast.CallStatement { + const start = this.token.start; + const first = this.suffixedExpression(); + if (this.check('=') || this.check(',')) { + const targets = [this.assignable(first)]; + while (this.accept(',')) targets.push(this.assignable(this.suffixedExpression())); + this.expect('='); + const values = this.expressionList(); + return { kind: 'AssignmentStatement', targets, values, start, end: this.previousEnd }; + } + if (first.kind !== 'CallExpression' && first.kind !== 'MethodCallExpression') { + this.fail('syntax error'); + } + return { kind: 'CallStatement', call: first, start, end: this.previousEnd }; + } + + private assignable(target: Ast.Expression): Ast.Expression { + if (target.kind !== 'Identifier' && target.kind !== 'MemberExpression' && target.kind !== 'IndexExpression') { + this.fail('syntax error'); + } + return target; + } + + /** `(params) block end`; `start` is the offset of `function` (or `local`). */ + private functionBody(start: number): Ast.FunctionExpression { + this.expect('('); + const parameters: Ast.Identifier[] = []; + let isVararg = false; + if (!this.check(')')) { + do { + if (this.accept('...')) { + isVararg = true; + } else if (this.token.type === 'name') { + parameters.push(this.name()); + } else { + this.fail(' expected'); + } + } while (!isVararg && this.accept(',')); + } + this.expect(')'); + this.functions.push({ isVararg, loopDepth: 0 }); + let body: Ast.Block; + try { + body = this.block(); + } finally { + this.functions.pop(); + } + const closeStart = this.close('end', 'function'); + return { kind: 'FunctionExpression', parameters, isVararg, body, closeStart, start, end: this.previousEnd }; + } + + // ---------------------------------------------------------- expressions + + private expressionList(): Ast.Expression[] { + const values = [this.expression()]; + while (this.accept(',')) values.push(this.expression()); + return values; + } + + private expression(): Ast.Expression { + return this.subexpression(0); + } + + private binaryOperator(): Ast.BinaryOperator | undefined { + const { type, value } = this.token; + if ((type === 'symbol' || type === 'keyword') && Object.hasOwn(BINARY_PRIORITY, value)) { + return value as Ast.BinaryOperator; + } + return undefined; + } + + /** lparser.c `subexpr`: operators with a left priority above `limit`. */ + private subexpression(limit: number): Ast.Expression { + const level = this.level; + try { + this.enterLevel(); + const start = this.token.start; + let left: Ast.Expression; + if (this.check('not') || this.check('-') || this.check('#')) { + const operator = this.advance().value as Ast.UnaryOperator; + const argument = this.subexpression(UNARY_PRIORITY); + left = { kind: 'UnaryExpression', operator, argument, start, end: this.previousEnd }; + } else { + left = this.simpleExpression(); + } + for (let operator = this.binaryOperator(); operator && BINARY_PRIORITY[operator][0] > limit; operator = this.binaryOperator()) { + this.advance(); + const right = this.subexpression(BINARY_PRIORITY[operator][1]); + left = { kind: 'BinaryExpression', operator, left, right, start, end: this.previousEnd }; + } + return left; + } finally { + this.level = level; + } + } + + private simpleExpression(): Ast.Expression { + const token = this.token; + const { start, end } = token; + switch (token.type) { + case 'number': + this.advance(); + return { kind: 'NumberLiteral', raw: token.value, start, end }; + case 'string': + this.advance(); + return { kind: 'StringLiteral', raw: token.value, start, end }; + case 'keyword': + if (token.value === 'nil') { + this.advance(); + return { kind: 'NilLiteral', start, end }; + } + if (token.value === 'true' || token.value === 'false') { + this.advance(); + return { kind: 'BooleanLiteral', value: token.value === 'true', start, end }; + } + if (token.value === 'function') { + this.advance(); + return this.functionBody(start); + } + break; + case 'symbol': + if (token.value === '...') { + if (!this.currentFunction.isVararg) { + this.fail("cannot use '...' outside a vararg function"); + } + this.advance(); + return { kind: 'VarargLiteral', start, end }; + } + if (token.value === '{') { + return this.tableConstructor(); + } + break; + default: + break; + } + return this.suffixedExpression(); + } + + private primaryExpression(): Ast.Expression { + const token = this.token; + if (token.type === 'name') { + return this.name(); + } + if (this.accept('(')) { + const expression = this.expression(); + this.expect(')'); + return { kind: 'ParenthesizedExpression', expression, start: token.start, end: this.previousEnd }; + } + this.fail('unexpected symbol'); + } + + private suffixedExpression(): Ast.Expression { + const start = this.token.start; + let expression = this.primaryExpression(); + for (;;) { + if (this.accept('.')) { + const member = this.name(); + expression = { kind: 'MemberExpression', base: expression, member, start, end: this.previousEnd }; + } else if (this.accept('[')) { + const index = this.expression(); + this.expect(']'); + expression = { kind: 'IndexExpression', base: expression, index, start, end: this.previousEnd }; + } else if (this.accept(':')) { + const method = this.name(); + const args = this.callArguments(); + expression = { kind: 'MethodCallExpression', base: expression, method, arguments: args, start, end: this.previousEnd }; + } else if (this.check('(') || this.check('{') || this.token.type === 'string') { + const args = this.callArguments(); + expression = { kind: 'CallExpression', base: expression, arguments: args, start, end: this.previousEnd }; + } else { + return expression; + } + } + } + + private callArguments(): Ast.CallArguments { + const token = this.token; + if (token.type === 'string') { + this.advance(); + const value: Ast.StringLiteral = { kind: 'StringLiteral', raw: token.value, start: token.start, end: token.end }; + return { form: 'string', values: [value], start: token.start, closeStart: undefined }; + } + if (this.check('{')) { + return { form: 'table', values: [this.tableConstructor()], start: token.start, closeStart: undefined }; + } + if (this.accept('(')) { + const values = this.check(')') ? [] : this.expressionList(); + const closeStart = this.expect(')').start; + return { form: 'parentheses', values, start: token.start, closeStart }; + } + this.fail('function arguments expected'); + } + + private tableConstructor(): Ast.TableConstructor { + const start = this.expect('{').start; + const fields: Ast.TableField[] = []; + while (!this.check('}')) { + const fieldStart = this.token.start; + if (this.token.type === 'name' && this.lookahead().type === 'symbol' && this.lookahead().value === '=') { + const key = this.name(); + this.advance(); + const value = this.expression(); + fields.push({ kind: 'TableField', form: 'named', key, value, start: fieldStart, end: this.previousEnd }); + } else if (this.accept('[')) { + const key = this.expression(); + this.expect(']'); + this.expect('='); + const value = this.expression(); + fields.push({ kind: 'TableField', form: 'keyed', key, value, start: fieldStart, end: this.previousEnd }); + } else { + const value = this.expression(); + fields.push({ kind: 'TableField', form: 'item', key: undefined, value, start: fieldStart, end: this.previousEnd }); + } + if (!this.accept(',') && !this.accept(';')) break; + } + const closeStart = this.expect('}').start; + return { kind: 'TableConstructor', fields, closeStart, start, end: this.previousEnd }; + } +} + +/** Parses `source[from, to)` into a syntax tree. Never throws. */ +export function parseChunk(source: string, options: ParseOptions = {}): Ast.Chunk { + 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 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/scope.ts b/src/server/syntax/scope.ts new file mode 100644 index 0000000..a64af76 --- /dev/null +++ b/src/server/syntax/scope.ts @@ -0,0 +1,210 @@ +// Name resolution for a Lua 5.2 chunk, following the visibility rules of the +// manual (§3.5). Pure: no LSP or `vscode` imports. +// +// - `local x = x`: the new `x` is visible only after the statement. +// - `local function f`: `f` is visible inside its own body. +// - Parameters, and the implicit `self` of `function a:m()`, are visible in the +// function body; `for` variables in the loop body. +// - `repeat … until cond`: `cond` sees the locals of the body. +// - Any other name is a global (a field of _ENV). + +import type * as Ast from './ast.ts'; + +export type DeclarationKind = 'local' | 'localFunction' | 'parameter' | 'self' | 'forVariable'; + +export interface Declaration { + readonly name: string; + readonly kind: DeclarationKind; + /** The declaring identifier; `undefined` for the implicit `self`. */ + readonly identifier: Ast.Identifier | undefined; + /** Uses of the declaration, in source order (the declaring identifier excluded). */ + readonly references: Ast.Identifier[]; +} + +export interface ScopeAnalysis { + /** Every local declaration, in source order. */ + readonly declarations: readonly Declaration[]; + /** The declaration of each identifier that names a local, including declaring identifiers. Globals are absent. */ + readonly resolved: ReadonlyMap; + /** Identifiers that name globals, by name, in source order. */ + readonly globals: ReadonlyMap; +} + +export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { + const declarations: Declaration[] = []; + const resolved = new Map(); + const globals = new Map(); + const scopes: Map[] = []; + + const declare = (kind: DeclarationKind, name: string, identifier: Ast.Identifier | undefined): void => { + const declaration: Declaration = { name, kind, identifier, references: [] }; + declarations.push(declaration); + if (identifier) resolved.set(identifier, declaration); + scopes.at(-1)?.set(name, declaration); + }; + + const use = (identifier: Ast.Identifier): void => { + for (let i = scopes.length - 1; i >= 0; i--) { + const declaration = scopes[i]?.get(identifier.name); + if (declaration) { + declaration.references.push(identifier); + resolved.set(identifier, declaration); + return; + } + } + const uses = globals.get(identifier.name); + if (uses) uses.push(identifier); + else globals.set(identifier.name, [identifier]); + }; + + const scoped = (body: () => void): void => { + scopes.push(new Map()); + try { + body(); + } finally { + scopes.pop(); + } + }; + + const block = (node: Ast.Block): void => { + for (const statement of node.body) visitStatement(statement); + }; + + const func = (node: Ast.FunctionExpression, isMethod: boolean): void => { + scoped(() => { + if (isMethod) declare('self', 'self', undefined); + for (const parameter of node.parameters) declare('parameter', parameter.name, parameter); + block(node.body); + }); + }; + + const expressions = (nodes: readonly Ast.Expression[]): void => { + for (const node of nodes) visitExpression(node); + }; + + function visitStatement(node: Ast.Statement): void { + switch (node.kind) { + case 'LocalStatement': + expressions(node.values); + for (const name of node.names) declare('local', name.name, name); + break; + case 'LocalFunctionStatement': + declare('localFunction', node.name.name, node.name); + func(node.func, false); + break; + case 'FunctionDeclaration': { + // Only the first name is a variable; the rest are field names. + const [first] = node.path; + if (first) use(first); + func(node.func, node.method !== undefined); + break; + } + case 'AssignmentStatement': + // No declaration happens in between, so visiting in source order is exact. + expressions(node.targets); + expressions(node.values); + break; + case 'CallStatement': + visitExpression(node.call); + break; + case 'DoStatement': + scoped(() => { + block(node.body); + }); + break; + case 'WhileStatement': + visitExpression(node.condition); + scoped(() => { + block(node.body); + }); + break; + case 'RepeatStatement': + scoped(() => { + block(node.body); + if (node.condition) visitExpression(node.condition); + }); + break; + case 'IfStatement': + for (const clause of node.clauses) { + if (clause.condition) visitExpression(clause.condition); + scoped(() => { + block(clause.body); + }); + } + break; + case 'NumericForStatement': + visitExpression(node.initial); + visitExpression(node.limit); + if (node.step) visitExpression(node.step); + scoped(() => { + declare('forVariable', node.variable.name, node.variable); + block(node.body); + }); + break; + case 'GenericForStatement': + expressions(node.iterators); + scoped(() => { + for (const variable of node.variables) declare('forVariable', variable.name, variable); + block(node.body); + }); + break; + case 'ReturnStatement': + expressions(node.values); + break; + case 'BreakStatement': + case 'GotoStatement': + case 'LabelStatement': + break; + } + } + + function visitExpression(node: Ast.Expression): void { + switch (node.kind) { + case 'Identifier': + use(node); + break; + case 'FunctionExpression': + func(node, false); + break; + case 'TableConstructor': + for (const field of node.fields) { + if (field.form === 'keyed' && field.key) visitExpression(field.key); + visitExpression(field.value); + } + break; + case 'BinaryExpression': + visitExpression(node.left); + visitExpression(node.right); + break; + case 'UnaryExpression': + visitExpression(node.argument); + break; + case 'ParenthesizedExpression': + visitExpression(node.expression); + break; + case 'MemberExpression': + visitExpression(node.base); + break; + case 'IndexExpression': + visitExpression(node.base); + visitExpression(node.index); + break; + case 'CallExpression': + case 'MethodCallExpression': + visitExpression(node.base); + expressions(node.arguments.values); + break; + case 'NilLiteral': + case 'BooleanLiteral': + case 'NumberLiteral': + case 'StringLiteral': + case 'VarargLiteral': + break; + } + } + + scoped(() => { + block(chunk.body); + }); + return { declarations, resolved, globals }; +} diff --git a/src/server/syntax/symbols.ts b/src/server/syntax/symbols.ts new file mode 100644 index 0000000..80c5940 --- /dev/null +++ b/src/server/syntax/symbols.ts @@ -0,0 +1,297 @@ +// Outline of a document (LSP `textDocument/documentSymbol`). Pure: no LSP or +// `vscode` imports; src/server/features/documentSymbols.ts converts the result. +// +// Lua: +// - functions: `function a.b:m()`, `local function f`, and `x = function` / +// `local x = function` / `t.f = function`, at any depth, nested under the +// function that contains them; +// - variables: locals declared by top-level statements of a chunk, and the +// first assignment to each global outside any function. Their table +// constructors list named fields as children. +// Assignments to existing locals and locals inside functions or blocks are not +// listed, so that the outline shows what a file defines rather than every name. +// +// .menu files: each `menu { … }` block is a namespace named by its `name` +// property, holding the Lua symbols of the chunks inside it. `"…"` scripts +// (`action`, `onOpen`, …) contribute functions only; their assignments are +// runtime state, not definitions. + +import type * as Ast from './ast.ts'; +import type { ParsedChunk, ParsedDocument } from './document.ts'; +import type { ScopeAnalysis } from './scope.ts'; + +export type OutlineKind = 'function' | 'method' | 'variable' | 'field' | 'namespace'; + +export interface OutlineSymbol { + /** Never empty (LSP clients reject empty names). */ + readonly name: string; + readonly kind: OutlineKind; + /** Parameter list of functions, e.g. `(a, b, ...)`. */ + readonly detail: string | undefined; + /** The whole construct, `[start, end)` document offsets. */ + readonly start: number; + readonly end: number; + /** The name, inside `[start, end)`. */ + readonly selectionStart: number; + readonly selectionEnd: number; + readonly children: OutlineSymbol[]; +} + +interface Context { + readonly container: OutlineSymbol[]; + readonly scopes: ScopeAnalysis; + /** Directly in the chunk's top-level block: locals are listed. */ + readonly topLevel: boolean; + /** Outside every function body (and not in a menu script): global assignments are listed. */ + readonly listGlobals: boolean; + /** Globals already listed in this document. */ + readonly seenGlobals: Set; +} + +const nested = (context: Context, container: OutlineSymbol[]): Context => ({ ...context, container, topLevel: false }); +const inFunction = (context: Context, container: OutlineSymbol[]): Context => ({ ...nested(context, container), listGlobals: false }); + +function parameters(func: Ast.FunctionExpression): string { + const names = func.parameters.map((p) => p.name); + if (func.isVararg) names.push('...'); + return `(${names.join(', ')})`; +} + +/** `a`, `a.b.c` for identifiers and `.` chains on an identifier; `undefined` otherwise. */ +function dottedName(expression: Ast.Expression): string | undefined { + if (expression.kind === 'Identifier') return expression.name; + if (expression.kind === 'MemberExpression') { + const base = dottedName(expression.base); + return base === undefined ? undefined : `${base}.${expression.member.name}`; + } + return undefined; +} + +function functionSymbol( + name: string, + kind: 'function' | 'method', + range: { start: number; end: number }, + selection: { start: number; end: number }, + func: Ast.FunctionExpression, + context: Context, +): OutlineSymbol { + const symbol: OutlineSymbol = { + name, kind, detail: parameters(func), start: range.start, end: range.end, + selectionStart: selection.start, selectionEnd: selection.end, children: [], + }; + block(func.body, inFunction(context, symbol.children)); + return symbol; +} + +/** A variable or field; named fields of a table constructor value become children. */ +function valueSymbol( + name: string, + kind: 'variable' | 'field', + range: { start: number; end: number }, + selection: { start: number; end: number }, + value: Ast.Expression | undefined, + context: Context, +): OutlineSymbol { + const symbol: OutlineSymbol = { + name, kind, detail: undefined, start: range.start, end: range.end, + selectionStart: selection.start, selectionEnd: selection.end, children: [], + }; + if (value?.kind === 'TableConstructor') { + tableFields(value, nested(context, symbol.children)); + } else if (value) { + expression(value, nested(context, symbol.children)); + } + return symbol; +} + +function tableFields(table: Ast.TableConstructor, context: Context): void { + for (const field of table.fields) { + if (field.form === 'named' && field.key?.kind === 'Identifier') { + context.container.push( + field.value.kind === 'FunctionExpression' + ? functionSymbol(field.key.name, 'function', field, field.key, field.value, context) + : valueSymbol(field.key.name, 'field', field, field.key, field.value, context), + ); + } else { + if (field.key) expression(field.key, context); + expression(field.value, context); + } + } +} + +/** Finds functions nested in an expression (callbacks, table fields, …). */ +function expression(node: Ast.Expression, context: Context): void { + switch (node.kind) { + case 'FunctionExpression': + block(node.body, inFunction(context, context.container)); + break; + case 'TableConstructor': + for (const field of node.fields) { + if (field.form === 'keyed' && field.key) expression(field.key, context); + expression(field.value, context); + } + break; + case 'BinaryExpression': + expression(node.left, context); + expression(node.right, context); + break; + case 'UnaryExpression': + expression(node.argument, context); + break; + case 'ParenthesizedExpression': + expression(node.expression, context); + break; + case 'MemberExpression': + expression(node.base, context); + break; + case 'IndexExpression': + expression(node.base, context); + expression(node.index, context); + break; + case 'CallExpression': + case 'MethodCallExpression': + expression(node.base, context); + for (const argument of node.arguments.values) expression(argument, context); + break; + default: + break; + } +} + +function block(node: Ast.Block, context: Context): void { + for (const statement of node.body) { + visit(statement, context); + } +} + +function visit(node: Ast.Statement, context: Context): void { + switch (node.kind) { + case 'LocalStatement': + node.names.forEach((name, index) => { + const value = node.values[index]; + if (value?.kind === 'FunctionExpression') { + context.container.push(functionSymbol(name.name, 'function', node, name, value, context)); + } else if (context.topLevel) { + context.container.push(valueSymbol(name.name, 'variable', node, name, value, context)); + } else if (value) { + expression(value, context); + } + }); + for (const value of node.values.slice(node.names.length)) expression(value, context); + break; + case 'LocalFunctionStatement': + context.container.push(functionSymbol(node.name.name, 'function', node, node.name, node.func, context)); + break; + case 'FunctionDeclaration': { + const [first] = node.path; + const last = node.method ?? node.path.at(-1); + if (!first || !last) break; + const path = node.path.map((p) => p.name).join('.'); + const name = node.method ? `${path}:${node.method.name}` : path; + context.container.push( + functionSymbol(name, node.method ? 'method' : 'function', node, { start: first.start, end: last.end }, node.func, context), + ); + break; + } + case 'AssignmentStatement': + node.targets.forEach((target, index) => { + const value = node.values[index]; + const name = dottedName(target); + if (value?.kind === 'FunctionExpression' && name !== undefined) { + context.container.push(functionSymbol(name, 'function', node, target, value, context)); + return; + } + if ( + target.kind === 'Identifier' && + context.listGlobals && + !context.scopes.resolved.has(target) && + !context.seenGlobals.has(target.name) + ) { + context.seenGlobals.add(target.name); + context.container.push(valueSymbol(target.name, 'variable', node, target, value, context)); + return; + } + expression(target, context); + if (value) expression(value, context); + }); + for (const value of node.values.slice(node.targets.length)) expression(value, context); + break; + case 'CallStatement': + expression(node.call, context); + break; + case 'DoStatement': + block(node.body, nested(context, context.container)); + break; + case 'WhileStatement': + expression(node.condition, context); + block(node.body, nested(context, context.container)); + break; + case 'RepeatStatement': + block(node.body, nested(context, context.container)); + if (node.condition) expression(node.condition, context); + break; + case 'IfStatement': + for (const clause of node.clauses) { + if (clause.condition) expression(clause.condition, context); + block(clause.body, nested(context, context.container)); + } + break; + case 'NumericForStatement': + for (const value of [node.initial, node.limit, node.step]) if (value) expression(value, context); + block(node.body, nested(context, context.container)); + break; + case 'GenericForStatement': + for (const value of node.iterators) expression(value, context); + block(node.body, nested(context, context.container)); + break; + case 'ReturnStatement': + for (const value of node.values) expression(value, context); + break; + case 'BreakStatement': + case 'GotoStatement': + case 'LabelStatement': + break; + } +} + +function chunkSymbols(parsed: ParsedChunk, container: OutlineSymbol[], seenGlobals: Set): void { + const script = parsed.chunk.origin === 'property'; + block(parsed.tree.body, { + container, + scopes: parsed.scopes, + topLevel: !script, + listGlobals: !script, + seenGlobals, + }); +} + +/** The outline of a parsed document, in document order. */ +export function documentSymbols(document: ParsedDocument, textLength: number): OutlineSymbol[] { + const root: OutlineSymbol[] = []; + const seenGlobals = new Set(); + const menus: OutlineSymbol[] = []; + for (const block of document.blocks) { + if (block.keyword?.text.toLowerCase() !== 'menu') continue; + const { keyword } = block; + const name = block.name && block.name.text.trim() !== '' ? block.name : keyword; + const menu: OutlineSymbol = { + name: name.text, + kind: 'namespace', + detail: undefined, + start: keyword.start, + end: block.close === undefined ? textLength : block.close + 1, + selectionStart: name.start, + selectionEnd: name.end, + children: [], + }; + menus.push(menu); + root.push(menu); + } + for (const parsed of document.chunks) { + const offset = parsed.chunk.offset; + const menu = menus.find((m) => m.start <= offset && offset < m.end); + chunkSymbols(parsed, menu?.children ?? root, seenGlobals); + } + root.sort((a, b) => a.start - b.start); + return root; +} diff --git a/src/server/validation/menuExtractor.ts b/src/server/validation/menuExtractor.ts index c1aee3f..78b2151 100644 --- a/src/server/validation/menuExtractor.ts +++ b/src/server/validation/menuExtractor.ts @@ -27,9 +27,42 @@ const STATEMENT_PROPERTIES: ReadonlySet = new Set([ */ const EXPRESSION_PROPERTIES: ReadonlySet = new Set(['enabled']); +/** A word of a .menu file, as half-open document offsets. */ +export interface MenuWord { + readonly text: string; + readonly start: number; + readonly end: number; +} + +/** 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. + */ + 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). */ + readonly name: MenuWord | undefined; + readonly children: readonly MenuBlock[]; +} + export interface MenuExtraction { readonly chunks: LuaChunk[]; readonly problems: Problem[]; + /** Top-level `{ … }` blocks, with their nested blocks. */ + readonly blocks: MenuBlock[]; +} + +interface OpenBlock { + keyword: MenuWord | undefined; + open: number; + close: number | undefined; + name: MenuWord | undefined; + children: OpenBlock[]; } function isWordChar(c: string | undefined): boolean { @@ -47,13 +80,18 @@ function isWordChar(c: string | undefined): boolean { * * `--` 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). + * + * The same scan also records the nesting of `{ … }` blocks and their `name`. */ export function extractMenuLua(text: string): MenuExtraction { const chunks: LuaChunk[] = []; const problems: Problem[] = []; + 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: string[] = []; - let previousLineWords: string[] = []; + let lineWords: MenuWord[] = []; + let previousLineWords: MenuWord[] = []; let i = 0; const endLine = (): void => { @@ -81,7 +119,7 @@ export function extractMenuLua(text: string): MenuExtraction { }); break; } - chunks.push({ kind: 'statements', offset: i + 1, text: text.slice(i + 1, close) }); + chunks.push({ kind: 'statements', origin: 'block', offset: i + 1, text: text.slice(i + 1, close) }); lineWords = []; previousLineWords = []; i = close + 1; @@ -98,37 +136,52 @@ export function extractMenuLua(text: string): MenuExtraction { } break; } + const words = lineWords.length > 0 ? lineWords : previousLineWords; if (c === '"') { const kind = classify(lineWords, previousLineWords); if (kind) { - chunks.push({ kind, offset: i + 1, text: text.slice(i + 1, close) }); + 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 }; + } // A string completes a property; the next string needs its own keyword. lineWords = []; previousLineWords = []; i = close + 1; - } else if (c === '{' || c === '}') { + } 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.slice(start, i)); + lineWords.push({ text: text.slice(start, i), start, end: i }); } else { i++; } } - return { chunks, problems }; + return { chunks, problems, blocks }; } -function classify(lineWords: readonly string[], previousLineWords: readonly string[]): LuaChunk['kind'] | undefined { - if (lineWords.at(-1)?.toLowerCase() === 'lua') { +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]?.toLowerCase(); + const property = words[0]?.text.toLowerCase(); if (property === undefined || words.length !== 1) { return undefined; } diff --git a/src/server/validation/types.ts b/src/server/validation/types.ts index 19926da..3abfa94 100644 --- a/src/server/validation/types.ts +++ b/src/server/validation/types.ts @@ -9,6 +9,11 @@ export interface LuaChunk { * validated as `return `. */ readonly kind: 'statements' | 'expression'; + /** + * Where the chunk comes from: a whole `.lua` file (`file`), a `` `…` `` block of + * a .menu file (`block`), or a `"…"` property value of a .menu file (`property`). + */ + readonly origin: 'file' | 'block' | 'property'; /** Offset of the first character of the Lua text in the document. */ readonly offset: number; /** The Lua text exactly as it appears in the document. */ diff --git a/src/server/validation/validateText.ts b/src/server/validation/validateText.ts index 8ac08d3..67ccf48 100644 --- a/src/server/validation/validateText.ts +++ b/src/server/validation/validateText.ts @@ -28,7 +28,7 @@ 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', offset: 0, text }, lua); + return validateChunk({ kind: 'statements', origin: 'file', offset: 0, text }, lua); } const { chunks, problems } = extractMenuLua(text); return [...problems, ...chunks.flatMap((chunk) => validateChunk(chunk, lua))]; diff --git a/test/fixtures/workspace/OUTLINE.MENU b/test/fixtures/workspace/OUTLINE.MENU new file mode 100644 index 0000000..04dba33 --- /dev/null +++ b/test/fixtures/workspace/OUTLINE.MENU @@ -0,0 +1,17 @@ +-- Original fixture: document symbols and folding. +` +function helper(value) + return value +end +` +menu +{ + name 'OUTLINE_MAIN' + button + { + action + " + helper(1) + " + } +} diff --git a/test/fixtures/workspace/outline.lua b/test/fixtures/workspace/outline.lua new file mode 100644 index 0000000..83a1766 --- /dev/null +++ b/test/fixtures/workspace/outline.lua @@ -0,0 +1,17 @@ +-- Original fixture: document symbols and folding. +local settings = { + speed = 2, + reset = function() end, +} + +--[[ +Block comment +spanning lines. +]] +function Panel:open(id) + if id then + return id + else + return 0 + end +end diff --git a/test/integration/documentSymbols.test.ts b/test/integration/documentSymbols.test.ts new file mode 100644 index 0000000..0129ca9 --- /dev/null +++ b/test/integration/documentSymbols.test.ts @@ -0,0 +1,40 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, fixtureUri } from './helpers.ts'; + +/** `kind name` per symbol, children indented, using VS Code's SymbolKind names. */ +function outline(symbols: readonly vscode.DocumentSymbol[], depth = 0): string[] { + return symbols.flatMap((s) => [`${' '.repeat(depth)}${vscode.SymbolKind[s.kind]} ${s.name}`, ...outline(s.children, depth + 1)]); +} + +async function symbolsOf(file: string): Promise { + const uri = fixtureUri(file); + await vscode.window.showTextDocument(await vscode.workspace.openTextDocument(uri)); + const symbols = await vscode.commands.executeCommand('vscode.executeDocumentSymbolProvider', uri); + assert.ok(symbols, 'no document symbol provider answered'); + return symbols; +} + +suite('Document symbols', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('outlines a Lua file hierarchically', async () => { + const symbols = await symbolsOf('outline.lua'); + assert.deepEqual(outline(symbols), ['Variable settings', ' Field speed', ' Function reset', 'Method Panel:open']); + const method = symbols[1]; + assert.ok(method); + assert.equal(method.detail, '(id)'); + assert.deepEqual([method.range.start.line, method.range.end.line, method.selectionRange.start.character], [10, 16, 9]); + }); + + test('outlines .menu files by menu, with their Lua functions', async () => { + const symbols = await symbolsOf('OUTLINE.MENU'); + assert.deepEqual(outline(symbols), ['Function helper', 'Namespace OUTLINE_MAIN']); + }); +}); diff --git a/test/integration/foldingRanges.test.ts b/test/integration/foldingRanges.test.ts new file mode 100644 index 0000000..3026ca0 --- /dev/null +++ b/test/integration/foldingRanges.test.ts @@ -0,0 +1,31 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, fixtureUri } from './helpers.ts'; + +async function foldsOf(file: string): Promise { + const uri = fixtureUri(file); + await vscode.window.showTextDocument(await vscode.workspace.openTextDocument(uri)); + const ranges = await vscode.commands.executeCommand('vscode.executeFoldingRangeProvider', uri); + assert.ok(ranges, 'no folding range provider answered'); + return [...ranges] + .sort((a, b) => a.start - b.start) + .map((r) => `${r.start}-${r.end}${r.kind === vscode.FoldingRangeKind.Comment ? ' comment' : ''}`); +} + +suite('Folding ranges', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('folds Lua functions, clauses, tables and block comments', async () => { + assert.deepEqual(await foldsOf('outline.lua'), ['1-3', '6-9 comment', '10-15', '11-12', '13-14']); + }); + + test('folds .menu blocks, Lua blocks, scripts and the Lua inside them', async () => { + assert.deepEqual(await foldsOf('OUTLINE.MENU'), ['1-4', '2-3', '6-15', '9-14', '12-13']); + }); +}); diff --git a/test/unit/scripts/release/version.test.ts b/test/unit/scripts/release/version.test.ts index 3cf93d4..0549e6d 100644 --- a/test/unit/scripts/release/version.test.ts +++ b/test/unit/scripts/release/version.test.ts @@ -6,6 +6,7 @@ import { latestTaggedVersion, nextVersion, parseVersion, + releaseVersion, type Bump, type Channel, } from '../../../../scripts/release/version.mts'; @@ -90,4 +91,37 @@ describe('scripts/release/version', () => { } }); }); + + describe('releaseVersion', () => { + const release = (latestTag: string | undefined, committed: string, bump: Bump, channel: Channel) => + formatVersion(releaseVersion(latestTag === undefined ? undefined : v(latestTag), v(committed), bump, channel)); + + it('releases the committed version as the first stable release, whatever the bump', () => { + for (const bump of ['major', 'minor', 'patch'] as const) { + assert.equal(release(undefined, '1.0.0', bump, 'stable'), '1.0.0', bump); + } + }); + + it('opens the odd line above the committed version for a first pre-release', () => { + assert.equal(release(undefined, '1.0.0', 'minor', 'pre-release'), '1.1.0'); + assert.equal(release(undefined, '1.0.0', 'patch', 'pre-release'), '1.1.0'); + assert.equal(release(undefined, '1.0.0', 'major', 'pre-release'), '2.1.0'); + }); + + it('refuses a first stable release from an odd (pre-release) minor', () => { + assert.throws(() => releaseVersion(undefined, v('1.1.0'), 'minor', 'stable'), (error: unknown) => { + assert.ok(error instanceof RangeError); + assert.match(error.message, /1\.1\.0 has an odd minor.*for example 1\.2\.0/); + return true; + }); + }); + + it('follows nextVersion from the latest tag once a release exists', () => { + assert.equal(release('1.0.0', '1.0.0', 'patch', 'stable'), '1.0.1'); + assert.equal(release('1.0.0', '1.0.0', 'minor', 'stable'), '1.2.0'); + assert.equal(release('1.0.0', '1.0.0', 'minor', 'pre-release'), '1.1.0'); + assert.equal(release('1.1.0', '1.1.0', 'patch', 'stable'), '1.2.0'); + assert.equal(release('1.0.0', '1.0.0', 'major', 'stable'), '2.0.0'); + }); + }); }); diff --git a/test/unit/server/documentCache.test.ts b/test/unit/server/documentCache.test.ts new file mode 100644 index 0000000..fee15dc --- /dev/null +++ b/test/unit/server/documentCache.test.ts @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import { ParsedDocumentCache, type VersionedDocument } from '../../../src/server/documentCache.ts'; + +function document(uri: string, version: number, text: string, languageId = 'lua'): VersionedDocument & { reads: number } { + return { + uri, + languageId, + version, + reads: 0, + getText() { + this.reads++; + return text; + }, + }; +} + +describe('server/documentCache', () => { + it('parses a document version once and reuses the result', () => { + const cache = new ParsedDocumentCache(); + const v1 = document('file:///a.lua', 1, 'x = 1'); + const first = cache.get(v1); + assert.equal(cache.get(v1), first); + assert.equal(v1.reads, 1); + }); + + it('parses again when the version changes', () => { + const cache = new ParsedDocumentCache(); + const first = cache.get(document('file:///a.lua', 1, 'x = 1')); + const second = cache.get(document('file:///a.lua', 2, 'local function f() end')); + assert.notEqual(second, first); + assert.equal(second.chunks[0]?.tree.body.body[0]?.kind, 'LocalFunctionStatement'); + assert.equal(cache.size, 1); + }); + + it('detects .menu documents and drops entries on delete', () => { + const cache = new ParsedDocumentCache(); + assert.equal(cache.get(document('file:///UI.MENU', 1, '`x = 1`', 'plaintext')).kind, 'menu'); + cache.delete('file:///UI.MENU'); + assert.equal(cache.size, 0); + }); +}); diff --git a/test/unit/server/features/documentSymbols.test.ts b/test/unit/server/features/documentSymbols.test.ts new file mode 100644 index 0000000..b0483e5 --- /dev/null +++ b/test/unit/server/features/documentSymbols.test.ts @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import { SymbolKind, type DocumentSymbol, type SymbolInformation } from 'vscode-languageserver/node'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { toLspSymbols } from '../../../../src/server/features/documentSymbols.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { documentSymbols } from '../../../../src/server/syntax/symbols.ts'; + +const text = 'local config = { size = 1 }\nfunction M:run(x)\n local function step() end\nend\n'; +const document = TextDocument.create('file:///a.lua', 'lua', 1, text); +const symbols = documentSymbols(parseDocument(text, 'lua'), text.length); +const convert = (hierarchical: boolean) => + toLspSymbols(symbols, { hierarchical, uri: document.uri, positionAt: (offset) => document.positionAt(offset) }); + +describe('server/features/documentSymbols toLspSymbols', () => { + it('returns nested DocumentSymbols with kinds, details and ranges for hierarchical clients', () => { + const [config, run] = convert(true) as DocumentSymbol[]; + assert.ok(config && run); + assert.equal(config.kind, SymbolKind.Variable); + assert.deepEqual(config.children?.map((c) => [c.name, c.kind]), [['size', SymbolKind.Field]]); + assert.equal(run.name, 'M:run'); + assert.equal(run.kind, SymbolKind.Method); + assert.equal(run.detail, '(x)'); + assert.deepEqual(run.range, { start: { line: 1, character: 0 }, end: { line: 3, character: 3 } }); + assert.deepEqual(run.selectionRange, { start: { line: 1, character: 9 }, end: { line: 1, character: 14 } }); + assert.deepEqual(run.children?.map((c) => [c.name, c.kind]), [['step', SymbolKind.Function]]); + }); + + it('returns a flat list in document order with container names for other clients', () => { + const flat = convert(false) as SymbolInformation[]; + assert.deepEqual( + flat.map((s) => [s.name, s.containerName, s.location.uri, s.location.range.start.line]), + [ + ['config', undefined, 'file:///a.lua', 0], + ['size', 'config', 'file:///a.lua', 0], + ['M:run', undefined, 'file:///a.lua', 1], + ['step', 'M:run', 'file:///a.lua', 2], + ], + ); + assert.ok(flat.every((s) => !('children' in s))); + }); +}); diff --git a/test/unit/server/features/foldingRanges.test.ts b/test/unit/server/features/foldingRanges.test.ts new file mode 100644 index 0000000..f161ee8 --- /dev/null +++ b/test/unit/server/features/foldingRanges.test.ts @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict'; +import { FoldingRangeKind } from 'vscode-languageserver/node'; +import { toLspFoldingRanges } from '../../../../src/server/features/foldingRanges.ts'; +import type { Fold } from '../../../../src/server/syntax/folding.ts'; + +const folds: Fold[] = [ + { startLine: 0, endLine: 2, kind: 'comment' }, + { startLine: 3, endLine: 5, kind: undefined }, + { startLine: 6, endLine: 9, kind: undefined }, +]; + +describe('server/features/foldingRanges toLspFoldingRanges', () => { + it('returns whole-line ranges with the comment kind when the client accepts any kind', () => { + assert.deepEqual(toLspFoldingRanges(folds, { rangeLimit: undefined, kinds: undefined }), [ + { startLine: 0, endLine: 2, kind: FoldingRangeKind.Comment }, + { startLine: 3, endLine: 5 }, + { startLine: 6, endLine: 9 }, + ]); + }); + + it('omits the comment kind when the client does not list it', () => { + const [first] = toLspFoldingRanges(folds, { rangeLimit: undefined, kinds: [FoldingRangeKind.Region] }); + assert.deepEqual(first, { startLine: 0, endLine: 2 }); + }); + + it('keeps only the first rangeLimit ranges', () => { + assert.deepEqual(toLspFoldingRanges(folds, { rangeLimit: 2, kinds: undefined }).map((r) => r.startLine), [0, 3]); + assert.deepEqual(toLspFoldingRanges(folds, { rangeLimit: 0, kinds: undefined }), []); + }); +}); diff --git a/test/unit/server/syntax/differential.test.ts b/test/unit/server/syntax/differential.test.ts new file mode 100644 index 0000000..0ae3a00 --- /dev/null +++ b/test/unit/server/syntax/differential.test.ts @@ -0,0 +1,120 @@ +// Differential test: the parser must accept exactly what the official Lua 5.2.4 +// compiler (the embedded WebAssembly module) accepts. Inputs are a fixed corpus +// plus deterministic mutations of valid seeds. Goto/label semantics are excluded +// by design (see src/server/syntax/parser.ts), so no input contains `goto` or `::`. +import assert from 'node:assert/strict'; +import { lex } from '../../../../src/server/syntax/lexer.ts'; +import { parseChunk } from '../../../../src/server/syntax/parser.ts'; +import { loadLua52, type Lua52Checker } from '../../../../src/server/validation/lua52.ts'; + +const CORPUS = [ + // Accepted + 'x = 1', '(a).b = 1', 'f()', 'f"x"', 'f[[x]]', 'f{1}', 'a:b"x"', 'local a = f\n(g)()', + 'return', 'return;', 'return 1;', 'do return end', 'while true do break end', + 'local function f(...) return ... end', 'return ...', 'for i = 1, 2 do end', 'for a, b, c in x do end', + 'x = 0x1p4', 'x = 0x.8', 'x = 3.', 'x = .5', 'x = 1e+5', 'x = 0xA.p1', "x = '\\z \n a'", "x = '\\255'", + 'x = [==[ a ]=] ]==]', '--[==x\nx = 1', 'x = a ~= b', 'x = a..b..c', 'x = -2^2', 'x = not a == b', + 't = {1, 2; x = 3, [4] = 5,}', 't = {x}', 'x = function(a, ...) end', 'local x = 1; ;; x = 2', + 'if a then elseif b then else end', 'repeat local x until x', 'x = y z = 1', 'f(g)(h)[1].x = 1', + 'x = a[b][c]:d()', 'function a.b.c:d() end', 'local x, y', 'x = - - 1', 'x = #"s" .. #t', + // Rejected + '(a) = 1', 'a.b', 'return 1 x()', 'break', 'function f() break end', 'function f() return ... end', + 'for i do end', 'local a = 1', 'x = 0x', 'x = 1e', 'x = 12abc', 'x = 3..2', "x = '\\x4'", + "x = '\\256'", "x = '\\q'", 'x = [=a', '--[[ unterminated', 'x = "a\nb"', 'x = ~1', 'x = !a', + '#!shebang\nx = 1', 'a, b() = 1', 't = {,}', 'x = function(..., a) end', 'x = function(a,) end', + 'a.b:c = 1', 'f() = 1', 'function a:b.c() end', 'local 1 = 2', 'x = a +', 'if a then', 'x = {', + 'x = (1', 'local function() end', 'x = a.1', 'x += 1', 'x = a ? b : c', +]; + +/** Valid seeds for the mutations: together they use every statement and expression form except goto/labels. */ +const SEEDS = [ + `local t = { 1, 2; name = "n", [k .. "x"] = function(a, ...) return select('#', ...) end } +for i = #t, 1, -1 do + if t[i] == nil then break elseif i % 2 == 0 then t[i] = i ^ 2 else t[i] = -i end +end`, + `function M.obj:method(a, b) + local s = self.items[a] or {} + while not s.done and b > 0 do s, b = s.next, b - 1 end + repeat local n = s:step() until n >= 10 + return s, (a .. b) ~= "x" +end`, + `local function f(x) return function(...) return x, ... end end +do local a, b = f(1)(2, 3); print(a, b) end +for k, v in pairs({ a = 1 }) do print(k, v) end`, + `x = [==[ long +string ]==] .. 'esc\\n\\x41\\65' .. 0x1Fp2 .. 3.5e-1 +t.a.b["c"] = g { y = 1 } "s" : m(true, false, nil)`, +]; + +/** mulberry32: small deterministic PRNG, so every run checks the same inputs. */ +function random(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** Deletes, duplicates or swaps tokens of `source`. */ +function mutations(source: string, count: number, seed: number): string[] { + const tokens = lex(source).tokens.slice(0, -1); + const next = random(seed); + const pick = (): number => Math.floor(next() * tokens.length); + const result: string[] = []; + for (let n = 0; n < count; n++) { + const i = pick(); + const token = tokens[i]; + const other = tokens[pick()]; + if (!token || !other) continue; + const operation = n % 3; + if (operation === 0) { + result.push(source.slice(0, token.start) + source.slice(token.end)); + } else if (operation === 1) { + result.push(source.slice(0, token.end) + ' ' + source.slice(token.start, token.end) + source.slice(token.end)); + } else { + const [a, b] = token.start < other.start ? [token, other] : [other, token]; + if (a.end > b.start) continue; + result.push(source.slice(0, a.start) + source.slice(b.start, b.end) + source.slice(a.end, b.start) + source.slice(a.start, a.end) + source.slice(b.end)); + } + } + return result; +} + +describe('server/syntax/parser agrees with the official Lua 5.2.4 compiler', () => { + let lua: Lua52Checker; + before(async () => { + lua = await loadLua52(); + }); + + const agree = (source: string): void => { + const official = lua.check(source); + const ours = parseChunk(source).errors; + assert.equal(ours.length === 0, official === undefined, `${JSON.stringify(source)}\n official: ${official ?? 'accepted'}\n parser: ${JSON.stringify(ours)}`); + }; + + it('on the fixed corpus', () => { + for (const source of CORPUS) agree(source); + }); + + it('on every seed', () => { + for (const seed of SEEDS) { + assert.equal(lua.check(seed), undefined, seed); + agree(seed); + } + }); + + it('on 1,600 deterministic token mutations of the seeds', () => { + let rejected = 0; + SEEDS.forEach((seed, index) => { + for (const mutant of mutations(seed, 400, index + 1)) { + agree(mutant); + if (lua.check(mutant) !== undefined) rejected++; + } + }); + // The mutations must exercise both outcomes to be meaningful. + assert.ok(rejected > 400, `only ${rejected} mutants were invalid`); + }); +}); diff --git a/test/unit/server/syntax/folding.test.ts b/test/unit/server/syntax/folding.test.ts new file mode 100644 index 0000000..9963377 --- /dev/null +++ b/test/unit/server/syntax/folding.test.ts @@ -0,0 +1,113 @@ +import assert from 'node:assert/strict'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { foldingRanges } from '../../../../src/server/syntax/folding.ts'; + +/** `start-end` (or `start-end comment`) per range; lines as LSP counts them. */ +function folds(lines: readonly string[], kind: 'lua' | 'menu' = 'lua'): string[] { + const text = lines.join('\n'); + const document = TextDocument.create('file:///x', kind === 'lua' ? 'lua' : 'ie-menu', 1, text); + return foldingRanges(parseDocument(text, kind), text, (offset) => document.positionAt(offset).line).map( + (f) => `${f.startLine}-${f.endLine}${f.kind ? ` ${f.kind}` : ''}`, + ); +} + +describe('server/syntax/folding', () => { + it('folds function bodies and loops, keeping the closing line visible', () => { + assert.deepEqual( + folds([ + 'function f()', // 0 + ' for i = 1, 2 do', // 1 + ' x()', // 2 + ' end', // 3 + 'end', // 4 + 'while a do', // 5 + ' b()', // 6 + 'end', // 7 + 'repeat', // 8 + ' c()', // 9 + 'until d', // 10 + ]), + ['0-3', '1-2', '5-6', '8-9'], + ); + }); + + it('folds each clause of an if statement separately', () => { + assert.deepEqual(folds(['if a then', ' x()', 'elseif b then', ' y()', 'else', ' z()', 'end']), ['0-1', '2-3', '4-5']); + }); + + it('folds multi-line tables, call arguments and long strings', () => { + assert.deepEqual( + folds([ + 'local t = {', // 0 + ' a = 1,', // 1 + '}', // 2 + 'print(', // 3 + ' t,', // 4 + ' [[long', // 5 + ' string', // 6 + ' ]]', // 7 + ')', // 8 + ]), + ['0-1', '3-7', '5-6'], + ); + }); + + it('does not fold constructs on a single line or on two lines', () => { + assert.deepEqual(folds(['function f() return 1 end', 'do x() end', 'if a then', 'end']), []); + }); + + it('folds whole long comments and runs of line comments', () => { + assert.deepEqual( + folds([ + '--[[', // 0 + 'block', // 1 + ']]', // 2 + '-- one', // 3 + '-- two', // 4 + ' -- three', // 5 + 'x = 1 -- trailing', // 6 + '-- alone', // 7 + 'y = 2', // 8 + ]), + ['0-2 comment', '3-5 comment'], + ); + }); + + it('folds to the last line when the closing keyword is missing', () => { + assert.deepEqual(folds(['function f()', ' x()', ' y()']), ['0-2']); + }); + + it('keeps the outermost range when several start on the same line', () => { + assert.deepEqual(folds(['f(function()', ' x()', 'end)']), ['0-1']); + }); + + it('folds .menu blocks, backtick blocks, scripts and the Lua inside them', () => { + assert.deepEqual( + folds( + [ + '`', // 0 + 'function f()', // 1 + ' x()', // 2 + 'end', // 3 + '`', // 4 + 'menu', // 5 + '{', // 6 + "\tname 'M'", // 7 + '\tbutton', // 8 + '\t{', // 9 + '\t\taction', // 10 + '\t\t"', // 11 + '\t\t\tif a then', // 12 + '\t\t\t\tb()', // 13 + '\t\t\tend', // 14 + '\t\t"', // 15 + '\t}', // 16 + '}', // 17 + ], + 'menu', + ), + ['0-3', '1-2', '5-16', '8-15', '11-14', '12-13'], + ); + }); +}); diff --git a/test/unit/server/syntax/lexer.test.ts b/test/unit/server/syntax/lexer.test.ts new file mode 100644 index 0000000..fc5ee5a --- /dev/null +++ b/test/unit/server/syntax/lexer.test.ts @@ -0,0 +1,94 @@ +import assert from 'node:assert/strict'; +import { KEYWORDS, lex } from '../../../../src/server/syntax/lexer.ts'; + +/** [type, value] of every token except the final `eof`. */ +function tokens(source: string): [string, string][] { + const result = lex(source); + assert.equal(result.tokens.at(-1)?.type, 'eof'); + return result.tokens.slice(0, -1).map((token) => [token.type, token.value]); +} + +function errors(source: string): string[] { + return lex(source).errors.map((error) => error.message); +} + +describe('server/syntax/lexer', () => { + it('knows exactly the 22 reserved words of Lua 5.2', () => { + assert.equal(KEYWORDS.size, 22); + assert.ok(KEYWORDS.has('goto')); + assert.deepEqual(tokens('goto continue self'), [['keyword', 'goto'], ['name', 'continue'], ['name', 'self']]); + }); + + it('reads names as ASCII letters, digits and underscores only', () => { + assert.deepEqual(tokens('_a1 b_2'), [['name', '_a1'], ['name', 'b_2']]); + assert.deepEqual(tokens('é'), [['symbol', 'é']]); + }); + + it('reads multi-character symbols greedily', () => { + assert.deepEqual( + tokens('... .. . == = ~= ~ <= < >= > ::').map(([, value]) => value), + ['...', '..', '.', '==', '=', '~=', '~', '<=', '<', '>=', '>', '::'], + ); + }); + + it('accepts the numerals of Lua 5.2, including hexadecimal fractions and exponents', () => { + for (const numeral of ['3', '3.', '.5', '3.0e-2', '1E+5', '0xff', '0XA.8p1', '0x.1P-2', '0x1p4']) { + assert.deepEqual(tokens(numeral), [['number', numeral]], numeral); + assert.deepEqual(errors(numeral), [], numeral); + } + }); + + it('reads malformed numerals as one token, like read_numeral, and reports them', () => { + for (const numeral of ['12abc', '3..2', '1e', '0x', '0x.p1', '1e+']) { + assert.deepEqual(tokens(numeral), [['number', numeral]], numeral); + assert.deepEqual(errors(numeral), ['malformed number'], numeral); + } + }); + + it('reads short strings with every Lua 5.2 escape sequence', () => { + const source = String.raw`'\a\b\f\n\r\t\v\\\"\'\x41\65\z ' "\ +"`; + assert.deepEqual(tokens(source).map(([type]) => type), ['string', 'string']); + assert.deepEqual(errors(source), []); + }); + + it('reports invalid escapes and unfinished strings', () => { + assert.deepEqual(errors(String.raw`'\q'`), ['invalid escape sequence']); + assert.deepEqual(errors(String.raw`'\x4'`), ['hexadecimal digit expected']); + assert.deepEqual(errors(String.raw`'\256'`), ['decimal escape too large']); + assert.deepEqual(errors("'abc\nx'"), ['unfinished string', 'unfinished string']); + }); + + it('matches long brackets of the same level only', () => { + assert.deepEqual(tokens('[==[ a ]=] ]] ]==] x'), [['string', '[==[ a ]=] ]] ]==]'], ['name', 'x']]); + assert.deepEqual(errors('[=[ never closed'), ['unfinished long string']); + assert.deepEqual(errors('x = [=a'), ['invalid long string delimiter']); + assert.deepEqual(tokens('t[1]'), [['name', 't'], ['symbol', '['], ['number', '1'], ['symbol', ']']]); + }); + + it('keeps comments apart from tokens and tells short from long ones', () => { + const source = '--[[ long\ncomment ]] x -- short\n--[==x is short\ny'; + const result = lex(source); + assert.deepEqual(result.tokens.slice(0, -1).map((token) => token.value), ['x', 'y']); + assert.deepEqual( + result.comments.map((comment) => [source.slice(comment.start, comment.end), comment.long]), + [['--[[ long\ncomment ]]', true], ['-- short', false], ['--[==x is short', false]], + ); + assert.deepEqual(errors('--[[ unterminated'), ['unfinished long comment']); + }); + + it('lexes only the requested slice and reports document offsets', () => { + const source = 'menu `x = 1` end'; + const result = lex(source, 6, 11); + assert.deepEqual(result.tokens.map((token) => [token.value, token.start, token.end]), [ + ['x', 6, 7], + ['=', 8, 9], + ['1', 10, 11], + ['', 11, 11], + ]); + }); + + it('never skips a leading #! line (luaL_loadbuffer does not)', () => { + assert.deepEqual(tokens('#!lua').slice(0, 2), [['symbol', '#'], ['symbol', '!']]); + }); +}); diff --git a/test/unit/server/syntax/parser.test.ts b/test/unit/server/syntax/parser.test.ts new file mode 100644 index 0000000..3f650fc --- /dev/null +++ b/test/unit/server/syntax/parser.test.ts @@ -0,0 +1,238 @@ +import assert from 'node:assert/strict'; +import type * as Ast from '../../../../src/server/syntax/ast.ts'; +import { MAX_SYNTAX_LEVELS, parseChunk } from '../../../../src/server/syntax/parser.ts'; + +/** Compact S-expression of an expression, to make precedence and structure readable. */ +function sexp(e: Ast.Expression | undefined): string { + if (!e) return '_'; + switch (e.kind) { + case 'NilLiteral': return 'nil'; + case 'BooleanLiteral': return String(e.value); + case 'NumberLiteral': + case 'StringLiteral': return e.raw; + case 'VarargLiteral': return '...'; + case 'Identifier': return e.name; + case 'FunctionExpression': return `(function (${e.parameters.map((p) => p.name).join(' ')}${e.isVararg ? ' ...' : ''}) ${e.body.body.length})`; + case 'TableConstructor': return `{${e.fields.map((f) => (f.form === 'item' ? sexp(f.value) : `${f.form === 'named' ? sexp(f.key) : `[${sexp(f.key)}]`}=${sexp(f.value)}`)).join(' ')}}`; + case 'BinaryExpression': return `(${e.operator} ${sexp(e.left)} ${sexp(e.right)})`; + case 'UnaryExpression': return `(${e.operator} ${sexp(e.argument)})`; + case 'ParenthesizedExpression': return `(paren ${sexp(e.expression)})`; + case 'MemberExpression': return `${sexp(e.base)}.${e.member.name}`; + case 'IndexExpression': return `${sexp(e.base)}[${sexp(e.index)}]`; + case 'CallExpression': return `(call ${sexp(e.base)}${e.arguments.values.map((v) => ` ${sexp(v)}`).join('')})`; + case 'MethodCallExpression': return `(call ${sexp(e.base)}:${e.method.name}${e.arguments.values.map((v) => ` ${sexp(v)}`).join('')})`; + } +} + +function only(source: string): Ast.Statement { + const chunk = parseChunk(source); + assert.deepEqual(chunk.errors, [], source); + assert.equal(chunk.body.body.length, 1, source); + const [statement] = chunk.body.body; + assert.ok(statement); + return statement; +} + +function value(source: string): string { + const statement = only(`x = ${source}`); + assert.equal(statement.kind, 'AssignmentStatement'); + return sexp(statement.values[0]); +} + +describe('server/syntax/parser', () => { + describe('expressions', () => { + it('applies the Lua 5.2 operator precedence', () => { + assert.equal(value('a or b and c'), '(or a (and b c))'); + assert.equal(value('a < b == c'), '(== (< a b) c)'); + assert.equal(value('a .. b + c'), '(.. a (+ b c))'); + assert.equal(value('a + b * c % d'), '(+ a (% (* b c) d))'); + assert.equal(value('not a == b'), '(== (not a) b)'); + assert.equal(value('-x ^ 2'), '(- (^ x 2))'); + assert.equal(value('#t - 1'), '(- (# t) 1)'); + }); + + it('makes .. and ^ right-associative and the others left-associative', () => { + assert.equal(value('a .. b .. c'), '(.. a (.. b c))'); + assert.equal(value('a ^ b ^ c'), '(^ a (^ b c))'); + assert.equal(value('a - b - c'), '(- (- a b) c)'); + assert.equal(value('2 ^ -3 ^ 2'), '(^ 2 (- (^ 3 2)))'); + }); + + it('parses literals, varargs, functions and table constructors', () => { + assert.equal(value('nil'), 'nil'); + assert.equal(value('false'), 'false'); + assert.equal(value('0x1p4'), '0x1p4'); + assert.equal(value('[[s]]'), '[[s]]'); + assert.equal(value('...'), '...'); + assert.equal(value('function(a, b, ...) return a end'), '(function (a b ...) 1)'); + assert.equal(value('{1, x = 2; [k] = 3,}'), '{1 x=2 [k]=3}'); + }); + + it('parses suffixes: members, indexes, calls and method calls in every argument form', () => { + assert.equal(value('a.b[c]:d(e)("f"){g}'), '(call (call (call a.b[c]:d e) "f") {g})'); + assert.equal(value('(f)()'), '(call (paren f))'); + assert.equal(value("s:format'x'"), "(call s:format 'x')"); + }); + + it('records the offsets of every node in the source', () => { + const source = 'x = a.b + f(1)'; + const statement = only(source); + assert.equal(statement.kind, 'AssignmentStatement'); + const sum = statement.values[0]; + assert.ok(sum?.kind === 'BinaryExpression'); + assert.equal(source.slice(sum.start, sum.end), 'a.b + f(1)'); + assert.equal(source.slice(sum.left.start, sum.left.end), 'a.b'); + assert.ok(sum.right.kind === 'CallExpression'); + assert.equal(sum.right.arguments.closeStart, source.length - 1); + }); + }); + + describe('statements', () => { + it('parses local declarations, assignments and calls', () => { + const local = only('local a, b = 1, 2'); + assert.ok(local.kind === 'LocalStatement'); + assert.deepEqual(local.names.map((n) => n.name), ['a', 'b']); + assert.deepEqual(local.values.map(sexp), ['1', '2']); + + const assignment = only('a, t.b, t[1] = f()'); + assert.ok(assignment.kind === 'AssignmentStatement'); + assert.deepEqual(assignment.targets.map(sexp), ['a', 't.b', 't[1]']); + + assert.equal(only('obj:method(1)').kind, 'CallStatement'); + }); + + it('parses function declarations with dotted paths and methods', () => { + const declaration = only('function a.b.c:m(x) end'); + assert.ok(declaration.kind === 'FunctionDeclaration'); + assert.deepEqual(declaration.path.map((n) => n.name), ['a', 'b', 'c']); + assert.equal(declaration.method?.name, 'm'); + assert.deepEqual(declaration.func.parameters.map((p) => p.name), ['x']); + + const local = only('local function f() end'); + assert.ok(local.kind === 'LocalFunctionStatement'); + assert.equal(local.name.name, 'f'); + assert.equal(local.func.start, 0, 'a local function starts at `local`'); + }); + + it('parses every control structure and records its closing keyword', () => { + const source = 'if a then elseif b then else end'; + const statement = only(source); + assert.ok(statement.kind === 'IfStatement'); + assert.deepEqual(statement.clauses.map((c) => [c.keyword, source.slice(c.start, c.start + c.keyword.length)]), [ + ['if', 'if'], + ['elseif', 'elseif'], + ['else', 'else'], + ]); + assert.equal(statement.closeStart, source.length - 3); + + for (const [code, kind] of [ + ['while x do end', 'WhileStatement'], + ['do end', 'DoStatement'], + ['repeat local y until y', 'RepeatStatement'], + ['for i = 1, 10, 2 do end', 'NumericForStatement'], + ['for k, v in pairs(t) do end', 'GenericForStatement'], + ['goto done', 'GotoStatement'], + ['::done::', 'LabelStatement'], + ['return 1, 2', 'ReturnStatement'], + ] as const) { + assert.equal(only(code).kind, kind, code); + } + assert.equal(only('while true do break end').kind, 'WhileStatement'); + }); + + it('ignores empty statements', () => { + const chunk = parseChunk(';;local x = 1;;'); + assert.deepEqual(chunk.errors, []); + assert.equal(chunk.body.body.length, 1); + }); + }); + + describe('compiler checks', () => { + const rejects = (source: string, message: RegExp): void => { + const { errors } = parseChunk(source); + assert.ok(errors.some((e) => message.test(e.message)), `${source}: ${JSON.stringify(errors)}`); + }; + + it('rejects ... outside a vararg function, but not in the main chunk', () => { + rejects('function f() return ... end', /cannot use '\.\.\.' outside a vararg function/); + assert.deepEqual(parseChunk('return ...').errors, []); + assert.deepEqual(parseChunk('local function f(...) return function(...) return ... end end').errors, []); + }); + + it('rejects break outside a loop, including in a function nested in a loop', () => { + rejects('break', /'break' not inside a loop/); + rejects('while x do local function f() break end end', /'break' not inside a loop/); + }); + + it('rejects assignments to non-variables and expressions used as statements', () => { + rejects('(a) = 1', /syntax error/); + rejects('f() = 1', /syntax error/); + rejects('a.b', /syntax error/); + }); + + it('requires return to be the last statement of its block', () => { + rejects('return 1 x()', /'' expected/); + assert.deepEqual(parseChunk('do return end x()').errors, []); + }); + + it(`limits nesting to LUAI_MAXCCALLS (${MAX_SYNTAX_LEVELS}) syntax levels`, () => { + const nested = (n: number): string => 'do '.repeat(n) + 'end '.repeat(n); + assert.deepEqual(parseChunk(nested(MAX_SYNTAX_LEVELS)).errors, []); + rejects(nested(MAX_SYNTAX_LEVELS + 1), /too many C levels/); + }); + }); + + describe('error tolerance', () => { + it('never throws, whatever the input', () => { + for (const source of ['', ')', 'end end', 'function', 'local', 'x = ', '{{{', 'if if if', '"', '[[', '::']) { + assert.ok(parseChunk(source).errors.length > 0 || source === '', source); + } + }); + + it('keeps the statements around a broken one', () => { + const chunk = parseChunk('local a = 1\nx = = 2\nlocal function f() end\n'); + assert.equal(chunk.errors.length, 1); + assert.deepEqual(chunk.body.body.map((s) => s.kind), ['LocalStatement', 'LocalFunctionStatement']); + }); + + it('keeps a function whose end is missing, with its body', () => { + const chunk = parseChunk('function f()\n local x = 1\n'); + const [declaration] = chunk.body.body; + assert.ok(declaration?.kind === 'FunctionDeclaration'); + assert.equal(declaration.func.closeStart, undefined); + assert.equal(declaration.func.body.body.length, 1); + assert.match(chunk.errors[0]?.message ?? '', /'end' expected \(to close 'function'\) near /); + }); + + it('recovers inside a function body without losing the function', () => { + const chunk = parseChunk('function f()\n x = = 1\n y()\nend\nz()'); + assert.deepEqual(chunk.body.body.map((s) => s.kind), ['FunctionDeclaration', 'CallStatement']); + const [declaration] = chunk.body.body; + assert.ok(declaration?.kind === 'FunctionDeclaration'); + assert.deepEqual(declaration.func.body.body.map((s) => s.kind), ['CallStatement']); + assert.notEqual(declaration.func.closeStart, undefined); + }); + }); + + describe('slices and expression mode', () => { + it('parses a slice of a larger document with document offsets', () => { + const source = 'action "f(1)" more'; + const chunk = parseChunk(source, { from: 8, to: 12 }); + assert.deepEqual(chunk.errors, []); + assert.equal(chunk.start, 8); + const [call] = chunk.body.body; + assert.ok(call); + assert.equal(source.slice(call.start, call.end), 'f(1)'); + }); + + it('parses expression chunks as `return `', () => { + const chunk = parseChunk('a == 1, b', { mode: 'expression' }); + assert.deepEqual(chunk.errors, []); + const [statement] = chunk.body.body; + assert.ok(statement?.kind === 'ReturnStatement'); + assert.deepEqual(statement.values.map(sexp), ['(== a 1)', 'b']); + assert.deepEqual(parseChunk('', { mode: 'expression' }).errors, []); + assert.ok(parseChunk('x = 1', { mode: 'expression' }).errors.length > 0); + }); + }); +}); diff --git a/test/unit/server/syntax/scope.test.ts b/test/unit/server/syntax/scope.test.ts new file mode 100644 index 0000000..3422a3a --- /dev/null +++ b/test/unit/server/syntax/scope.test.ts @@ -0,0 +1,84 @@ +import assert from 'node:assert/strict'; +import { parseChunk } from '../../../../src/server/syntax/parser.ts'; +import { analyzeScopes, type ScopeAnalysis } from '../../../../src/server/syntax/scope.ts'; + +function analyze(source: string): ScopeAnalysis { + const chunk = parseChunk(source); + assert.deepEqual(chunk.errors, [], source); + return analyzeScopes(chunk); +} + +/** + * For each declaration: `name@offset -> [offsets of its references]`, where + * offset is the declaring identifier's offset (or `self`). + */ +function bindings(source: string): string[] { + return analyze(source).declarations.map( + (d) => `${d.name}@${d.identifier ? String(d.identifier.start) : d.kind} -> [${d.references.map((r) => r.start).join(',')}]`, + ); +} + +const globalNames = (source: string): string[] => [...analyze(source).globals.keys()]; + +describe('server/syntax/scope', () => { + it('makes `local x = x` refer to the outer x on the right-hand side', () => { + // 0 1 + // 0123456789012345678 + const source = 'local x = 1 local x = x'; + assert.deepEqual(bindings(source), ['x@6 -> [22]', 'x@18 -> []']); + }); + + it('makes a local function visible inside its own body, unlike `local f = function`', () => { + assert.deepEqual(bindings('local function f() return f() end'), ['f@15 -> [26]']); + assert.deepEqual(globalNames('local f = function() return f() end'), ['f']); + }); + + it('scopes parameters and the implicit self to the function body', () => { + const source = 'function t:m(a) return self, a end return a'; + assert.deepEqual(bindings(source), ['self@self -> [23]', 'a@13 -> [29]']); + assert.deepEqual(globalNames(source), ['t', 'a']); + }); + + it('scopes for variables to the loop body, and evaluates the loop expressions outside it', () => { + assert.deepEqual(bindings('local i = 1 for i = i, 2 do print(i) end'), ['i@6 -> [20]', 'i@16 -> [34]']); + assert.deepEqual(bindings('for k, v in pairs(t) do f(k, v) end'), ['k@4 -> [26]', 'v@7 -> [29]']); + }); + + it('lets the until condition see the locals of the repeat body', () => { + assert.deepEqual(bindings('repeat local done = true until done'), ['done@13 -> [31]']); + }); + + it('ends block scopes at their end keyword', () => { + const source = 'do local x = 1 end x = 2'; + assert.deepEqual(bindings(source), ['x@9 -> []']); + assert.deepEqual(globalNames(source), ['x']); + assert.deepEqual(globalNames('if a then local b = 1 else c = b end'), ['a', 'c', 'b']); + }); + + it('resolves shadowing to the innermost declaration', () => { + // 0 1 2 3 4 + // 01234567890123456789012345678901234567890123 + const source = 'local x = 1 do local x = 2 y = x end z = x'; + assert.deepEqual(bindings(source), ['x@6 -> [41]', 'x@21 -> [31]']); + }); + + it('treats only the first name of a function path as a variable', () => { + const analysis = analyze('local M = {} function M.a.b() end function g() end'); + assert.deepEqual(analysis.declarations.map((d) => [d.name, d.references.length]), [['M', 1]]); + assert.deepEqual([...analysis.globals.keys()], ['g']); + }); + + it('maps declaring identifiers to their own declaration', () => { + const chunk = parseChunk('local a, b = 1'); + const analysis = analyzeScopes(chunk); + const [statement] = chunk.body.body; + assert.ok(statement?.kind === 'LocalStatement'); + for (const name of statement.names) { + assert.equal(analysis.resolved.get(name)?.identifier, name); + } + }); + + it('ignores field names in table constructors and member accesses', () => { + assert.deepEqual(globalNames('t = { name = value, [key] = 1 } u = t.name'), ['t', 'value', 'key', 'u']); + }); +}); diff --git a/test/unit/server/syntax/symbols.test.ts b/test/unit/server/syntax/symbols.test.ts new file mode 100644 index 0000000..d5df85c --- /dev/null +++ b/test/unit/server/syntax/symbols.test.ts @@ -0,0 +1,130 @@ +import assert from 'node:assert/strict'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { documentSymbols, type OutlineSymbol } from '../../../../src/server/syntax/symbols.ts'; + +/** `kind name detail` per symbol, children indented. */ +function outline(text: string, kind: 'lua' | 'menu' = 'lua'): string[] { + const lines: string[] = []; + const walk = (symbols: readonly OutlineSymbol[], depth: number): void => { + for (const s of symbols) { + lines.push(`${' '.repeat(depth)}${s.kind} ${s.name}${s.detail ? ` ${s.detail}` : ''}`); + walk(s.children, depth + 1); + } + }; + walk(documentSymbols(parseDocument(text, kind), text.length), 0); + return lines; +} + +/** Checks the LSP invariant selection ⊆ range for every symbol, recursively. */ +function assertWellFormed(symbols: readonly OutlineSymbol[]): void { + for (const s of symbols) { + assert.ok(s.name.length > 0); + assert.ok(s.start <= s.selectionStart && s.selectionEnd <= s.end && s.selectionStart <= s.selectionEnd, s.name); + assertWellFormed(s.children); + } +} + +describe('server/syntax/symbols', () => { + it('lists every kind of function declaration, with its parameters', () => { + assert.deepEqual( + outline('function a.b.c(x, ...) end\nfunction obj:m(y) end\nlocal function f() end\nlocal g = function() end\nh = function(z) end\nt.u = function() end'), + [ + 'function a.b.c (x, ...)', + 'method obj:m (y)', + 'function f ()', + 'function g ()', + 'function h (z)', + 'function t.u ()', + ], + ); + }); + + it('nests functions under the function that contains them', () => { + assert.deepEqual(outline('function outer()\n local function inner() end\n callback(function() function deep() end end)\nend'), [ + 'function outer ()', + ' function inner ()', + ' function deep ()', + ]); + }); + + it('lists top-level locals and the first assignment to each global, with table fields', () => { + assert.deepEqual(outline('local a, b = 1\nconfig = { size = 2, run = function() end, nested = { x = 1 }, 3 }\nconfig = {}\n'), [ + 'variable a', + 'variable b', + 'variable config', + ' field size', + ' function run ()', + ' field nested', + ' field x', + ]); + }); + + it('omits locals in blocks or functions, and assignments to existing locals', () => { + assert.deepEqual(outline('local x = 1\nx = 2\ndo local hidden = 1 end\nif c then shown = 1 end\nfunction f() local y = 1; g = 2 end'), [ + 'variable x', + 'variable shown', + 'function f ()', + ]); + }); + + it('gives every symbol a selection range on its name, inside its range', () => { + const text = 'function a.b:c() end\nlocal t = { f = function() end }'; + const symbols = documentSymbols(parseDocument(text, 'lua'), text.length); + assertWellFormed(symbols); + const [method] = symbols; + assert.ok(method); + assert.equal(text.slice(method.selectionStart, method.selectionEnd), 'a.b:c'); + assert.equal(text.slice(method.start, method.end), 'function a.b:c() end'); + }); + + it('still lists symbols around a syntax error', () => { + assert.deepEqual(outline('function ok() end\nx = = 1\nfunction unfinished()\n local y = 1\n'), [ + 'function ok ()', + 'function unfinished ()', + ]); + }); + + describe('.menu files', () => { + const menu = [ + '`', + 'function topLevel() end', + 'state = 1', + '`', + 'menu', + '{', + "\tname 'MAIN'", + '\tonOpen "function opened() end; counter = 1"', + '\tbutton', + '\t{', + '\t\tenabled "ready"', + '\t}', + '}', + 'menu', + '{', + '}', + ].join('\n'); + + it('lists each menu by name with the Lua symbols inside it', () => { + assert.deepEqual(outline(menu, 'menu'), [ + 'function topLevel ()', + 'variable state', + 'namespace MAIN', + ' function opened ()', + 'namespace menu', + ]); + }); + + it('selects the menu name, and the menu keyword when it has no name', () => { + const symbols = documentSymbols(parseDocument(menu, 'menu'), menu.length); + assertWellFormed(symbols); + const names = symbols.filter((s) => s.kind === 'namespace').map((s) => menu.slice(s.selectionStart, s.selectionEnd)); + assert.deepEqual(names, ['MAIN', 'menu']); + }); + + it('extends an unclosed menu to the end of the document', () => { + const text = 'menu\n{\n\tname "OPEN"\n'; + const [symbol] = documentSymbols(parseDocument(text, 'menu'), text.length); + assert.equal(symbol?.end, text.length); + }); + }); +}); diff --git a/test/unit/server/validation/menuExtractor.test.ts b/test/unit/server/validation/menuExtractor.test.ts index 1c214bf..b8ca0ca 100644 --- a/test/unit/server/validation/menuExtractor.test.ts +++ b/test/unit/server/validation/menuExtractor.test.ts @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { extractMenuLua } from '../../../../src/server/validation/menuExtractor.ts'; +import { extractMenuLua, type MenuBlock } from '../../../../src/server/validation/menuExtractor.ts'; /** Returns [kind, text] pairs and checks every chunk's offset points at its text. */ function chunksOf(menu: string): [string, string][] { @@ -70,4 +70,46 @@ describe('server/validation/menuExtractor', () => { const { problems } = extractMenuLua('action "x()'); assert.deepEqual(problems.map((p) => [p.code, p.start]), [['menu-unterminated-string', 7]]); }); + + describe('blocks', () => { + /** keyword(name)[children] per block; `!` marks a block that is never closed. */ + function outline(blocks: readonly MenuBlock[]): string { + return blocks + .map((b) => `${b.keyword?.text ?? '?'}${b.name ? `(${b.name.text})` : ''}${b.close === undefined ? '!' : ''}${b.children.length > 0 ? `[${outline(b.children)}]` : ''}`) + .join(' '); + } + + it('records nested blocks with their keyword, on the same line or the line before', () => { + const menu = "menu\n{\n\tname 'MAIN'\n\tbutton {\n\t\taction \"f()\"\n\t}\n\tlabel\n\t{\n\t}\n}\nmenu\n{\n}\n"; + assert.equal(outline(extractMenuLua(menu).blocks), 'menu(MAIN)[button label] menu'); + }); + + 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; + assert.ok(block?.keyword && block.name && block.close !== undefined); + assert.equal(menu.slice(block.keyword.start, block.keyword.end), 'menu'); + assert.equal(menu[block.open], '{'); + assert.equal(menu[block.close], '}'); + assert.equal(menu.slice(block.name.start, block.name.end), 'M'); + }); + + it('takes only a name property directly inside the block, and only the first one', () => { + const menu = "menu\n{\n\tbutton\n\t{\n\t\tname 'B'\n\t}\n\tname 'M'\n\tname 'IGNORED'\n}"; + assert.equal(outline(extractMenuLua(menu).blocks), 'menu(M)[button(B)]'); + }); + + it('ignores braces inside strings, comments and Lua blocks', () => { + const menu = "menu\n{\n\ttext \"{\"\n\t-- }\n\taction \"t = {}\"\n}\n`x = {}`"; + assert.equal(outline(extractMenuLua(menu).blocks), 'menu'); + }); + + it('leaves unclosed blocks open and ignores unmatched closing braces', () => { + assert.equal(outline(extractMenuLua('}\nmenu\n{\n\tbutton\n\t{\n').blocks), 'menu![button!]'); + }); + }); + + it('tells backtick blocks from property values', () => { + assert.deepEqual(extractMenuLua('`a()`\naction "b()"').chunks.map((c) => c.origin), ['block', 'property']); + }); });