diff --git a/CHANGELOG.md b/CHANGELOG.md index fe5c6a9..5fb1236 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,28 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). resolved through a local `_ENV`. - The server's own labels are localized into the 14 VS Code display languages from the client's `locale` (`InitializeParams.locale`), in every editor. +- Completion (`textDocument/completion`, `completionItem/resolve`; triggered by `.` and `:`), with + the rules of hover so that a completed name hovers as offered: + - Variables: the locals visible at the cursor (the innermost of each name, the implicit + `self` included), then the globals the document assigns (in any Lua chunk of a `.menu` file), + the Lua 5.2 library globals the engine opens, the EEex and game functions, and the keywords. + Each name once, from the first of these that has it. While a local `_ENV` is visible, only + locals and keywords. Keywords are the 22 reserved words (manual §3.1); in `.menu` expressions + (`enabled "…"`, …) only `nil`, `false`, `true`, `function`, `not`, `and` and `or` (§3.4). + - Members of globals (`_G.` prefixes removed): after `_G.` the globals; after `t.` and `t:` the + fields the document assigns on `t`; the manual's members of `string`, `table`, `math`, + `bit32` and `debug`, unless the document assigns the module table or defines that member; + EEex-Docs names after the operator they are documented with (`EEex_Options_Option.new`, + `C:AddGold`). After `("…"):`, the string library (§6.4). Nothing after locals, calls or + indexes (no type inference). + - Nothing in comments, strings and numbers, outside the Lua of a `.menu` file, or where a name + is declared (after `local`, `function`, `for`, `goto`, `::`, in their name lists and in + parameter lists). `io`, `os`, `package` (`require`) and `coroutine` are never offered. + - Each item has the hover's code line as `detail`; the manual text or EEex-Docs link is added + when the item is resolved, in Markdown or plain text as the client prefers + (`completionItem.documentationFormat`). The edit range is the name around the cursor, sent + once per list when the client supports `itemDefaults.editRange`, as an insert/replace edit + when it supports `insertReplaceSupport`. - 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, UI strings and the language server's hover labels into all 14 VS diff --git a/CLAUDE.md b/CLAUDE.md index 63973de..6f00916 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ |---|---| | Name | `IE Lua Language Server` | | Publisher | `infinity-engine-tools` | -| Purpose | Lua 5.2 language support (diagnostics, hover, document and workspace symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | +| Purpose | Lua 5.2 language support (diagnostics, hover, completion, document and workspace symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors | | Language | TypeScript (strict) | | Bundler | esbuild (two bundles: client + language server) | | Minimum VS Code | `^1.91.0` (see `engines.vscode` in `package.json`; required by `vscode-languageclient` ≥ 10) | @@ -33,6 +33,7 @@ │ │ ├── server.ts # Connection, capabilities, handlers │ │ ├── features/ # completion.ts, diagnostics.ts, hover.ts, ... │ │ ├── hover/ # Hover targets, library knowledge and rendering (pure, no LSP imports) +│ │ ├── completion/ # Completion candidates (pure, no LSP imports) │ │ ├── l10n.ts # Server messages in the client's locale (tables in l10n/server/) │ │ ├── syntax/ # Lua 5.2 lexer, parser, scopes, symbols, folding (pure, no LSP imports) │ │ ├── validation/ # Pure analysis logic (no LSP imports) — unit-tested directly diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dc18930..e533b1d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,6 +30,7 @@ server (port 6009). | `src/server/` | Language server (separate Node process; no `vscode` import) | | `src/server/validation/` | Pure validation logic, unit-tested without LSP or VS Code | | `src/server/hover/` | What a hover describes and its text (pure; library data from `data/lua52/` and `data/eeex/`) | +| `src/server/completion/` | What completion offers at the cursor (pure; reuses the hover's knowledge and text) | | `src/server/syntax/` | Error-tolerant Lua 5.2 parser, scope analysis, document symbols and folding (pure; checked against the official compiler by `test/unit/server/syntax/differential.test.ts`) | | `src/server/workspace/` | Index of the workspace's Lua and `.menu` files, and `files.exclude` matching as VS Code applies it (file system injected, unit-tested with an in-memory one) | | `src/shared/` | Types and constants used by both sides | @@ -121,9 +122,10 @@ it from there. The Lua tarball is verified against the SHA-256 published on [!NOTE] > This is an early version. It currently provides **syntax diagnostics**, **hover**, -> **document symbols**, **workspace symbols**, **folding**, and **go to definition**, -> **find references** and **rename** within a file; completion, cross-file navigation, formatting -> and more are planned. +> **completion**, **document symbols**, **workspace symbols**, **folding**, and **go to definition**, +> **find references** and **rename** within a file; cross-file navigation, formatting and more are +> planned. ## Features @@ -44,6 +44,11 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the `Infinity_DisplayString` or `C:AddGold` link to the [EEex documentation](https://eeex-docs.readthedocs.io/en/latest/), and your own variables show how they are declared. +- **Code completion** for the variables in scope, the globals your file defines, the Lua functions + the game provides (`string.` lists the string library), and EEex and game functions + (`Infinity_…`, `EEex_…`, and methods after `C:`), with the same documentation as on hover. + Nothing the game lacks is suggested (`io`, `os`, `require`, coroutines). In `.menu` files, + completion works inside the Lua only. - **Go to Definition, Find All References and Rename Symbol** for variables within a file. Locals follow Lua's scoping rules; globals are followed across all the Lua of a `.menu` file. Rename refuses, and says why, when it could change what the code does: a name already in use nearby, diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index e47274f..1904da7 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -38,6 +38,11 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea `Infinity_DisplayString` for a link to its EEex documentation, or over your own variables to see how they are declared. Only the libraries the game provides are documented, and `print` tells you that the game replaces it. +- **Code completion.** Suggestions for the variables in scope, the globals your file defines, + the Lua functions the game provides (type `string.` for the string library), and EEex and + game functions such as `Infinity_DisplayString`, or methods after `C:`. Lua functions show + their description from the Lua 5.2 manual, EEex and game functions a link to their + documentation. In `.menu` files, completion works inside the Lua. - **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 e0ef1b7..590bf36 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -69,6 +69,7 @@ node /path/to/server.js --stdio | Find references | `textDocument/references` | Every use of a local or global in the same file. | | Rename | `textDocument/prepareRename`, `textDocument/rename` | Same file only; refused, with the reason as the error message, when the rename could change what the code does. | | Hover | `textDocument/hover` | Markdown or plain text, whichever the editor prefers (`hover.contentFormat`); the server's own words follow the editor's `locale`. See below. | +| Completion | `textDocument/completion`, `completionItem/resolve` | Triggered by `.` and `:`. Documentation is sent on resolve, in the editor's preferred `completionItem.documentationFormat`. See below. | | Workspace symbols | `workspace/symbol` | Every `*.lua` and `*.menu` file under the workspace folders, plus open files. See below. | Workspace symbols need an editor that sends **workspace folders** when it starts the server; @@ -88,6 +89,13 @@ others get plain text with the links written out. The few words of the server's `parameter`) are translated when the editor sends a `locale` the extension supports (one of the 14 VS Code display languages, or its language alone: `de-AT` uses German); otherwise English. -Symbols, folding, hover and navigation always reflect the current text, whatever `validate.mode` is. +Completion offers the variables in scope, the globals the file assigns, the Lua 5.2 libraries the +game provides and the EEex and game functions, with the hover's declaration line as the item's +detail and its documentation on resolve. Members are offered after `.` and `:` on globals +(`string.`, `C:`) and after `("…"):`; there is no type inference, so fields of locals are not. +Each item replaces the name around the cursor (`insertReplaceSupport` and +`completionList.itemDefaults` are used when the editor has them). + +Symbols, folding, hover, completion and navigation always reflect the current text, whatever `validate.mode` is. Navigation works on variables: table fields (`t.x`) and `goto` labels are not followed, and in a `.menu` file globals are shared by all its Lua, while locals stay in their own block or script. diff --git a/src/server/completion/candidates.ts b/src/server/completion/candidates.ts new file mode 100644 index 0000000..5690fc4 --- /dev/null +++ b/src/server/completion/candidates.ts @@ -0,0 +1,268 @@ +// What completion offers at a completion site (see syntax/completionContext.ts). +// Pure: no LSP or `vscode` imports. +// +// Names come from the document and from what the server knows, by the rules +// of hover (hover/resolve.ts), so that a completed name hovers as offered: +// +// - Variables: the locals visible at the cursor (the innermost of each name), +// then the globals the document assigns (in any Lua chunk of a .menu file), +// then the Lua 5.2 library globals the engine opens, then the EEex and game +// functions, then keywords. A name is offered once, from the first of these +// that has it: a local hides a global, and a global the document assigns is +// the document's, not the library's. While a local `_ENV` is visible, other +// names are fields of that table: only locals and keywords are offered. +// - Keywords: the 22 reserved words (manual §3.1); in an expression chunk of +// a .menu file, only those an expression can contain (manual §3.4: `nil`, +// `false`, `true`, `function`, `not`, `and`, `or`). +// - `a.b.` and `a.b:` on a global (not on a local or a field of a local +// `_ENV`), `_G.` prefixes removed: `_G.` offers the globals; `t.` and `t:` +// the fields the document assigns on `t`; `string.`, `math.`, … the manual's +// members unless the document assigns the module table itself, and except +// members the document defines; EEex-Docs names (`EEex_Options_Option.new` +// after `.`, `C:AddGold` after `:`). +// - `("…"):`: the string library (strings have it as their `__index`, manual +// §6.4), except members the document defines. +// +// The manual data covers only the libraries the engine opens, so `io`, `os`, +// `require` and `coroutine` are never offered. + +import type { HoverTarget } from '../hover/resolve.ts'; +import { + allExternalEntries, + allManualEntries, + engineReplacement, + externalEntry, + manualEntry, + type ExternalEntry, + type ManualEntry, +} from '../hover/knowledge.ts'; +import type * as Ast from '../syntax/ast.ts'; +import type { CompletionSite } from '../syntax/completionContext.ts'; +import type { ParsedDocument } from '../syntax/document.ts'; +import { fieldWrites, withoutG } from '../syntax/globalPaths.ts'; +import { KEYWORDS } from '../syntax/lexer.ts'; +import { definitions } from '../syntax/navigation.ts'; +import { visibleAt, type Declaration } from '../syntax/scope.ts'; +import { declarationSite, type DeclarationSite } from '../syntax/signatures.ts'; + +export type CandidateKind = 'function' | 'variable' | 'module' | 'field' | 'method' | 'keyword'; + +/** + * Sort groups, in the order the variables rule lists the sources; editors + * still rank by how well the typed text matches first. + */ +export const CandidateGroup = { + Local: 0, + Document: 1, + Library: 2, + External: 3, + Keyword: 4, +} as const; +export type CandidateGroup = (typeof CandidateGroup)[keyof typeof CandidateGroup]; + +/** Where the documentation of a candidate comes from; looked up again by name when it is resolved. */ +export interface DocumentationSource { + readonly source: 'manual' | 'engineReplaced' | 'external'; + readonly name: string; +} + +export interface Candidate { + readonly label: string; + readonly kind: CandidateKind; + readonly group: CandidateGroup; + /** What the name refers to, as a hover describes it (for the code line); `undefined` for keywords and document fields. */ + readonly target: HoverTarget | undefined; +} + +/** Keywords that can appear in an expression (manual §3.4). */ +const EXPRESSION_KEYWORDS: ReadonlySet = new Set(['nil', 'false', 'true', 'function', 'not', 'and', 'or']); + +const isFunctionValue = (site: DeclarationSite | undefined): boolean => + site?.kind === 'localFunction' || site?.kind === 'functionDeclaration' || ((site?.kind === 'local' || site?.kind === 'assignment') && site.value?.kind === 'FunctionExpression'); + +function localCandidate(document: ParsedDocument, declaration: Declaration): Candidate { + const site = declaration.identifier && declarationSite(document, declaration.identifier); + return { + label: declaration.name, + kind: isFunctionValue(site) ? 'function' : 'variable', + group: CandidateGroup.Local, + target: { kind: 'local', declaration, site }, + }; +} + +/** The target of a library global or member, as hover describes it. */ +function libraryTarget(entry: ManualEntry): HoverTarget { + const replacement = engineReplacement(entry.name); + return replacement ? { kind: 'engineReplaced', replacement, entry } : { kind: 'library', entry }; +} + +function libraryKind(entry: ManualEntry, member: boolean): CandidateKind { + if (entry.kind === 'function') return 'function'; + if (entry.kind === 'module') return 'module'; + return member ? 'field' : 'variable'; +} + +/** The last part of a documented name: `format` for `string.format`, `AddGold` for `C:AddGold`. */ +const lastName = (name: string): string => name.slice(Math.max(name.lastIndexOf('.'), name.lastIndexOf(':')) + 1); + +// The library and EEex-Docs names that are globals, built once. +const LIBRARY_GLOBALS: readonly Candidate[] = allManualEntries() + .filter((entry) => !entry.name.includes('.')) + .map((entry) => ({ label: entry.name, kind: libraryKind(entry, false), group: CandidateGroup.Library, target: libraryTarget(entry) })); +const EXTERNAL_GLOBALS: readonly Candidate[] = allExternalEntries() + .filter((entry) => !/[.:]/.test(entry.name)) + .map((entry) => ({ label: entry.name, kind: 'function', group: CandidateGroup.External, target: { kind: 'external', entry } })); + +/** Globals each document assigns, in document order; dropped with the document. */ +const documentGlobalLists = new WeakMap(); + +/** The globals the document assigns in any chunk (`x = …`, `function x()`), not fields of a local `_ENV`. */ +function documentGlobals(document: ParsedDocument): readonly Candidate[] { + let list = documentGlobalLists.get(document); + if (!list) { + // One pass in document order (chunks, then identifiers in source order). The + // first write of each name is what hover describes (`definitions(…)[0]`). + const firstWrites = new Map(); + const assigned = new Set(); + for (const { scopes } of document.chunks) { + for (const [name, identifiers] of scopes.globals) { + for (const identifier of identifiers) { + if (!scopes.writes.has(identifier)) continue; + if (!firstWrites.has(name)) firstWrites.set(name, identifier); + if (!scopes.environmentFields.has(identifier)) assigned.add(name); + } + } + } + list = [...assigned].map((name): Candidate => { + const write = firstWrites.get(name); + const site = write && declarationSite(document, write); + return { label: name, kind: isFunctionValue(site) ? 'function' : 'variable', group: CandidateGroup.Document, target: { kind: 'global', name, site, link: externalEntry(name) } }; + }); + documentGlobalLists.set(document, list); + } + return list; +} + +/** Adds each candidate whose label is not taken yet, in order. */ +function addFirst(into: Map, candidates: Iterable): void { + for (const candidate of candidates) { + if (!into.has(candidate.label)) into.set(candidate.label, candidate); + } +} + +/** The globals, in the order of the variables rule. */ +function globalCandidates(document: ParsedDocument, into: Map): void { + addFirst(into, documentGlobals(document)); + addFirst(into, LIBRARY_GLOBALS); + addFirst(into, EXTERNAL_GLOBALS); +} + +function keywordCandidates(expression: boolean): Candidate[] { + return [...KEYWORDS] + .filter((keyword) => !expression || EXPRESSION_KEYWORDS.has(keyword)) + .map((keyword) => ({ label: keyword, kind: 'keyword', group: CandidateGroup.Keyword, target: undefined })); +} + +/** The fields the document assigns on the global table `table` (see `fieldWrites`). */ +function documentFields(document: ParsedDocument, table: string, kind: CandidateKind): Candidate[] { + const prefix = `${table}.`; + return [...fieldWrites(document)] + .filter((dotted) => dotted.startsWith(prefix)) + .map((dotted) => ({ label: dotted.slice(prefix.length), kind, group: CandidateGroup.Document, target: undefined })); +} + +/** The manual's members of `module` (`string.format`), except those the document defines. */ +function libraryMembers(document: ParsedDocument, module: string): Candidate[] { + const prefix = `${module}.`; + const defined = fieldWrites(document); + return allManualEntries() + .filter((entry) => entry.name.startsWith(prefix) && !defined.has(entry.name)) + .map((entry) => ({ label: lastName(entry.name), kind: libraryKind(entry, true), group: CandidateGroup.Library, target: libraryTarget(entry) })); +} + +/** EEex-Docs names one level below `dotted`, after `operator` (`EEex_Options_Option.new`, `C:AddGold`). */ +function externalMembers(dotted: string, operator: '.' | ':'): Candidate[] { + const prefix = `${dotted}${operator}`; + return allExternalEntries() + .filter((entry: ExternalEntry) => entry.name.startsWith(prefix) && !/[.:]/.test(entry.name.slice(prefix.length))) + .map((entry) => ({ label: lastName(entry.name), kind: operator === ':' ? 'method' : 'function', group: CandidateGroup.External, target: { kind: 'external', entry } })); +} + +/** Whether a local named `name` is visible at `offset` in the chunk. */ +function hasVisibleLocal(document: ParsedDocument, chunkIndex: number, offset: number, name: string): boolean { + const scopes = document.chunks[chunkIndex]?.scopes; + return scopes !== undefined && visibleAt(scopes, offset).some((declaration) => declaration.name === name); +} + +/** The candidates at a completion site, in group order, each label once. */ +export function completionCandidates(document: ParsedDocument, site: CompletionSite): Candidate[] { + const { context, chunkIndex, start } = site; + const found = new Map(); + if (context.kind === 'variable') { + const scopes = document.chunks[chunkIndex]?.scopes; + const locals = scopes ? visibleAt(scopes, start) : []; + addFirst(found, locals.map((declaration) => localCandidate(document, declaration))); + if (!locals.some((declaration) => declaration.name === '_ENV')) globalCandidates(document, found); + addFirst(found, keywordCandidates(site.expression)); + return [...found.values()]; + } + if (context.kind === 'stringMethod') { + addFirst(found, documentFields(document, 'string', 'method')); + addFirst(found, libraryMembers(document, 'string').map((candidate) => ({ ...candidate, kind: candidate.kind === 'function' ? 'method' : candidate.kind }))); + return [...found.values()]; + } + const [head = ''] = context.path; + if (hasVisibleLocal(document, chunkIndex, start, head) || hasVisibleLocal(document, chunkIndex, start, '_ENV')) return []; + const names = withoutG(context.path); + const dotted = names.join('.'); + if (context.operator === '.' && dotted === '_G') { + globalCandidates(document, found); + return [...found.values()]; + } + if (names.length === 1) { + addFirst(found, documentFields(document, dotted, context.operator === ':' ? 'method' : 'field')); + // A module table the document assigns itself is not the library's. + if (context.operator === '.' && !definitions(document, { kind: 'global', name: dotted }).length) addFirst(found, libraryMembers(document, dotted)); + } + addFirst(found, externalMembers(dotted, context.operator)); + return [...found.values()]; +} + +/** The documentation source of a candidate's target, if it has documentation to resolve. */ +export function documentationSource(target: HoverTarget | undefined): DocumentationSource | undefined { + switch (target?.kind) { + case 'library': + return { source: 'manual', name: target.entry.name }; + case 'engineReplaced': + return { source: 'engineReplaced', name: target.replacement.name }; + case 'external': + return { source: 'external', name: target.entry.name }; + case 'global': + return target.link && { source: 'external', name: target.link.name }; + default: + return undefined; + } +} + +/** The hover target whose documentation `value` (from a completion item's `data`) refers to; `undefined` for anything else. */ +export function documentationTarget(value: unknown): HoverTarget | undefined { + if (typeof value !== 'object' || value === null) return undefined; + const { source, name } = value as Partial>; + if (typeof name !== 'string') return undefined; + switch (source) { + case 'manual': { + const entry = manualEntry(name); + return entry && { kind: 'library', entry }; + } + case 'engineReplaced': { + const replacement = engineReplacement(name); + return replacement && { kind: 'engineReplaced', replacement, entry: manualEntry(name) }; + } + case 'external': { + const entry = externalEntry(name); + return entry && { kind: 'external', entry }; + } + default: + return undefined; + } +} diff --git a/src/server/features/completion.ts b/src/server/features/completion.ts new file mode 100644 index 0000000..9234dc2 --- /dev/null +++ b/src/server/features/completion.ts @@ -0,0 +1,102 @@ +import type { CompletionItem, CompletionList, Connection, Range, TextDocuments } from 'vscode-languageserver/node'; +import { CompletionItemKind, InsertReplaceEdit, MarkupKind, TextEdit } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import { completionCandidates, documentationSource, documentationTarget, type Candidate, type CandidateKind } from '../completion/candidates.ts'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { renderDocumentation, renderSignature, type HoverFormat } from '../hover/render.ts'; +import type { Messages } from '../l10n.ts'; +import { completionSiteAt } from '../syntax/completionContext.ts'; + +/** What the client supports, from `textDocument.completion` and `completionList` of its capabilities. */ +export interface CompletionClientOptions { + /** Format of `documentation` (see `markupFormat`). */ + readonly format: HoverFormat; + /** `completionItem.insertReplaceSupport`: edits may give both an insert and a replace range. */ + readonly insertReplace: boolean; + /** `completionList.itemDefaults` includes `editRange`: the range is sent once for the whole list. */ + readonly defaultEditRange: boolean; +} + +export interface CompletionDeps extends CompletionClientOptions { + readonly cache: ParsedDocumentCache; + /** Messages in the client's locale. */ + readonly messages: Messages; +} + +/** Characters after which the client asks for completion without being invoked (see syntax/completionContext.ts). */ +export const TRIGGER_CHARACTERS: readonly string[] = ['.', ':']; + +const ITEM_KINDS: Readonly> = { + function: CompletionItemKind.Function, + variable: CompletionItemKind.Variable, + module: CompletionItemKind.Module, + field: CompletionItemKind.Field, + method: CompletionItemKind.Method, + keyword: CompletionItemKind.Keyword, +}; + +/** + * The completion list for candidates. `insert` is the name before the cursor, + * `replace` the whole name around it; clients without insert/replace support + * get `insert`, which leaves the text after the cursor as it is. + */ +export function toCompletionList(candidates: readonly Candidate[], insert: Range, replace: Range, options: CompletionClientOptions, messages: Messages): CompletionList { + const editRange = options.insertReplace ? { insert, replace } : insert; + const items = candidates.map((candidate): CompletionItem => { + const data = documentationSource(candidate.target); + let textEdit: TextEdit | InsertReplaceEdit | undefined; + if (!options.defaultEditRange) { + textEdit = options.insertReplace ? InsertReplaceEdit.create(candidate.label, insert, replace) : TextEdit.replace(insert, candidate.label); + } + return { + label: candidate.label, + kind: ITEM_KINDS[candidate.kind], + sortText: String(candidate.group), + ...(candidate.target ? { detail: renderSignature(candidate.target, messages) } : {}), + ...(data ? { data } : {}), + ...(textEdit ? { textEdit } : {}), + }; + }); + return { isIncomplete: false, ...(options.defaultEditRange ? { itemDefaults: { editRange } } : {}), items }; +} + +/** `item` with its documentation, when its `data` names any. */ +export function resolveCompletionItem(item: CompletionItem, format: HoverFormat, messages: Messages): CompletionItem { + const target = documentationTarget(item.data); + const documentation = target && renderDocumentation(target, format, messages); + if (documentation === undefined) return item; + return { ...item, documentation: { kind: format === 'markdown' ? MarkupKind.Markdown : MarkupKind.PlainText, value: documentation } }; +} + +/** `textDocument/completion` and `completionItem/resolve` (see src/server/completion/). */ +export function register(connection: Connection, documents: TextDocuments, deps: CompletionDeps): void { + connection.onCompletion(({ textDocument, position }, token): CompletionList | null => { + try { + const document = documents.get(textDocument.uri); + if (!document || token.isCancellationRequested) { + return null; + } + // Synchronous from here on: a cancellation can only arrive after the response. + const parsed = deps.cache.get(document); + const offset = document.offsetAt(position); + const site = completionSiteAt(parsed, document.getText(), offset); + if (!site) { + return null; + } + const start = document.positionAt(site.start); + const insert = { start, end: document.positionAt(offset) }; + return toCompletionList(completionCandidates(parsed, site), insert, { start, end: document.positionAt(site.end) }, deps, deps.messages); + } catch (error) { + connection.console.error(`Completion for ${textDocument.uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }); + connection.onCompletionResolve((item, token): CompletionItem => { + try { + return token.isCancellationRequested ? item : resolveCompletionItem(item, deps.format, deps.messages); + } catch (error) { + connection.console.error(`Resolving the completion item "${item.label}" failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return item; + } + }); +} diff --git a/src/server/features/hover.ts b/src/server/features/hover.ts index 78ebb87..7ba0484 100644 --- a/src/server/features/hover.ts +++ b/src/server/features/hover.ts @@ -13,16 +13,6 @@ export interface HoverDeps { readonly messages: Messages; } -/** - * The format to answer in: the first of the client's `hover.contentFormat` - * (listed in order of preference) that the server can produce; plain text - * when the client lists none, which every client can display. - */ -export function hoverFormat(contentFormat: readonly string[] | undefined): HoverFormat { - const supported = contentFormat?.find((kind) => kind === MarkupKind.Markdown || kind === MarkupKind.PlainText); - return supported === MarkupKind.Markdown ? 'markdown' : 'plaintext'; -} - /** `textDocument/hover` (see src/server/hover/). */ export function register(connection: Connection, documents: TextDocuments, deps: HoverDeps): void { connection.onHover(({ textDocument, position }, token): Hover | null => { diff --git a/src/server/features/markup.ts b/src/server/features/markup.ts new file mode 100644 index 0000000..daa905d --- /dev/null +++ b/src/server/features/markup.ts @@ -0,0 +1,13 @@ +import { MarkupKind } from 'vscode-languageserver/node'; +import type { HoverFormat } from '../hover/render.ts'; + +/** + * The format to answer in, from a client's list of supported formats in order + * of preference (`hover.contentFormat`, `completionItem.documentationFormat`): + * the first one the server can produce; plain text when the client lists none, + * which every client can display. + */ +export function markupFormat(formats: readonly string[] | undefined): HoverFormat { + const supported = formats?.find((kind) => kind === MarkupKind.Markdown || kind === MarkupKind.PlainText); + return supported === MarkupKind.Markdown ? 'markdown' : 'plaintext'; +} diff --git a/src/server/hover/knowledge.ts b/src/server/hover/knowledge.ts index 4351a3b..84d0645 100644 --- a/src/server/hover/knowledge.ts +++ b/src/server/hover/knowledge.ts @@ -60,6 +60,11 @@ export function manualEntry(name: string): ManualEntry | undefined { return manualEntries.get(name); } +/** Every manual entry, in the manual's order. */ +export function allManualEntries(): readonly ManualEntry[] { + return [...manualEntries.values()]; +} + // ------------------------------------------------- engine replacements /** A standard function the engine replaces, so the manual does not describe it. */ @@ -102,3 +107,8 @@ const externalEntries: ReadonlyMap = new Map( export function externalEntry(name: string): ExternalEntry | undefined { return externalEntries.get(name); } + +/** Every EEex-Docs entry, EEex Functions first, each section in its published order. */ +export function allExternalEntries(): readonly ExternalEntry[] { + return [...externalEntries.values()]; +} diff --git a/src/server/hover/render.ts b/src/server/hover/render.ts index 74739aa..d8d2b95 100644 --- a/src/server/hover/render.ts +++ b/src/server/hover/render.ts @@ -76,11 +76,29 @@ function parts(target: HoverTarget, format: HoverFormat, messages: Messages): Pa } } +/** The code line of a hover: how the target is declared or documented (`local function f(a)`, `string.format (formatstring, ···)`). */ +export function renderSignature(target: HoverTarget, messages: Messages): string { + // The code line is the same in both formats. + return parts(target, 'plaintext', messages).code; +} + +/** The parts after the code line, already formatted. */ +function documentationParts({ documentation, link }: Parts, format: HoverFormat): string[] { + const linkPart = link && (format === 'markdown' ? `[${link.text}](${link.url})` : `${link.text}: ${link.url}`); + return [documentation, linkPart].filter((part) => part !== undefined); +} + +const separator = (format: HoverFormat): string => (format === 'markdown' ? '\n\n---\n\n' : '\n\n'); + +/** A hover without its code line (the documentation and the source link), or `undefined` when there is neither. */ +export function renderDocumentation(target: HoverTarget, format: HoverFormat, messages: Messages): string | undefined { + const rest = documentationParts(parts(target, format, messages), format); + return rest.length > 0 ? rest.join(separator(format)) : undefined; +} + /** The hover text for `target`. */ export function renderHover(target: HoverTarget, format: HoverFormat, messages: Messages): string { - const { code, documentation, link } = parts(target, format, messages); - if (format === 'plaintext') { - return [code, documentation, link && `${link.text}: ${link.url}`].filter((part) => part !== undefined).join('\n\n'); - } - return [`\`\`\`lua\n${code}\n\`\`\``, documentation, link && `[${link.text}](${link.url})`].filter((part) => part !== undefined).join('\n\n---\n\n'); + const hover = parts(target, format, messages); + const code = format === 'markdown' ? `\`\`\`lua\n${hover.code}\n\`\`\`` : hover.code; + return [code, ...documentationParts(hover, format)].join(separator(format)); } diff --git a/src/server/hover/resolve.ts b/src/server/hover/resolve.ts index 9c93bb2..f7d22e8 100644 --- a/src/server/hover/resolve.ts +++ b/src/server/hover/resolve.ts @@ -22,8 +22,8 @@ import type * as Ast from '../syntax/ast.ts'; import type { ParsedDocument } from '../syntax/document.ts'; +import { fieldWrites, globalPath, withoutG } from '../syntax/globalPaths.ts'; import { memberAt, type MemberOccurrence } from '../syntax/members.ts'; -import { walk } from '../syntax/walk.ts'; import { definitions, targetAt, type TargetHit } from '../syntax/navigation.ts'; import type { Declaration } from '../syntax/scope.ts'; import { declarationSite, type DeclarationSite } from '../syntax/signatures.ts'; @@ -79,64 +79,6 @@ function variableTarget(document: ParsedDocument, { target, identifier, chunkInd return globalTarget(document, target.name); } -/** - * The names of a `.` chain on a global: `string` for `string`, `[_G, string]` - * for `_G.string`; `undefined` when the chain starts with anything else (a - * local, a call, an index, a field of a local `_ENV`). - */ -function globalPath(document: ParsedDocument, chunkIndex: number, expression: Ast.Expression): string[] | undefined { - if (expression.kind === 'MemberExpression') { - const base = globalPath(document, chunkIndex, expression.base); - return base && [...base, expression.member.name]; - } - if (expression.kind !== 'Identifier') return undefined; - const scopes = document.chunks[chunkIndex]?.scopes; - if (!scopes || scopes.resolved.has(expression) || scopes.environmentFields.has(expression)) return undefined; - return [expression.name]; -} - -/** `[a, b]` for `_G.a.b`: the `_G.` prefix removed while another name follows (manual §6.1, `_G`). */ -function withoutG(names: string[]): string[] { - const rest = [...names]; - while (rest.length > 1 && rest[0] === '_G') rest.shift(); - return rest; -} - -/** Fields of global tables each document assigns, as `table.field`; dropped with the document. */ -const fieldWriteIndexes = new WeakMap>(); - -/** - * The `table.field` names the document assigns on a global table: - * `t.f = …` (`_G.t.f = …` too), `function t.f()` and `function t:f()`. - */ -function fieldWrites(document: ParsedDocument): ReadonlySet { - let writes = fieldWriteIndexes.get(document); - if (!writes) { - const found = new Set(); - document.chunks.forEach(({ tree, scopes }, chunkIndex) => { - const isGlobal = (identifier: Ast.Identifier): boolean => !scopes.resolved.has(identifier) && !scopes.environmentFields.has(identifier); - walk(tree.body, (node) => { - if (node.kind === 'AssignmentStatement') { - for (const target of node.targets) { - const path = target.kind === 'MemberExpression' ? globalPath(document, chunkIndex, target) : undefined; - const names = path && withoutG(path); - if (names?.length === 2) found.add(names.join('.')); - } - } else if (node.kind === 'FunctionDeclaration') { - const [head, field] = node.path; - if (head && isGlobal(head)) { - if (node.path.length === 2 && field && node.method === undefined) found.add(`${head.name}.${field.name}`); - if (node.path.length === 1 && node.method) found.add(`${head.name}.${node.method.name}`); - } - } - }); - }); - writes = found; - fieldWriteIndexes.set(document, writes); - } - return writes; -} - /** The manual's entry for the library member `dotted` (`string.format`), unless the document defines that member itself. */ function libraryMember(document: ParsedDocument, dotted: string): ManualEntry | undefined { return fieldWrites(document).has(dotted) ? undefined : manualEntry(dotted); diff --git a/src/server/server.ts b/src/server/server.ts index 4d546a7..7508ea2 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -15,11 +15,13 @@ import { } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { ParsedDocumentCache } from './documentCache.ts'; +import * as completion from './features/completion.ts'; import * as definition from './features/definition.ts'; import * as diagnostics from './features/diagnostics.ts'; import * as documentSymbols from './features/documentSymbols.ts'; import * as foldingRanges from './features/foldingRanges.ts'; import * as hover from './features/hover.ts'; +import { markupFormat } from './features/markup.ts'; import * as references from './features/references.ts'; import * as rename from './features/rename.ts'; import * as workspaceSymbols from './features/workspaceSymbols.ts'; @@ -80,6 +82,8 @@ connection.onInitialize((params) => { // Null or absent when no folder is open or the client does not support workspace folders // (the deprecated rootUri is not used): then only open documents are searched. folders = params.workspaceFolders?.map((folder) => folder.uri) ?? []; + /** The server's messages in the client's display language. */ + const messages = createMessages(params.locale); const diagnosticsFeature = diagnostics.register(connection, documents, { lua, settings: new SettingsStore(connection, configurationPull, params.initializationOptions), @@ -101,8 +105,16 @@ connection.onInitialize((params) => { workspaceSymbols.register(connection, documents, { cache: parsed, index }); hover.register(connection, documents, { cache: parsed, - format: hover.hoverFormat(params.capabilities.textDocument?.hover?.contentFormat), - messages: createMessages(params.locale), + format: markupFormat(params.capabilities.textDocument?.hover?.contentFormat), + messages, + }); + const completionCapabilities = params.capabilities.textDocument?.completion; + completion.register(connection, documents, { + cache: parsed, + format: markupFormat(completionCapabilities?.completionItem?.documentationFormat), + insertReplace: completionCapabilities?.completionItem?.insertReplaceSupport === true, + defaultEditRange: completionCapabilities?.completionList?.itemDefaults?.includes('editRange') === true, + messages, }); // One handler per notification: settings changes go to every feature that needs them. connection.onDidChangeConfiguration(({ settings }) => { @@ -125,6 +137,7 @@ connection.onInitialize((params) => { renameProvider: prepareRename ? { prepareProvider: true } : true, workspaceSymbolProvider: true, hoverProvider: true, + completionProvider: { triggerCharacters: [...completion.TRIGGER_CHARACTERS], resolveProvider: true }, ...(workspaceFolderChanges ? { workspace: { workspaceFolders: { supported: true, changeNotifications: true } } } : {}), }, serverInfo: { name: 'IE Lua Language Server' }, diff --git a/src/server/syntax/completionContext.ts b/src/server/syntax/completionContext.ts new file mode 100644 index 0000000..1ff5b23 --- /dev/null +++ b/src/server/syntax/completionContext.ts @@ -0,0 +1,177 @@ +// What kind of name can be typed at a position, for completion. Pure: no LSP +// or `vscode` imports. +// +// The context comes from the tokens before the cursor, not from the syntax +// tree: the statement being typed is usually incomplete, and the parser +// abandons it. Only the Lua chunks of a document are considered (in a .menu +// file, the Lua the engine compiles); anything else has no context. +// +// - Inside a comment, a string or a number: none. +// - Where a name is declared rather than used: none. That is after `local`, +// `function`, `for`, `goto` and an opening `::`, after `,` in the name lists +// of `local` and `for`, and in the parameter list of a function. +// - After `.` or `:` that follow a chain of names (`a.b.`, `a.b:`): a member of +// that chain. Chains that start at anything else (a call, an index, a +// string) are not followed, except `("…"):`, a method of the string library. +// - Anywhere else: a variable (or a keyword). + +import type { ParsedChunk, ParsedDocument } from './document.ts'; +import { lex, type Comment, type ParseError, type Token } from './lexer.ts'; + +export type CompletionContext = + /** A variable or keyword. */ + | { readonly kind: 'variable' } + /** A field (`.`) or method (`:`) of the chain `path` (`['_G', 'string']` for `_G.string.`). */ + | { readonly kind: 'member'; readonly path: readonly string[]; readonly operator: '.' | ':' } + /** A method of a string literal, `("…"):`. */ + | { readonly kind: 'stringMethod' }; + +export interface CompletionSite { + readonly context: CompletionContext; + /** Index in `ParsedDocument.chunks` of the chunk the cursor is in. */ + readonly chunkIndex: number; + /** The chunk is an expression (a .menu value such as `enabled "…"`), not statements. */ + readonly expression: boolean; + /** Offset of the start of the name being typed; the cursor when none is. */ + readonly start: number; + /** End of the name around the cursor: a completion replaces `[start, end)`. */ + readonly end: number; + /** The part of the name before the cursor. */ + readonly prefix: string; +} + +const isNameCharacter = (c: string | undefined): boolean => c !== undefined && /[A-Za-z0-9_]/.test(c); + +const isSymbol = (token: Token | undefined, value: string): boolean => token?.type === 'symbol' && token.value === value; +const isKeyword = (token: Token | undefined, value: string): boolean => token?.type === 'keyword' && token.value === value; + +/** Whether the cursor is inside a comment that `lex` cut at the cursor (`to`). */ +function inComment(comments: readonly Comment[], errors: readonly ParseError[], offset: number): boolean { + const last = comments.at(-1); + if (last?.end !== offset) return false; + // A `--` comment runs to the end of the line; a long one only until it is closed. + return !last.long || errors.some((error) => error.start >= last.start && error.start < last.end && error.message === 'unfinished long comment'); +} + +/** + * Whether `tokens[index]` is the `(` of a parameter list: preceded by + * `function`, or by `function a.b:c`. + */ +function isParameterListOpen(tokens: readonly Token[], index: number): boolean { + let i = index - 1; + if (isKeyword(tokens[i], 'function')) return true; + if (tokens[i]?.type !== 'name') return false; + i--; + while ((isSymbol(tokens[i], '.') || isSymbol(tokens[i], ':')) && tokens[i - 1]?.type === 'name') i -= 2; + return isKeyword(tokens[i], 'function'); +} + +/** Whether a name typed after `tokens[index]` declares a variable, a label or a parameter. */ +function isDeclaration(tokens: readonly Token[], index: number): boolean { + const previous = tokens[index]; + if (isKeyword(previous, 'local') || isKeyword(previous, 'function') || isKeyword(previous, 'for') || isKeyword(previous, 'goto')) return true; + // `::name::`: the first `::` opens a label; the second closes it. + if (isSymbol(previous, '::')) return !(tokens[index - 1]?.type === 'name' && isSymbol(tokens[index - 2], '::')); + if (isSymbol(previous, '(')) return isParameterListOpen(tokens, index); + if (isSymbol(previous, ',')) { + // Back over `a, b,` to what comes before the list. + let i = index - 1; + while (tokens[i]?.type === 'name' && isSymbol(tokens[i - 1], ',')) i -= 2; + if (tokens[i]?.type !== 'name') return false; + const before = tokens[i - 1]; + return isKeyword(before, 'local') || isKeyword(before, 'for') || (isSymbol(before, '(') && isParameterListOpen(tokens, i - 1)); + } + return false; +} + +/** The context after the `.` or `:` at `tokens[index]`, or `undefined` when there is none to offer. */ +function memberContext(tokens: readonly Token[], index: number): CompletionContext | undefined { + const operator = tokens[index]?.value === ':' ? ':' : '.'; + let i = index - 1; + if (operator === ':' && isSymbol(tokens[i], ')') && tokens[i - 1]?.type === 'string' && isSymbol(tokens[i - 2], '(')) { + return { kind: 'stringMethod' }; + } + const path: string[] = []; + for (;;) { + const token = tokens[i]; + if (token?.type !== 'name') return undefined; + path.unshift(token.value); + if (!isSymbol(tokens[i - 1], '.')) break; + i -= 2; + } + const before = tokens[i - 1]; + // `x:y.` is not Lua; `function a.b` names the function being declared. + if (isSymbol(before, ':') || isKeyword(before, 'function')) return undefined; + return { kind: 'member', path, operator }; +} + +/** + * Where to start lexing for a cursor at `offset`: the start of the last + * top-level statement of the chunk that starts before it and no later than + * the first syntax error, else the chunk start. Such a statement was parsed + * from the chunk start without errors, so it starts at a token of the whole + * chunk (never inside a string or comment), and the tokens the context looks + * back at belong to it or to later statements. After an error, the parser + * resumes at likely statement starts, such as a name at the start of a line, + * which may still be inside an expression (`t.` then `z` on the next line is + * `t.z`), so those are not used. This keeps a request proportional to one + * statement rather than to the file while the code above it parses. + */ +export function lexStart({ chunk, tree }: ParsedChunk, offset: number): number { + const statements = tree.body.body; + const limit = Math.min(offset - 1, tree.errors[0]?.start ?? Infinity); + let low = 0; + let high = statements.length - 1; + let from = chunk.offset; + while (low <= high) { + const middle = (low + high) >> 1; + const statement = statements[middle]; + if (statement && statement.start <= limit) { + from = Math.max(from, statement.start); + low = middle + 1; + } else { + high = middle - 1; + } + } + return from; +} + +/** The completion site at `offset` of a parsed document whose text is `text`, or `undefined` when nothing can be completed there. */ +export function completionSiteAt(document: ParsedDocument, text: string, offset: number): CompletionSite | undefined { + const chunkIndex = document.chunks.findIndex(({ chunk }) => chunk.offset <= offset && offset <= chunk.offset + chunk.text.length); + const parsed = document.chunks[chunkIndex]; + if (!parsed) return undefined; + return siteFrom(parsed, chunkIndex, text, offset, lexStart(parsed, offset)); +} + +/** `completionSiteAt` for the chunk `parsed`, lexing from `from` (exported for tests: from the chunk start, the result must be the same). */ +export function siteFrom(parsed: ParsedChunk, chunkIndex: number, text: string, offset: number, from: number): CompletionSite | undefined { + const { chunk } = parsed; + const { tokens, comments, errors } = lex(text, from, offset); + if (inComment(comments, errors, offset)) return undefined; + tokens.pop(); // eof + + let previousIndex = tokens.length - 1; + let start = offset; + const last = tokens[previousIndex]; + if (last?.end === offset) { + if (last.type === 'string' || last.type === 'number') return undefined; + if (last.type === 'name' || last.type === 'keyword') { + start = last.start; + previousIndex--; + } + } + if (isDeclaration(tokens, previousIndex)) return undefined; + + const previous = tokens[previousIndex]; + let context: CompletionContext | undefined = { kind: 'variable' }; + if (isSymbol(previous, '.') || isSymbol(previous, ':')) { + context = memberContext(tokens, previousIndex); + } + if (!context) return undefined; + + let end = offset; + const chunkEnd = chunk.offset + chunk.text.length; + while (end < chunkEnd && isNameCharacter(text[end])) end++; + return { context, chunkIndex, expression: chunk.kind === 'expression', start, end, prefix: text.slice(start, offset) }; +} diff --git a/src/server/syntax/globalPaths.ts b/src/server/syntax/globalPaths.ts new file mode 100644 index 0000000..38b9b05 --- /dev/null +++ b/src/server/syntax/globalPaths.ts @@ -0,0 +1,68 @@ +// `.` chains on globals (`string.format`, `_G.string.format`) and the fields a +// document assigns on global tables, shared by hover and completion. Pure: no +// LSP or `vscode` imports. +// +// Names resolved through a local `_ENV` are fields of that table, not globals, +// so a chain that starts with one is not a global path. + +import type * as Ast from './ast.ts'; +import type { ParsedDocument } from './document.ts'; +import { walk } from './walk.ts'; + +/** + * The names of a `.` chain on a global: `string` for `string`, `[_G, string]` + * for `_G.string`; `undefined` when the chain starts with anything else (a + * local, a call, an index, a field of a local `_ENV`). + */ +export function globalPath(document: ParsedDocument, chunkIndex: number, expression: Ast.Expression): string[] | undefined { + if (expression.kind === 'MemberExpression') { + const base = globalPath(document, chunkIndex, expression.base); + return base && [...base, expression.member.name]; + } + if (expression.kind !== 'Identifier') return undefined; + const scopes = document.chunks[chunkIndex]?.scopes; + if (!scopes || scopes.resolved.has(expression) || scopes.environmentFields.has(expression)) return undefined; + return [expression.name]; +} + +/** `[a, b]` for `_G.a.b`: the `_G.` prefix removed while another name follows (manual §6.1, `_G`). */ +export function withoutG(names: readonly string[]): string[] { + const rest = [...names]; + while (rest.length > 1 && rest[0] === '_G') rest.shift(); + return rest; +} + +/** Fields of global tables each document assigns, as `table.field`; dropped with the document. */ +const fieldWriteIndexes = new WeakMap>(); + +/** + * The `table.field` names the document assigns on a global table: + * `t.f = …` (`_G.t.f = …` too), `function t.f()` and `function t:f()`. + */ +export function fieldWrites(document: ParsedDocument): ReadonlySet { + let writes = fieldWriteIndexes.get(document); + if (!writes) { + const found = new Set(); + document.chunks.forEach(({ tree, scopes }, chunkIndex) => { + const isGlobal = (identifier: Ast.Identifier): boolean => !scopes.resolved.has(identifier) && !scopes.environmentFields.has(identifier); + walk(tree.body, (node) => { + if (node.kind === 'AssignmentStatement') { + for (const target of node.targets) { + const path = target.kind === 'MemberExpression' ? globalPath(document, chunkIndex, target) : undefined; + const names = path && withoutG(path); + if (names?.length === 2) found.add(names.join('.')); + } + } else if (node.kind === 'FunctionDeclaration') { + const [head, field] = node.path; + if (head && isGlobal(head)) { + if (node.path.length === 2 && field && node.method === undefined) found.add(`${head.name}.${field.name}`); + if (node.path.length === 1 && node.method) found.add(`${head.name}.${node.method.name}`); + } + } + }); + }); + writes = found; + fieldWriteIndexes.set(document, writes); + } + return writes; +} diff --git a/src/server/syntax/scope.ts b/src/server/syntax/scope.ts index b028438..5b16d2a 100644 --- a/src/server/syntax/scope.ts +++ b/src/server/syntax/scope.ts @@ -9,11 +9,27 @@ // - Any other name is a global (a field of _ENV). While a local named `_ENV` // is visible, such a name is a field of that local table instead (§2.2); it // is still listed with the globals, and also in `environmentFields`. +// +// Each declaration also records where it is visible (`Declaration.visible`), +// for features that work at a position where no name is written yet +// (completion). A scope ends at its closing keyword (`end`, or the `until` +// condition); when the parser found none, at the end of the enclosing scope. import type * as Ast from './ast.ts'; export type DeclarationKind = 'local' | 'localFunction' | 'parameter' | 'self' | 'forVariable'; +/** + * Where a declaration is visible: the offsets `o` with `start < o <= end`. The + * start is exclusive, so a cursor at the end of `local x = y` (still typing + * `y`) does not see the new `x`; the end is inclusive, so a cursor just before + * the closing keyword still does. + */ +export interface Visibility { + readonly start: number; + readonly end: number; +} + export interface Declaration { readonly name: string; readonly kind: DeclarationKind; @@ -21,6 +37,7 @@ export interface Declaration { readonly identifier: Ast.Identifier | undefined; /** Uses of the declaration, in source order (the declaring identifier excluded). */ readonly references: Ast.Identifier[]; + readonly visible: Visibility; } export interface ScopeAnalysis { @@ -50,18 +67,21 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { const globals = new Map(); const writes = new Set(); const environmentFields = new Set(); - const scopes: Map[] = []; + /** Open scopes, innermost last, each with the offset where it ends. */ + const scopes: { readonly names: Map; readonly end: number }[] = []; + const scopeEnd = (): number => scopes.at(-1)?.end ?? chunk.end; - const declare = (kind: DeclarationKind, name: string, identifier: Ast.Identifier | undefined): void => { - const declaration: Declaration = { name, kind, identifier, references: [] }; + /** Declares `name`, visible after offset `from` until the end of the current scope. */ + const declare = (kind: DeclarationKind, name: string, identifier: Ast.Identifier | undefined, from: number): void => { + const declaration: Declaration = { name, kind, identifier, references: [], visible: { start: from, end: scopeEnd() } }; declarations.push(declaration); if (identifier) resolved.set(identifier, declaration); - scopes.at(-1)?.set(name, declaration); + scopes.at(-1)?.names.set(name, declaration); }; const lookup = (name: string): Declaration | undefined => { for (let i = scopes.length - 1; i >= 0; i--) { - const declaration = scopes[i]?.get(name); + const declaration = scopes[i]?.names.get(name); if (declaration) return declaration; } return undefined; @@ -81,8 +101,9 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { else globals.set(identifier.name, [identifier]); }; - const scoped = (body: () => void): void => { - scopes.push(new Map()); + /** Runs `body` in a new scope that ends at `closeAt`, or with the enclosing scope when the closing keyword is missing. */ + const scoped = (closeAt: number | undefined, body: () => void): void => { + scopes.push({ names: new Map(), end: closeAt ?? scopeEnd() }); try { body(); } finally { @@ -95,9 +116,9 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { }; 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); + scoped(node.closeStart, () => { + if (isMethod) declare('self', 'self', undefined, node.start); + for (const parameter of node.parameters) declare('parameter', parameter.name, parameter, parameter.end); block(node.body); }); }; @@ -110,10 +131,10 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { switch (node.kind) { case 'LocalStatement': expressions(node.values); - for (const name of node.names) declare('local', name.name, name); + for (const name of node.names) declare('local', name.name, name, node.end); break; case 'LocalFunctionStatement': - declare('localFunction', node.name.name, node.name); + declare('localFunction', node.name.name, node.name, node.name.end); func(node.func, false); break; case 'FunctionDeclaration': { @@ -139,43 +160,45 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { visitExpression(node.call); break; case 'DoStatement': - scoped(() => { + scoped(node.closeStart, () => { block(node.body); }); break; case 'WhileStatement': visitExpression(node.condition); - scoped(() => { + scoped(node.closeStart, () => { block(node.body); }); break; case 'RepeatStatement': - scoped(() => { + // The `until` condition is in the scope of the body. + scoped(node.closeStart === undefined ? undefined : node.end, () => { block(node.body); if (node.condition) visitExpression(node.condition); }); break; case 'IfStatement': - for (const clause of node.clauses) { + node.clauses.forEach((clause, i) => { if (clause.condition) visitExpression(clause.condition); - scoped(() => { + scoped(node.clauses[i + 1]?.start ?? node.closeStart, () => { 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); + scoped(node.closeStart, () => { + declare('forVariable', node.variable.name, node.variable, (node.step ?? node.limit).end); block(node.body); }); break; case 'GenericForStatement': expressions(node.iterators); - scoped(() => { - for (const variable of node.variables) declare('forVariable', variable.name, variable); + scoped(node.closeStart, () => { + const from = node.iterators.at(-1)?.end ?? node.variables.at(-1)?.end ?? node.start; + for (const variable of node.variables) declare('forVariable', variable.name, variable, from); block(node.body); }); break; @@ -234,8 +257,23 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { } } - scoped(() => { + scoped(chunk.end, () => { block(chunk.body); }); return { declarations, resolved, globals, writes, environmentFields }; } + +/** + * The declarations visible at `offset`, one per name: the innermost, which + * hides the others (the one that became visible last). + */ +export function visibleAt(scopes: ScopeAnalysis, offset: number): Declaration[] { + const byName = new Map(); + for (const declaration of scopes.declarations) { + const { start, end } = declaration.visible; + if (start < offset && offset <= end && (byName.get(declaration.name)?.visible.start ?? -1) < start) { + byName.set(declaration.name, declaration); + } + } + return [...byName.values()]; +} diff --git a/test/fixtures/workspace/COMPLETION.MENU b/test/fixtures/workspace/COMPLETION.MENU new file mode 100644 index 0000000..753db97 --- /dev/null +++ b/test/fixtures/workspace/COMPLETION.MENU @@ -0,0 +1,10 @@ +-- Original fixture: completion in the Lua of a .menu file. +` +completionShown = false +` +menu +{ + name 'COMPLETION_MAIN' + onOpen "completionShown = true" + enabled "completionShown" +} diff --git a/test/fixtures/workspace/completion.lua b/test/fixtures/workspace/completion.lua new file mode 100644 index 0000000..ebd1250 --- /dev/null +++ b/test/fixtures/workspace/completion.lua @@ -0,0 +1,18 @@ +-- Original fixture: completion. +local function tally(items) + local total = 0 + for _, item in ipairs(items) do + total = total + item + end + return total +end + +CompletionCounter = 0 + +function CompletionReport(prefix) + local line = prefix .. tostring(CompletionCounter) + local width = string.len(line) + C:AddGold(width) + -- A comment mentioning prefix. + Infinity_DisplayString("prefix " .. line) +end diff --git a/test/integration/completion.test.ts b/test/integration/completion.test.ts new file mode 100644 index 0000000..976509a --- /dev/null +++ b/test/integration/completion.test.ts @@ -0,0 +1,87 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, openFixture } from './helpers.ts'; + +/** + * The completion items offered just after the `occurrence`-th (0-based) + * `needle` of a fixture, without VS Code's word-based suggestions (kind + * `Text`), which every document gets. `resolve` items are resolved. + */ +async function completionsAfter(file: string, needle: string, { occurrence = 0, resolve = 0 } = {}): Promise { + const uri = await openFixture(file); + const document = await vscode.workspace.openTextDocument(uri); + const text = document.getText(); + let offset = -1; + for (let i = 0; i <= occurrence; i++) { + offset = text.indexOf(needle, offset + 1); + assert.ok(offset >= 0, `"${needle}" #${String(i)} not found in ${file}`); + } + const position = document.positionAt(offset + needle.length); + const list = await vscode.commands.executeCommand('vscode.executeCompletionItemProvider', uri, position, undefined, resolve); + return list.items.filter((item) => item.kind !== vscode.CompletionItemKind.Text); +} + +const labelOf = (item: vscode.CompletionItem): string => (typeof item.label === 'string' ? item.label : item.label.label); +const labels = (items: readonly vscode.CompletionItem[]): string[] => items.map(labelOf); + +function itemNamed(items: readonly vscode.CompletionItem[], label: string): vscode.CompletionItem { + const found = items.find((item) => labelOf(item) === label); + assert.ok(found, `no item "${label}" in ${labels(items).join(', ')}`); + return found; +} + +suite('Completion', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('offers the locals in scope, document globals, library and game functions', async () => { + const items = await completionsAfter('completion.lua', 'local line = prefix'); + const names = labels(items); + assert.equal(itemNamed(items, 'prefix').detail, '(parameter) prefix'); + assert.equal(itemNamed(items, 'tally').detail, 'local function tally(items)'); + assert.equal(itemNamed(items, 'tally').kind, vscode.CompletionItemKind.Function); + assert.equal(itemNamed(items, 'CompletionCounter').detail, '(global) CompletionCounter'); + assert.equal(itemNamed(items, 'string').kind, vscode.CompletionItemKind.Module); + assert.equal(itemNamed(items, 'Infinity_DisplayString').detail, 'Infinity_DisplayString'); + assert.equal(itemNamed(items, 'while').kind, vscode.CompletionItemKind.Keyword); + for (const absent of ['line', 'total', 'item', 'io', 'os', 'require', 'coroutine']) { + assert.ok(!names.includes(absent), `"${absent}" should not be offered`); + } + }); + + test('offers library members with the manual text when resolved', async () => { + const items = await completionsAfter('completion.lua', 'string.', { resolve: 100 }); + assert.ok(!labels(items).includes('pairs')); + const format = itemNamed(items, 'format'); + assert.equal(format.detail, 'string.format (formatstring, ···)'); + const documentation = format.documentation; + assert.ok(documentation instanceof vscode.MarkdownString, 'expected Markdown documentation'); + assert.ok(documentation.value.startsWith('Returns a formatted version of its variable number of arguments'), documentation.value); + assert.ok(documentation.value.endsWith('(https://www.lua.org/manual/5.2/manual.html#pdf-string.format)'), documentation.value); + }); + + test('offers game object methods after `:`', async () => { + const items = await completionsAfter('completion.lua', 'C:'); + assert.equal(itemNamed(items, 'AddGold').kind, vscode.CompletionItemKind.Method); + assert.ok(!labels(items).includes('format')); + }); + + test('offers nothing in comments and strings', async () => { + assert.deepEqual(labels(await completionsAfter('completion.lua', '-- A comment mentioning pre')), []); + assert.deepEqual(labels(await completionsAfter('completion.lua', '"pre')), []); + }); + + test('offers .menu globals across chunks, only inside the Lua', async () => { + const statements = await completionsAfter('COMPLETION.MENU', 'onOpen "completion'); + assert.equal(itemNamed(statements, 'completionShown').detail, '(global) completionShown'); + const expression = await completionsAfter('COMPLETION.MENU', 'enabled "completion'); + assert.ok(labels(expression).includes('completionShown')); + assert.ok(!labels(expression).includes('local'), 'statement keywords in an expression'); + assert.deepEqual(labels(await completionsAfter('COMPLETION.MENU', 'name')), []); + }); +}); diff --git a/test/unit/server/completion/candidates.test.ts b/test/unit/server/completion/candidates.test.ts new file mode 100644 index 0000000..b0898f0 --- /dev/null +++ b/test/unit/server/completion/candidates.test.ts @@ -0,0 +1,187 @@ +import assert from 'node:assert/strict'; +import { completionCandidates, documentationSource, documentationTarget, type Candidate } from '../../../../src/server/completion/candidates.ts'; +import { completionSiteAt } from '../../../../src/server/syntax/completionContext.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; + +/** The candidates where `|` is in `marked` (the marker is removed first). */ +function candidates(marked: string, kind: 'lua' | 'menu' = 'lua'): Candidate[] { + const offset = marked.indexOf('|'); + assert.ok(offset >= 0 && marked.indexOf('|', offset + 1) < 0, 'exactly one marker'); + const text = marked.slice(0, offset) + marked.slice(offset + 1); + const document = parseDocument(text, kind); + const site = completionSiteAt(document, text, offset); + assert.ok(site, 'no completion site'); + return completionCandidates(document, site); +} + +const labels = (marked: string, kind: 'lua' | 'menu' = 'lua'): string[] => candidates(marked, kind).map((candidate) => candidate.label); + +/** `label kind group target` for the candidate labelled `label`. */ +function candidate(marked: string, label: string): string | undefined { + const found = candidates(marked).find((candidate) => candidate.label === label); + if (!found) return undefined; + const target = found.target; + let what = '-'; + if (target?.kind === 'local') what = `local ${target.declaration.kind}`; + else if (target?.kind === 'global') what = `global ${target.site?.kind ?? '-'} ${target.link?.name ?? '-'}`; + else if (target?.kind === 'library') what = `library ${target.entry.name}`; + else if (target?.kind === 'engineReplaced') what = `engine ${target.replacement.name}`; + else if (target?.kind === 'external') what = `external ${target.entry.name}`; + return `${found.kind} ${String(found.group)} ${what}`; +} + +const KEYWORDS_22 = ['and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while']; + +describe('server/completion/candidates', () => { + describe('variables', () => { + it('offers locals, document globals, library globals, EEex globals and keywords, in that order', () => { + const all = labels('local a = 1 G = 2 |'); + assert.deepEqual(all.slice(0, 2), ['a', 'G']); + assert.ok(all.indexOf('print') > all.indexOf('G')); + assert.ok(all.indexOf('EEex_AIBase_GetScriptLevel') > all.indexOf('bit32')); + assert.ok(all.indexOf('Infinity_DisplayString') > all.indexOf('print')); + assert.deepEqual(all.slice(-22), KEYWORDS_22); + assert.equal(candidate('local a = 1 G = 2 |', 'a'), 'variable 0 local local'); + assert.equal(candidate('local a = 1 G = 2 |', 'G'), 'variable 1 global assignment -'); + assert.equal(candidate('|', 'string'), 'module 2 library string'); + assert.equal(candidate('|', '_VERSION'), 'variable 2 library _VERSION'); + assert.equal(candidate('|', 'pairs'), 'function 2 library pairs'); + assert.equal(candidate('|', 'print'), 'function 2 engine print'); + assert.equal(candidate('|', 'Infinity_DisplayString'), 'function 3 external Infinity_DisplayString'); + assert.equal(candidate('|', 'if'), 'keyword 4 -'); + }); + + it('never offers what the engine does not open', () => { + const all = labels('|'); + for (const name of ['io', 'os', 'package', 'require', 'coroutine', 'module', 'unpack', 'loadstring']) assert.ok(!all.includes(name), name); + }); + + it('offers only the locals visible at the cursor, the innermost of each name', () => { + assert.equal(candidate('local function f(a) local b = a end |', 'f'), 'function 0 local localFunction'); + assert.equal(candidate('local function f(a) local b = a end |', 'a'), undefined); + assert.equal(candidate('local function f(a) | end', 'a'), 'variable 0 local parameter'); + assert.equal(candidate('function t:m() | end', 'self'), 'variable 0 local self'); + assert.equal(candidate('local f = function() end |', 'f'), 'function 0 local local'); + assert.equal(candidate('for i = 1, 2 do | end', 'i'), 'variable 0 local forVariable'); + assert.equal(labels('local x = 1 do local x = 2 | end').filter((label) => label === 'x').length, 1); + }); + + it('lets a local hide a global, and a document global hide the library', () => { + assert.equal(candidate('local string = {} |', 'string'), 'variable 0 local local'); + assert.equal(candidate('function print(x) end |', 'print'), 'function 1 global functionDeclaration -'); + assert.equal(candidate('Infinity_DisplayString = f |', 'Infinity_DisplayString'), 'variable 1 global assignment Infinity_DisplayString'); + }); + + it('offers globals assigned in any chunk of a .menu file, and locals of the cursor chunk only', () => { + const menu = 'menu { name "M" onOpen "local hidden = 1 shared = 2" action "|" }'; + const all = labels(menu, 'menu'); + assert.ok(all.includes('shared')); + assert.ok(!all.includes('hidden')); + }); + + it('offers only locals and keywords while a local _ENV is visible', () => { + const all = labels('G = 1 local _ENV = {} local a |'); + assert.deepEqual(all.slice(0, 2).sort(), ['_ENV', 'a']); + assert.ok(!all.includes('G')); + assert.ok(!all.includes('print')); + assert.deepEqual(all.slice(-22), KEYWORDS_22); + }); + + it('offers only expression keywords in a .menu expression', () => { + const all = labels('menu { name "M" enabled "|" }', 'menu'); + assert.deepEqual(all.filter((label) => KEYWORDS_22.includes(label)), ['and', 'false', 'function', 'nil', 'not', 'or', 'true']); + }); + + it('describes a document global by its first assignment, in document order across .menu chunks', () => { + assert.equal(candidate('G = 1 function G() end |', 'G'), 'variable 1 global assignment -'); + assert.equal(candidate('function G() end G = 1 |', 'G'), 'function 1 global functionDeclaration -'); + const menu = 'menu { name "M" onOpen "function G() end" action "G = 1 |" }'; + const found = candidates(menu, 'menu').find((c) => c.label === 'G'); + assert.equal(found?.target?.kind === 'global' ? found.target.site?.kind : undefined, 'functionDeclaration'); + }); + + it('does not offer globals the document only reads', () => { + assert.ok(!labels('print(undefinedName) |').includes('undefinedName')); + }); + }); + + describe('members', () => { + it('offers the manual members of a library module', () => { + const all = labels('string.|'); + assert.ok(all.includes('format')); + assert.ok(all.includes('rep')); + assert.ok(all.every((label) => !label.includes('.'))); + assert.equal(candidate('math.|', 'pi'), 'field 2 library math.pi'); + assert.equal(candidate('math.|', 'floor'), 'function 2 library math.floor'); + assert.deepEqual(labels('_G._G.string.|'), labels('string.|')); + }); + + it('offers the fields the document assigns, and drops library members it defines', () => { + const all = labels('string.format = f function string.trim() end string.|'); + assert.ok(all.includes('trim')); + assert.equal(candidate('string.format = f string.|', 'format'), 'field 1 -'); + assert.equal(candidate('t.a = 1 function t:m() end t.|', 'a'), 'field 1 -'); + assert.equal(candidate('t.a = 1 function t:m() end t:|', 'm'), 'method 1 -'); + }); + + it('offers no library members of a module table the document assigns', () => { + assert.deepEqual(labels('string = {} string.x = 1 string.|'), ['x']); + }); + + it('offers EEex-Docs members after the operator they are documented with', () => { + assert.equal(candidate('C:|', 'AddGold'), 'method 3 external C:AddGold'); + assert.ok(!labels('C.|').includes('AddGold')); + assert.deepEqual(labels('EEex_Options_Option.|'), ['new']); + }); + + it('offers the globals after _G.', () => { + const all = labels('G = 1 local l = 2 _G.|'); + assert.ok(all.includes('G')); + assert.ok(all.includes('print')); + assert.ok(!all.includes('l')); + assert.ok(!all.includes('if')); + }); + + it('offers nothing on locals and fields of a local _ENV', () => { + assert.deepEqual(labels('local string = {} string.|'), []); + assert.deepEqual(labels('local _ENV = {} string.|'), []); + assert.deepEqual(labels('t.|'), []); + }); + + it('offers string library methods on a parenthesized string', () => { + const all = labels('x = ("x"):|'); + assert.ok(all.includes('rep')); + assert.equal(candidate('x = ("x"):|', 'rep'), 'method 2 library string.rep'); + assert.equal(candidate('function string:rep() end x = ("x"):|', 'rep'), 'method 1 -'); + }); + }); + + describe('documentation', () => { + it('refers to documentation by source and name, and finds it again', () => { + const find = (marked: string, label: string): Candidate => { + const found = candidates(marked).find((candidate) => candidate.label === label); + assert.ok(found, label); + return found; + }; + for (const [marked, label, expected] of [ + ['|', 'pairs', { source: 'manual', name: 'pairs' }], + ['string.|', 'format', { source: 'manual', name: 'string.format' }], + ['|', 'print', { source: 'engineReplaced', name: 'print' }], + ['C:|', 'AddGold', { source: 'external', name: 'C:AddGold' }], + ['Infinity_DisplayString = f |', 'Infinity_DisplayString', { source: 'external', name: 'Infinity_DisplayString' }], + ] as const) { + const source = documentationSource(find(marked, label).target); + assert.deepEqual(source, expected); + assert.ok(documentationTarget(JSON.parse(JSON.stringify(source)) as unknown), label); + } + assert.equal(documentationSource(find('local a = 1 |', 'a').target), undefined); + assert.equal(documentationSource(find('|', 'if').target), undefined); + }); + + it('ignores data it did not produce', () => { + for (const value of [undefined, null, 1, 'pairs', {}, { source: 'manual' }, { source: 'manual', name: 'io.open' }, { source: 'file', name: 'pairs' }, { source: 'external', name: 'pairs' }]) { + assert.equal(documentationTarget(value), undefined, JSON.stringify(value)); + } + }); + }); +}); diff --git a/test/unit/server/features/completion.test.ts b/test/unit/server/features/completion.test.ts new file mode 100644 index 0000000..8eba493 --- /dev/null +++ b/test/unit/server/features/completion.test.ts @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import { CompletionItemKind, MarkupKind, type CompletionItem, type Range } from 'vscode-languageserver/node'; +import type { Candidate } from '../../../../src/server/completion/candidates.ts'; +import { resolveCompletionItem, toCompletionList, type CompletionClientOptions } from '../../../../src/server/features/completion.ts'; +import { allManualEntries, externalEntry } from '../../../../src/server/hover/knowledge.ts'; +import { createMessages } from '../../../../src/server/l10n.ts'; + +const english = createMessages(undefined); +const insert: Range = { start: { line: 1, character: 4 }, end: { line: 1, character: 6 } }; +const replace: Range = { start: { line: 1, character: 4 }, end: { line: 1, character: 9 } }; + +const pairs = allManualEntries().find((entry) => entry.name === 'pairs'); +const addGold = externalEntry('C:AddGold'); +assert.ok(pairs && addGold); +const candidates: Candidate[] = [ + { label: 'pairs', kind: 'function', group: 2, target: { kind: 'library', entry: pairs } }, + { label: 'AddGold', kind: 'method', group: 3, target: { kind: 'external', entry: addGold } }, + { label: 'field', kind: 'field', group: 1, target: undefined }, + { label: 'while', kind: 'keyword', group: 4, target: undefined }, +]; + +const options = (overrides: Partial = {}): CompletionClientOptions => ({ format: 'markdown', insertReplace: false, defaultEditRange: false, ...overrides }); + +describe('server/features/completion', () => { + describe('toCompletionList', () => { + it('gives each item its kind, sort group, code line and documentation source', () => { + const { isIncomplete, items } = toCompletionList(candidates, insert, replace, options({ defaultEditRange: true }), english); + assert.equal(isIncomplete, false); + assert.deepEqual(items, [ + { label: 'pairs', kind: CompletionItemKind.Function, sortText: '2', detail: 'pairs (t)', data: { source: 'manual', name: 'pairs' } }, + { label: 'AddGold', kind: CompletionItemKind.Method, sortText: '3', detail: 'C:AddGold', data: { source: 'external', name: 'C:AddGold' } }, + { label: 'field', kind: CompletionItemKind.Field, sortText: '1' }, + { label: 'while', kind: CompletionItemKind.Keyword, sortText: '4' }, + ]); + }); + + it('sends the edit range once when the client supports item defaults', () => { + assert.deepEqual(toCompletionList(candidates, insert, replace, options({ defaultEditRange: true }), english).itemDefaults, { editRange: insert }); + assert.deepEqual(toCompletionList(candidates, insert, replace, options({ defaultEditRange: true, insertReplace: true }), english).itemDefaults, { + editRange: { insert, replace }, + }); + }); + + it('otherwise gives every item its edit: insert/replace when supported, else up to the cursor', () => { + const [plain] = toCompletionList(candidates, insert, replace, options(), english).items; + assert.deepEqual(plain?.textEdit, { range: insert, newText: 'pairs' }); + const [both] = toCompletionList(candidates, insert, replace, options({ insertReplace: true }), english).items; + assert.deepEqual(both?.textEdit, { insert, replace, newText: 'pairs' }); + assert.equal(toCompletionList(candidates, insert, replace, options(), english).itemDefaults, undefined); + }); + }); + + describe('resolveCompletionItem', () => { + it('adds the hover documentation in the client format, without the code line', () => { + const item: CompletionItem = { label: 'pairs', data: { source: 'manual', name: 'pairs' } }; + const markdown = resolveCompletionItem(item, 'markdown', english).documentation; + assert.ok(typeof markdown === 'object' && markdown.kind === MarkupKind.Markdown); + assert.ok(markdown.value.startsWith('If `t` has a metamethod `__pairs`'), markdown.value); + assert.ok(markdown.value.endsWith('[Lua 5.2 Reference Manual, §6.1 – Basic Functions](https://www.lua.org/manual/5.2/manual.html#pdf-pairs)')); + const plain = resolveCompletionItem(item, 'plaintext', english).documentation; + assert.ok(typeof plain === 'object' && plain.kind === MarkupKind.PlainText && !plain.value.includes('`')); + }); + + it('links EEex-Docs entries and notes the engine replacement of print', () => { + const link = resolveCompletionItem({ label: 'AddGold', data: { source: 'external', name: 'C:AddGold' } }, 'markdown', english).documentation; + assert.ok(typeof link === 'object' && /^\[EE Game Lua Functions\]\(https:\/\/eeex-docs\.readthedocs\.io\//.test(link.value)); + const print = resolveCompletionItem({ label: 'print', data: { source: 'engineReplaced', name: 'print' } }, 'markdown', english).documentation; + assert.ok(typeof print === 'object' && print.value.startsWith('The game engine replaces `print`')); + }); + + it('returns other items unchanged', () => { + for (const item of [{ label: 'x' }, { label: 'x', data: 1 }, { label: 'x', data: { source: 'manual', name: 'io.open' } }] as CompletionItem[]) { + assert.equal(resolveCompletionItem(item, 'markdown', english), item); + } + }); + }); +}); diff --git a/test/unit/server/features/hover.test.ts b/test/unit/server/features/hover.test.ts deleted file mode 100644 index c9425bc..0000000 --- a/test/unit/server/features/hover.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import assert from 'node:assert/strict'; -import { hoverFormat } from '../../../../src/server/features/hover.ts'; - -describe('server/features/hover hoverFormat', () => { - it('answers in the first format the client prefers that the server produces', () => { - assert.equal(hoverFormat(['markdown', 'plaintext']), 'markdown'); - assert.equal(hoverFormat(['plaintext', 'markdown']), 'plaintext'); - assert.equal(hoverFormat(['html', 'markdown']), 'markdown'); - }); - - it('answers in plain text when the client lists no format it knows', () => { - assert.equal(hoverFormat(undefined), 'plaintext'); - assert.equal(hoverFormat([]), 'plaintext'); - assert.equal(hoverFormat(['html']), 'plaintext'); - }); -}); diff --git a/test/unit/server/features/markup.test.ts b/test/unit/server/features/markup.test.ts new file mode 100644 index 0000000..e6c867c --- /dev/null +++ b/test/unit/server/features/markup.test.ts @@ -0,0 +1,16 @@ +import assert from 'node:assert/strict'; +import { markupFormat } from '../../../../src/server/features/markup.ts'; + +describe('server/features/markup markupFormat', () => { + it('answers in the first format the client prefers that the server produces', () => { + assert.equal(markupFormat(['markdown', 'plaintext']), 'markdown'); + assert.equal(markupFormat(['plaintext', 'markdown']), 'plaintext'); + assert.equal(markupFormat(['html', 'markdown']), 'markdown'); + }); + + it('answers in plain text when the client lists no format it knows', () => { + assert.equal(markupFormat(undefined), 'plaintext'); + assert.equal(markupFormat([]), 'plaintext'); + assert.equal(markupFormat(['html']), 'plaintext'); + }); +}); diff --git a/test/unit/server/hover/render.test.ts b/test/unit/server/hover/render.test.ts index a2b302b..9b4830b 100644 --- a/test/unit/server/hover/render.test.ts +++ b/test/unit/server/hover/render.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { createMessages } from '../../../../src/server/l10n.ts'; -import { renderHover, type HoverFormat } from '../../../../src/server/hover/render.ts'; +import { renderDocumentation, renderHover, renderSignature, type HoverFormat } from '../../../../src/server/hover/render.ts'; import { hoverTargetAt } from '../../../../src/server/hover/resolve.ts'; import { parseDocument } from '../../../../src/server/syntax/document.ts'; @@ -92,4 +92,30 @@ describe('server/hover/render', () => { assert.match(render('EEex_AIBase_GetScriptLevel()', 'EEex', 'plaintext'), /^EEex_AIBase_GetScriptLevel\n\nEEex Functions: https:\/\/eeex-docs\.readthedocs\.io\//); }); }); + + describe('signature and documentation separately', () => { + const hit = (text: string, needle: string): Parameters[0] => { + const found = hoverTargetAt(parseDocument(text, 'lua'), text.indexOf(needle)); + assert.ok(found, needle); + return found.target; + }; + + it('make up the hover: code line, then documentation and link', () => { + for (const [text, needle] of [['return math.huge', 'huge'], ['print(1)', 'print'], ['C:AddGold(1)', 'AddGold'], ['local x = 1 return x', 'x']] as const) { + const target = hit(text, needle); + for (const format of ['markdown', 'plaintext'] as const) { + const code = format === 'markdown' ? fence(renderSignature(target, english)) : renderSignature(target, english); + const documentation = renderDocumentation(target, format, english); + const separator = format === 'markdown' ? '\n\n---\n\n' : '\n\n'; + assert.equal(renderHover(target, format, english), documentation === undefined ? code : `${code}${separator}${documentation}`, `${needle} ${format}`); + } + } + }); + + it('give the code line alone for names without documentation', () => { + const target = hit('local function f(a) end', 'f('); + assert.equal(renderSignature(target, english), 'local function f(a)'); + assert.equal(renderDocumentation(target, 'markdown', english), undefined); + }); + }); }); diff --git a/test/unit/server/syntax/completionContext.test.ts b/test/unit/server/syntax/completionContext.test.ts new file mode 100644 index 0000000..b380ec8 --- /dev/null +++ b/test/unit/server/syntax/completionContext.test.ts @@ -0,0 +1,173 @@ +import assert from 'node:assert/strict'; +import { completionSiteAt, lexStart, siteFrom } from '../../../../src/server/syntax/completionContext.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; + +/** + * The completion site where `|` is in `marked` (the marker is removed first), + * as `context [prefix] start-end`, or `undefined` when there is none. + */ +function site(marked: string, kind: 'lua' | 'menu' = 'lua'): string | undefined { + const offset = marked.indexOf('|'); + assert.ok(offset >= 0 && marked.indexOf('|', offset + 1) < 0, 'exactly one marker'); + const text = marked.slice(0, offset) + marked.slice(offset + 1); + const found = completionSiteAt(parseDocument(text, kind), text, offset); + if (!found) return undefined; + const { context } = found; + const description = + context.kind === 'member' ? `${context.path.join('.')}${context.operator}` : context.kind; + return `${description}${found.expression ? ' (expression)' : ''} [${found.prefix}] ${String(found.start)}-${String(found.end)}`; +} + +describe('server/syntax/completionContext', () => { + describe('variables', () => { + it('completes the name before the cursor, replacing the whole name', () => { + assert.equal(site('pri|'), 'variable [pri] 0-3'); + assert.equal(site('pri|nt()'), 'variable [pri] 0-5'); + assert.equal(site('x = |'), 'variable [] 4-4'); + assert.equal(site('|'), 'variable [] 0-0'); + }); + + it('treats a keyword being typed as a prefix (`do` may become `dofile`)', () => { + assert.equal(site('do|'), 'variable [do] 0-2'); + assert.equal(site('x = f(a) and|'), 'variable [and] 9-12'); + }); + + it('completes after operators, `..`, `(`, `,` and keywords that start expressions', () => { + assert.equal(site('x = a .. |'), 'variable [] 9-9'); + assert.equal(site('x = a..b|'), 'variable [b] 7-8'); + assert.equal(site('f(a, |'), 'variable [] 5-5'); + assert.equal(site('if |'), 'variable [] 3-3'); + assert.equal(site('return |'), 'variable [] 7-7'); + assert.equal(site('for k, v in |'), 'variable [] 12-12'); + assert.equal(site('local a, b = |'), 'variable [] 13-13'); + assert.equal(site('::top:: |'), 'variable [] 8-8'); + }); + }); + + describe('nothing to complete', () => { + it('in comments', () => { + assert.equal(site('-- pri|'), undefined); + assert.equal(site('--[[ pri|'), undefined); + assert.equal(site('--[[ pri|\n]]'), undefined); + assert.equal(site('--[==[ ]] pri|'), undefined); + assert.equal(site('--[[ x ]]|'), 'variable [] 9-9'); + assert.equal(site('-- x\n|'), 'variable [] 5-5'); + }); + + it('in strings and numbers', () => { + assert.equal(site('x = "pri|'), undefined); + assert.equal(site('x = "pri|"'), undefined); + assert.equal(site('x = [[pri|]]'), undefined); + assert.equal(site('x = "a"|'), undefined); + assert.equal(site('x = 1|'), undefined); + assert.equal(site('x = 1.|'), undefined); + }); + + it('where a name is declared', () => { + assert.equal(site('local |'), undefined); + assert.equal(site('local x|'), undefined); + assert.equal(site('local a, |'), undefined); + assert.equal(site('local function |'), undefined); + assert.equal(site('function |'), undefined); + assert.equal(site('function t.|'), undefined); + assert.equal(site('function t:m|'), undefined); + assert.equal(site('function f(|'), undefined); + assert.equal(site('function t.a:b(x, |'), undefined); + assert.equal(site('x = function(a, b|'), undefined); + assert.equal(site('for |'), undefined); + assert.equal(site('for k, |'), undefined); + assert.equal(site('goto |'), undefined); + assert.equal(site('::|'), undefined); + }); + + it('after members of anything but a chain of names', () => { + assert.equal(site('f().|'), undefined); + assert.equal(site('t[1].|'), undefined); + assert.equal(site('t[1].a.|'), undefined); + assert.equal(site('x = "s":|'), undefined); + }); + }); + + describe('members', () => { + it('follows `.` chains of names', () => { + assert.equal(site('string.|'), 'string. [] 7-7'); + assert.equal(site('string.fo|rmat'), 'string. [fo] 7-13'); + assert.equal(site('_G.string.|'), '_G.string. [] 10-10'); + assert.equal(site('x = a .b. |'), 'a.b. [] 10-10'); + }); + + it('follows `:` after a chain of names, and `("…"):` for string methods', () => { + assert.equal(site('C:|'), 'C: [] 2-2'); + assert.equal(site('a.b:c|'), 'a.b: [c] 4-5'); + assert.equal(site('x = ("x"):r|'), 'stringMethod [r] 10-11'); + assert.equal(site('x = ([[x]]):|'), 'stringMethod [] 12-12'); + }); + + it('completes members in incomplete code inside a function', () => { + assert.equal(site('local function f(a)\n string.|\nend'), 'string. [] 29-29'); + }); + }); + + describe('.menu files', () => { + const menu = (code: string): string => `menu\n{\n\tname 'M'\n\t${code}\n}\n`; + + it('completes only inside the Lua chunks', () => { + assert.equal(site(menu('onOpen "pri|"'), 'menu'), 'variable [pri] 26-29'); + assert.equal(site(menu('enabled "x |"'), 'menu'), 'variable (expression) [] 29-29'); + assert.equal(site(menu('ena|bled "x"'), 'menu'), undefined); + assert.equal(site(`\`\nstring.| \`\n${menu('')}`, 'menu'), 'string. [] 9-9'); + assert.equal(site(`|${menu('')}`, 'menu'), undefined); + }); + }); + + describe('lexing from the last statement before the cursor', () => { + const sources: [string, 'lua' | 'menu'][] = [ + [ + [ + 'local a, b = 1, "two" -- comment', + '--[[ long', + 'comment ]] local t = { x = [[long', + 'string]] }', + '::top:: goto top', + 'function M.f(p, q) for i = 1, p do print(i .. q) end return string.format("%d", p) end', + 'local function g(...) return ("x"):rep(2), C:AddGold(1), _G.string.len end', + 'if a then local c = a elseif b then t.x = b else repeat local d = 1 until d end', + 'x = f(a, ', + 'y = t.', + 'z = 1 local', + ].join('\n'), + 'lua', + ], + ['`\nshown = false\n`\nmenu { name "M" onOpen "local n = 1 shown = n" enabled "shown and not x." action "for k, v in pairs(t) do f(v) end" }', 'menu'], + ]; + + it('finds the same site at every offset as lexing the whole chunk', () => { + for (const [text, kind] of sources) { + const document = parseDocument(text, kind); + for (let offset = 0; offset <= text.length; offset++) { + const chunkIndex = document.chunks.findIndex(({ chunk }) => chunk.offset <= offset && offset <= chunk.offset + chunk.text.length); + const parsed = document.chunks[chunkIndex]; + if (!parsed) continue; + assert.deepEqual(completionSiteAt(document, text, offset), siteFrom(parsed, chunkIndex, text, offset, parsed.chunk.offset), `offset ${String(offset)}`); + } + } + }); + + it('starts at the last top-level statement that starts before the cursor', () => { + const text = 'local a = 1\nlocal b = 2\nb = '; + const [parsed] = parseDocument(text, 'lua').chunks; + assert.ok(parsed); + assert.equal(lexStart(parsed, 0), 0); + assert.equal(lexStart(parsed, 12), 0); + assert.equal(lexStart(parsed, 13), 12); + assert.equal(lexStart(parsed, text.length), 12); + }); + + it('does not start at statements the parser found after a syntax error', () => { + const text = 'local a = 1\ny = t.\nz = 1'; + const [parsed] = parseDocument(text, 'lua').chunks; + assert.ok(parsed); + assert.equal(lexStart(parsed, text.length), 12); + }); + }); +}); diff --git a/test/unit/server/syntax/globalPaths.test.ts b/test/unit/server/syntax/globalPaths.test.ts new file mode 100644 index 0000000..cc2087a --- /dev/null +++ b/test/unit/server/syntax/globalPaths.test.ts @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { fieldWrites, globalPath, withoutG } from '../../../../src/server/syntax/globalPaths.ts'; + +/** The global path of the value of the last statement `return ` of `text`. */ +function pathOfReturn(text: string): string[] | undefined { + const document = parseDocument(text, 'lua'); + const last = document.chunks[0]?.tree.body.body.at(-1); + assert.ok(last?.kind === 'ReturnStatement'); + const [value] = last.values; + assert.ok(value); + return globalPath(document, 0, value); +} + +describe('server/syntax/globalPaths', () => { + it('lists the names of a `.` chain that starts at a global', () => { + assert.deepEqual(pathOfReturn('return string'), ['string']); + assert.deepEqual(pathOfReturn('return _G.string.format'), ['_G', 'string', 'format']); + }); + + it('gives no path for chains that start at a local, a call, an index or a field of a local _ENV', () => { + assert.equal(pathOfReturn('local string = {} return string.format'), undefined); + assert.equal(pathOfReturn('return f().x'), undefined); + assert.equal(pathOfReturn('return t[1].x'), undefined); + assert.equal(pathOfReturn('local _ENV = {} return string.format'), undefined); + }); + + it('removes `_G.` prefixes while another name follows', () => { + assert.deepEqual(withoutG(['_G', '_G', 'string']), ['string']); + assert.deepEqual(withoutG(['_G']), ['_G']); + }); + + it('collects the fields a document assigns on global tables, in every form and chunk', () => { + const text = 't.a = 1 _G.t.b = 2 function t.c() end function t:d() end local l = {} l.e = 3 t.f.g = 4'; + assert.deepEqual([...fieldWrites(parseDocument(text, 'lua'))].sort(), ['t.a', 't.b', 't.c', 't.d']); + const menu = 'menu { name "M" onOpen "u.x = 1" action "function u:y() end" }'; + assert.deepEqual([...fieldWrites(parseDocument(menu, 'menu'))].sort(), ['u.x', 'u.y']); + }); +}); diff --git a/test/unit/server/syntax/scope.test.ts b/test/unit/server/syntax/scope.test.ts index 4b601f9..a35aa0a 100644 --- a/test/unit/server/syntax/scope.test.ts +++ b/test/unit/server/syntax/scope.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { parseChunk } from '../../../../src/server/syntax/parser.ts'; -import { analyzeScopes, type ScopeAnalysis } from '../../../../src/server/syntax/scope.ts'; +import { analyzeScopes, visibleAt, type ScopeAnalysis } from '../../../../src/server/syntax/scope.ts'; function analyze(source: string): ScopeAnalysis { const chunk = parseChunk(source); @@ -122,4 +122,71 @@ describe('server/syntax/scope', () => { it('does not record declarations, reads or function paths with fields or methods as writes', () => { assert.deepEqual([...analyze('local x = y function t.f() end function t:m() end print(x)').writes], []); }); + + describe('visibility', () => { + /** + * Names visible where `|` is in `marked` (the marker is removed before parsing, + * which may leave the code incomplete), sorted, as `name:kind@declaringOffset`. + */ + function visible(marked: string): string[] { + const offset = marked.indexOf('|'); + assert.ok(offset >= 0 && marked.indexOf('|', offset + 1) < 0, 'exactly one marker'); + const source = marked.slice(0, offset) + marked.slice(offset + 1); + return visibleAt(analyzeScopes(parseChunk(source)), offset) + .map((d) => `${d.name}:${d.kind}@${d.identifier ? String(d.identifier.start) : '-'}`) + .sort(); + } + + it('makes a local visible after its statement, not in its own initializer', () => { + assert.deepEqual(visible('local x = 1 |'), ['x:local@6']); + assert.deepEqual(visible('local x = |'), []); + assert.deepEqual(visible('local x = y|'), []); + assert.deepEqual(visible('local x = 1 local y = x|'), ['x:local@6']); + }); + + it('makes a local function visible in its own body', () => { + assert.deepEqual(visible('local function f() | end'), ['f:localFunction@15']); + }); + + it('makes parameters and the implicit self visible in the body only', () => { + assert.deepEqual(visible('function t:m(a) | end'), ['a:parameter@13', 'self:self@-']); + assert.deepEqual(visible('function t:m(a) end |'), []); + }); + + it('makes for variables visible in the loop body, not in the loop expressions', () => { + assert.deepEqual(visible('for i = 1, 2 do | end'), ['i:forVariable@4']); + assert.deepEqual(visible('for i = 1, n| do end'), []); + assert.deepEqual(visible('for k, v in pairs(t) do | end'), ['k:forVariable@4', 'v:forVariable@7']); + assert.deepEqual(visible('for k, v in pairs(t) do end |'), []); + }); + + it('ends block scopes at their closing keyword, and lets until see the repeat body', () => { + assert.deepEqual(visible('do local x = 1 | end'), ['x:local@9']); + assert.deepEqual(visible('do local x = 1 end |'), []); + assert.deepEqual(visible('while c do local x = 1 | end'), ['x:local@17']); + assert.deepEqual(visible('repeat local x = 1 until x|'), ['x:local@13']); + assert.deepEqual(visible('repeat local x = 1 until x |'), []); + assert.deepEqual(visible('if a then local x = 1 | else end'), ['x:local@16']); + assert.deepEqual(visible('if a then local x = 1 else | end'), []); + assert.deepEqual(visible('if a then local x = 1 elseif | then end'), []); + }); + + it('keeps the innermost declaration of each name', () => { + assert.deepEqual(visible('local x = 1 do local x = 2 | end'), ['x:local@21']); + assert.deepEqual(visible('local x = 1 do local x = 2 end |'), ['x:local@6']); + assert.deepEqual(visible('local x = 1 local x = 2 |'), ['x:local@18']); + assert.deepEqual(visible('local a = 1 function f(a) | end'), ['a:parameter@23']); + }); + + it('sees through code that does not parse, up to the closing keyword', () => { + assert.deepEqual(visible('local function f(a)\n local b = 1\n a.|\nend'), ['a:parameter@17', 'b:local@28', 'f:localFunction@15']); + assert.deepEqual(visible('local function f(a)\n local b = 1\n print(|\nend'), ['a:parameter@17', 'b:local@28', 'f:localFunction@15']); + assert.deepEqual(visible('local function f(a)\n local b = 1\nend\nprint(|'), ['f:localFunction@15']); + }); + + it('extends scopes without a closing keyword to the end of the enclosing scope', () => { + assert.deepEqual(visible('local function f(a)\n local b = 1\n |'), ['a:parameter@17', 'b:local@28', 'f:localFunction@15']); + assert.deepEqual(visible('do\n for i = 1, 2 do\n local x = i\nend\n|'), []); + }); + }); });