From 10edc96b3365f5fa53f48746cb580c4f0cb437ee Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:46:39 +0100 Subject: [PATCH 1/5] refactor(server): record where the parser begins each statement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Chunk.statementStarts` lists the offset of the first token of every statement the parser began, in source order. It includes statements that an error made the parser abandon, which are missing from `body`: after `if a then … elseif ` the whole `if` statement is dropped, but the statements typed inside it are still known. Range and on-type formatting need this to indent the lines before a syntax error that is still being typed. Nothing else changes; a unit test pins the abandoned-statement case. Co-Authored-By: Claude Opus 5.5 --- src/server/syntax/ast.ts | 5 +++++ src/server/syntax/parser.ts | 5 ++++- test/unit/server/syntax/parser.test.ts | 11 +++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/server/syntax/ast.ts b/src/server/syntax/ast.ts index d80a150..2a2dbbe 100644 --- a/src/server/syntax/ast.ts +++ b/src/server/syntax/ast.ts @@ -19,6 +19,11 @@ export interface Chunk extends Node { readonly comments: readonly Comment[]; /** Lexical and syntax errors, in source order. Empty when the chunk is valid Lua 5.2 (see parser.ts for the checks that are not done). */ readonly errors: readonly ParseError[]; + /** + * Offset of the first token of every statement the parser began, in source order, + * including statements abandoned after an error (which are missing from `body`). + */ + readonly statementStarts: readonly number[]; } export interface Block extends Node { diff --git a/src/server/syntax/parser.ts b/src/server/syntax/parser.ts index ee0434f..8b4ace2 100644 --- a/src/server/syntax/parser.ts +++ b/src/server/syntax/parser.ts @@ -67,6 +67,8 @@ interface FunctionState { class Parser { readonly errors: ParseError[] = []; + /** See `Ast.Chunk.statementStarts`. */ + readonly statementStarts: number[] = []; private readonly tokens: readonly Token[]; private readonly eof: Token; private readonly source: string; @@ -238,6 +240,7 @@ class Parser { while (!this.blockFollow(true)) { const isReturn = this.check('return'); const startIndex = this.p; + this.statementStarts.push(this.token.start); try { const statement = this.statement(); if (statement) body.push(statement); @@ -629,5 +632,5 @@ export function parseChunk(source: string, options: ParseOptions = {}): Ast.Chun const parser = new Parser(source, tokens, from, to, options.functionBody ?? false); const body = options.mode === 'expression' ? parser.expressionChunk(from) : parser.chunk(from); const errors = [...lexErrors, ...parser.errors].sort((a, b) => a.start - b.start); - return { kind: 'Chunk', body, comments, errors, start: from, end: to }; + return { kind: 'Chunk', body, comments, errors, statementStarts: parser.statementStarts, start: from, end: to }; } diff --git a/test/unit/server/syntax/parser.test.ts b/test/unit/server/syntax/parser.test.ts index 3f650fc..2f14094 100644 --- a/test/unit/server/syntax/parser.test.ts +++ b/test/unit/server/syntax/parser.test.ts @@ -212,6 +212,17 @@ describe('server/syntax/parser', () => { assert.deepEqual(declaration.func.body.body.map((s) => s.kind), ['CallStatement']); assert.notEqual(declaration.func.closeStart, undefined); }); + + it('records the start of every statement it began, also of statements abandoned after an error', () => { + const source = 'local a = 1\nif a then\n do x() end\n elseif'; + const chunk = parseChunk(source); + // The `if` statement is abandoned at ``: it is missing from the body, not from `statementStarts`. + assert.deepEqual(chunk.body.body.map((s) => s.kind), ['LocalStatement']); + assert.deepEqual( + chunk.statementStarts.map((offset) => source.slice(offset).split(/\s/, 1)[0]), + ['local', 'if', 'do', 'x()'], + ); + }); }); describe('slices and expression mode', () => { From f67d8a23252e7cd90f905c3225c34c02bf0233da Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:46:39 +0100 Subject: [PATCH 2/5] feat(server): compute layout-preserving formatting edits for Lua `formatting/format.ts` (pure) computes the edits for document, range and on-type formatting of a Lua 5.2 chunk. Only the white space between tokens and comments changes: line breaks are kept exactly (characters and count), and the inside of strings, long strings and long comments is never touched. - Indentation by the constructs open at the start of each line (`function`, `do`, `then`, `else`, `repeat`, brackets), once per line that opens them, so `f(function()` indents its body once; a line led by closers takes the level of the line that opened them (`end)`, `}, {`); a line continuing a statement in a block gets one more level, and `then`/`do` open from the statement. - Spacing within a line from an ordered rule table (spaces around binary operators, `=` and keywords; none inside `()`/`[]`, around `.`/`:`, after unary `-`/`#`, before call parentheses; `{ a }`; string and table call arguments joined or apart as written; space kept before trailing comments). The rules use token neighbors only, exact for valid Lua 5.2, so they hold before a syntax error that makes the parser abandon a statement. - Trailing white space removed; `insertFinalNewline`/`trimFinalNewlines` honored for document formatting when the client sends `true`. - Document formatting is refused on any lexical or syntax error; range and on-type formatting only on errors that start before the end of the lines they change (a line's layout depends only on the text up to it). - Safety check: the result is lexed again and must have the same tokens, comments, errors and line breaks before its last token, or nothing is returned (`unsafe`). This guards e.g. `- -x` and `t[ [[s]] ]`. Checked beyond the unit tests on 133 local Lua files (4 MB, not committed): no unsafe result, idempotent, everything the official Lua 5.2.4 compiler accepted still compiles, range over the whole text equals document formatting, and the 41 refusals are exactly the files the compiler rejects. Co-Authored-By: Claude Opus 5.5 --- src/server/formatting/format.ts | 486 +++++++++++++++++++++ test/unit/server/formatting/format.test.ts | 385 ++++++++++++++++ 2 files changed, 871 insertions(+) create mode 100644 src/server/formatting/format.ts create mode 100644 test/unit/server/formatting/format.test.ts diff --git a/src/server/formatting/format.ts b/src/server/formatting/format.ts new file mode 100644 index 0000000..eab22b8 --- /dev/null +++ b/src/server/formatting/format.ts @@ -0,0 +1,486 @@ +// Layout-preserving formatting of a Lua 5.2 chunk (LSP `textDocument/formatting`, +// `/rangeFormatting` and `/onTypeFormatting`). Pure: no LSP or `vscode` imports; +// src/server/features/formatting.ts converts the result. +// +// Only the white space between tokens and comments is rewritten. Line breaks are +// kept exactly as written (same characters, same count), and the inside of every +// token and comment (strings, long strings, long comments) is never touched, apart +// from trailing white space at the end of a `--` comment. Within that white space: +// +// - Indentation: each line is indented by the constructs open at its start +// (`function`, `do`, `then`, `else`, `repeat`, `(`, `[`, `{`), counted once per +// line that opens them; a line that starts with closers (`end`, `until`, `else`, +// `elseif`, `)`, `]`, `}`) is indented like the line that opened the construct. +// A line that continues a statement inside a block (`if a and` / `b then`) gets +// one more level. +// - Spacing within a line: see `inlineSpace`. +// - Trailing white space is removed, and lines holding only white space become empty. +// +// Safety: the formatted text is lexed again and must have exactly the same tokens +// and comments (`--` comments compared without trailing white space) and the same +// line breaks up to its last token or comment (only the final newlines may change, as +// `insertFinalNewline` and `trimFinalNewlines` ask); otherwise no edit is returned. +// White space between two tokens +// never changes their meaning in Lua 5.2 once it neither joins them (checked here) +// nor adds or removes a line break (never done), so the result compiles to the +// same program. + +import type * as Ast from '../syntax/ast.ts'; +import { lex, type Comment, type LexResult, type Token } from '../syntax/lexer.ts'; + +/** The LSP `FormattingOptions` the formatter honors. */ +export interface FormattingOptions { + /** Width of one indentation level in spaces, when `insertSpaces` is set. */ + readonly tabSize: number; + /** Indent with `tabSize` spaces per level instead of one tab. */ + readonly insertSpaces: boolean; + /** Document formatting only: add a line break at the end when there is none. */ + readonly insertFinalNewline?: boolean | undefined; + /** Document formatting only: remove the line breaks after the last one that ends a line with content. */ + readonly trimFinalNewlines?: boolean | undefined; +} + +/** Replace `[start, end)` of the original text with `newText`. */ +export interface OffsetEdit { + readonly start: number; + readonly end: number; + readonly newText: string; +} + +export type FormatResult = + | { readonly ok: true; readonly edits: readonly OffsetEdit[] } + /** + * `syntax-error`: the chunk has a lexical or syntax error where the formatted lines + * depend on it. `unsafe`: the result would not have lexed to the same tokens (a + * bug in the rules; nothing is changed). + */ + | { readonly ok: false; readonly reason: 'syntax-error' | 'unsafe' }; + +/** Characters after which clients ask for on-type formatting. */ +export const ON_TYPE_FIRST_TRIGGER = '\n'; +export const ON_TYPE_MORE_TRIGGERS: readonly string[] = ['d', 'e', 'f', 'l', ')', ']', '}']; + +/** Closers that can be completed by typing one of `ON_TYPE_MORE_TRIGGERS` (their last character). */ +const CLOSERS: ReadonlySet = new Set(['end', 'until', 'else', 'elseif', ')', ']', '}']); +const BLOCK_OPENERS: ReadonlySet = new Set(['function', 'do', 'then', 'else', 'repeat']); +const BRACKET_OPENERS: ReadonlySet = new Set(['(', '[', '{']); +/** Line-starting tokens that end a statement head and are indented like the statement (`while x` / `do`). */ +const HEAD_ENDS: ReadonlySet = new Set(['then', 'do']); +/** Horizontal white space as llex.c `lisspace` counts it, without the line breaks. */ +const TRAILING_SPACE = /[ \t\v\f]+$/; + +interface Item { + readonly start: number; + readonly end: number; + /** Exactly one of `token` and `comment` is set. */ + readonly token: Token | undefined; + readonly comment: Comment | undefined; +} + +/** + * What a token is, from its neighbors. Each rule is exact for valid Lua 5.2 + * (manual §9), and works from tokens alone, so that it holds before a syntax error + * that makes the parser abandon the statement around it. + */ +interface TokenFacts { + /** Offsets of the first token of every statement (`Ast.Chunk.statementStarts`). */ + readonly statementStarts: ReadonlySet; + /** + * Offsets of unary `-` and `#` (`not` is a keyword and spaced like one). `#` is + * always unary; `-` is unary unless it follows the end of an operand. + */ + readonly unaryOperators: ReadonlySet; + /** + * Offsets of string and table call arguments (`f"x"`, `f{…}`): a string or `{` that + * follows the end of a prefix expression (a name, `)`, `]`, or another such argument). + */ + readonly bareArguments: ReadonlySet; + /** Offsets of the name and the closing `::` of `::name::` labels, which join what precedes them. */ + readonly labelParts: ReadonlySet; +} + +/** Tokens after which an expression can end: then `-` is binary. */ +function endsOperand(token: Token | undefined): boolean { + if (token === undefined) return false; + switch (token.type) { + case 'name': + case 'number': + case 'string': + return true; + case 'keyword': + // `end` closes a function expression; after any other `end`, `-` cannot follow. + return token.value === 'nil' || token.value === 'true' || token.value === 'false' || token.value === 'end'; + case 'symbol': + return token.value === ')' || token.value === ']' || token.value === '}' || token.value === '...'; + case 'eof': + return false; + } +} + +function tokenFacts(tokens: readonly Token[], tree: Ast.Chunk): TokenFacts { + const unaryOperators = new Set(); + const bareArguments = new Set(); + const labelParts = new Set(); + /** Offsets of the `}` that close a table call argument. */ + const bareArgumentEnds = new Set(); + /** For each open `{`: whether it is a call argument. */ + const braces: boolean[] = []; + const symbol = (token: Token | undefined, value: string): boolean => token?.type === 'symbol' && token.value === value; + tokens.forEach((token, i) => { + const previous = tokens[i - 1]; + if (symbol(token, '#') || (symbol(token, '-') && !endsOperand(previous))) unaryOperators.add(token.start); + const afterPrefix = + previous !== undefined && + (previous.type === 'name' || + symbol(previous, ')') || + symbol(previous, ']') || + (previous.type === 'string' && bareArguments.has(previous.start)) || + bareArgumentEnds.has(previous.start)); + if (afterPrefix && (token.type === 'string' || symbol(token, '{'))) bareArguments.add(token.start); + if (symbol(token, '{')) braces.push(bareArguments.has(token.start)); + if (symbol(token, '}') && braces.pop() === true) bareArgumentEnds.add(token.start); + if (symbol(token, '::') && tokens[i + 1]?.type === 'name' && symbol(tokens[i + 2], '::')) { + labelParts.add((tokens[i + 1] as Token).start); + labelParts.add((tokens[i + 2] as Token).start); + } + }); + return { statementStarts: new Set(tree.statementStarts), unaryOperators, bareArguments, labelParts }; +} + +/** Line start offsets as LSP counts lines (`\r\n`, `\r` and `\n` each end one). */ +function lineStarts(text: string): number[] { + const starts = [0]; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (c === '\r') { + if (text[i + 1] === '\n') i++; + starts.push(i + 1); + } else if (c === '\n') { + starts.push(i + 1); + } + } + return starts; +} + +/** Zero-based line of `offset`. */ +function lineAt(starts: readonly number[], offset: number): number { + let low = 0; + let high = starts.length - 1; + while (low < high) { + const middle = (low + high + 1) >> 1; + if ((starts[middle] ?? 0) <= offset) low = middle; + else high = middle - 1; + } + return low; +} + +/** Splits white space `[start, end)` at its line breaks into the horizontal runs between them. */ +function horizontalRuns(text: string, start: number, end: number): { start: number; end: number }[] { + const runs: { start: number; end: number }[] = []; + let runStart = start; + for (let i = start; i < end; i++) { + const c = text[i]; + if (c !== '\r' && c !== '\n') continue; + runs.push({ start: runStart, end: i }); + if (c === '\r' && text[i + 1] === '\n' && i + 1 < end) i++; + runStart = i + 1; + } + runs.push({ start: runStart, end }); + return runs; +} + +const isToken = (item: Item | undefined, value: string): boolean => item?.token?.value === value && item.token.type !== 'string'; +const isLongString = (item: Item): boolean => item.token?.type === 'string' && item.token.value.startsWith('['); + +/** + * The space between two items on one line. `original` is the white space written + * between them. Rules, first match wins: + * + * 1. before a comment: as written, at least one space; after a comment: one space + * 2. inside `::name::`: none + * 3. before `,` and `;`: none; after them: one space + * 4. after `(` and `[`, before `)` and `]`: none (one between `[`/`]` and a long string, which would otherwise read as `[[`) + * 5. after `{` and before `}`: one space; none in `{}` + * 6. around `.` and `:`: none + * 7. after unary `-` and `#`: none (one before another `-`, which would start a comment) + * 8. before the `(` of a call, of a function's parameters, or the `[` of an index: none + * 9. before a string or table call argument (`f"x"`, `f{…}`): none if none was written, otherwise one space + * 10. anything else (keywords, binary operators, `=`, names): one space + */ +function inlineSpace(previous: Item, next: Item, original: string, facts: TokenFacts): string { + if (next.comment) return original === '' ? ' ' : original; + if (previous.comment) return ' '; + if (facts.labelParts.has(next.start)) return ''; + if (isToken(next, ',') || isToken(next, ';')) return ''; + if (isToken(previous, ',') || isToken(previous, ';')) return ' '; + if (isToken(previous, '(')) return ''; + if (isToken(next, ')')) return ''; + if (isToken(previous, '[')) return isLongString(next) ? ' ' : ''; + if (isToken(next, ']')) return isLongString(previous) ? ' ' : ''; + if (isToken(previous, '{')) return isToken(next, '}') ? '' : ' '; + if (isToken(next, '}')) return ' '; + if (isToken(previous, '.') || isToken(next, '.') || isToken(previous, ':') || isToken(next, ':')) return ''; + if (facts.unaryOperators.has(previous.start)) return isToken(next, '-') ? ' ' : ''; + const prefix = + previous.token?.type === 'name' || + previous.token?.type === 'string' || + isToken(previous, ')') || + isToken(previous, ']') || + isToken(previous, '}'); + if (isToken(next, '(') && (prefix || isToken(previous, 'function'))) return ''; + if (isToken(next, '[') && prefix) return ''; + if (facts.bareArguments.has(next.start)) return original === '' ? '' : ' '; + return ' '; +} + +interface Frame { + /** `true` for `function`, `do`, `then`, `else`, `repeat`; `false` for brackets. */ + readonly block: boolean; + /** Indentation level of the lines inside the construct. */ + readonly inner: number; +} + +interface Edits { + readonly edits: OffsetEdit[]; + /** The lexed original text, reused by the safety check. */ + readonly lexed: LexResult; +} + +/** + * The edits of the document up to `limit` (edits may extend past it), without the + * safety check. Edits are line-local, disjoint and in order. + */ +function allEdits(text: string, tree: Ast.Chunk, options: FormattingOptions, finalNewlines: boolean, limit = tree.end): Edits { + const lexed = lex(text, tree.start, tree.end); + const { tokens, comments } = lexed; + const items: Item[] = [ + ...tokens.filter((token) => token.type !== 'eof').map((token) => ({ start: token.start, end: token.end, token, comment: undefined })), + ...comments.map((comment) => ({ start: comment.start, end: comment.end, token: undefined, comment })), + ].sort((a, b) => a.start - b.start); + const facts = tokenFacts(tokens, tree); + const unit = options.insertSpaces ? ' '.repeat(Number.isFinite(options.tabSize) ? Math.max(0, Math.floor(options.tabSize)) : 0) : '\t'; + const edits: OffsetEdit[] = []; + const replace = (start: number, end: number, newText: string): void => { + if (text.slice(start, end) !== newText) edits.push({ start, end, newText }); + }; + + const stack: Frame[] = []; + const innerLevel = (): number => stack.at(-1)?.inner ?? 0; + /** Closes the innermost construct when `token` is a closer; returns the level of the line that opened it. */ + const close = (token: Token | undefined): number | undefined => { + if (token === undefined || token.type === 'string' || !CLOSERS.has(token.value)) return undefined; + const frame = stack.pop(); + // No frame: a closer too many, only possible after a syntax error. + return frame === undefined ? 0 : frame.inner - 1; + }; + /** Indentation level of the current line, and that level without the continuation level. */ + let level = 0; + let statementLevel = 0; + /** + * Opens a construct when `token` is an opener. `then` and `do` end the head of their + * statement, so their block is indented from the statement even on a continuation line. + */ + const open = (token: Token | undefined): void => { + if (token === undefined || token.type === 'string') return; + if (BLOCK_OPENERS.has(token.value)) stack.push({ block: true, inner: (HEAD_ENDS.has(token.value) ? statementLevel : level) + 1 }); + else if (BRACKET_OPENERS.has(token.value)) stack.push({ block: false, inner: level + 1 }); + }; + /** Whether a line break separates two items. */ + const broken = (a: Item, b: Item): boolean => horizontalRuns(text, a.end, b.start).length > 1; + const space = (a: Item, b: Item): void => { + replace(a.end, b.start, inlineSpace(a, b, text.slice(a.end, b.start), facts)); + }; + + for (let i = 0; i < items.length; i++) { + // `items[i]` exists: the loop bound. + const item = items[i] as Item; + const previous = items[i - 1]; + // Nothing from here on lies before `limit`: the white space before this item starts at or after it. + if (previous !== undefined && previous.end >= limit) return { edits, lexed }; + if (previous !== undefined && !broken(previous, item)) { + space(previous, item); + close(item.token); + open(item.token); + } else { + // First item of a line: trailing white space and blank lines before it become empty. + const runs = horizontalRuns(text, previous?.end ?? tree.start, item.start); + for (const run of runs.slice(0, -1)) replace(run.start, run.end, ''); + // Closers that lead the line give it the level of the line that opened the last of them. + let j = i; + let leading: number | undefined; + for (let candidate = items[j]; candidate !== undefined; candidate = items[j]) { + if (j > i && broken(items[j - 1] as Item, candidate)) break; + const closed = close(candidate.token); + if (closed === undefined) break; + leading = closed; + j++; + } + const token = item.token; + const continuation = + token !== undefined && + !facts.statementStarts.has(item.start) && + !(token.type === 'keyword' && HEAD_ENDS.has(token.value)) && + (stack.at(-1)?.block ?? true); + statementLevel = leading ?? innerLevel(); + level = statementLevel + (leading === undefined && continuation ? 1 : 0); + // `horizontalRuns` always returns at least one run. + const indentation = runs.at(-1) as { start: number; end: number }; + replace(indentation.start, indentation.end, unit.repeat(level)); + if (j === i) { + open(token); + } else { + // `else` closes `then` and opens its own block at this level. + for (let k = i; k < j; k++) { + if (k > i) space(items[k - 1] as Item, items[k] as Item); + open(items[k]?.token); + } + i = j - 1; + } + } + if (item.comment && !item.comment.long) { + const trailing = TRAILING_SPACE.exec(text.slice(item.start, item.end)); + if (trailing) replace(item.end - trailing[0].length, item.end, ''); + } + } + + // After the last item. + const lastEnd = items.at(-1)?.end ?? tree.start; + const runs = horizontalRuns(text, lastEnd, tree.end); + if (!finalNewlines || items.length === 0) { + for (const run of runs) replace(run.start, run.end, ''); + } else if (runs.length === 1) { + // No line break after the last item. + replace(lastEnd, tree.end, options.insertFinalNewline === true ? endOfLine(text) : ''); + } else if (options.trimFinalNewlines === true && runs.length > 2) { + const first = runs[0] as { start: number; end: number }; + replace(first.start, first.end, ''); + replace((runs[1] as { start: number }).start, tree.end, ''); + } else { + for (const run of runs) replace(run.start, run.end, ''); + } + return { edits, lexed }; +} + +/** The first line break of the text, or `\n` when it has none. */ +function endOfLine(text: string): string { + return /\r\n|\r|\n/.exec(text)?.[0] ?? '\n'; +} + +function applyEdits(text: string, edits: readonly OffsetEdit[]): string { + let result = ''; + let position = 0; + for (const edit of edits) { + result += text.slice(position, edit.start) + edit.newText; + position = edit.end; + } + return result + text.slice(position); +} + +/** + * The safety check: the edited text lexes to the same tokens, comments and errors, + * with as many line breaks before its last token or comment. + */ +function preservesTokens(text: string, edits: readonly OffsetEdit[], before: LexResult, tree: Ast.Chunk): boolean { + const formatted = applyEdits(text, edits); + const delta = formatted.length - text.length; + const after = lex(formatted, tree.start, tree.end + delta); + const sameTokens = + before.tokens.length === after.tokens.length && + before.tokens.every((token, i) => { + const other = after.tokens[i]; + return other !== undefined && token.type === other.type && token.value === other.value; + }); + const commentText = (source: string, comment: Comment): string => { + const raw = source.slice(comment.start, comment.end); + return comment.long ? raw : raw.replace(TRAILING_SPACE, ''); + }; + const sameComments = + before.comments.length === after.comments.length && + before.comments.every((comment, i) => { + const other = after.comments[i]; + return other !== undefined && other.long === comment.long && commentText(text, comment) === commentText(formatted, other); + }); + // Line breaks after the last token or comment are the final newlines that the options may change. + const contentEnd = (result: LexResult): number => + Math.max(result.tokens.at(-2)?.end ?? 0, result.comments.at(-1)?.end ?? 0); + const sameLines = + lineStarts(text.slice(0, contentEnd(before))).length === lineStarts(formatted.slice(0, contentEnd(after))).length; + return sameTokens && sameComments && sameLines && after.errors.length === before.errors.length; +} + +function checked(text: string, tree: Ast.Chunk, edits: readonly OffsetEdit[], lexed: LexResult): FormatResult { + return preservesTokens(text, edits, lexed, tree) ? { ok: true, edits } : { ok: false, reason: 'unsafe' }; +} + +/** Whether an error of the chunk starts before `offset`, i.e. can affect text before it. */ +const errorBefore = (tree: Ast.Chunk, offset: number): boolean => tree.errors.some((error) => error.start < offset); + +/** Formats a whole chunk. Refused when it has any lexical or syntax error. */ +export function formatDocument(text: string, tree: Ast.Chunk, options: FormattingOptions): FormatResult { + if (tree.errors.length > 0) return { ok: false, reason: 'syntax-error' }; + const { edits, lexed } = allEdits(text, tree, options, true); + return checked(text, tree, edits, lexed); +} + +/** + * Formats the whole lines that `[start, end)` touches (a range that ends at the + * start of a line does not include that line). Errors after those lines are + * allowed: the layout of a line depends only on the text up to it. + */ +export function formatRange(text: string, tree: Ast.Chunk, options: FormattingOptions, start: number, end: number): FormatResult { + const starts = lineStarts(text); + const firstLine = lineAt(starts, start); + let lastLine = lineAt(starts, end); + if (lastLine > firstLine && starts[lastLine] === end) lastLine--; + return formatSpan(text, tree, options, { from: starts[firstLine] ?? 0, to: starts[lastLine + 1] ?? text.length }); +} + +interface Span { + /** + * Only the edits within `[from, to)` are kept; an insertion at `to` belongs to the + * next line (its indentation) and is not kept. + */ + readonly from: number; + readonly to: number; + readonly keep?: (edit: OffsetEdit) => boolean; +} + +function formatSpan(text: string, tree: Ast.Chunk, options: FormattingOptions, span: Span): FormatResult { + if (errorBefore(tree, span.to)) return { ok: false, reason: 'syntax-error' }; + const { edits: all, lexed } = allEdits(text, tree, options, false, span.to); + const edits = all.filter( + (edit) => edit.start >= span.from && edit.start < span.to && edit.end <= span.to && (span.keep?.(edit) ?? true), + ); + return checked(text, tree, edits, lexed); +} + +/** + * On-type formatting after `character` was typed and the cursor is at `offset`. + * - A line break: formats the line it ended, and indents the new line when it has + * text after the cursor (a blank new line keeps the editor's indentation). + * - The last character of `end`, `else`, `elseif`, `until`, `)`, `]` or `}`: indents + * the line when that closer is its first token. Anything else: no edits. + */ +export function formatOnType(text: string, tree: Ast.Chunk, options: FormattingOptions, offset: number, character: string): FormatResult { + const starts = lineStarts(text); + const line = lineAt(starts, offset); + const lineStart = starts[line] ?? 0; + const lineEnd = starts[line + 1] ?? text.length; + if (character === ON_TYPE_FIRST_TRIGGER) { + if (line === 0) return { ok: true, edits: [] }; + const blank = text.slice(lineStart, lineEnd).trim() === ''; + return formatSpan(text, tree, options, { from: starts[line - 1] ?? 0, to: lineEnd, keep: (edit) => !(blank && edit.start >= lineStart) }); + } + if (!ON_TYPE_MORE_TRIGGERS.includes(character)) return { ok: true, edits: [] }; + const { tokens } = lex(text, tree.start, tree.end); + const index = tokens.findIndex((token) => token.end === offset && token.type !== 'string'); + const token = tokens[index]; + const before = tokens[index - 1]; + if (token === undefined || !CLOSERS.has(token.value) || !token.value.endsWith(character)) return { ok: true, edits: [] }; + // The closer must be the first token of its line, and no comment may come before it there. + const firstOnLine = (before === undefined || before.end <= lineStart) && text.slice(lineStart, token.start).trim() === ''; + if (!firstOnLine) return { ok: true, edits: [] }; + // Up to the end of the closer, which must not be an error itself (an `end` too many). + // A keyword or symbol has no edits inside, so only the indentation is kept. + return formatSpan(text, tree, options, { from: lineStart, to: token.end }); +} diff --git a/test/unit/server/formatting/format.test.ts b/test/unit/server/formatting/format.test.ts new file mode 100644 index 0000000..50f3670 --- /dev/null +++ b/test/unit/server/formatting/format.test.ts @@ -0,0 +1,385 @@ +import assert from 'node:assert/strict'; +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { + formatDocument, + formatOnType, + formatRange, + type FormatResult, + type FormattingOptions, + type OffsetEdit, +} from '../../../../src/server/formatting/format.ts'; +import { lex } from '../../../../src/server/syntax/lexer.ts'; +import { parseChunk } from '../../../../src/server/syntax/parser.ts'; +import { loadLua52, type Lua52Checker } from '../../../../src/server/validation/lua52.ts'; + +const SPACES: FormattingOptions = { tabSize: 2, insertSpaces: true }; + +function apply(text: string, edits: readonly OffsetEdit[]): string { + let result = ''; + let position = 0; + for (const edit of edits) { + assert.ok(edit.start >= position, 'edits are disjoint and in order'); + result += text.slice(position, edit.start) + edit.newText; + position = edit.end; + } + return result + text.slice(position); +} + +function edits(result: FormatResult): readonly OffsetEdit[] { + assert.ok(result.ok, `formatting was refused: ${result.ok ? '' : result.reason}`); + return result.edits; +} + +/** Formats a whole document given as lines joined with `\n`. */ +function format(lines: readonly string[], options: FormattingOptions = SPACES): string[] { + const text = lines.join('\n'); + return apply(text, edits(formatDocument(text, parseChunk(text), options))).split('\n'); +} + +/** Formats one line of code on its own. */ +const line = (code: string): string => format([code])[0] ?? ''; + +describe('server/formatting/format', () => { + describe('spacing within a line', () => { + it('puts one space around binary operators, `=` and `..`', () => { + assert.equal(line('x=a+b*c-d/e%f^g'), 'x = a + b * c - d / e % f ^ g'); + assert.equal(line('x=a==b and c~=d or e<=f'), 'x = a == b and c ~= d or e <= f'); + assert.equal(line('x=ad)==(e>=f)'), 'x = a < b == (c > d) == (e >= f)'); + assert.equal(line("s=a..'x'..1 .. 2"), "s = a .. 'x' .. 1 .. 2"); + }); + + it('puts no space after unary `-` and `#`, and one after `not`', () => { + assert.equal(line('x = - a + # t'), 'x = -a + #t'); + assert.equal(line('x = not a'), 'x = not a'); + assert.equal(line('x = -(a)'), 'x = -(a)'); + }); + + it('keeps a space between two minus signs, which would otherwise start a comment', () => { + assert.equal(line('x = - -a'), 'x = - -a'); + assert.equal(line('x = a- -b'), 'x = a - -b'); + assert.equal(line('x = -#t'), 'x = -#t'); + }); + + it('puts no space before `,` and `;`, and one after them', () => { + assert.equal(line('local a ,b,c = 1 ,2;'), 'local a, b, c = 1, 2;'); + assert.equal(line('t = {1;2 , 3}'), 't = { 1; 2, 3 }'); + }); + + it('puts no space inside parentheses and brackets', () => { + assert.equal(line('x = ( a + b ) * t[ 1 ]'), 'x = (a + b) * t[1]'); + assert.equal(line('f( )'), 'f()'); + }); + + it('keeps a space between a bracket and a long string, which would otherwise read as `[[`', () => { + assert.equal(line('x = t[ [[k]] ]'), 'x = t[ [[k]] ]'); + assert.equal(line('x = t[[=[k]=]]'), 'x = t[[=[k]=]]'); + }); + + it('puts one space inside braces, and none in `{}`', () => { + assert.equal(line('t = {a,b}'), 't = { a, b }'); + assert.equal(line('t = { }'), 't = {}'); + assert.equal(line('t = {[1]=2,x=3}'), 't = { [1] = 2, x = 3 }'); + }); + + it('puts no space around `.` and `:`', () => { + assert.equal(line('a . b : c ( )'), 'a.b:c()'); + assert.equal(line('function a . b : c ( ) end'), 'function a.b:c() end'); + }); + + it('puts no space before the parentheses of a call, a function or the bracket of an index', () => { + assert.equal(line('f (a) (b)'), 'f(a)(b)'); + assert.equal(line('x = function (a) end'), 'x = function(a) end'); + assert.equal(line('local function f (a) end'), 'local function f(a) end'); + assert.equal(line('x = t [1] [2]'), 'x = t[1][2]'); + assert.equal(line('x = f() [1]'), 'x = f()[1]'); + }); + + it('keeps string and table call arguments joined or apart, as written', () => { + assert.equal(line('f"x" g "y"'), 'f"x" g "y"'); + assert.equal(line('f{1} g {2}'), 'f{ 1 } g { 2 }'); + assert.equal(line('f[[x]] g [[y]]'), 'f[[x]] g [[y]]'); + }); + + it('puts one space around keywords', () => { + assert.equal(line('if(a)then return(b)end'), 'if (a) then return (b) end'); + assert.equal(line('for i=1,2 do end'), 'for i = 1, 2 do end'); + assert.equal(line('for k,v in pairs(t)do end'), 'for k, v in pairs(t) do end'); + }); + + it('writes labels without spaces inside, and spaces around them', () => { + assert.equal(line(':: top ::goto top'), '::top:: goto top'); + }); + + it('keeps the space written before a trailing comment, and puts one where none was', () => { + assert.equal(line('x = 1 -- aligned'), 'x = 1 -- aligned'); + assert.equal(line('x = 1-- joined'), 'x = 1 -- joined'); + assert.equal(line('x = --[[ a ]]1'), 'x = --[[ a ]] 1'); + }); + }); + + describe('indentation', () => { + it('indents the bodies of functions, loops, `do`, `if` clauses and `repeat`', () => { + assert.deepEqual( + format([ + 'function f(a)', + 'for i = 1, a do', + 'if i then', + 'x()', + 'elseif a then', + 'y()', + 'else', + 'z()', + 'end', + 'end', + 'while a do', + 'do', + 'b()', + 'end', + 'end', + 'repeat', + 'c()', + 'until a', + 'end', + ]), + [ + 'function f(a)', + ' for i = 1, a do', + ' if i then', + ' x()', + ' elseif a then', + ' y()', + ' else', + ' z()', + ' end', + ' end', + ' while a do', + ' do', + ' b()', + ' end', + ' end', + ' repeat', + ' c()', + ' until a', + 'end', + ], + ); + }); + + it('indents the contents of tables and multi-line call arguments', () => { + assert.deepEqual( + format(['local t = {', 'a = 1,', 'b = {', '2,', '},', '}', 'f(a,', 'b)']), + ['local t = {', ' a = 1,', ' b = {', ' 2,', ' },', '}', 'f(a,', ' b)'], + ); + }); + + it('indents once for several constructs opened on one line', () => { + assert.deepEqual( + format(['f(function()', 'x()', 'end)', 'g({', 'a = 1,', '}, {', 'b = 2,', '})']), + ['f(function()', ' x()', 'end)', 'g({', ' a = 1,', '}, {', ' b = 2,', '})'], + ); + }); + + it('indents a line that continues a statement once more', () => { + assert.deepEqual( + format(['local x = a +', 'b', 'if a and', 'b then', 'c()', 'end', 'obj', ':m()']), + ['local x = a +', ' b', 'if a and', ' b then', ' c()', 'end', 'obj', ' :m()'], + ); + }); + + it('indents `then` and `do` on their own line like their statement', () => { + assert.deepEqual( + format(['if a', 'then', 'b()', 'end', 'while a', 'do', 'b()', 'end']), + ['if a', 'then', ' b()', 'end', 'while a', 'do', ' b()', 'end'], + ); + }); + + it('indents comment lines like the code around them', () => { + assert.deepEqual(format(['do', '-- a', 'x()', ' -- b', 'end']), ['do', ' -- a', ' x()', ' -- b', 'end']); + }); + + it('indents with tabs, or with `tabSize` spaces per level', () => { + assert.deepEqual(format(['do', 'do', 'x()', 'end', 'end'], { tabSize: 4, insertSpaces: false }), ['do', '\tdo', '\t\tx()', '\tend', 'end']); + assert.deepEqual(format(['do', 'x()', 'end'], { tabSize: 4, insertSpaces: true }), ['do', ' x()', 'end']); + }); + + it('never changes the inside of long strings and long comments', () => { + const lines = ['do', 'x = [[', ' keep ', ']]', '--[==[', ' keep ', ']==]', 'end']; + assert.deepEqual(format(lines), ['do', ' x = [[', ' keep ', ']]', ' --[==[', ' keep ', ']==]', 'end']); + }); + }); + + describe('lines and white space', () => { + it('removes trailing white space and empties blank lines, keeping every line', () => { + assert.deepEqual(format(['x = 1 ', ' ', '\t', 'y = 2 -- c ']), ['x = 1', '', '', 'y = 2 -- c']); + }); + + it('keeps CRLF and CR line breaks as written', () => { + const text = 'do\r\nx = 1\ry = 2\r\nend\r\n'; + assert.equal(apply(text, edits(formatDocument(text, parseChunk(text), SPACES))), 'do\r\n x = 1\r y = 2\r\nend\r\n'); + }); + + it('adds a final line break only when `insertFinalNewline` is set, with the line breaks of the text', () => { + const run = (text: string, options: FormattingOptions): string => apply(text, edits(formatDocument(text, parseChunk(text), options))); + assert.equal(run('x = 1 ', SPACES), 'x = 1'); + assert.equal(run('x = 1 ', { ...SPACES, insertFinalNewline: true }), 'x = 1\n'); + assert.equal(run('do\r\nend', { ...SPACES, insertFinalNewline: true }), 'do\r\nend\r\n'); + assert.equal(run('x = 1\n', { ...SPACES, insertFinalNewline: true }), 'x = 1\n'); + }); + + it('removes the line breaks after the last one only when `trimFinalNewlines` is set', () => { + const run = (text: string, options: FormattingOptions): string => apply(text, edits(formatDocument(text, parseChunk(text), options))); + assert.equal(run('x = 1\n\n \n', SPACES), 'x = 1\n\n\n'); + assert.equal(run('x = 1\n\n \n', { ...SPACES, trimFinalNewlines: true }), 'x = 1\n'); + assert.equal(run('x = 1', { ...SPACES, trimFinalNewlines: true }), 'x = 1'); + }); + + it('returns no edits for text that is already formatted', () => { + const text = 'local t = { 1, 2 }\nfor i = 1, #t do\n print(t[i])\nend\n'; + assert.deepEqual(edits(formatDocument(text, parseChunk(text), SPACES)), []); + }); + + it('returns edits that touch only white space, one line at a time', () => { + const text = 'do\n x=1 \n\n \nend'; + for (const edit of edits(formatDocument(text, parseChunk(text), SPACES))) { + assert.match(text.slice(edit.start, edit.end), /^[ \t]*$/); + assert.doesNotMatch(edit.newText, /[\r\n]/); + } + }); + }); + + describe('syntax errors', () => { + it('refuses to format a document with any error', () => { + for (const text of ['x = ', 'x = "open', 'do', 'x = 1 end']) { + assert.deepEqual(formatDocument(text, parseChunk(text), SPACES), { ok: false, reason: 'syntax-error' }); + } + }); + }); + + describe('range formatting', () => { + const text = ['do', 'a=1', 'b=2', 'c=3', 'end'].join('\n'); + const lineOffset = (n: number): number => text.split('\n').slice(0, n).join('\n').length + (n > 0 ? 1 : 0); + + it('formats only the lines the range touches', () => { + const result = formatRange(text, parseChunk(text), SPACES, lineOffset(2) + 1, lineOffset(2) + 2); + assert.equal(apply(text, edits(result)), ['do', 'a=1', ' b = 2', 'c=3', 'end'].join('\n')); + }); + + it('does not include a line where the range ends at its first character', () => { + const result = formatRange(text, parseChunk(text), SPACES, lineOffset(1), lineOffset(3)); + assert.equal(apply(text, edits(result)), ['do', ' a = 1', ' b = 2', 'c=3', 'end'].join('\n')); + }); + + it('allows errors after the range, and refuses errors before its end', () => { + const open = 'function f()\nx=1\ny=2'; + const firstLines = formatRange(open, parseChunk(open), SPACES, 0, 'function f()\nx'.length); + assert.equal(apply(open, edits(firstLines)), 'function f()\n x = 1\ny=2'); + // The `if` statement is abandoned at its `elseif`: its lines are still formatted with their own rules. + const abandoned = 'if a then\nx=-a f{1} ::l:: goto l\nelseif'; + const inside = formatRange(abandoned, parseChunk(abandoned), SPACES, 'if a then\n'.length, 'if a then\nx'.length); + assert.equal(apply(abandoned, edits(inside)), 'if a then\n x = -a f{ 1 } ::l:: goto l\nelseif'); + const broken = 'x = = 1\ny=2'; + assert.deepEqual(formatRange(broken, parseChunk(broken), SPACES, broken.length - 1, broken.length), { ok: false, reason: 'syntax-error' }); + }); + }); + + describe('on-type formatting', () => { + it('formats the line a line break ended, keeping the indentation of a blank new line', () => { + const text = 'function f()\nx=1\n '; + const result = formatOnType(text, parseChunk(text), SPACES, text.length, '\n'); + assert.equal(apply(text, edits(result)), 'function f()\n x = 1\n '); + }); + + it('indents a new line that has text after the cursor', () => { + const inner = 'do\nx()\nend'; + const typed = formatOnType(inner, parseChunk(inner), SPACES, 'do\n'.length, '\n'); + assert.equal(apply(inner, edits(typed)), 'do\n x()\nend'); + }); + + it('re-indents a line when its first token, a closer, was just completed', () => { + for (const [text, character] of [ + ['do\n x()\n end', 'd'], + ['if a then\n x()\n else', 'e'], + ['if a then\n x()\n elseif', 'f'], + ['repeat\n x()\n until', 'l'], + ['f(\n a\n )', ')'], + ['t = {\n a\n }', '}'], + ['t[\n a\n ]', ']'], + ] as const) { + const result = formatOnType(text, parseChunk(text), SPACES, text.length, character); + const lines = apply(text, edits(result)).split('\n'); + assert.equal(lines.at(-1), lines.at(-1)?.trimStart(), `${JSON.stringify(text)} after ${character}`); + } + }); + + it('does nothing for other characters, closers after other tokens, and partial keywords', () => { + const cases: [string, string][] = [ + ['do\n x()\n en', 'n'], + ['do\n x() end', 'd'], + ['do\n x()\n send', 'd'], + [' x = "end"', 'd'], + ]; + for (const [text, character] of cases) { + assert.deepEqual(formatOnType(text, parseChunk(text), SPACES, text.length, character), { ok: true, edits: [] }, text); + } + }); + + it('refuses when the closer itself is an error', () => { + const text = 'x()\n end'; + assert.deepEqual(formatOnType(text, parseChunk(text), SPACES, text.length, 'd'), { ok: false, reason: 'syntax-error' }); + }); + }); + + describe('properties', () => { + let lua: Lua52Checker; + before(async () => { + lua = await loadLua52(); + }); + + const fixtures = join(import.meta.dirname, '../../../fixtures/workspace'); + const SAMPLES: string[] = [ + ...readdirSync(fixtures) + .filter((name) => name.endsWith('.lua')) + .map((name) => readFileSync(join(fixtures, name), 'utf8')), + `local t = { 1, 2; name = "n", [k .. "x"] = function(a, ...) return select('#', ...) end } +for i = #t, 1, -1 do + if t[i] == nil then break elseif i % 2 == 0 then t[i] = i ^ 2 else t[i] = -i end +end`, + `function M.obj:method(a, b) +local s = self.items[a] or {} + while not s.done and b > 0 do s, b = s.next, b - 1 end +repeat local n = s:step() until n >= 10 + return s, (a .. b) ~= "x" +end`, + 'x=- - -1 local y=a- -b z=#t--c\n::l:: goto l', + "s = 'a\\z\n b' .. [==[\n ]] ]==] --[[ x\n ]] .. \"q\"", + 'f{a={b={c}}}(function() return function() end end)()', + 'local a =\n1\nlocal b = {\n[1] =\n2,\n}\nreturn a,\nb', + ]; + + it('never changes tokens or comments, and is idempotent', () => { + for (const text of SAMPLES) { + const tree = parseChunk(text); + if (tree.errors.length > 0) continue; + const once = apply(text, edits(formatDocument(text, tree, SPACES))); + const strip = (s: string): string[] => { + const { tokens, comments } = lex(s); + return [...tokens.map((t) => `${t.type}:${t.value}`), ...comments.map((c) => s.slice(c.start, c.end).trimEnd())]; + }; + assert.deepEqual(strip(once), strip(text)); + assert.deepEqual(edits(formatDocument(once, parseChunk(once), SPACES)), [], `not idempotent:\n${once}`); + } + }); + + it('formats code the official Lua 5.2 compiler accepts into code it accepts', () => { + let checked = 0; + for (const text of SAMPLES) { + if (lua.check(text) !== undefined) continue; + const once = apply(text, edits(formatDocument(text, parseChunk(text), SPACES))); + assert.equal(lua.check(once), undefined, once); + checked++; + } + assert.ok(checked >= 6, `only ${checked} samples compiled`); + }); + }); +}); From 55760fc4e77b030c9c872d38be3642bd70de260a Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:55:41 +0100 Subject: [PATCH 3/5] fix(server): refuse invalid tab sizes and skip lexing for on-type keys in names Two findings of the project review of the formatter: - `insertSpaces` with a `tabSize` that is not an integer from 1 to 100 is now refused (`invalid-options`) instead of floored and clamped to 0. The bounds are those of VS Code's `editor.tabSize` setting (`minimum: 1, maximum: 100` in its settings schema, checked in the 1.145.0 build); LSP only says `uinteger`, and an absurd value made `' '.repeat()` allocate a huge string. - On-type requests for `d`, `e`, `f`, `l`, `)`, `]`, `}` arrive for every such key typed inside a name (`field`, `self`). The line up to the cursor must now be exactly a closer before the document is lexed: 0.15 ms instead of a full lex for a 78 KB file. Also pins call-argument chains (`f"a""b"`, `f{}{}`, `t[1]"x"`) in tests. Co-Authored-By: Claude Opus 5.5 --- src/server/formatting/format.ts | 26 +++++++++++++++++++--- test/unit/server/formatting/format.test.ts | 16 +++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/server/formatting/format.ts b/src/server/formatting/format.ts index eab22b8..434c52b 100644 --- a/src/server/formatting/format.ts +++ b/src/server/formatting/format.ts @@ -52,9 +52,21 @@ export type FormatResult = /** * `syntax-error`: the chunk has a lexical or syntax error where the formatted lines * depend on it. `unsafe`: the result would not have lexed to the same tokens (a - * bug in the rules; nothing is changed). + * bug in the rules; nothing is changed). `invalid-options`: `insertSpaces` with a + * `tabSize` that is not an integer from `MIN_TAB_SIZE` to `MAX_TAB_SIZE`. */ - | { readonly ok: false; readonly reason: 'syntax-error' | 'unsafe' }; + | { readonly ok: false; readonly reason: 'syntax-error' | 'unsafe' | 'invalid-options' }; + +/** + * The `tabSize` values accepted with `insertSpaces`: the bounds of VS Code's + * `editor.tabSize` setting (`minimum: 1, maximum: 100` in its settings schema). LSP + * only says `uinteger`; anything outside is refused rather than replaced by a guess. + */ +export const MIN_TAB_SIZE = 1; +export const MAX_TAB_SIZE = 100; + +const validOptions = (options: FormattingOptions): boolean => + !options.insertSpaces || (Number.isInteger(options.tabSize) && options.tabSize >= MIN_TAB_SIZE && options.tabSize <= MAX_TAB_SIZE); /** Characters after which clients ask for on-type formatting. */ export const ON_TYPE_FIRST_TRIGGER = '\n'; @@ -258,7 +270,8 @@ function allEdits(text: string, tree: Ast.Chunk, options: FormattingOptions, fin ...comments.map((comment) => ({ start: comment.start, end: comment.end, token: undefined, comment })), ].sort((a, b) => a.start - b.start); const facts = tokenFacts(tokens, tree); - const unit = options.insertSpaces ? ' '.repeat(Number.isFinite(options.tabSize) ? Math.max(0, Math.floor(options.tabSize)) : 0) : '\t'; + // `validOptions` was checked by the caller. + const unit = options.insertSpaces ? ' '.repeat(options.tabSize) : '\t'; const edits: OffsetEdit[] = []; const replace = (start: number, end: number, newText: string): void => { if (text.slice(start, end) !== newText) edits.push({ start, end, newText }); @@ -417,6 +430,7 @@ const errorBefore = (tree: Ast.Chunk, offset: number): boolean => tree.errors.so /** Formats a whole chunk. Refused when it has any lexical or syntax error. */ export function formatDocument(text: string, tree: Ast.Chunk, options: FormattingOptions): FormatResult { + if (!validOptions(options)) return { ok: false, reason: 'invalid-options' }; if (tree.errors.length > 0) return { ok: false, reason: 'syntax-error' }; const { edits, lexed } = allEdits(text, tree, options, true); return checked(text, tree, edits, lexed); @@ -446,6 +460,7 @@ interface Span { } function formatSpan(text: string, tree: Ast.Chunk, options: FormattingOptions, span: Span): FormatResult { + if (!validOptions(options)) return { ok: false, reason: 'invalid-options' }; if (errorBefore(tree, span.to)) return { ok: false, reason: 'syntax-error' }; const { edits: all, lexed } = allEdits(text, tree, options, false, span.to); const edits = all.filter( @@ -472,6 +487,11 @@ export function formatOnType(text: string, tree: Ast.Chunk, options: FormattingO return formatSpan(text, tree, options, { from: starts[line - 1] ?? 0, to: lineEnd, keep: (edit) => !(blank && edit.start >= lineStart) }); } if (!ON_TYPE_MORE_TRIGGERS.includes(character)) return { ok: true, edits: [] }; + // Cheap test first: these characters are typed inside any word (`field`, `self`), and lexing + // the document for each of them would cost a full pass. The lexer then confirms the closer + // is a token, not part of a string, a comment or a longer name. + const typed = text.slice(lineStart, offset).trim(); + if (!CLOSERS.has(typed) || !typed.endsWith(character)) return { ok: true, edits: [] }; const { tokens } = lex(text, tree.start, tree.end); const index = tokens.findIndex((token) => token.end === offset && token.type !== 'string'); const token = tokens[index]; diff --git a/test/unit/server/formatting/format.test.ts b/test/unit/server/formatting/format.test.ts index 50f3670..ec7ee6e 100644 --- a/test/unit/server/formatting/format.test.ts +++ b/test/unit/server/formatting/format.test.ts @@ -99,6 +99,10 @@ describe('server/formatting/format', () => { assert.equal(line('f"x" g "y"'), 'f"x" g "y"'); assert.equal(line('f{1} g {2}'), 'f{ 1 } g { 2 }'); assert.equal(line('f[[x]] g [[y]]'), 'f[[x]] g [[y]]'); + // Chains: an argument after another argument, or after an index. + assert.equal(line('f"a""b" "c"'), 'f"a""b" "c"'); + assert.equal(line('f{}{} {}'), 'f{}{} {}'); + assert.equal(line('t[1]"x" t[1] "y"'), 't[1]"x" t[1] "y"'); }); it('puts one space around keywords', () => { @@ -248,6 +252,18 @@ describe('server/formatting/format', () => { }); }); + describe('options', () => { + it('refuses a tabSize outside VS Code\'s bounds (1 to 100) or not an integer, with insertSpaces only', () => { + const text = 'do\nx()\nend'; + for (const tabSize of [0, 101, 2.5, Number.NaN, -1]) { + assert.deepEqual(formatDocument(text, parseChunk(text), { tabSize, insertSpaces: true }), { ok: false, reason: 'invalid-options' }, String(tabSize)); + assert.deepEqual(formatRange(text, parseChunk(text), { tabSize, insertSpaces: true }, 0, 1), { ok: false, reason: 'invalid-options' }, String(tabSize)); + } + assert.equal(apply(text, edits(formatDocument(text, parseChunk(text), { tabSize: 0, insertSpaces: false }))), 'do\n\tx()\nend'); + assert.equal(apply(text, edits(formatDocument(text, parseChunk(text), { tabSize: 100, insertSpaces: true }))).split('\n')[1]?.length, 103); + }); + }); + describe('syntax errors', () => { it('refuses to format a document with any error', () => { for (const text of ['x = ', 'x = "open', 'do', 'x = 1 end']) { From 667ab36087c446478bc4b227867984a6b35777ae Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:55:43 +0100 Subject: [PATCH 4/5] feat(server): add document, range and on-type formatting for Lua files Serves `textDocument/formatting`, `/rangeFormatting` and `/onTypeFormatting` with the edits of `formatting/format.ts`, converted to LSP ranges. - Lua only. When the client supports dynamic registration of a request, it is registered after `initialized` with a selector for language `lua` and for `**/*.[lL][uU][aA]` (other editors' language IDs), for the `file` and `untitled` schemes, so VS Code keeps reporting that `.menu` files have no formatter. Otherwise the capability is static, and the handler answers `null` for `.menu` documents. - On-type triggers: `\n`, then `d e f l ) ] }` (the last characters of `end`, `else`, `elseif`, `until` and the closing brackets). - Options: `tabSize`, `insertSpaces`, `insertFinalNewline`, `trimFinalNewlines`. No new settings. - Refusals answer `null` and are logged: syntax errors at info level for explicit requests and at debug level for on-type ones (sent on every key while code is incomplete); invalid options and unsafe results as errors. - Cancellation is checked before the synchronous work; nothing throws. Tests: unit tests for the conversion, the `.menu` refusal, the logging levels, the static/dynamic split and the selector; integration tests for the three requests on the new original fixture `format.lua`, and for no formatter on a `.menu` file. Both changelogs have entries under [Unreleased]. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 26 +++ docs/CHANGELOG.vsix.md | 5 + src/server/features/formatting.ts | 180 +++++++++++++++++++ src/server/server.ts | 7 + test/fixtures/workspace/format.lua | 11 ++ test/integration/formatting.test.ts | 82 +++++++++ test/unit/server/features/formatting.test.ts | 95 ++++++++++ 7 files changed, 406 insertions(+) create mode 100644 src/server/features/formatting.ts create mode 100644 test/fixtures/workspace/format.lua create mode 100644 test/integration/formatting.test.ts create mode 100644 test/unit/server/features/formatting.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1180641..eea2fc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -130,6 +130,32 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). - Fields are `property`, or `method` after `:`; library and EEex-Docs members (`string.format`, `C:AddGold`) as documented. Assignment targets have `modification`, declared names `declaration`, labels are `label`. +- Formatting of `.lua` files (`textDocument/formatting`, `/rangeFormatting` and + `/onTypeFormatting`), layout-preserving: only the white space between tokens and comments + changes. `.menu` files are not formatted (no formatter is offered for them). + - Line breaks are kept exactly as written; strings, long strings and long comments are never + touched. Trailing white space is removed (also after a `--` comment) and blank lines are + emptied. + - Indentation by the constructs open at the start of each line (`function`, `do`, `then`, + `else`, `repeat`, `(`, `[`, `{`), counted once per line that opens them (`f(function()` indents + its body once); a line that starts with `end`, `until`, `else`, `elseif`, `)`, `]` or `}` is + indented like the line that opened the construct; a line that continues a statement gets one + more level. One level is a tab, or `tabSize` spaces with `insertSpaces`; a `tabSize` that is + not an integer from 1 to 100 (the bounds of VS Code's `editor.tabSize`) is refused and logged. + - Spacing within a line: one space around binary operators, `=` and keywords and after `,`/`;`; + none inside `()`/`[]`, around `.`/`:`, after unary `-`/`#` or before the parentheses of a call + or function; `{ a }` and `{}`; string and table call arguments (`f"x"`, `f{…}`) stay joined or + apart as written; the space before a trailing comment is kept. + - `insertFinalNewline` and `trimFinalNewlines` are honored for document formatting when the + client sends `true`. No new settings. + - A file with a syntax error is not formatted (the reason is logged); range and on-type + formatting only refuse errors before the end of the lines they change. + - On-type: after a line break the finished line is formatted (a blank new line keeps the + editor's indentation); after the last character of `end`, `else`, `elseif`, `until`, `)`, + `]` or `}` that starts a line, the line is re-indented. VS Code needs `editor.formatOnType`. + - Every result is lexed again and must have the same tokens and comments, or nothing changes. + - Registered dynamically for Lua documents only (language `lua`, or `*.lua` in any letter case) + when the client supports it, so `.menu` files have no formatter; static otherwise. - 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/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 75bd715..da199ec 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -47,6 +47,11 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea VS Code's default theme, parameters, local and global variables, functions, table fields and the functions the game provides can be colored differently, in Lua files and the Lua of `.menu` files. Themes can style globals with the `global` modifier. +- **Format Document and Format Selection** for Lua files. Fixes indentation and spacing without + moving your line breaks, and never changes strings or the text of comments. It uses your + editor's tab and indentation settings, and with *Editor: Format On Type* it re-indents `end`, + `else` and closing brackets as you type them. Files with syntax errors are left as they are; + `.menu` files are not formatted yet. - **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/src/server/features/formatting.ts b/src/server/features/formatting.ts new file mode 100644 index 0000000..1646219 --- /dev/null +++ b/src/server/features/formatting.ts @@ -0,0 +1,180 @@ +import type { + Connection, + DocumentSelector, + FormattingOptions as LspFormattingOptions, + ServerCapabilities, + TextDocumentClientCapabilities, + TextDocuments, + TextEdit, +} from 'vscode-languageserver/node'; +import { DocumentFormattingRequest, DocumentOnTypeFormattingRequest, DocumentRangeFormattingRequest } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import { DOCUMENT_SCHEMES } from '../../shared/protocol.ts'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { + formatDocument, + formatOnType, + formatRange, + ON_TYPE_FIRST_TRIGGER, + ON_TYPE_MORE_TRIGGERS, + MAX_TAB_SIZE, + MIN_TAB_SIZE, + type FormatResult, + type FormattingOptions, +} from '../formatting/format.ts'; +import type * as Ast from '../syntax/ast.ts'; + +export interface FormattingDeps { + readonly cache: ParsedDocumentCache; +} + +/** + * The documents formatting is offered for: Lua files, by language ID (VS Code) or by + * extension in any letter case (editors with other language IDs). Not .menu files, + * which are not formatted yet, so VS Code keeps reporting that they have no formatter. + */ +export const LUA_SELECTOR: DocumentSelector = DOCUMENT_SCHEMES.flatMap((scheme) => [ + { language: 'lua', scheme }, + { scheme, pattern: '**/*.[lL][uU][aA]' }, +]); + +const ON_TYPE_OPTIONS = { firstTriggerCharacter: ON_TYPE_FIRST_TRIGGER, moreTriggerCharacter: [...ON_TYPE_MORE_TRIGGERS] }; + +/** Which formatting requests the client registers dynamically (with `LUA_SELECTOR`); the others are advertised statically. */ +export interface FormattingRegistration { + readonly document: boolean; + readonly range: boolean; + readonly onType: boolean; +} + +export function dynamicRegistration(capabilities: TextDocumentClientCapabilities | undefined): FormattingRegistration { + return { + document: capabilities?.formatting?.dynamicRegistration === true, + range: capabilities?.rangeFormatting?.dynamicRegistration === true, + onType: capabilities?.onTypeFormatting?.dynamicRegistration === true, + }; +} + +/** + * Server capabilities for the requests the client does not register dynamically. + * A static capability cannot carry a document selector, so these handlers answer + * `null` for .menu documents. + */ +export function staticCapabilities(dynamic: FormattingRegistration): Pick< + ServerCapabilities, + 'documentFormattingProvider' | 'documentRangeFormattingProvider' | 'documentOnTypeFormattingProvider' +> { + return { + ...(dynamic.document ? {} : { documentFormattingProvider: true }), + ...(dynamic.range ? {} : { documentRangeFormattingProvider: true }), + ...(dynamic.onType ? {} : { documentOnTypeFormattingProvider: ON_TYPE_OPTIONS }), + }; +} + +/** Registers the dynamically registered requests; call after `initialized`. */ +export function registerDynamically(connection: Connection, dynamic: FormattingRegistration): void { + const failed = (request: string) => (error: unknown) => { + connection.console.warn(`Could not register ${request}; it is unavailable: ${String(error)}`); + }; + if (dynamic.document) { + connection.client.register(DocumentFormattingRequest.type, { documentSelector: LUA_SELECTOR }).catch(failed('document formatting')); + } + if (dynamic.range) { + connection.client.register(DocumentRangeFormattingRequest.type, { documentSelector: LUA_SELECTOR }).catch(failed('range formatting')); + } + if (dynamic.onType) { + connection.client + .register(DocumentOnTypeFormattingRequest.type, { documentSelector: LUA_SELECTOR, ...ON_TYPE_OPTIONS }) + .catch(failed('on-type formatting')); + } +} + +/** The LSP options the formatter honors; the others (`trimTrailingWhitespace`, …) do not change its result. */ +export function formatterOptions(options: LspFormattingOptions): FormattingOptions { + return { + tabSize: options.tabSize, + insertSpaces: options.insertSpaces, + insertFinalNewline: options.insertFinalNewline, + trimFinalNewlines: options.trimFinalNewlines, + }; +} + +/** + * What the server logs about a request it did not answer with edits. Refusals of + * explicit requests are `info`; refusals of on-type requests, sent at every key the + * user types while the code is incomplete, are `debug`. + */ +export type FormattingLog = (level: 'debug' | 'info' | 'error', message: string) => void; + +/** + * Runs `format` on the Lua chunk of `document` and converts its result to LSP edits. + * `null` for .menu documents, refused requests and failures, which are logged. + */ +export function formattingEdits( + document: TextDocument, + cache: ParsedDocumentCache, + format: (text: string, tree: Ast.Chunk) => FormatResult, + log: FormattingLog, + refusalLevel: 'debug' | 'info' = 'info', +): TextEdit[] | null { + const parsed = cache.get(document); + const chunk = parsed.chunks[0]; + if (parsed.kind !== 'lua' || chunk === undefined) return null; + const result = format(document.getText(), chunk.tree); + if (!result.ok) { + if (result.reason === 'syntax-error') { + log(refusalLevel, `Not formatting ${document.uri}: it has a syntax error before the end of the formatted lines.`); + } else if (result.reason === 'invalid-options') { + log('error', `Not formatting ${document.uri}: with insertSpaces, tabSize must be an integer from ${MIN_TAB_SIZE} to ${MAX_TAB_SIZE}.`); + } else { + log('error', `Not formatting ${document.uri}: the result would not lex to the same tokens. Please report this with the file.`); + } + return null; + } + return result.edits.map((edit) => ({ + range: { start: document.positionAt(edit.start), end: document.positionAt(edit.end) }, + newText: edit.newText, + })); +} + +/** `textDocument/formatting`, `/rangeFormatting` and `/onTypeFormatting` (see src/server/formatting/format.ts). */ +export function register(connection: Connection, documents: TextDocuments, deps: FormattingDeps): void { + const log: FormattingLog = (level, message) => { + if (level === 'debug') connection.console.debug(message); + else if (level === 'info') connection.console.info(message); + else connection.console.error(message); + }; + /** Shared by the three handlers: synchronous after the lookup, so a cancellation can only arrive after the response. */ + const answer = ( + uri: string, + cancelled: boolean, + format: (document: TextDocument, text: string, tree: Ast.Chunk) => FormatResult, + refusalLevel: 'debug' | 'info' = 'info', + ): TextEdit[] | null => { + try { + const document = documents.get(uri); + if (!document || cancelled) return null; + return formattingEdits(document, deps.cache, (text, tree) => format(document, text, tree), log, refusalLevel); + } catch (error) { + connection.console.error(`Formatting ${uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }; + + connection.onDocumentFormatting(({ textDocument, options }, token) => + answer(textDocument.uri, token.isCancellationRequested, (_document, text, tree) => formatDocument(text, tree, formatterOptions(options))), + ); + connection.onDocumentRangeFormatting(({ textDocument, range, options }, token) => + answer(textDocument.uri, token.isCancellationRequested, (document, text, tree) => + formatRange(text, tree, formatterOptions(options), document.offsetAt(range.start), document.offsetAt(range.end)), + ), + ); + connection.onDocumentOnTypeFormatting(({ textDocument, position, ch, options }, token) => + answer( + textDocument.uri, + token.isCancellationRequested, + (document, text, tree) => formatOnType(text, tree, formatterOptions(options), document.offsetAt(position), ch), + 'debug', + ), + ); +} diff --git a/src/server/server.ts b/src/server/server.ts index fdb30fa..d7cd6c6 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -20,6 +20,7 @@ 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 formatting from './features/formatting.ts'; import * as hover from './features/hover.ts'; import { markupFormat } from './features/markup.ts'; import * as references from './features/references.ts'; @@ -48,6 +49,8 @@ lua.catch((error: unknown) => { let configurationPull = false; let watchedFilesRegistration = false; let workspaceFolderChanges = false; +/** Formatting requests registered in `initialized`, for .lua documents only. */ +let formattingRegistration: formatting.FormattingRegistration = { document: false, range: false, onType: false }; /** Workspace folder URIs, kept up to date from `workspace/didChangeWorkspaceFolders`. */ let folders: string[] = []; @@ -105,6 +108,8 @@ connection.onInitialize((params) => { rename.register(connection, documents, { cache: parsed, documentChanges: workspace?.workspaceEdit?.documentChanges === true }); workspaceSymbols.register(connection, documents, { cache: parsed, index }); semanticTokens.register(connection, documents, { cache: parsed }); + formatting.register(connection, documents, { cache: parsed }); + formattingRegistration = formatting.dynamicRegistration(params.capabilities.textDocument); hover.register(connection, documents, { cache: parsed, format: markupFormat(params.capabilities.textDocument?.hover?.contentFormat), @@ -141,6 +146,7 @@ connection.onInitialize((params) => { hoverProvider: true, completionProvider: { triggerCharacters: [...completion.TRIGGER_CHARACTERS], resolveProvider: true }, semanticTokensProvider: { legend: semanticTokens.LEGEND, full: { delta: true }, range: true }, + ...formatting.staticCapabilities(formattingRegistration), ...(workspaceFolderChanges ? { workspace: { workspaceFolders: { supported: true, changeNotifications: true } } } : {}), }, serverInfo: { name: 'IE Lua Language Server' }, @@ -166,6 +172,7 @@ connection.onInitialized(() => { connection.console.warn(`Could not register file watchers; files changed outside the editor are indexed again only on restart: ${String(error)}`); }); } + formatting.registerDynamically(connection, formattingRegistration); if (workspaceFolderChanges) { connection.workspace.onDidChangeWorkspaceFolders(({ added, removed }) => { const gone = new Set(removed.map((folder) => folder.uri)); diff --git a/test/fixtures/workspace/format.lua b/test/fixtures/workspace/format.lua new file mode 100644 index 0000000..6dca128 --- /dev/null +++ b/test/fixtures/workspace/format.lua @@ -0,0 +1,11 @@ +-- Original fixture: formatting. Deliberately unformatted. +local function fmtScale(value,factor) +local result=value*factor + if result>10 then +return - result + else +return result +end +end + +FmtTable={1,2 ;name="n",[ "k" ]=fmtScale(2,3)} diff --git a/test/integration/formatting.test.ts b/test/integration/formatting.test.ts new file mode 100644 index 0000000..566f2ce --- /dev/null +++ b/test/integration/formatting.test.ts @@ -0,0 +1,82 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, openFixture } from './helpers.ts'; + +const OPTIONS: vscode.FormattingOptions = { tabSize: 2, insertSpaces: true }; + +/** The document text with `edits` applied, without changing the document. */ +function applied(document: vscode.TextDocument, edits: readonly vscode.TextEdit[]): string { + const sorted = [...edits].sort((a, b) => document.offsetAt(b.range.start) - document.offsetAt(a.range.start)); + let text = document.getText(); + for (const edit of sorted) { + text = text.slice(0, document.offsetAt(edit.range.start)) + edit.newText + text.slice(document.offsetAt(edit.range.end)); + } + return text; +} + +async function open(file: string): Promise { + return vscode.workspace.openTextDocument(await openFixture(file)); +} + +suite('Formatting', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('formats a Lua document, keeping its lines and comments', async () => { + const document = await open('format.lua'); + const edits = await vscode.commands.executeCommand('vscode.executeFormatDocumentProvider', document.uri, OPTIONS); + assert.ok(edits && edits.length > 0, 'no formatting provider answered'); + assert.equal( + applied(document, edits), + [ + '-- Original fixture: formatting. Deliberately unformatted.', + 'local function fmtScale(value, factor)', + ' local result = value * factor', + ' if result > 10 then', + ' return -result', + ' else', + ' return result', + ' end', + 'end', + '', + 'FmtTable = { 1, 2; name = "n", ["k"] = fmtScale(2, 3) }', + '', + ].join('\n'), + ); + }); + + test('formats only the lines of a range', async () => { + const document = await open('format.lua'); + const range = new vscode.Range(3, 0, 3, 5); + const edits = await vscode.commands.executeCommand('vscode.executeFormatRangeProvider', document.uri, range, OPTIONS); + assert.ok(edits && edits.length > 0, 'no range formatting provider answered'); + assert.deepEqual(new Set(edits.map((edit) => edit.range.start.line)), new Set([3])); + assert.equal(applied(document, edits).split('\n')[3], ' if result > 10 then'); + }); + + test('re-indents a line whose first token, a closer, was just typed', async () => { + const document = await open('format.lua'); + // Line 5 is ` else`: as if its last character had just been typed. + const edits = await vscode.commands.executeCommand( + 'vscode.executeFormatOnTypeProvider', + document.uri, + new vscode.Position(5, 8), + 'e', + OPTIONS, + ); + assert.ok(edits, 'no on-type formatting provider answered'); + assert.equal(edits.length, 1); + assert.equal(applied(document, edits).split('\n')[5], ' else'); + }); + + test('offers no formatter for .menu files', async () => { + const document = await open('OUTLINE.MENU'); + const edits = await vscode.commands.executeCommand('vscode.executeFormatDocumentProvider', document.uri, OPTIONS); + assert.ok(edits === undefined || edits.length === 0, `unexpected edits: ${JSON.stringify(edits)}`); + }); +}); diff --git a/test/unit/server/features/formatting.test.ts b/test/unit/server/features/formatting.test.ts new file mode 100644 index 0000000..a95d58a --- /dev/null +++ b/test/unit/server/features/formatting.test.ts @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict'; +import { TextDocument } from 'vscode-languageserver-textdocument'; +import { ParsedDocumentCache } from '../../../../src/server/documentCache.ts'; +import { + dynamicRegistration, + formatterOptions, + formattingEdits, + LUA_SELECTOR, + staticCapabilities, + type FormattingLog, +} from '../../../../src/server/features/formatting.ts'; +import { formatDocument } from '../../../../src/server/formatting/format.ts'; + +const OPTIONS = { tabSize: 2, insertSpaces: true }; + +function run(uri: string, languageId: string, text: string, refusalLevel?: 'debug' | 'info'): { edits: ReturnType; logged: string[] } { + const logged: string[] = []; + const log: FormattingLog = (level, message) => logged.push(`${level}: ${message}`); + const document = TextDocument.create(uri, languageId, 1, text); + const edits = formattingEdits(document, new ParsedDocumentCache(), (source, tree) => formatDocument(source, tree, OPTIONS), log, refusalLevel); + return { edits, logged }; +} + +describe('server/features/formatting', () => { + it('converts offset edits to LSP ranges', () => { + const { edits } = run('file:///a.lua', 'lua', 'do\nx=1\nend'); + assert.deepEqual(edits, [ + { range: { start: { line: 1, character: 0 }, end: { line: 1, character: 0 } }, newText: ' ' }, + { range: { start: { line: 1, character: 1 }, end: { line: 1, character: 1 } }, newText: ' ' }, + { range: { start: { line: 1, character: 2 }, end: { line: 1, character: 2 } }, newText: ' ' }, + ]); + }); + + it('does not format .menu documents, by language ID or by extension', () => { + assert.equal(run('file:///UI.MENU', 'ie-menu', '`x=1`').edits, null); + assert.equal(run('file:///UI.MENU', 'plaintext', '`x=1`').edits, null); + }); + + it('answers null and logs why for syntax errors', () => { + const { edits, logged } = run('file:///a.lua', 'lua', 'x = '); + assert.equal(edits, null); + assert.deepEqual(logged, ['info: Not formatting file:///a.lua: it has a syntax error before the end of the formatted lines.']); + }); + + it('logs an invalid tabSize as an error, whatever the request', () => { + const logged: string[] = []; + const document = TextDocument.create('file:///a.lua', 'lua', 1, 'x = 1'); + const edits = formattingEdits( + document, + new ParsedDocumentCache(), + (source, tree) => formatDocument(source, tree, { tabSize: 0, insertSpaces: true }), + (level, message) => logged.push(`${level}: ${message}`), + 'debug', + ); + assert.equal(edits, null); + assert.deepEqual(logged, ['error: Not formatting file:///a.lua: with insertSpaces, tabSize must be an integer from 1 to 100.']); + }); + + it('logs refusals at the level asked for, so that on-type requests stay quiet', () => { + const { logged } = run('file:///a.lua', 'lua', 'x = ', 'debug'); + assert.deepEqual(logged, ['debug: Not formatting file:///a.lua: it has a syntax error before the end of the formatted lines.']); + }); + + it('passes on only the options the formatter honors', () => { + assert.deepEqual(formatterOptions({ tabSize: 4, insertSpaces: false, trimTrailingWhitespace: true, insertFinalNewline: true, custom: 'x' }), { + tabSize: 4, + insertSpaces: false, + insertFinalNewline: true, + trimFinalNewlines: undefined, + }); + }); + + it('advertises statically only what the client does not register dynamically', () => { + assert.deepEqual(staticCapabilities(dynamicRegistration(undefined)), { + documentFormattingProvider: true, + documentRangeFormattingProvider: true, + documentOnTypeFormattingProvider: { firstTriggerCharacter: '\n', moreTriggerCharacter: ['d', 'e', 'f', 'l', ')', ']', '}'] }, + }); + const dynamic = dynamicRegistration({ + formatting: { dynamicRegistration: true }, + rangeFormatting: { dynamicRegistration: true }, + onTypeFormatting: { dynamicRegistration: false }, + }); + assert.deepEqual(Object.keys(staticCapabilities(dynamic)), ['documentOnTypeFormattingProvider']); + }); + + it('selects Lua documents by language ID and by extension in any letter case, for the served schemes', () => { + assert.deepEqual(LUA_SELECTOR, [ + { language: 'lua', scheme: 'file' }, + { scheme: 'file', pattern: '**/*.[lL][uU][aA]' }, + { language: 'lua', scheme: 'untitled' }, + { scheme: 'untitled', pattern: '**/*.[lL][uU][aA]' }, + ]); + }); +}); From 96b4d787cfce773b4666a0e149e99a31bb573e65 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:55:43 +0100 Subject: [PATCH 5/5] docs: document formatting README (feature list and status note), the editors guide (feature table and what formatting does over LSP), CONTRIBUTING (layout) and CLAUDE.md (purpose and layout). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 ++- CONTRIBUTING.md | 1 + README.md | 12 +++++++++--- docs/editors/README.md | 15 ++++++++++++++- 4 files changed, 26 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9fe4a0c..a19961c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ |---|---| | Name | `IE Lua Language Server` | | Publisher | `infinity-engine-tools` | -| Purpose | Lua 5.2 language support (diagnostics, hover, completion, semantic tokens, 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, semantic tokens, formatting of `.lua` files, 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) | @@ -35,6 +35,7 @@ │ │ ├── hover/ # Hover targets, library knowledge and rendering (pure, no LSP imports) │ │ ├── completion/ # Completion candidates (pure, no LSP imports) │ │ ├── semanticTokens/ # Name classification for semantic tokens (pure, no LSP imports) +│ │ ├── formatting/ # Layout-preserving Lua formatting edits (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 e4f6288..de7b3bd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,7 @@ server (port 6009). | `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/semanticTokens/` | What each name is, for semantic highlighting (pure; follows the hover's rules) | +| `src/server/formatting/` | Layout-preserving formatting edits for Lua (pure; every result re-lexed and checked) | | `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 | diff --git a/README.md b/README.md index 3881efb..dd24993 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,9 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the > [!NOTE] > This is an early version. It currently provides **syntax diagnostics**, **hover**, -> **completion**, **semantic highlighting**, **document symbols**, **workspace symbols**, **folding**, -> and **go to definition**, **find references** and **rename** within a file; cross-file navigation, -> formatting and more are planned. +> **completion**, **semantic highlighting**, **formatting** (Lua files), **document symbols**, +> **workspace symbols**, **folding**, and **go to definition**, **find references** and **rename** +> within a file; cross-file navigation, formatting of `.menu` files and more are planned. ## Features @@ -60,6 +60,12 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the "rules": { "*.global": { "bold": true } } } ``` +- **Format Document and Format Selection** for Lua files: indentation, spacing within a line and + trailing white space are fixed, while your line breaks stay where they are and strings and + comments are never changed (apart from trailing white space after a `--` comment). Tabs or spaces follow your editor settings (*Editor: Tab Size*, + *Editor: Insert Spaces*). Turn on *Editor: Format On Type* to have `end`, `else` and closing + brackets re-indented as you type them, or *Editor: Format On Save*. Files with a syntax error + are left unchanged. `.menu` files are not formatted yet. - **Go to Definition, Find All References and Rename Symbol** for variables within a file. Locals follow Lua's scoping rules; globals are followed across all the Lua of a `.menu` file. Rename refuses, and says why, when it could change what the code does: a name already in use nearby, diff --git a/docs/editors/README.md b/docs/editors/README.md index 97c9f47..c9072fd 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -71,6 +71,7 @@ node /path/to/server.js --stdio | 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. | | Semantic tokens | `textDocument/semanticTokens/full`, `/full/delta`, `/range` | Names only (keywords, strings and comments are left to the editor's highlighting). See below. | +| Formatting | `textDocument/formatting`, `/rangeFormatting`, `/onTypeFormatting` | `.lua` files only. Keeps your line breaks; uses the editor's tab size and spaces/tabs option. 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; @@ -104,6 +105,18 @@ Semantic tokens classify every name in the Lua with standard token types (`names functions. How the names are colored depends on the editor and its color scheme; an editor that ignores the `global` modifier still gets the token type. -Symbols, folding, hover, completion, semantic tokens and navigation always reflect the current text, whatever `validate.mode` is. +Formatting changes only the white space between tokens and comments: indentation, spacing +within a line and trailing white space. Line breaks stay where you put them, and strings and +comments are never changed, apart from trailing white space after a `--` comment. It follows the +`tabSize` and `insertSpaces` the editor sends, and `insertFinalNewline` / `trimFinalNewlines` +when the editor sends them. A file with a syntax error is not formatted (the reason goes to the +server log). On-type formatting re-indents a line when you type the last character of `end`, +`else`, `elseif`, `until`, `)`, `]` or `}` at its start, and formats the line you leave with +Enter, if your editor sends on-type formatting requests (some send them only when an option is +turned on; see its documentation). When the editor supports dynamic registration, formatting is +offered for Lua documents only (language `lua`, or `*.lua` in any letter case), so `.menu` files +have no formatter; other editors get no edits for `.menu` files. + +Symbols, folding, hover, completion, semantic tokens, formatting 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.