From d9c1bea2bb0d7ca06952a1cd93ddaaccb9f1b169 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:42:07 +0100 Subject: [PATCH 01/15] refactor(wasm): share the verified Lua 5.2.4 tarball download Move the pinned tarball URL, its published SHA-256, the download into .cache/lua and the verification from build.mts into tarball.mts, so the Lua manual data generator (next commits) uses the same verified source instead of a second copy of the logic. tarball.mts throws instead of exiting, so each caller reports failures under its own annotation title. No behaviour change: `npm run build:wasm -- --check` still reports that third_party/lua52/dist matches a fresh build byte for byte. Co-Authored-By: Claude Opus 5.5 --- third_party/lua52/build.mts | 45 +++++++++----------------------- third_party/lua52/tarball.mts | 48 +++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 33 deletions(-) create mode 100644 third_party/lua52/tarball.mts diff --git a/third_party/lua52/build.mts b/third_party/lua52/build.mts index d00968b..bbeff3e 100644 --- a/third_party/lua52/build.mts +++ b/third_party/lua52/build.mts @@ -5,19 +5,15 @@ // // Requires Emscripten (see EMSCRIPTEN_VERSION) on PATH, e.g. via // `source .cache/emsdk/emsdk_env.sh`. Inputs are pinned and verified: -// the tarball by its SHA-256 published on https://www.lua.org/ftp/, and the -// compiler by its exact version string. -import { createHash } from 'node:crypto'; +// the tarball by its SHA-256 published on https://www.lua.org/ftp/ (tarball.mts), +// and the compiler by its exact version string. import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { fetchLuaTarball, LUA_VERSION, sha256 } from './tarball.mts'; -const LUA_VERSION = '5.2.4'; -const LUA_URL = `https://www.lua.org/ftp/lua-${LUA_VERSION}.tar.gz`; -// Published next to the tarball on https://www.lua.org/ftp/ ("checksum (sha256)"). -const LUA_SHA256 = 'b9e2e4aad6789b3b63a056d442f7b39f0ecfca3ae0f1fc0ae4e9614401b69f4b'; // https://github.com/emscripten-core/emsdk tag; keep in sync with .github/workflows/ci.yml. const EMSCRIPTEN_VERSION = '6.0.13'; @@ -31,8 +27,6 @@ const SOURCES = [ const here = dirname(fileURLToPath(import.meta.url)); const root = resolve(here, '..', '..'); -const cacheDir = join(root, '.cache', 'lua'); -const tarball = join(cacheDir, `lua-${LUA_VERSION}.tar.gz`); function fail(message: string): never { // `::error::` renders as an annotation on GitHub Actions and reads fine locally. @@ -40,10 +34,6 @@ function fail(message: string): never { process.exit(1); } -function sha256(data: Buffer | string): string { - return createHash('sha256').update(data).digest('hex'); -} - function run(command: string, args: string[], cwd: string): string { try { return execFileSync(command, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); @@ -61,22 +51,6 @@ function run(command: string, args: string[], cwd: string): string { } } -async function fetchTarball(): Promise { - if (!existsSync(tarball)) { - mkdirSync(cacheDir, { recursive: true }); - const response = await fetch(LUA_URL); - if (!response.ok) { - fail(`Downloading ${LUA_URL} failed: HTTP ${response.status} ${response.statusText}`); - } - writeFileSync(tarball, Buffer.from(await response.arrayBuffer())); - } - const actual = sha256(readFileSync(tarball)); - if (actual !== LUA_SHA256) { - rmSync(tarball); - fail(`${LUA_URL} has SHA-256 ${actual}, expected ${LUA_SHA256}. The cached file was deleted; re-run to download it again.`); - } -} - function checkCompiler(): void { const version = run('emcc', ['--version'], root).split('\n')[0] ?? ''; // First line looks like: "emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 6.0.13 ()" @@ -98,7 +72,7 @@ declare function createLua52(): Promise; export default createLua52; `; -function build(outDir: string): void { +function build(tarball: string, outDir: string): void { const work = mkdtempSync(join(tmpdir(), 'lua52-')); try { run('tar', ['-xzf', tarball, '-C', work], root); @@ -134,17 +108,22 @@ function build(outDir: string): void { async function main(): Promise { const check = process.argv.includes('--check'); - await fetchTarball(); + let tarball: string; + try { + tarball = await fetchLuaTarball(); + } catch (error) { + fail(error instanceof Error ? error.message : String(error)); + } checkCompiler(); const committed = join(here, 'dist'); if (!check) { - build(committed); + build(tarball, committed); console.log(`Built ${relative(root, join(committed, 'lua52.js'))} (${readFileSync(join(committed, 'lua52.js.sha256'), 'utf8').trim()})`); return; } const scratch = mkdtempSync(join(tmpdir(), 'lua52-check-')); try { - build(scratch); + build(tarball, scratch); for (const file of ['lua52.js', 'lua52.d.ts', 'lua52.js.sha256']) { const expectedPath = join(committed, file); if (!existsSync(expectedPath)) { diff --git a/third_party/lua52/tarball.mts b/third_party/lua52/tarball.mts new file mode 100644 index 0000000..4ae491e --- /dev/null +++ b/third_party/lua52/tarball.mts @@ -0,0 +1,48 @@ +// The official Lua 5.2.4 source tarball, downloaded once into .cache/lua and +// verified by its SHA-256 before every use. Shared by the WASM build +// (build.mts) and the Lua manual data generator (scripts/lua-manual/). +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export const LUA_VERSION = '5.2.4'; +export const LUA_URL = `https://www.lua.org/ftp/lua-${LUA_VERSION}.tar.gz`; +// Published next to the tarball on https://www.lua.org/ftp/ ("checksum (sha256)"). +export const LUA_SHA256 = 'b9e2e4aad6789b3b63a056d442f7b39f0ecfca3ae0f1fc0ae4e9614401b69f4b'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'); +const cacheDir = join(root, '.cache', 'lua'); +const tarball = join(cacheDir, `lua-${LUA_VERSION}.tar.gz`); + +export function sha256(data: Buffer | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +/** + * Path of the verified tarball, downloading it first when it is not cached. + * Throws an `Error` with an actionable message when the download fails or the + * file does not have the published SHA-256 (the bad file is then deleted). + */ +export async function fetchLuaTarball(): Promise { + if (!existsSync(tarball)) { + mkdirSync(cacheDir, { recursive: true }); + const response = await fetch(LUA_URL); + if (!response.ok) { + throw new Error(`Downloading ${LUA_URL} failed: HTTP ${response.status} ${response.statusText}`); + } + writeFileSync(tarball, Buffer.from(await response.arrayBuffer())); + } + const actual = sha256(readFileSync(tarball)); + if (actual !== LUA_SHA256) { + rmSync(tarball); + throw new Error(`${LUA_URL} has SHA-256 ${actual}, expected ${LUA_SHA256}. The cached file was deleted; re-run to download it again.`); + } + return tarball; +} + +/** The bytes of one member of the tarball (`member` as listed by `tar -t`, e.g. `lua-5.2.4/doc/manual.html`). */ +export function readTarballMember(path: string, member: string): Buffer { + return execFileSync('tar', ['-xzOf', path, member], { maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }); +} From 30ccf56d5ad583ef6eea0a3d2d8b88c08f6b8355 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:45:25 +0100 Subject: [PATCH 02/15] build: convert the Lua 5.2 manual's HTML subset to Markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit plan.md requires help text that keeps the wording and formatting of the Lua 5.2 reference manual. Add a pure converter from the manual's HTML to Markdown (for hovers) and plain text (for clients without Markdown). It accepts exactly the HTML the library entries of chapter 6 use (inventoried from lua-5.2.4/doc/manual.html: p, pre, ul/li, code, em, b, a href="#…", a name, sup; entities ·   § – π < >, plus &, " and the © of the copyright line) and throws on anything else, so a manual that changes shape fails the generator instead of producing wrong text: - paragraphs keep their text; whitespace collapses as in HTML, also across element boundaries, and a non-breaking space stays one; -
 becomes a fenced block, verbatim; list items keep their nested
  code blocks and paragraphs;
- links into the manual become absolute links to
  https://www.lua.org/manual/5.2/manual.html#…;
- text Markdown would interpret (* _ [ ] < > & ~ | ` \ and a leading
  #, -, + or 1.) is escaped.

Three constructs have no Markdown equivalent; hovers render Markdown
without HTML in VS Code, and other clients may not render HTML at all:

-  becomes Unicode superscripts (2³², eˣ);
-  inside  (`%d` in string.gsub) becomes an
  emphasized code span of its own: `%`*`d`*;
-  inside 
 (the placeholder `body` in the ipairs and pairs
  examples) keeps its text without emphasis.

Co-Authored-By: Claude Opus 5.5 
---
 scripts/lua-manual/convert.mts               | 378 +++++++++++++++++++
 test/unit/scripts/lua-manual/convert.test.ts |  95 +++++
 2 files changed, 473 insertions(+)
 create mode 100644 scripts/lua-manual/convert.mts
 create mode 100644 test/unit/scripts/lua-manual/convert.test.ts

diff --git a/scripts/lua-manual/convert.mts b/scripts/lua-manual/convert.mts
new file mode 100644
index 0000000..1be67d8
--- /dev/null
+++ b/scripts/lua-manual/convert.mts
@@ -0,0 +1,378 @@
+// Converts the HTML of the Lua 5.2 reference manual's library entries into
+// Markdown and plain text, keeping the manual's wording and formatting.
+// Pure: no I/O. Used by generate.mts.
+//
+// The manual (lua-5.2.4/doc/manual.html) is hand-written HTML 4 with a small
+// vocabulary. This converter accepts exactly the subset the library entries
+// use and throws on anything else, so a manual that changes shape fails the
+// generator instead of producing silently wrong text:
+//
+//   

starts a paragraph (it is never closed in the manual) +//

…
a code block, kept verbatim (an inside is shown +// without emphasis: code blocks cannot show it) +//
  • …
a list; items hold paragraphs and code blocks +// code span, emphasis, strong emphasis (an inside +// becomes an emphasized code span of its own) +// link into the manual, made absolute +// anchor, unwrapped +// superscript, as Unicode superscript characters +// (hovers render Markdown without HTML) +// +// Entities: only those the entries use, plus & and " (and ©, for +// the copyright line). + +/** Thrown for HTML outside the supported subset; the message says what and where. */ +export class UnsupportedHtmlError extends Error {} + +const ENTITIES: Readonly> = { + amp: '&', + quot: '"', + lt: '<', + gt: '>', + nbsp: '\u00a0', + middot: '\u00b7', + ndash: '\u2013', + sect: '\u00a7', + pi: '\u03c0', + // Only in the manual's copyright line, which generate.mts records. + copy: '\u00a9', +}; + +// Unicode has superscript forms for digits and some letters; only the +// characters the manual puts in are listed (2^32, 2^51, e^x, x^y, m2^e). +const SUPERSCRIPTS: Readonly> = { + '0': '\u2070', '1': '\u00b9', '2': '\u00b2', '3': '\u00b3', '4': '\u2074', + '5': '\u2075', '6': '\u2076', '7': '\u2077', '8': '\u2078', '9': '\u2079', + e: '\u1d49', x: '\u02e3', y: '\u02b8', +}; + +/** Replaces the supported character entities; throws on any other `&…;`. */ +export function decodeEntities(text: string): string { + return text.replace(/&([a-zA-Z0-9#]+);/g, (match, name: string) => { + const decoded = ENTITIES[name]; + if (decoded === undefined) { + throw new UnsupportedHtmlError(`Unsupported HTML entity ${match}.`); + } + return decoded; + }); +} + +// ------------------------------------------------------------------ tokens + +type Token = + | { readonly type: 'text'; readonly text: string } + | { readonly type: 'open'; readonly name: string; readonly attributes: Readonly>; readonly source: string } + | { readonly type: 'close'; readonly name: string; readonly source: string }; + +function tokenize(html: string): Token[] { + const tokens: Token[] = []; + const tag = /<(\/?)([a-zA-Z][a-zA-Z0-9]*)((?:\s+[a-zA-Z]+="[^"]*")*)\s*>/g; + let last = 0; + for (let match = tag.exec(html); match; match = tag.exec(html)) { + if (match.index > last) tokens.push({ type: 'text', text: html.slice(last, match.index) }); + const [source, slash, rawName = '', rawAttributes = ''] = match; + const name = rawName.toLowerCase(); + if (slash) { + tokens.push({ type: 'close', name, source }); + } else { + const attributes: Record = {}; + for (const [, key = '', value = ''] of rawAttributes.matchAll(/([a-zA-Z]+)="([^"]*)"/g)) attributes[key.toLowerCase()] = value; + tokens.push({ type: 'open', name, attributes, source }); + } + last = match.index + source.length; + } + if (last < html.length) tokens.push({ type: 'text', text: html.slice(last) }); + for (const token of tokens) { + if (token.type === 'text' && /[<>]/.test(token.text)) { + throw new UnsupportedHtmlError(`Unparsed markup in text: ${JSON.stringify(token.text.trim().slice(0, 60))}.`); + } + } + return tokens; +} + +// ------------------------------------------------------------------ tree + +type Inline = + | { readonly kind: 'text'; readonly text: string } + /** Code; `emphasized` parts are placeholders (`%d` in `string.gsub`). */ + | { readonly kind: 'code'; readonly parts: readonly { readonly text: string; readonly emphasized: boolean }[] } + | { readonly kind: 'em' | 'strong' | 'sup'; readonly children: readonly Inline[] } + | { readonly kind: 'link'; readonly fragment: string; readonly children: readonly Inline[] }; + +type Block = + | { readonly kind: 'paragraph'; readonly children: readonly Inline[] } + | { readonly kind: 'pre'; readonly text: string } + | { readonly kind: 'list'; readonly items: readonly (readonly Block[])[] }; + +class Parser { + private index = 0; + private readonly tokens: readonly Token[]; + constructor(tokens: readonly Token[]) { + this.tokens = tokens; + } + + /** Blocks until the end of input, or until `` (consumed). */ + blocks(until?: string): Block[] { + const blocks: Block[] = []; + let paragraph: Inline[] = []; + const flush = (): void => { + if (paragraph.some((inline) => inline.kind !== 'text' || inline.text.trim() !== '')) { + blocks.push({ kind: 'paragraph', children: paragraph }); + } + paragraph = []; + }; + for (;;) { + const token = this.tokens[this.index]; + if (!token) { + if (until) throw new UnsupportedHtmlError(`Missing .`); + break; + } + if (token.type === 'close' && token.name === until) { + this.index++; + break; + } + if (token.type === 'open' && token.name === 'p') { + this.index++; + flush(); + } else if (token.type === 'open' && token.name === 'pre') { + this.index++; + flush(); + blocks.push({ kind: 'pre', text: this.pre() }); + } else if (token.type === 'open' && token.name === 'ul') { + this.index++; + flush(); + blocks.push({ kind: 'list', items: this.listItems() }); + } else { + paragraph.push(...this.inline(token)); + } + } + flush(); + return blocks; + } + + /** + * The text of a `
`. `` marks placeholders in two examples
+   * (`for i,v in ipairs(t) do body end`); a code block cannot show
+   * emphasis, so its text is kept and the emphasis dropped.
+   */
+  private pre(): string {
+    let text = '';
+    for (;;) {
+      const token = this.tokens[this.index++];
+      if (token?.type === 'close' && token.name === 'pre') break;
+      if (token?.type === 'text') {
+        text += token.text;
+      } else if (token?.type === 'open' && token.name === 'em') {
+        const [inner, close] = [this.tokens[this.index], this.tokens[this.index + 1]];
+        if (inner?.type !== 'text' || close?.type !== 'close' || close.name !== 'em') {
+          throw new UnsupportedHtmlError(' in 
 must contain only text.');
+        }
+        text += inner.text;
+        this.index += 2;
+      } else {
+        throw new UnsupportedHtmlError(`
 must contain only text and , found ${token ? describe(token) : 'the end of input'}.`);
+      }
+    }
+    // HTML ignores a newline right after 
; the one before 
ends the last line. + return decodeEntities(text).replace(/^\r?\n/, '').replace(/\r?\n$/, ''); + } + + private listItems(): Block[][] { + const items: Block[][] = []; + for (;;) { + const token = this.tokens[this.index]; + if (!token) throw new UnsupportedHtmlError('Missing .'); + this.index++; + if (token.type === 'text' && token.text.trim() === '') continue; + if (token.type === 'close' && token.name === 'ul') return items; + if (token.type === 'open' && token.name === 'li') { + const item = this.blocks('li'); + if (item.some((block) => block.kind === 'list')) throw new UnsupportedHtmlError('Nested lists are not supported.'); + items.push(item); + continue; + } + throw new UnsupportedHtmlError(`Unexpected ${describe(token)} in
    .`); + } + } + + /** One inline element; an anchor (``) yields its children. */ + private inline(token: Token): Inline[] { + this.index++; + if (token.type === 'text') return [{ kind: 'text', text: decodeEntities(token.text) }]; + if (token.type === 'close') throw new UnsupportedHtmlError(`Unexpected ${token.source}.`); + switch (token.name) { + case 'code': { + const parts = this.inlines('code').map((child) => { + if (child.kind === 'text') return { text: child.text, emphasized: false }; + const [only] = child.kind === 'em' ? child.children : []; + if (child.kind === 'em' && child.children.length === 1 && only?.kind === 'text') return { text: only.text, emphasized: true }; + throw new UnsupportedHtmlError('Markup inside other than around text is not supported.'); + }); + return [{ kind: 'code', parts }]; + } + case 'em': + return [{ kind: 'em', children: this.inlines('em') }]; + case 'b': + return [{ kind: 'strong', children: this.inlines('b') }]; + case 'sup': + return [{ kind: 'sup', children: this.inlines('sup') }]; + case 'a': { + const { href, name } = token.attributes; + if (href !== undefined) { + if (!href.startsWith('#') || href.length === 1) throw new UnsupportedHtmlError(`Only links into the manual are supported, found href="${href}".`); + return [{ kind: 'link', fragment: href.slice(1), children: this.inlines('a') }]; + } + if (name !== undefined) { + // An anchor only marks a position; its content is ordinary text. + return this.inlines('a'); + } + throw new UnsupportedHtmlError(` without href or name: ${token.source}.`); + } + default: + throw new UnsupportedHtmlError(`Unsupported tag ${token.source}.`); + } + } + + private inlines(until: string): Inline[] { + const children: Inline[] = []; + for (;;) { + const token = this.tokens[this.index]; + if (!token) throw new UnsupportedHtmlError(`Missing .`); + if (token.type === 'close' && token.name === until) { + this.index++; + return children; + } + if (token.type === 'open' && ['p', 'pre', 'ul', 'li'].includes(token.name)) { + throw new UnsupportedHtmlError(`Block ${token.source} inside <${until}>.`); + } + children.push(...this.inline(token)); + } + } +} + +function describe(token: Token): string { + return token.type === 'text' ? `text ${JSON.stringify(token.text.trim().slice(0, 40))}` : token.source; +} + +// ------------------------------------------------------------------ output + +export interface Converted { + readonly markdown: string; + readonly plaintext: string; +} + +/** HTML collapses runs of ASCII whitespace; U+00A0 ( ) is not whitespace. */ +const collapse = (text: string): string => text.replace(/[ \t\r\n]+/g, ' '); + +/** Backslash-escapes the characters that Markdown (CommonMark + GFM) would interpret in text. */ +function escapeMarkdown(text: string): string { + return text.replace(/[\\`*_[\]<>&~|]/g, '\\$&'); +} + +/** Escapes a paragraph or list item start that Markdown would read as a heading, list, quote or rule. */ +function escapeLineStart(line: string): string { + return line.replace(/^(#|>|[-+=]|\d+(?=[.)]))/, (start) => (/^\d/.test(start) ? `${start}\\` : `\\${start}`)); +} + +function codeSpan(text: string): string { + const longest = Math.max(0, ...[...text.matchAll(/`+/g)].map(([run]) => run.length)); + const fence = '`'.repeat(longest + 1); + // CommonMark strips one space from each side when both are present, and a + // backtick next to the fence would merge with it: pad in those cases. + const pad = text.startsWith('`') || text.endsWith('`') || (text.startsWith(' ') && text.endsWith(' ') && text.trim() !== '') ? ' ' : ''; + return `${fence}${pad}${text}${pad}${fence}`; +} + +function superscript(text: string): string { + return text.replace(/./gsu, (character) => { + const mapped = SUPERSCRIPTS[character]; + if (mapped === undefined) throw new UnsupportedHtmlError(`No Unicode superscript for ${JSON.stringify(character)}.`); + return mapped; + }); +} + +function plainInlines(children: readonly Inline[], baseUrl: string): string { + return children.map((child): string => { + switch (child.kind) { + case 'text': + return collapse(child.text); + case 'code': + return collapse(child.parts.map((part) => part.text).join('')); + case 'em': + case 'strong': + return plainInlines(child.children, baseUrl); + case 'sup': + return superscript(plainInlines(child.children, baseUrl)); + case 'link': + return `${plainInlines(child.children, baseUrl)} (${baseUrl}#${child.fragment})`; + } + }).join(''); +} + +/** Wraps `inner` in `marker`, moving surrounding spaces outside so the delimiters stay flanking. */ +function delimit(marker: string, inner: string): string { + const match = /^( *)(.*?)( *)$/s.exec(inner); + const [, before = '', core = '', after = ''] = match ?? []; + return core === '' ? inner : `${before}${marker}${core}${marker}${after}`; +} + +function markdownInlines(children: readonly Inline[], baseUrl: string): string { + return children.map((child): string => { + switch (child.kind) { + case 'text': + return escapeMarkdown(collapse(child.text)); + case 'code': + // A code span cannot contain emphasis: an emphasized part becomes an emphasized code span of its own. + return child.parts.map((part) => (part.emphasized ? `*${codeSpan(collapse(part.text))}*` : codeSpan(collapse(part.text)))).join(''); + case 'em': + return delimit('*', markdownInlines(child.children, baseUrl)); + case 'strong': + return delimit('**', markdownInlines(child.children, baseUrl)); + case 'sup': + return superscript(plainInlines(child.children, baseUrl)); + case 'link': + return `[${markdownInlines(child.children, baseUrl)}](${baseUrl}#${encodeURI(child.fragment)})`; + } + }).join(''); +} + +function fenced(text: string): string { + const longest = Math.max(0, ...[...text.matchAll(/`+/g)].map(([run]) => run.length)); + const fence = '`'.repeat(Math.max(3, longest + 1)); + return `${fence}\n${text}\n${fence}`; +} + +const indent = (text: string, prefix: string): string => text.split('\n').map((line) => (line === '' ? line : prefix + line)).join('\n'); + +function render(blocks: readonly Block[], baseUrl: string, markdown: boolean): string { + return blocks.map((block): string => { + switch (block.kind) { + case 'paragraph': { + // HTML also collapses whitespace across element boundaries (`x: \nmore`). + const text = collapse(markdown ? markdownInlines(block.children, baseUrl) : plainInlines(block.children, baseUrl)).trim(); + return markdown ? escapeLineStart(text) : text; + } + case 'pre': + return markdown ? fenced(block.text) : block.text; + case 'list': { + const loose = block.items.some((item) => item.length > 1); + return block.items + .map((item) => { + const body = indent(render(item, baseUrl, markdown), ' '); + return `- ${body.slice(2)}`; + }) + .join(loose ? '\n\n' : '\n'); + } + } + }).join('\n\n'); +} + +/** + * Markdown and plain text of a fragment of the manual (the HTML between an + * entry's heading and the next one). `baseUrl` makes `#fragment` links absolute. + * Throws `UnsupportedHtmlError` for anything outside the supported subset. + */ +export function convertFragment(html: string, baseUrl: string): Converted { + const blocks = new Parser(tokenize(html)).blocks(); + return { markdown: render(blocks, baseUrl, true), plaintext: render(blocks, baseUrl, false) }; +} diff --git a/test/unit/scripts/lua-manual/convert.test.ts b/test/unit/scripts/lua-manual/convert.test.ts new file mode 100644 index 0000000..d918976 --- /dev/null +++ b/test/unit/scripts/lua-manual/convert.test.ts @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict'; +import { convertFragment, decodeEntities, UnsupportedHtmlError } from '../../../../scripts/lua-manual/convert.mts'; + +const BASE = 'https://www.lua.org/manual/5.2/manual.html'; +const convert = (html: string): { markdown: string; plaintext: string } => convertFragment(html, BASE); + +describe('scripts/lua-manual/convert', () => { + it('decodes exactly the supported entities', () => { + assert.equal(decodeEntities('a b ··· §2 – π <> &"'), 'a\u00a0b ··· §2 – π <> &"'); + assert.throws(() => decodeEntities('é'), UnsupportedHtmlError); + assert.throws(() => decodeEntities('é'), UnsupportedHtmlError); + }); + + it('splits paragraphs at

    , collapses whitespace and drops empty paragraphs', () => { + const { markdown, plaintext } = convert('\nFirst\nline here.\n\n\n

    \n

    \nSecond.\n\n

    \n'); + assert.equal(markdown, 'First line here.\n\nSecond.'); + assert.equal(plaintext, 'First line here.\n\nSecond.'); + }); + + it('keeps a non-breaking space, which HTML does not collapse', () => { + assert.equal(convert('position 1').markdown, 'position\u00a01'); + }); + + it('collapses whitespace across element boundaries', () => { + assert.equal(convert('"x": \ndoes').markdown, '**"`x`":** does'); + }); + + it('renders code spans, using a longer fence when the code contains backticks', () => { + assert.equal(convert('call f(x) now').markdown, 'call `f(x)` now'); + assert.equal(convert('a`b').markdown, '``a`b``'); + assert.equal(convert('`').markdown, '`` ` ``'); + assert.equal(convert('call f(x) now').plaintext, 'call f(x) now'); + }); + + it('renders a placeholder marked inside code as an emphasized code span', () => { + assert.equal(convert('form %d, with').markdown, 'form `%`*`d`*, with'); + assert.equal(convert('form %d, with').plaintext, 'form %d, with'); + }); + + it('renders emphasis, keeping spaces outside the delimiters', () => { + assert.equal(convert('the pause of').markdown, 'the *pause* of'); + assert.equal(convert('is nil or false x').markdown, 'is **nil** or **false** x'); + assert.equal(convert('is nil').plaintext, 'is nil'); + }); + + it('makes links into the manual absolute and unwraps anchors', () => { + const { markdown, plaintext } = convert('see §2.5 and tostring; string'); + assert.equal(markdown, `see [§2.5](${BASE}#2.5) and [\`tostring\`](${BASE}#pdf-tostring); \`string\``); + assert.equal(plaintext, `see §2.5 (${BASE}#2.5) and tostring (${BASE}#pdf-tostring); string`); + }); + + it('renders superscripts as Unicode superscript characters', () => { + assert.equal(convert('232 and ex').markdown, '2³² and *eˣ*'); + assert.equal(convert('xy').plaintext, 'xʸ'); + assert.throws(() => convert('z'), /No Unicode superscript for "z"/); + }); + + it('keeps preformatted text verbatim in a fenced block', () => { + const html = 'For instance\n\n

    \n     f("a < b")\n       --   indented\n

    \nAfter.'; + assert.equal(convert(html).markdown, 'For instance\n\n```\n f("a < b")\n -- indented\n```\n\nAfter.'); + assert.equal(convert(html).plaintext, 'For instance\n\n f("a < b")\n -- indented\n\nAfter.'); + assert.equal(convert('

    \nx = ```\n
    ').markdown, '````\nx = ```\n````'); + }); + + it('keeps the text of placeholders marked in preformatted text', () => { + assert.equal(convert('
    \n     for i,v in ipairs(t) do body end\n
    ').markdown, '```\n for i,v in ipairs(t) do body end\n```'); + }); + + it('renders lists, indenting the blocks of an item', () => { + assert.equal(convert('
      \n
    • one
    • \n
    • two
    • \n
    ').markdown, '- one\n- two'); + const loose = convert('
      \n
    • one\n
      \ncode\n

      \nmore\n

    • \n
    • two
    • \n
    '); + assert.equal(loose.markdown, '- one\n\n ```\n code\n ```\n\n more\n\n- two'); + assert.equal(loose.plaintext, '- one\n\n code\n\n more\n\n- two'); + }); + + it('escapes text Markdown would interpret', () => { + assert.equal(convert('a*b_c [d] <e> & ~f~ \\ `').markdown, 'a\\*b\\_c \\[d\\] \\ \\& \\~f\\~ \\\\ \\`'); + assert.equal(convert('# not a heading').markdown, '\\# not a heading'); + assert.equal(convert('- not a list').markdown, '\\- not a list'); + assert.equal(convert('1. not a list').markdown, '1\\. not a list'); + assert.equal(convert('a*b').plaintext, 'a*b'); + }); + + it('rejects HTML outside the supported subset', () => { + assert.throws(() => convert('

    Title

    '), /Unsupported tag

    /); + assert.throws(() => convert('
    x
    '), UnsupportedHtmlError); + assert.throws(() => convert('x'), /Only links into the manual/); + assert.throws(() => convert('d'), /Markup inside /); + assert.throws(() => convert('
    \nx\n
    '), /
     must contain only text/);
    +    assert.throws(() => convert('
    \nx\n
    '), / in
     must contain only text/);
    +    assert.throws(() => convert('
    • a
      • b
    '), /Nested lists/); + assert.throws(() => convert('open'), /Missing <\/em>/); + assert.throws(() => convert('a < b'), /Unparsed markup/); + }); +}); From d10795df18cf43efa72c9c6f5e4b0adee5059e63 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:50:25 +0100 Subject: [PATCH 03/15] build: generate the Lua 5.2 library reference from the official manual MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `npm run lua-manual`, which writes data/lua52/manual.json from lua-5.2.4/doc/manual.html in the SHA-256-verified tarball (the release of the embedded compiler). `--check` fails when the committed file differs from a fresh run; `--compare-online` audits the online manual. Only the libraries the engine opens are included (CLAUDE.md §7, IESDP "Engine Lua globals"): §6.1 basic functions (24 entries), §6.4 string, §6.5 table, §6.6 math, §6.7 bit32 and §6.10 debug, each with its module table, 106 entries in all. Coroutines, modules (`require`), io and os are left out. Each entry keeps the manual's heading verbatim (`string.format (formatstring, ···)`), its anchor, and its text as Markdown and plain text (previous commit). Links point to https://www.lua.org/manual/5.2/manual.html, the URL plan.md names. The generator fails, with the section and entry at fault, when a section, an entry heading or a module anchor is missing, an entry belongs to another library, or the HTML is outside the supported subset. Audit (`--compare-online`, 2026-10-29): the sections and all 106 entries generated from https://www.lua.org/manual/5.2/manual.html are identical to those from the tarball. The only difference is the copyright line: 2011–2015 in the tarball, 2011–2013 online (that page was last modified on 2019-08-29). The tarball stays the source: it is pinned and verifiable, and it is the newer text. Tests check the committed data: the provenance, the section list, the per-section counts, the absence of coroutine/io/os/package/require, and golden text for math.huge, math.exp, select, bit32.extract, table.sort, debug.sethook, collectgarbage, string.gsub and the string module. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 1 + data/lua52/manual.json | 998 ++++++++++++++++++ package.json | 1 + scripts/lua-manual/generate.mts | 221 ++++ test/unit/scripts/lua-manual/generate.test.ts | 137 +++ 5 files changed, 1358 insertions(+) create mode 100644 data/lua52/manual.json create mode 100644 scripts/lua-manual/generate.mts create mode 100644 test/unit/scripts/lua-manual/generate.test.ts diff --git a/.gitattributes b/.gitattributes index dd61639..40fe381 100644 --- a/.gitattributes +++ b/.gitattributes @@ -16,6 +16,7 @@ # Generated or vendored content: collapsed in diffs, excluded from language stats. third_party/lua52/dist/** linguist-generated=true data/eeex/**.json linguist-generated=true +data/lua52/**.json linguist-generated=true package-lock.json linguist-generated=true -diff # Third-party upstream sources. diff --git a/data/lua52/manual.json b/data/lua52/manual.json new file mode 100644 index 0000000..152f700 --- /dev/null +++ b/data/lua52/manual.json @@ -0,0 +1,998 @@ +{ + "source": { + "url": "https://www.lua.org/ftp/lua-5.2.4.tar.gz", + "sha256": "b9e2e4aad6789b3b63a056d442f7b39f0ecfca3ae0f1fc0ae4e9614401b69f4b", + "member": "lua-5.2.4/doc/manual.html", + "encoding": "iso-8859-1" + }, + "title": "Lua 5.2 Reference Manual", + "copyright": "Copyright © 2011–2015 Lua.org, PUC-Rio. Freely available under the terms of the Lua license.", + "baseUrl": "https://www.lua.org/manual/5.2/manual.html", + "sections": [ + { + "number": "6.1", + "title": "Basic Functions" + }, + { + "number": "6.4", + "title": "String Manipulation", + "module": "string" + }, + { + "number": "6.5", + "title": "Table Manipulation", + "module": "table" + }, + { + "number": "6.6", + "title": "Mathematical Functions", + "module": "math" + }, + { + "number": "6.7", + "title": "Bitwise Operations", + "module": "bit32" + }, + { + "number": "6.10", + "title": "The Debug Library", + "module": "debug" + } + ], + "entries": [ + { + "name": "assert", + "kind": "function", + "section": "6.1", + "anchor": "pdf-assert", + "heading": "assert (v [, message])", + "markdown": "Issues an error when the value of its argument `v` is false (i.e., **nil** or **false**); otherwise, returns all its arguments. `message` is an error message; when absent, it defaults to \"assertion failed!\"", + "plaintext": "Issues an error when the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. message is an error message; when absent, it defaults to \"assertion failed!\"" + }, + { + "name": "collectgarbage", + "kind": "function", + "section": "6.1", + "anchor": "pdf-collectgarbage", + "heading": "collectgarbage ([opt [, arg]])", + "markdown": "This function is a generic interface to the garbage collector. It performs different functions according to its first argument, `opt`:\n\n- **\"`collect`\":** performs a full garbage-collection cycle. This is the default option.\n\n- **\"`stop`\":** stops automatic execution of the garbage collector. The collector will run only when explicitly invoked, until a call to restart it.\n\n- **\"`restart`\":** restarts automatic execution of the garbage collector.\n\n- **\"`count`\":** returns the total memory in use by Lua (in Kbytes) and a second value with the total memory in bytes modulo 1024. The first value has a fractional part, so the following equality is always true:\n\n ```\n k, b = collectgarbage(\"count\")\n assert(k*1024 == math.floor(k)*1024 + b)\n ```\n\n (The second result is useful when Lua is compiled with a non floating-point type for numbers.)\n\n- **\"`step`\":** performs a garbage-collection step. The step \"size\" is controlled by `arg` (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of `arg`. Returns **true** if the step finished a collection cycle.\n\n- **\"`setpause`\":** sets `arg` as the new value for the *pause* of the collector (see [§2.5](https://www.lua.org/manual/5.2/manual.html#2.5)). Returns the previous value for *pause*.\n\n- **\"`setstepmul`\":** sets `arg` as the new value for the *step multiplier* of the collector (see [§2.5](https://www.lua.org/manual/5.2/manual.html#2.5)). Returns the previous value for *step*.\n\n- **\"`isrunning`\":** returns a boolean that tells whether the collector is running (i.e., not stopped).\n\n- **\"`generational`\":** changes the collector to generational mode. This is an experimental feature (see [§2.5](https://www.lua.org/manual/5.2/manual.html#2.5)).\n\n- **\"`incremental`\":** changes the collector to incremental mode. This is the default mode.", + "plaintext": "This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt:\n\n- \"collect\": performs a full garbage-collection cycle. This is the default option.\n\n- \"stop\": stops automatic execution of the garbage collector. The collector will run only when explicitly invoked, until a call to restart it.\n\n- \"restart\": restarts automatic execution of the garbage collector.\n\n- \"count\": returns the total memory in use by Lua (in Kbytes) and a second value with the total memory in bytes modulo 1024. The first value has a fractional part, so the following equality is always true:\n\n k, b = collectgarbage(\"count\")\n assert(k*1024 == math.floor(k)*1024 + b)\n\n (The second result is useful when Lua is compiled with a non floating-point type for numbers.)\n\n- \"step\": performs a garbage-collection step. The step \"size\" is controlled by arg (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of arg. Returns true if the step finished a collection cycle.\n\n- \"setpause\": sets arg as the new value for the pause of the collector (see §2.5 (https://www.lua.org/manual/5.2/manual.html#2.5)). Returns the previous value for pause.\n\n- \"setstepmul\": sets arg as the new value for the step multiplier of the collector (see §2.5 (https://www.lua.org/manual/5.2/manual.html#2.5)). Returns the previous value for step.\n\n- \"isrunning\": returns a boolean that tells whether the collector is running (i.e., not stopped).\n\n- \"generational\": changes the collector to generational mode. This is an experimental feature (see §2.5 (https://www.lua.org/manual/5.2/manual.html#2.5)).\n\n- \"incremental\": changes the collector to incremental mode. This is the default mode." + }, + { + "name": "dofile", + "kind": "function", + "section": "6.1", + "anchor": "pdf-dofile", + "heading": "dofile ([filename])", + "markdown": "Opens the named file and executes its contents as a Lua chunk. When called without arguments, `dofile` executes the contents of the standard input (`stdin`). Returns all values returned by the chunk. In case of errors, `dofile` propagates the error to its caller (that is, `dofile` does not run in protected mode).", + "plaintext": "Opens the named file and executes its contents as a Lua chunk. When called without arguments, dofile executes the contents of the standard input (stdin). Returns all values returned by the chunk. In case of errors, dofile propagates the error to its caller (that is, dofile does not run in protected mode)." + }, + { + "name": "error", + "kind": "function", + "section": "6.1", + "anchor": "pdf-error", + "heading": "error (message [, level])", + "markdown": "Terminates the last protected function called and returns `message` as the error message. Function `error` never returns.\n\nUsually, `error` adds some information about the error position at the beginning of the message, if the message is a string. The `level` argument specifies how to get the error position. With level 1 (the default), the error position is where the `error` function was called. Level 2 points the error to where the function that called `error` was called; and so on. Passing a level 0 avoids the addition of error position information to the message.", + "plaintext": "Terminates the last protected function called and returns message as the error message. Function error never returns.\n\nUsually, error adds some information about the error position at the beginning of the message, if the message is a string. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message." + }, + { + "name": "_G", + "kind": "value", + "section": "6.1", + "anchor": "pdf-_G", + "heading": "_G", + "markdown": "A global variable (not a function) that holds the global environment (see [§2.2](https://www.lua.org/manual/5.2/manual.html#2.2)). Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa.", + "plaintext": "A global variable (not a function) that holds the global environment (see §2.2 (https://www.lua.org/manual/5.2/manual.html#2.2)). Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa." + }, + { + "name": "getmetatable", + "kind": "function", + "section": "6.1", + "anchor": "pdf-getmetatable", + "heading": "getmetatable (object)", + "markdown": "If `object` does not have a metatable, returns **nil**. Otherwise, if the object's metatable has a `\"__metatable\"` field, returns the associated value. Otherwise, returns the metatable of the given object.", + "plaintext": "If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a \"__metatable\" field, returns the associated value. Otherwise, returns the metatable of the given object." + }, + { + "name": "ipairs", + "kind": "function", + "section": "6.1", + "anchor": "pdf-ipairs", + "heading": "ipairs (t)", + "markdown": "If `t` has a metamethod `__ipairs`, calls it with `t` as argument and returns the first three results from the call.\n\nOtherwise, returns three values: an iterator function, the table `t`, and 0, so that the construction\n\n```\n for i,v in ipairs(t) do body end\n```\n\nwill iterate over the pairs (`1,t[1]`), (`2,t[2]`), ..., up to the first integer key absent from the table.", + "plaintext": "If t has a metamethod __ipairs, calls it with t as argument and returns the first three results from the call.\n\nOtherwise, returns three values: an iterator function, the table t, and 0, so that the construction\n\n for i,v in ipairs(t) do body end\n\nwill iterate over the pairs (1,t[1]), (2,t[2]), ..., up to the first integer key absent from the table." + }, + { + "name": "load", + "kind": "function", + "section": "6.1", + "anchor": "pdf-load", + "heading": "load (ld [, source [, mode [, env]]])", + "markdown": "Loads a chunk.\n\nIf `ld` is a string, the chunk is this string. If `ld` is a function, `load` calls it repeatedly to get the chunk pieces. Each call to `ld` must return a string that concatenates with previous results. A return of an empty string, **nil**, or no value signals the end of the chunk.\n\nIf there are no syntactic errors, returns the compiled chunk as a function; otherwise, returns **nil** plus the error message.\n\nIf the resulting function has upvalues, the first upvalue is set to the value of `env`, if that parameter is given, or to the value of the global environment. (When you load a main chunk, the resulting function will always have exactly one upvalue, the `_ENV` variable (see [§2.2](https://www.lua.org/manual/5.2/manual.html#2.2)). When you load a binary chunk created from a function (see [`string.dump`](https://www.lua.org/manual/5.2/manual.html#pdf-string.dump)), the resulting function can have arbitrary upvalues.)\n\n`source` is used as the source of the chunk for error messages and debug information (see [§4.9](https://www.lua.org/manual/5.2/manual.html#4.9)). When absent, it defaults to `ld`, if `ld` is a string, or to \"`=(load)`\" otherwise.\n\nThe string `mode` controls whether the chunk can be text or binary (that is, a precompiled chunk). It may be the string \"`b`\" (only binary chunks), \"`t`\" (only text chunks), or \"`bt`\" (both binary and text). The default is \"`bt`\".", + "plaintext": "Loads a chunk.\n\nIf ld is a string, the chunk is this string. If ld is a function, load calls it repeatedly to get the chunk pieces. Each call to ld must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk.\n\nIf there are no syntactic errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message.\n\nIf the resulting function has upvalues, the first upvalue is set to the value of env, if that parameter is given, or to the value of the global environment. (When you load a main chunk, the resulting function will always have exactly one upvalue, the _ENV variable (see §2.2 (https://www.lua.org/manual/5.2/manual.html#2.2)). When you load a binary chunk created from a function (see string.dump (https://www.lua.org/manual/5.2/manual.html#pdf-string.dump)), the resulting function can have arbitrary upvalues.)\n\nsource is used as the source of the chunk for error messages and debug information (see §4.9 (https://www.lua.org/manual/5.2/manual.html#4.9)). When absent, it defaults to ld, if ld is a string, or to \"=(load)\" otherwise.\n\nThe string mode controls whether the chunk can be text or binary (that is, a precompiled chunk). It may be the string \"b\" (only binary chunks), \"t\" (only text chunks), or \"bt\" (both binary and text). The default is \"bt\"." + }, + { + "name": "loadfile", + "kind": "function", + "section": "6.1", + "anchor": "pdf-loadfile", + "heading": "loadfile ([filename [, mode [, env]]])", + "markdown": "Similar to [`load`](https://www.lua.org/manual/5.2/manual.html#pdf-load), but gets the chunk from file `filename` or from the standard input, if no file name is given.", + "plaintext": "Similar to load (https://www.lua.org/manual/5.2/manual.html#pdf-load), but gets the chunk from file filename or from the standard input, if no file name is given." + }, + { + "name": "next", + "kind": "function", + "section": "6.1", + "anchor": "pdf-next", + "heading": "next (table [, index])", + "markdown": "Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. `next` returns the next index of the table and its associated value. When called with **nil** as its second argument, `next` returns an initial index and its associated value. When called with the last index, or with **nil** in an empty table, `next` returns **nil**. If the second argument is absent, then it is interpreted as **nil**. In particular, you can use `next(t)` to check whether a table is empty.\n\nThe order in which the indices are enumerated is not specified, *even for numeric indices*. (To traverse a table in numeric order, use a numerical **for**.)\n\nThe behavior of `next` is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.", + "plaintext": "Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.\n\nThe order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for.)\n\nThe behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields." + }, + { + "name": "pairs", + "kind": "function", + "section": "6.1", + "anchor": "pdf-pairs", + "heading": "pairs (t)", + "markdown": "If `t` has a metamethod `__pairs`, calls it with `t` as argument and returns the first three results from the call.\n\nOtherwise, returns three values: the [`next`](https://www.lua.org/manual/5.2/manual.html#pdf-next) function, the table `t`, and **nil**, so that the construction\n\n```\n for k,v in pairs(t) do body end\n```\n\nwill iterate over all key–value pairs of table `t`.\n\nSee function [`next`](https://www.lua.org/manual/5.2/manual.html#pdf-next) for the caveats of modifying the table during its traversal.", + "plaintext": "If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.\n\nOtherwise, returns three values: the next (https://www.lua.org/manual/5.2/manual.html#pdf-next) function, the table t, and nil, so that the construction\n\n for k,v in pairs(t) do body end\n\nwill iterate over all key–value pairs of table t.\n\nSee function next (https://www.lua.org/manual/5.2/manual.html#pdf-next) for the caveats of modifying the table during its traversal." + }, + { + "name": "pcall", + "kind": "function", + "section": "6.1", + "anchor": "pdf-pcall", + "heading": "pcall (f [, arg1, ···])", + "markdown": "Calls function `f` with the given arguments in *protected mode*. This means that any error inside `f` is not propagated; instead, `pcall` catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, `pcall` also returns all results from the call, after this first result. In case of any error, `pcall` returns **false** plus the error message.", + "plaintext": "Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error message." + }, + { + "name": "print", + "kind": "function", + "section": "6.1", + "anchor": "pdf-print", + "heading": "print (···)", + "markdown": "Receives any number of arguments and prints their values to `stdout`, using the [`tostring`](https://www.lua.org/manual/5.2/manual.html#pdf-tostring) function to convert each argument to a string. `print` is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use [`string.format`](https://www.lua.org/manual/5.2/manual.html#pdf-string.format) and [`io.write`](https://www.lua.org/manual/5.2/manual.html#pdf-io.write).", + "plaintext": "Receives any number of arguments and prints their values to stdout, using the tostring (https://www.lua.org/manual/5.2/manual.html#pdf-tostring) function to convert each argument to a string. print is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use string.format (https://www.lua.org/manual/5.2/manual.html#pdf-string.format) and io.write (https://www.lua.org/manual/5.2/manual.html#pdf-io.write)." + }, + { + "name": "rawequal", + "kind": "function", + "section": "6.1", + "anchor": "pdf-rawequal", + "heading": "rawequal (v1, v2)", + "markdown": "Checks whether `v1` is equal to `v2`, without invoking any metamethod. Returns a boolean.", + "plaintext": "Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean." + }, + { + "name": "rawget", + "kind": "function", + "section": "6.1", + "anchor": "pdf-rawget", + "heading": "rawget (table, index)", + "markdown": "Gets the real value of `table[index]`, without invoking any metamethod. `table` must be a table; `index` may be any value.", + "plaintext": "Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value." + }, + { + "name": "rawlen", + "kind": "function", + "section": "6.1", + "anchor": "pdf-rawlen", + "heading": "rawlen (v)", + "markdown": "Returns the length of the object `v`, which must be a table or a string, without invoking any metamethod. Returns an integer number.", + "plaintext": "Returns the length of the object v, which must be a table or a string, without invoking any metamethod. Returns an integer number." + }, + { + "name": "rawset", + "kind": "function", + "section": "6.1", + "anchor": "pdf-rawset", + "heading": "rawset (table, index, value)", + "markdown": "Sets the real value of `table[index]` to `value`, without invoking any metamethod. `table` must be a table, `index` any value different from **nil** and NaN, and `value` any Lua value.\n\nThis function returns `table`.", + "plaintext": "Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil and NaN, and value any Lua value.\n\nThis function returns table." + }, + { + "name": "select", + "kind": "function", + "section": "6.1", + "anchor": "pdf-select", + "heading": "select (index, ···)", + "markdown": "If `index` is a number, returns all arguments after argument number `index`; a negative number indexes from the end (-1 is the last argument). Otherwise, `index` must be the string `\"#\"`, and `select` returns the total number of extra arguments it received.", + "plaintext": "If index is a number, returns all arguments after argument number index; a negative number indexes from the end (-1 is the last argument). Otherwise, index must be the string \"#\", and select returns the total number of extra arguments it received." + }, + { + "name": "setmetatable", + "kind": "function", + "section": "6.1", + "anchor": "pdf-setmetatable", + "heading": "setmetatable (table, metatable)", + "markdown": "Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) If `metatable` is **nil**, removes the metatable of the given table. If the original metatable has a `\"__metatable\"` field, raises an error.\n\nThis function returns `table`.", + "plaintext": "Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) If metatable is nil, removes the metatable of the given table. If the original metatable has a \"__metatable\" field, raises an error.\n\nThis function returns table." + }, + { + "name": "tonumber", + "kind": "function", + "section": "6.1", + "anchor": "pdf-tonumber", + "heading": "tonumber (e [, base])", + "markdown": "When called with no `base`, `tonumber` tries to convert its argument to a number. If the argument is already a number or a string convertible to a number (see [§3.4.2](https://www.lua.org/manual/5.2/manual.html#3.4.2)), then `tonumber` returns this number; otherwise, it returns **nil**.\n\nWhen called with `base`, then `e` should be a string to be interpreted as an integer numeral in that base. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter '`A`' (in either upper or lower case) represents 10, '`B`' represents 11, and so forth, with '`Z`' representing 35. If the string `e` is not a valid numeral in the given base, the function returns **nil**.", + "plaintext": "When called with no base, tonumber tries to convert its argument to a number. If the argument is already a number or a string convertible to a number (see §3.4.2 (https://www.lua.org/manual/5.2/manual.html#3.4.2)), then tonumber returns this number; otherwise, it returns nil.\n\nWhen called with base, then e should be a string to be interpreted as an integer numeral in that base. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. If the string e is not a valid numeral in the given base, the function returns nil." + }, + { + "name": "tostring", + "kind": "function", + "section": "6.1", + "anchor": "pdf-tostring", + "heading": "tostring (v)", + "markdown": "Receives a value of any type and converts it to a string in a reasonable format. (For complete control of how numbers are converted, use [`string.format`](https://www.lua.org/manual/5.2/manual.html#pdf-string.format).)\n\nIf the metatable of `v` has a `\"__tostring\"` field, then `tostring` calls the corresponding value with `v` as argument, and uses the result of the call as its result.", + "plaintext": "Receives a value of any type and converts it to a string in a reasonable format. (For complete control of how numbers are converted, use string.format (https://www.lua.org/manual/5.2/manual.html#pdf-string.format).)\n\nIf the metatable of v has a \"__tostring\" field, then tostring calls the corresponding value with v as argument, and uses the result of the call as its result." + }, + { + "name": "type", + "kind": "function", + "section": "6.1", + "anchor": "pdf-type", + "heading": "type (v)", + "markdown": "Returns the type of its only argument, coded as a string. The possible results of this function are \"`nil`\" (a string, not the value **nil**), \"`number`\", \"`string`\", \"`boolean`\", \"`table`\", \"`function`\", \"`thread`\", and \"`userdata`\".", + "plaintext": "Returns the type of its only argument, coded as a string. The possible results of this function are \"nil\" (a string, not the value nil), \"number\", \"string\", \"boolean\", \"table\", \"function\", \"thread\", and \"userdata\"." + }, + { + "name": "_VERSION", + "kind": "value", + "section": "6.1", + "anchor": "pdf-_VERSION", + "heading": "_VERSION", + "markdown": "A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is \"`Lua 5.2`\".", + "plaintext": "A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is \"Lua 5.2\"." + }, + { + "name": "xpcall", + "kind": "function", + "section": "6.1", + "anchor": "pdf-xpcall", + "heading": "xpcall (f, msgh [, arg1, ···])", + "markdown": "This function is similar to [`pcall`](https://www.lua.org/manual/5.2/manual.html#pdf-pcall), except that it sets a new message handler `msgh`.", + "plaintext": "This function is similar to pcall (https://www.lua.org/manual/5.2/manual.html#pdf-pcall), except that it sets a new message handler msgh." + }, + { + "name": "string", + "kind": "module", + "section": "6.4", + "anchor": "6.4", + "heading": "string", + "markdown": "This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.\n\nThe string library provides all its functions inside the table `string`. It also sets a metatable for strings where the `__index` field points to the `string` table. Therefore, you can use the string functions in object-oriented style. For instance, `string.byte(s,i)` can be written as `s:byte(i)`.\n\nThe string library assumes one-byte character encodings.", + "plaintext": "This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.\n\nThe string library provides all its functions inside the table string. It also sets a metatable for strings where the __index field points to the string table. Therefore, you can use the string functions in object-oriented style. For instance, string.byte(s,i) can be written as s:byte(i).\n\nThe string library assumes one-byte character encodings." + }, + { + "name": "string.byte", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.byte", + "heading": "string.byte (s [, i [, j]])", + "markdown": "Returns the internal numerical codes of the characters `s[i]`, `s[i+1]`, ..., `s[j]`. The default value for `i` is 1; the default value for `j` is `i`. These indices are corrected following the same rules of function [`string.sub`](https://www.lua.org/manual/5.2/manual.html#pdf-string.sub).\n\nNumerical codes are not necessarily portable across platforms.", + "plaintext": "Returns the internal numerical codes of the characters s[i], s[i+1], ..., s[j]. The default value for i is 1; the default value for j is i. These indices are corrected following the same rules of function string.sub (https://www.lua.org/manual/5.2/manual.html#pdf-string.sub).\n\nNumerical codes are not necessarily portable across platforms." + }, + { + "name": "string.char", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.char", + "heading": "string.char (···)", + "markdown": "Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.\n\nNumerical codes are not necessarily portable across platforms.", + "plaintext": "Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.\n\nNumerical codes are not necessarily portable across platforms." + }, + { + "name": "string.dump", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.dump", + "heading": "string.dump (function)", + "markdown": "Returns a string containing a binary representation of the given function, so that a later [`load`](https://www.lua.org/manual/5.2/manual.html#pdf-load) on this string returns a copy of the function (but with new upvalues).", + "plaintext": "Returns a string containing a binary representation of the given function, so that a later load (https://www.lua.org/manual/5.2/manual.html#pdf-load) on this string returns a copy of the function (but with new upvalues)." + }, + { + "name": "string.find", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.find", + "heading": "string.find (s, pattern [, init [, plain]])", + "markdown": "Looks for the first match of `pattern` in the string `s`. If it finds a match, then `find` returns the indices of `s` where this occurrence starts and ends; otherwise, it returns **nil**. A third, optional numerical argument `init` specifies where to start the search; its default value is 1 and can be negative. A value of **true** as a fourth, optional argument `plain` turns off the pattern matching facilities, so the function does a plain \"find substring\" operation, with no characters in `pattern` being considered magic. Note that if `plain` is given, then `init` must be given as well.\n\nIf the pattern has captures, then in a successful match the captured values are also returned, after the two indices.", + "plaintext": "Looks for the first match of pattern in the string s. If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain \"find substring\" operation, with no characters in pattern being considered magic. Note that if plain is given, then init must be given as well.\n\nIf the pattern has captures, then in a successful match the captured values are also returned, after the two indices." + }, + { + "name": "string.format", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.format", + "heading": "string.format (formatstring, ···)", + "markdown": "Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the ISO C function `sprintf`. The only differences are that the options/modifiers `*`, `h`, `L`, `l`, `n`, and `p` are not supported and that there is an extra option, `q`. The `q` option formats a string between double quotes, using escape sequences when necessary to ensure that it can safely be read back by the Lua interpreter. For instance, the call\n\n```\n string.format('%q', 'a string with \"quotes\" and \\n new line')\n```\n\nmay produce the string:\n\n```\n \"a string with \\\"quotes\\\" and \\\n new line\"\n```\n\nOptions `A` and `a` (when available), `E`, `e`, `f`, `G`, and `g` all expect a number as argument. Options `c`, `d`, `i`, `o`, `u`, `X`, and `x` also expect a number, but the range of that number may be limited by the underlying C implementation. For options `o`, `u`, `X`, and `x`, the number cannot be negative. Option `q` expects a string; option `s` expects a string without embedded zeros. If the argument to option `s` is not a string, it is converted to one following the same rules of [`tostring`](https://www.lua.org/manual/5.2/manual.html#pdf-tostring).", + "plaintext": "Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the ISO C function sprintf. The only differences are that the options/modifiers *, h, L, l, n, and p are not supported and that there is an extra option, q. The q option formats a string between double quotes, using escape sequences when necessary to ensure that it can safely be read back by the Lua interpreter. For instance, the call\n\n string.format('%q', 'a string with \"quotes\" and \\n new line')\n\nmay produce the string:\n\n \"a string with \\\"quotes\\\" and \\\n new line\"\n\nOptions A and a (when available), E, e, f, G, and g all expect a number as argument. Options c, d, i, o, u, X, and x also expect a number, but the range of that number may be limited by the underlying C implementation. For options o, u, X, and x, the number cannot be negative. Option q expects a string; option s expects a string without embedded zeros. If the argument to option s is not a string, it is converted to one following the same rules of tostring (https://www.lua.org/manual/5.2/manual.html#pdf-tostring)." + }, + { + "name": "string.gmatch", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.gmatch", + "heading": "string.gmatch (s, pattern)", + "markdown": "Returns an iterator function that, each time it is called, returns the next captures from `pattern` over the string `s`. If `pattern` specifies no captures, then the whole match is produced in each call.\n\nAs an example, the following loop will iterate over all the words from string `s`, printing one per line:\n\n```\n s = \"hello world from Lua\"\n for w in string.gmatch(s, \"%a+\") do\n print(w)\n end\n```\n\nThe next example collects all pairs `key=value` from the given string into a table:\n\n```\n t = {}\n s = \"from=world, to=Lua\"\n for k, v in string.gmatch(s, \"(%w+)=(%w+)\") do\n t[k] = v\n end\n```\n\nFor this function, a caret '`^`' at the start of a pattern does not work as an anchor, as this would prevent the iteration.", + "plaintext": "Returns an iterator function that, each time it is called, returns the next captures from pattern over the string s. If pattern specifies no captures, then the whole match is produced in each call.\n\nAs an example, the following loop will iterate over all the words from string s, printing one per line:\n\n s = \"hello world from Lua\"\n for w in string.gmatch(s, \"%a+\") do\n print(w)\n end\n\nThe next example collects all pairs key=value from the given string into a table:\n\n t = {}\n s = \"from=world, to=Lua\"\n for k, v in string.gmatch(s, \"(%w+)=(%w+)\") do\n t[k] = v\n end\n\nFor this function, a caret '^' at the start of a pattern does not work as an anchor, as this would prevent the iteration." + }, + { + "name": "string.gsub", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.gsub", + "heading": "string.gsub (s, pattern, repl [, n])", + "markdown": "Returns a copy of `s` in which all (or the first `n`, if given) occurrences of the `pattern` have been replaced by a replacement string specified by `repl`, which can be a string, a table, or a function. `gsub` also returns, as its second value, the total number of matches that occurred. The name `gsub` comes from *Global SUBstitution*.\n\nIf `repl` is a string, then its value is used for replacement. The character `%` works as an escape character: any sequence in `repl` of the form `%`*`d`*, with *d* between 1 and 9, stands for the value of the *d*-th captured substring. The sequence `%0` stands for the whole match. The sequence `%%` stands for a single `%`.\n\nIf `repl` is a table, then the table is queried for every match, using the first capture as the key.\n\nIf `repl` is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.\n\nIn any case, if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture.\n\nIf the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is **false** or **nil**, then there is no replacement (that is, the original match is kept in the string).\n\nHere are some examples:\n\n```\n x = string.gsub(\"hello world\", \"(%w+)\", \"%1 %1\")\n --> x=\"hello hello world world\"\n \n x = string.gsub(\"hello world\", \"%w+\", \"%0 %0\", 1)\n --> x=\"hello hello world\"\n \n x = string.gsub(\"hello world from Lua\", \"(%w+)%s*(%w+)\", \"%2 %1\")\n --> x=\"world hello Lua from\"\n \n x = string.gsub(\"home = $HOME, user = $USER\", \"%$(%w+)\", os.getenv)\n --> x=\"home = /home/roberto, user = roberto\"\n \n x = string.gsub(\"4+5 = $return 4+5$\", \"%$(.-)%$\", function (s)\n return load(s)()\n end)\n --> x=\"4+5 = 9\"\n \n local t = {name=\"lua\", version=\"5.2\"}\n x = string.gsub(\"$name-$version.tar.gz\", \"%$(%w+)\", t)\n --> x=\"lua-5.2.tar.gz\"\n```", + "plaintext": "Returns a copy of s in which all (or the first n, if given) occurrences of the pattern have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred. The name gsub comes from Global SUBstitution.\n\nIf repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %d, with d between 1 and 9, stands for the value of the d-th captured substring. The sequence %0 stands for the whole match. The sequence %% stands for a single %.\n\nIf repl is a table, then the table is queried for every match, using the first capture as the key.\n\nIf repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.\n\nIn any case, if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture.\n\nIf the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).\n\nHere are some examples:\n\n x = string.gsub(\"hello world\", \"(%w+)\", \"%1 %1\")\n --> x=\"hello hello world world\"\n \n x = string.gsub(\"hello world\", \"%w+\", \"%0 %0\", 1)\n --> x=\"hello hello world\"\n \n x = string.gsub(\"hello world from Lua\", \"(%w+)%s*(%w+)\", \"%2 %1\")\n --> x=\"world hello Lua from\"\n \n x = string.gsub(\"home = $HOME, user = $USER\", \"%$(%w+)\", os.getenv)\n --> x=\"home = /home/roberto, user = roberto\"\n \n x = string.gsub(\"4+5 = $return 4+5$\", \"%$(.-)%$\", function (s)\n return load(s)()\n end)\n --> x=\"4+5 = 9\"\n \n local t = {name=\"lua\", version=\"5.2\"}\n x = string.gsub(\"$name-$version.tar.gz\", \"%$(%w+)\", t)\n --> x=\"lua-5.2.tar.gz\"" + }, + { + "name": "string.len", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.len", + "heading": "string.len (s)", + "markdown": "Receives a string and returns its length. The empty string `\"\"` has length 0. Embedded zeros are counted, so `\"a\\000bc\\000\"` has length 5.", + "plaintext": "Receives a string and returns its length. The empty string \"\" has length 0. Embedded zeros are counted, so \"a\\000bc\\000\" has length 5." + }, + { + "name": "string.lower", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.lower", + "heading": "string.lower (s)", + "markdown": "Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.", + "plaintext": "Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale." + }, + { + "name": "string.match", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.match", + "heading": "string.match (s, pattern [, init])", + "markdown": "Looks for the first *match* of `pattern` in the string `s`. If it finds one, then `match` returns the captures from the pattern; otherwise it returns **nil**. If `pattern` specifies no captures, then the whole match is returned. A third, optional numerical argument `init` specifies where to start the search; its default value is 1 and can be negative.", + "plaintext": "Looks for the first match of pattern in the string s. If it finds one, then match returns the captures from the pattern; otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative." + }, + { + "name": "string.rep", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.rep", + "heading": "string.rep (s, n [, sep])", + "markdown": "Returns a string that is the concatenation of `n` copies of the string `s` separated by the string `sep`. The default value for `sep` is the empty string (that is, no separator).", + "plaintext": "Returns a string that is the concatenation of n copies of the string s separated by the string sep. The default value for sep is the empty string (that is, no separator)." + }, + { + "name": "string.reverse", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.reverse", + "heading": "string.reverse (s)", + "markdown": "Returns a string that is the string `s` reversed.", + "plaintext": "Returns a string that is the string s reversed." + }, + { + "name": "string.sub", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.sub", + "heading": "string.sub (s, i [, j])", + "markdown": "Returns the substring of `s` that starts at `i` and continues until `j`; `i` and `j` can be negative. If `j` is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call `string.sub(s,1,j)` returns a prefix of `s` with length `j`, and `string.sub(s, -i)` returns a suffix of `s` with length `i`.\n\nIf, after the translation of negative indices, `i` is less than 1, it is corrected to 1. If `j` is greater than the string length, it is corrected to that length. If, after these corrections, `i` is greater than `j`, the function returns the empty string.", + "plaintext": "Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.\n\nIf, after the translation of negative indices, i is less than 1, it is corrected to 1. If j is greater than the string length, it is corrected to that length. If, after these corrections, i is greater than j, the function returns the empty string." + }, + { + "name": "string.upper", + "kind": "function", + "section": "6.4", + "anchor": "pdf-string.upper", + "heading": "string.upper (s)", + "markdown": "Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.", + "plaintext": "Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale." + }, + { + "name": "table", + "kind": "module", + "section": "6.5", + "anchor": "6.5", + "heading": "table", + "markdown": "This library provides generic functions for table manipulation. It provides all its functions inside the table `table`.\n\nRemember that, whenever an operation needs the length of a table, the table should be a proper sequence or have a `__len` metamethod (see [§3.4.6](https://www.lua.org/manual/5.2/manual.html#3.4.6)). All functions ignore non-numeric keys in tables given as arguments.\n\nFor performance reasons, all table accesses (get/set) performed by these functions are raw.", + "plaintext": "This library provides generic functions for table manipulation. It provides all its functions inside the table table.\n\nRemember that, whenever an operation needs the length of a table, the table should be a proper sequence or have a __len metamethod (see §3.4.6 (https://www.lua.org/manual/5.2/manual.html#3.4.6)). All functions ignore non-numeric keys in tables given as arguments.\n\nFor performance reasons, all table accesses (get/set) performed by these functions are raw." + }, + { + "name": "table.concat", + "kind": "function", + "section": "6.5", + "anchor": "pdf-table.concat", + "heading": "table.concat (list [, sep [, i [, j]]])", + "markdown": "Given a list where all elements are strings or numbers, returns the string `list[i]..sep..list[i+1] ··· sep..list[j]`. The default value for `sep` is the empty string, the default for `i` is 1, and the default for `j` is `#list`. If `i` is greater than `j`, returns the empty string.", + "plaintext": "Given a list where all elements are strings or numbers, returns the string list[i]..sep..list[i+1] ··· sep..list[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is #list. If i is greater than j, returns the empty string." + }, + { + "name": "table.insert", + "kind": "function", + "section": "6.5", + "anchor": "pdf-table.insert", + "heading": "table.insert (list, [pos,] value)", + "markdown": "Inserts element `value` at position `pos` in `list`, shifting up the elements `list[pos], list[pos+1], ···, list[#list]`. The default value for `pos` is `#list+1`, so that a call `table.insert(t,x)` inserts `x` at the end of list `t`.", + "plaintext": "Inserts element value at position pos in list, shifting up the elements list[pos], list[pos+1], ···, list[#list]. The default value for pos is #list+1, so that a call table.insert(t,x) inserts x at the end of list t." + }, + { + "name": "table.pack", + "kind": "function", + "section": "6.5", + "anchor": "pdf-table.pack", + "heading": "table.pack (···)", + "markdown": "Returns a new table with all parameters stored into keys 1, 2, etc. and with a field \"`n`\" with the total number of parameters. Note that the resulting table may not be a sequence.", + "plaintext": "Returns a new table with all parameters stored into keys 1, 2, etc. and with a field \"n\" with the total number of parameters. Note that the resulting table may not be a sequence." + }, + { + "name": "table.remove", + "kind": "function", + "section": "6.5", + "anchor": "pdf-table.remove", + "heading": "table.remove (list [, pos])", + "markdown": "Removes from `list` the element at position `pos`, returning the value of the removed element. When `pos` is an integer between 1 and `#list`, it shifts down the elements `list[pos+1], list[pos+2], ···, list[#list]` and erases element `list[#list]`; The index `pos` can also be 0 when `#list` is 0, or `#list + 1`; in those cases, the function erases the element `list[pos]`.\n\nThe default value for `pos` is `#list`, so that a call `table.remove(t)` removes the last element of list `t`.", + "plaintext": "Removes from list the element at position pos, returning the value of the removed element. When pos is an integer between 1 and #list, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list] and erases element list[#list]; The index pos can also be 0 when #list is 0, or #list + 1; in those cases, the function erases the element list[pos].\n\nThe default value for pos is #list, so that a call table.remove(t) removes the last element of list t." + }, + { + "name": "table.sort", + "kind": "function", + "section": "6.5", + "anchor": "pdf-table.sort", + "heading": "table.sort (list [, comp])", + "markdown": "Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. If `comp` is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order (so that `not comp(list[i+1],list[i])` will be true after the sort). If `comp` is not given, then the standard Lua operator `<` is used instead.\n\nThe sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.", + "plaintext": "Sorts list elements in a given order, in-place, from list[1] to list[#list]. If comp is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order (so that not comp(list[i+1],list[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.\n\nThe sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort." + }, + { + "name": "table.unpack", + "kind": "function", + "section": "6.5", + "anchor": "pdf-table.unpack", + "heading": "table.unpack (list [, i [, j]])", + "markdown": "Returns the elements from the given table. This function is equivalent to\n\n```\n return list[i], list[i+1], ···, list[j]\n```\n\nBy default, `i` is 1 and `j` is `#list`.", + "plaintext": "Returns the elements from the given table. This function is equivalent to\n\n return list[i], list[i+1], ···, list[j]\n\nBy default, i is 1 and j is #list." + }, + { + "name": "math", + "kind": "module", + "section": "6.6", + "anchor": "6.6", + "heading": "math", + "markdown": "This library is an interface to the standard C math library. It provides all its functions inside the table `math`.", + "plaintext": "This library is an interface to the standard C math library. It provides all its functions inside the table math." + }, + { + "name": "math.abs", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.abs", + "heading": "math.abs (x)", + "markdown": "Returns the absolute value of `x`.", + "plaintext": "Returns the absolute value of x." + }, + { + "name": "math.acos", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.acos", + "heading": "math.acos (x)", + "markdown": "Returns the arc cosine of `x` (in radians).", + "plaintext": "Returns the arc cosine of x (in radians)." + }, + { + "name": "math.asin", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.asin", + "heading": "math.asin (x)", + "markdown": "Returns the arc sine of `x` (in radians).", + "plaintext": "Returns the arc sine of x (in radians)." + }, + { + "name": "math.atan", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.atan", + "heading": "math.atan (x)", + "markdown": "Returns the arc tangent of `x` (in radians).", + "plaintext": "Returns the arc tangent of x (in radians)." + }, + { + "name": "math.atan2", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.atan2", + "heading": "math.atan2 (y, x)", + "markdown": "Returns the arc tangent of `y/x` (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of `x` being zero.)", + "plaintext": "Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of x being zero.)" + }, + { + "name": "math.ceil", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.ceil", + "heading": "math.ceil (x)", + "markdown": "Returns the smallest integer larger than or equal to `x`.", + "plaintext": "Returns the smallest integer larger than or equal to x." + }, + { + "name": "math.cos", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.cos", + "heading": "math.cos (x)", + "markdown": "Returns the cosine of `x` (assumed to be in radians).", + "plaintext": "Returns the cosine of x (assumed to be in radians)." + }, + { + "name": "math.cosh", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.cosh", + "heading": "math.cosh (x)", + "markdown": "Returns the hyperbolic cosine of `x`.", + "plaintext": "Returns the hyperbolic cosine of x." + }, + { + "name": "math.deg", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.deg", + "heading": "math.deg (x)", + "markdown": "Returns the angle `x` (given in radians) in degrees.", + "plaintext": "Returns the angle x (given in radians) in degrees." + }, + { + "name": "math.exp", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.exp", + "heading": "math.exp (x)", + "markdown": "Returns the value *eˣ*.", + "plaintext": "Returns the value eˣ." + }, + { + "name": "math.floor", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.floor", + "heading": "math.floor (x)", + "markdown": "Returns the largest integer smaller than or equal to `x`.", + "plaintext": "Returns the largest integer smaller than or equal to x." + }, + { + "name": "math.fmod", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.fmod", + "heading": "math.fmod (x, y)", + "markdown": "Returns the remainder of the division of `x` by `y` that rounds the quotient towards zero.", + "plaintext": "Returns the remainder of the division of x by y that rounds the quotient towards zero." + }, + { + "name": "math.frexp", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.frexp", + "heading": "math.frexp (x)", + "markdown": "Returns `m` and `e` such that *x = m2ᵉ*, `e` is an integer and the absolute value of `m` is in the range *\\[0.5, 1)* (or zero when `x` is zero).", + "plaintext": "Returns m and e such that x = m2ᵉ, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero)." + }, + { + "name": "math.huge", + "kind": "value", + "section": "6.6", + "anchor": "pdf-math.huge", + "heading": "math.huge", + "markdown": "The value `HUGE_VAL`, a value larger than or equal to any other numerical value.", + "plaintext": "The value HUGE_VAL, a value larger than or equal to any other numerical value." + }, + { + "name": "math.ldexp", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.ldexp", + "heading": "math.ldexp (m, e)", + "markdown": "Returns *m2ᵉ* (`e` should be an integer).", + "plaintext": "Returns m2ᵉ (e should be an integer)." + }, + { + "name": "math.log", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.log", + "heading": "math.log (x [, base])", + "markdown": "Returns the logarithm of `x` in the given base. The default for `base` is *e* (so that the function returns the natural logarithm of `x`).", + "plaintext": "Returns the logarithm of x in the given base. The default for base is e (so that the function returns the natural logarithm of x)." + }, + { + "name": "math.max", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.max", + "heading": "math.max (x, ···)", + "markdown": "Returns the maximum value among its arguments.", + "plaintext": "Returns the maximum value among its arguments." + }, + { + "name": "math.min", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.min", + "heading": "math.min (x, ···)", + "markdown": "Returns the minimum value among its arguments.", + "plaintext": "Returns the minimum value among its arguments." + }, + { + "name": "math.modf", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.modf", + "heading": "math.modf (x)", + "markdown": "Returns two numbers, the integral part of `x` and the fractional part of `x`.", + "plaintext": "Returns two numbers, the integral part of x and the fractional part of x." + }, + { + "name": "math.pi", + "kind": "value", + "section": "6.6", + "anchor": "pdf-math.pi", + "heading": "math.pi", + "markdown": "The value of *π*.", + "plaintext": "The value of π." + }, + { + "name": "math.pow", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.pow", + "heading": "math.pow (x, y)", + "markdown": "Returns *xʸ*. (You can also use the expression `x^y` to compute this value.)", + "plaintext": "Returns xʸ. (You can also use the expression x^y to compute this value.)" + }, + { + "name": "math.rad", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.rad", + "heading": "math.rad (x)", + "markdown": "Returns the angle `x` (given in degrees) in radians.", + "plaintext": "Returns the angle x (given in degrees) in radians." + }, + { + "name": "math.random", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.random", + "heading": "math.random ([m [, n]])", + "markdown": "This function is an interface to the simple pseudo-random generator function `rand` provided by Standard C. (No guarantees can be given for its statistical properties.)\n\nWhen called without arguments, returns a uniform pseudo-random real number in the range *\\[0,1)*. When called with an integer number `m`, `math.random` returns a uniform pseudo-random integer in the range *\\[1, m\\]*. When called with two integer numbers `m` and `n`, `math.random` returns a uniform pseudo-random integer in the range *\\[m, n\\]*.", + "plaintext": "This function is an interface to the simple pseudo-random generator function rand provided by Standard C. (No guarantees can be given for its statistical properties.)\n\nWhen called without arguments, returns a uniform pseudo-random real number in the range [0,1). When called with an integer number m, math.random returns a uniform pseudo-random integer in the range [1, m]. When called with two integer numbers m and n, math.random returns a uniform pseudo-random integer in the range [m, n]." + }, + { + "name": "math.randomseed", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.randomseed", + "heading": "math.randomseed (x)", + "markdown": "Sets `x` as the \"seed\" for the pseudo-random generator: equal seeds produce equal sequences of numbers.", + "plaintext": "Sets x as the \"seed\" for the pseudo-random generator: equal seeds produce equal sequences of numbers." + }, + { + "name": "math.sin", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.sin", + "heading": "math.sin (x)", + "markdown": "Returns the sine of `x` (assumed to be in radians).", + "plaintext": "Returns the sine of x (assumed to be in radians)." + }, + { + "name": "math.sinh", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.sinh", + "heading": "math.sinh (x)", + "markdown": "Returns the hyperbolic sine of `x`.", + "plaintext": "Returns the hyperbolic sine of x." + }, + { + "name": "math.sqrt", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.sqrt", + "heading": "math.sqrt (x)", + "markdown": "Returns the square root of `x`. (You can also use the expression `x^0.5` to compute this value.)", + "plaintext": "Returns the square root of x. (You can also use the expression x^0.5 to compute this value.)" + }, + { + "name": "math.tan", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.tan", + "heading": "math.tan (x)", + "markdown": "Returns the tangent of `x` (assumed to be in radians).", + "plaintext": "Returns the tangent of x (assumed to be in radians)." + }, + { + "name": "math.tanh", + "kind": "function", + "section": "6.6", + "anchor": "pdf-math.tanh", + "heading": "math.tanh (x)", + "markdown": "Returns the hyperbolic tangent of `x`.", + "plaintext": "Returns the hyperbolic tangent of x." + }, + { + "name": "bit32", + "kind": "module", + "section": "6.7", + "anchor": "6.7", + "heading": "bit32", + "markdown": "This library provides bitwise operations. It provides all its functions inside the table `bit32`.\n\nUnless otherwise stated, all functions accept numeric arguments in the range *(-2⁵¹,+2⁵¹)*; each argument is normalized to the remainder of its division by *2³²* and truncated to an integer (in some unspecified way), so that its final value falls in the range *\\[0,2³² - 1\\]*. Similarly, all results are in the range *\\[0,2³² - 1\\]*. Note that `bit32.bnot(0)` is `0xFFFFFFFF`, which is different from `-1`.", + "plaintext": "This library provides bitwise operations. It provides all its functions inside the table bit32.\n\nUnless otherwise stated, all functions accept numeric arguments in the range (-2⁵¹,+2⁵¹); each argument is normalized to the remainder of its division by 2³² and truncated to an integer (in some unspecified way), so that its final value falls in the range [0,2³² - 1]. Similarly, all results are in the range [0,2³² - 1]. Note that bit32.bnot(0) is 0xFFFFFFFF, which is different from -1." + }, + { + "name": "bit32.arshift", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.arshift", + "heading": "bit32.arshift (x, disp)", + "markdown": "Returns the number `x` shifted `disp` bits to the right. The number `disp` may be any representable integer. Negative displacements shift to the left.\n\nThis shift operation is what is called arithmetic shift. Vacant bits on the left are filled with copies of the higher bit of `x`; vacant bits on the right are filled with zeros. In particular, displacements with absolute values higher than 31 result in zero or `0xFFFFFFFF` (all original bits are shifted out).", + "plaintext": "Returns the number x shifted disp bits to the right. The number disp may be any representable integer. Negative displacements shift to the left.\n\nThis shift operation is what is called arithmetic shift. Vacant bits on the left are filled with copies of the higher bit of x; vacant bits on the right are filled with zeros. In particular, displacements with absolute values higher than 31 result in zero or 0xFFFFFFFF (all original bits are shifted out)." + }, + { + "name": "bit32.band", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.band", + "heading": "bit32.band (···)", + "markdown": "Returns the bitwise *and* of its operands.", + "plaintext": "Returns the bitwise and of its operands." + }, + { + "name": "bit32.bnot", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.bnot", + "heading": "bit32.bnot (x)", + "markdown": "Returns the bitwise negation of `x`. For any integer `x`, the following identity holds:\n\n```\n assert(bit32.bnot(x) == (-1 - x) % 2^32)\n```", + "plaintext": "Returns the bitwise negation of x. For any integer x, the following identity holds:\n\n assert(bit32.bnot(x) == (-1 - x) % 2^32)" + }, + { + "name": "bit32.bor", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.bor", + "heading": "bit32.bor (···)", + "markdown": "Returns the bitwise *or* of its operands.", + "plaintext": "Returns the bitwise or of its operands." + }, + { + "name": "bit32.btest", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.btest", + "heading": "bit32.btest (···)", + "markdown": "Returns a boolean signaling whether the bitwise *and* of its operands is different from zero.", + "plaintext": "Returns a boolean signaling whether the bitwise and of its operands is different from zero." + }, + { + "name": "bit32.bxor", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.bxor", + "heading": "bit32.bxor (···)", + "markdown": "Returns the bitwise *exclusive or* of its operands.", + "plaintext": "Returns the bitwise exclusive or of its operands." + }, + { + "name": "bit32.extract", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.extract", + "heading": "bit32.extract (n, field [, width])", + "markdown": "Returns the unsigned number formed by the bits `field` to `field + width - 1` from `n`. Bits are numbered from 0 (least significant) to 31 (most significant). All accessed bits must be in the range *\\[0, 31\\]*.\n\nThe default for `width` is 1.", + "plaintext": "Returns the unsigned number formed by the bits field to field + width - 1 from n. Bits are numbered from 0 (least significant) to 31 (most significant). All accessed bits must be in the range [0, 31].\n\nThe default for width is 1." + }, + { + "name": "bit32.replace", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.replace", + "heading": "bit32.replace (n, v, field [, width])", + "markdown": "Returns a copy of `n` with the bits `field` to `field + width - 1` replaced by the value `v`. See [`bit32.extract`](https://www.lua.org/manual/5.2/manual.html#pdf-bit32.extract) for details about `field` and `width`.", + "plaintext": "Returns a copy of n with the bits field to field + width - 1 replaced by the value v. See bit32.extract (https://www.lua.org/manual/5.2/manual.html#pdf-bit32.extract) for details about field and width." + }, + { + "name": "bit32.lrotate", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.lrotate", + "heading": "bit32.lrotate (x, disp)", + "markdown": "Returns the number `x` rotated `disp` bits to the left. The number `disp` may be any representable integer.\n\nFor any valid displacement, the following identity holds:\n\n```\n assert(bit32.lrotate(x, disp) == bit32.lrotate(x, disp % 32))\n```\n\nIn particular, negative displacements rotate to the right.", + "plaintext": "Returns the number x rotated disp bits to the left. The number disp may be any representable integer.\n\nFor any valid displacement, the following identity holds:\n\n assert(bit32.lrotate(x, disp) == bit32.lrotate(x, disp % 32))\n\nIn particular, negative displacements rotate to the right." + }, + { + "name": "bit32.lshift", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.lshift", + "heading": "bit32.lshift (x, disp)", + "markdown": "Returns the number `x` shifted `disp` bits to the left. The number `disp` may be any representable integer. Negative displacements shift to the right. In any direction, vacant bits are filled with zeros. In particular, displacements with absolute values higher than 31 result in zero (all bits are shifted out).\n\nFor positive displacements, the following equality holds:\n\n```\n assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)\n```", + "plaintext": "Returns the number x shifted disp bits to the left. The number disp may be any representable integer. Negative displacements shift to the right. In any direction, vacant bits are filled with zeros. In particular, displacements with absolute values higher than 31 result in zero (all bits are shifted out).\n\nFor positive displacements, the following equality holds:\n\n assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)" + }, + { + "name": "bit32.rrotate", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.rrotate", + "heading": "bit32.rrotate (x, disp)", + "markdown": "Returns the number `x` rotated `disp` bits to the right. The number `disp` may be any representable integer.\n\nFor any valid displacement, the following identity holds:\n\n```\n assert(bit32.rrotate(x, disp) == bit32.rrotate(x, disp % 32))\n```\n\nIn particular, negative displacements rotate to the left.", + "plaintext": "Returns the number x rotated disp bits to the right. The number disp may be any representable integer.\n\nFor any valid displacement, the following identity holds:\n\n assert(bit32.rrotate(x, disp) == bit32.rrotate(x, disp % 32))\n\nIn particular, negative displacements rotate to the left." + }, + { + "name": "bit32.rshift", + "kind": "function", + "section": "6.7", + "anchor": "pdf-bit32.rshift", + "heading": "bit32.rshift (x, disp)", + "markdown": "Returns the number `x` shifted `disp` bits to the right. The number `disp` may be any representable integer. Negative displacements shift to the left. In any direction, vacant bits are filled with zeros. In particular, displacements with absolute values higher than 31 result in zero (all bits are shifted out).\n\nFor positive displacements, the following equality holds:\n\n```\n assert(bit32.rshift(b, disp) == math.floor(b % 2^32 / 2^disp))\n```\n\nThis shift operation is what is called logical shift.", + "plaintext": "Returns the number x shifted disp bits to the right. The number disp may be any representable integer. Negative displacements shift to the left. In any direction, vacant bits are filled with zeros. In particular, displacements with absolute values higher than 31 result in zero (all bits are shifted out).\n\nFor positive displacements, the following equality holds:\n\n assert(bit32.rshift(b, disp) == math.floor(b % 2^32 / 2^disp))\n\nThis shift operation is what is called logical shift." + }, + { + "name": "debug", + "kind": "module", + "section": "6.10", + "anchor": "6.10", + "heading": "debug", + "markdown": "This library provides the functionality of the debug interface ([§4.9](https://www.lua.org/manual/5.2/manual.html#4.9)) to Lua programs. You should exert care when using this library. Several of its functions violate basic assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside; that userdata metatables cannot be changed by Lua code; that Lua programs do not crash) and therefore can compromise otherwise secure code. Moreover, some functions in this library may be slow.\n\nAll functions in this library are provided inside the `debug` table. All functions that operate over a thread have an optional first argument which is the thread to operate over. The default is always the current thread.", + "plaintext": "This library provides the functionality of the debug interface (§4.9 (https://www.lua.org/manual/5.2/manual.html#4.9)) to Lua programs. You should exert care when using this library. Several of its functions violate basic assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside; that userdata metatables cannot be changed by Lua code; that Lua programs do not crash) and therefore can compromise otherwise secure code. Moreover, some functions in this library may be slow.\n\nAll functions in this library are provided inside the debug table. All functions that operate over a thread have an optional first argument which is the thread to operate over. The default is always the current thread." + }, + { + "name": "debug.debug", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.debug", + "heading": "debug.debug ()", + "markdown": "Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word `cont` finishes this function, so that the caller continues its execution.\n\nNote that commands for `debug.debug` are not lexically nested within any function and so have no direct access to local variables.", + "plaintext": "Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word cont finishes this function, so that the caller continues its execution.\n\nNote that commands for debug.debug are not lexically nested within any function and so have no direct access to local variables." + }, + { + "name": "debug.gethook", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.gethook", + "heading": "debug.gethook ([thread])", + "markdown": "Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the [`debug.sethook`](https://www.lua.org/manual/5.2/manual.html#pdf-debug.sethook) function).", + "plaintext": "Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the debug.sethook (https://www.lua.org/manual/5.2/manual.html#pdf-debug.sethook) function)." + }, + { + "name": "debug.getinfo", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.getinfo", + "heading": "debug.getinfo ([thread,] f [, what])", + "markdown": "Returns a table with information about a function. You can give the function directly or you can give a number as the value of `f`, which means the function running at level `f` of the call stack of the given thread: level 0 is the current function (`getinfo` itself); level 1 is the function that called `getinfo` (except for tail calls, which do not count on the stack); and so on. If `f` is a number larger than the number of active functions, then `getinfo` returns **nil**.\n\nThe returned table can contain all the fields returned by [`lua_getinfo`](https://www.lua.org/manual/5.2/manual.html#lua_getinfo), with the string `what` describing which fields to fill in. The default for `what` is to get all information available, except the table of valid lines. If present, the option '`f`' adds a field named `func` with the function itself. If present, the option '`L`' adds a field named `activelines` with the table of valid lines.\n\nFor instance, the expression `debug.getinfo(1,\"n\").name` returns a table with a name for the current function, if a reasonable name can be found, and the expression `debug.getinfo(print)` returns a table with all available information about the [`print`](https://www.lua.org/manual/5.2/manual.html#pdf-print) function.", + "plaintext": "Returns a table with information about a function. You can give the function directly or you can give a number as the value of f, which means the function running at level f of the call stack of the given thread: level 0 is the current function (getinfo itself); level 1 is the function that called getinfo (except for tail calls, which do not count on the stack); and so on. If f is a number larger than the number of active functions, then getinfo returns nil.\n\nThe returned table can contain all the fields returned by lua_getinfo (https://www.lua.org/manual/5.2/manual.html#lua_getinfo), with the string what describing which fields to fill in. The default for what is to get all information available, except the table of valid lines. If present, the option 'f' adds a field named func with the function itself. If present, the option 'L' adds a field named activelines with the table of valid lines.\n\nFor instance, the expression debug.getinfo(1,\"n\").name returns a table with a name for the current function, if a reasonable name can be found, and the expression debug.getinfo(print) returns a table with all available information about the print (https://www.lua.org/manual/5.2/manual.html#pdf-print) function." + }, + { + "name": "debug.getlocal", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.getlocal", + "heading": "debug.getlocal ([thread,] f, local)", + "markdown": "This function returns the name and the value of the local variable with index `local` of the function at level `f` of the stack. This function accesses not only explicit local variables, but also parameters, temporaries, etc.\n\nThe first parameter or local variable has index 1, and so on, until the last active variable. Negative indices refer to vararg parameters; -1 is the first vararg parameter. The function returns **nil** if there is no variable with the given index, and raises an error when called with a level out of range. (You can call [`debug.getinfo`](https://www.lua.org/manual/5.2/manual.html#pdf-debug.getinfo) to check whether the level is valid.)\n\nVariable names starting with '`(`' (open parenthesis) represent internal variables (loop control variables, temporaries, varargs, and C function locals).\n\nThe parameter `f` may also be a function. In that case, `getlocal` returns only the name of function parameters.", + "plaintext": "This function returns the name and the value of the local variable with index local of the function at level f of the stack. This function accesses not only explicit local variables, but also parameters, temporaries, etc.\n\nThe first parameter or local variable has index 1, and so on, until the last active variable. Negative indices refer to vararg parameters; -1 is the first vararg parameter. The function returns nil if there is no variable with the given index, and raises an error when called with a level out of range. (You can call debug.getinfo (https://www.lua.org/manual/5.2/manual.html#pdf-debug.getinfo) to check whether the level is valid.)\n\nVariable names starting with '(' (open parenthesis) represent internal variables (loop control variables, temporaries, varargs, and C function locals).\n\nThe parameter f may also be a function. In that case, getlocal returns only the name of function parameters." + }, + { + "name": "debug.getmetatable", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.getmetatable", + "heading": "debug.getmetatable (value)", + "markdown": "Returns the metatable of the given `value` or **nil** if it does not have a metatable.", + "plaintext": "Returns the metatable of the given value or nil if it does not have a metatable." + }, + { + "name": "debug.getregistry", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.getregistry", + "heading": "debug.getregistry ()", + "markdown": "Returns the registry table (see [§4.5](https://www.lua.org/manual/5.2/manual.html#4.5)).", + "plaintext": "Returns the registry table (see §4.5 (https://www.lua.org/manual/5.2/manual.html#4.5))." + }, + { + "name": "debug.getupvalue", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.getupvalue", + "heading": "debug.getupvalue (f, up)", + "markdown": "This function returns the name and the value of the upvalue with index `up` of the function `f`. The function returns **nil** if there is no upvalue with the given index.", + "plaintext": "This function returns the name and the value of the upvalue with index up of the function f. The function returns nil if there is no upvalue with the given index." + }, + { + "name": "debug.getuservalue", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.getuservalue", + "heading": "debug.getuservalue (u)", + "markdown": "Returns the Lua value associated to `u`. If `u` is not a userdata, returns **nil**.", + "plaintext": "Returns the Lua value associated to u. If u is not a userdata, returns nil." + }, + { + "name": "debug.sethook", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.sethook", + "heading": "debug.sethook ([thread,] hook, mask [, count])", + "markdown": "Sets the given function as a hook. The string `mask` and the number `count` describe when the hook will be called. The string mask may have any combination of the following characters, with the given meaning:\n\n- **'`c`':** the hook is called every time Lua calls a function;\n- **'`r`':** the hook is called every time Lua returns from a function;\n- **'`l`':** the hook is called every time Lua enters a new line of code.\n\nMoreover, with a `count` different from zero, the hook is called also after every `count` instructions.\n\nWhen called without arguments, [`debug.sethook`](https://www.lua.org/manual/5.2/manual.html#pdf-debug.sethook) turns off the hook.\n\nWhen the hook is called, its first parameter is a string describing the event that has triggered its call: `\"call\"` (or `\"tail call\"`), `\"return\"`, `\"line\"`, and `\"count\"`. For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call `getinfo` with level 2 to get more information about the running function (level 0 is the `getinfo` function, and level 1 is the hook function).", + "plaintext": "Sets the given function as a hook. The string mask and the number count describe when the hook will be called. The string mask may have any combination of the following characters, with the given meaning:\n\n- 'c': the hook is called every time Lua calls a function;\n- 'r': the hook is called every time Lua returns from a function;\n- 'l': the hook is called every time Lua enters a new line of code.\n\nMoreover, with a count different from zero, the hook is called also after every count instructions.\n\nWhen called without arguments, debug.sethook (https://www.lua.org/manual/5.2/manual.html#pdf-debug.sethook) turns off the hook.\n\nWhen the hook is called, its first parameter is a string describing the event that has triggered its call: \"call\" (or \"tail call\"), \"return\", \"line\", and \"count\". For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call getinfo with level 2 to get more information about the running function (level 0 is the getinfo function, and level 1 is the hook function)." + }, + { + "name": "debug.setlocal", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.setlocal", + "heading": "debug.setlocal ([thread,] level, local, value)", + "markdown": "This function assigns the value `value` to the local variable with index `local` of the function at level `level` of the stack. The function returns **nil** if there is no local variable with the given index, and raises an error when called with a `level` out of range. (You can call `getinfo` to check whether the level is valid.) Otherwise, it returns the name of the local variable.\n\nSee [`debug.getlocal`](https://www.lua.org/manual/5.2/manual.html#pdf-debug.getlocal) for more information about variable indices and names.", + "plaintext": "This function assigns the value value to the local variable with index local of the function at level level of the stack. The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call getinfo to check whether the level is valid.) Otherwise, it returns the name of the local variable.\n\nSee debug.getlocal (https://www.lua.org/manual/5.2/manual.html#pdf-debug.getlocal) for more information about variable indices and names." + }, + { + "name": "debug.setmetatable", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.setmetatable", + "heading": "debug.setmetatable (value, table)", + "markdown": "Sets the metatable for the given `value` to the given `table` (which can be **nil**). Returns `value`.", + "plaintext": "Sets the metatable for the given value to the given table (which can be nil). Returns value." + }, + { + "name": "debug.setupvalue", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.setupvalue", + "heading": "debug.setupvalue (f, up, value)", + "markdown": "This function assigns the value `value` to the upvalue with index `up` of the function `f`. The function returns **nil** if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.", + "plaintext": "This function assigns the value value to the upvalue with index up of the function f. The function returns nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue." + }, + { + "name": "debug.setuservalue", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.setuservalue", + "heading": "debug.setuservalue (udata, value)", + "markdown": "Sets the given `value` as the Lua value associated to the given `udata`. `value` must be a table or **nil**; `udata` must be a full userdata.\n\nReturns `udata`.", + "plaintext": "Sets the given value as the Lua value associated to the given udata. value must be a table or nil; udata must be a full userdata.\n\nReturns udata." + }, + { + "name": "debug.traceback", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.traceback", + "heading": "debug.traceback ([thread,] [message [, level]])", + "markdown": "If `message` is present but is neither a string nor **nil**, this function returns `message` without further processing. Otherwise, it returns a string with a traceback of the call stack. An optional `message` string is appended at the beginning of the traceback. An optional `level` number tells at which level to start the traceback (default is 1, the function calling `traceback`).", + "plaintext": "If message is present but is neither a string nor nil, this function returns message without further processing. Otherwise, it returns a string with a traceback of the call stack. An optional message string is appended at the beginning of the traceback. An optional level number tells at which level to start the traceback (default is 1, the function calling traceback)." + }, + { + "name": "debug.upvalueid", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.upvalueid", + "heading": "debug.upvalueid (f, n)", + "markdown": "Returns an unique identifier (as a light userdata) for the upvalue numbered `n` from the given function.\n\nThese unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices.", + "plaintext": "Returns an unique identifier (as a light userdata) for the upvalue numbered n from the given function.\n\nThese unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices." + }, + { + "name": "debug.upvaluejoin", + "kind": "function", + "section": "6.10", + "anchor": "pdf-debug.upvaluejoin", + "heading": "debug.upvaluejoin (f1, n1, f2, n2)", + "markdown": "Make the `n1`-th upvalue of the Lua closure `f1` refer to the `n2`-th upvalue of the Lua closure `f2`.", + "plaintext": "Make the n1-th upvalue of the Lua closure f1 refer to the n2-th upvalue of the Lua closure f2." + } + ] +} diff --git a/package.json b/package.json index f5474e7..93e72c8 100644 --- a/package.json +++ b/package.json @@ -124,6 +124,7 @@ "test": "vscode-test", "check-l10n": "node scripts/check-l10n.mts", "build:wasm": "node third_party/lua52/build.mts", + "lua-manual": "node scripts/lua-manual/generate.mts", "notices": "node scripts/third-party-notices.mts" }, "dependencies": { diff --git a/scripts/lua-manual/generate.mts b/scripts/lua-manual/generate.mts new file mode 100644 index 0000000..e1d8769 --- /dev/null +++ b/scripts/lua-manual/generate.mts @@ -0,0 +1,221 @@ +// Generates data/lua52/manual.json, the Lua 5.2 library reference shown in +// hovers, from the official manual. +// +// npm run lua-manual regenerate the data file +// npm run lua-manual -- --check fail if the committed file differs from a fresh run +// npm run lua-manual -- --compare-online report whether https://www.lua.org/manual/5.2/ +// gives the same entries (manual audit; not run in CI) +// +// Source: lua-5.2.4/doc/manual.html from the official tarball, verified by its +// published SHA-256 (third_party/lua52/tarball.mts): the same release as the +// compiler the extension embeds. The online manual is unversioned; the audit +// option checks that it still agrees. +// +// Only the libraries the game engine opens are included (CLAUDE.md, section 7; +// IESDP "Engine Lua globals"): the basic functions (§6.1), string (§6.4), +// table (§6.5), math (§6.6), bit32 (§6.7) and debug (§6.10). Coroutines (§6.2), +// modules (§6.3, including `require`), io (§6.8) and os (§6.9) are left out. +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { fetchLuaTarball, LUA_SHA256, LUA_URL, LUA_VERSION, readTarballMember } from '../../third_party/lua52/tarball.mts'; +import { convertFragment, decodeEntities } from './convert.mts'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'); +const output = join(root, 'data', 'lua52', 'manual.json'); + +const MEMBER = `lua-${LUA_VERSION}/doc/manual.html`; +const ONLINE_URL = 'https://www.lua.org/manual/5.2/manual.html'; +/** Links in the data point to the online manual, the URL plan.md names. */ +const BASE_URL = ONLINE_URL; + +/** The sections included, with the module table each one documents (none for the basic functions). */ +const SECTIONS: readonly { readonly number: string; readonly module?: string }[] = [ + { number: '6.1' }, + { number: '6.4', module: 'string' }, + { number: '6.5', module: 'table' }, + { number: '6.6', module: 'math' }, + { number: '6.7', module: 'bit32' }, + { number: '6.10', module: 'debug' }, +]; + +export interface ManualSection { + readonly number: string; + readonly title: string; + readonly module?: string; +} + +export interface ManualEntry { + /** `print`, `string.format`, or the module name for a module. */ + readonly name: string; + /** `function` when the heading has a parameter list, `value` otherwise (`_G`, `math.pi`); `module` for a library table. */ + readonly kind: 'function' | 'value' | 'module'; + readonly section: string; + /** Fragment of the entry in the manual (`pdf-string.format`, or the section number for a module). */ + readonly anchor: string; + /** The heading as the manual prints it (`string.format (formatstring, ···)`); the module name for a module. */ + readonly heading: string; + readonly markdown: string; + readonly plaintext: string; +} + +export interface ManualData { + readonly source: { readonly url: string; readonly sha256: string; readonly member: string; readonly encoding: 'iso-8859-1' }; + readonly title: string; + readonly copyright: string; + readonly baseUrl: string; + readonly sections: readonly ManualSection[]; + readonly entries: readonly ManualEntry[]; +} + +class ManualFormatError extends Error {} + +function expectMatch(pattern: RegExp, html: string, what: string): RegExpExecArray { + const match = pattern.exec(html); + if (!match) { + throw new ManualFormatError(`${what} was not found (pattern ${String(pattern)}).`); + } + return match; +} + +/** Library entries of the manual's HTML: the data file's content, without `source`. */ +export function extract(html: string): Omit { + const title = decodeEntities(expectMatch(/([^<]*)<\/title>/, html, 'The title')[1] ?? '').trim(); + const copyright = decodeEntities(expectMatch(/<small>\s*(Copyright[\s\S]*?)<\/small>/, html, 'The copyright notice')[1] ?? '') + .replace(/<a href="[^"]*">([^<]*)<\/a>/g, '$1') + .replace(/[ \t\r\n]+/g, ' ') + .trim(); + const sections: ManualSection[] = []; + const entries: ManualEntry[] = []; + for (const { number, module } of SECTIONS) { + const escaped = number.replace('.', '\\.'); + const heading = expectMatch(new RegExp(`<h2>${escaped} – <a name="${escaped}">([^<]*)</a></h2>`), html, `The heading of §${number}`); + const sectionTitle = decodeEntities(heading[1] ?? ''); + sections.push(module === undefined ? { number, title: sectionTitle } : { number, title: sectionTitle, module }); + const start = heading.index + heading[0].length; + const next = html.slice(start).search(/<h[12]>/); + const body = html.slice(start, next < 0 ? undefined : start + next); + const location = (what: string): string => `§${number} ${sectionTitle}, ${what}`; + + const firstEntry = body.indexOf('<hr><h3>'); + if (firstEntry < 0) throw new ManualFormatError(`${location('entries')}: none found.`); + if (module !== undefined) { + const intro = body.slice(0, firstEntry); + if (!intro.includes(`<a name="pdf-${module}">`)) { + throw new ManualFormatError(`${location('introduction')}: no anchor "pdf-${module}" for the module table.`); + } + entries.push({ name: module, kind: 'module', section: number, anchor: number, heading: module, ...convert(intro, location('introduction')) }); + } + + const entryHeading = /<hr><h3><a name="pdf-([^"]+)"><code>([^<]*)<\/code><\/a><\/h3>/g; + const rest = body.slice(firstEntry); + for (let match = entryHeading.exec(rest); match; match = entryHeading.exec(rest)) { + const [source, name = '', rawHeading = ''] = match; + const entryStart = match.index + source.length; + const end = rest.slice(entryStart).search(/<hr>|<h[1-4]>/); + const html = rest.slice(entryStart, end < 0 ? undefined : entryStart + end); + const expected = module === undefined ? /^[A-Za-z_][A-Za-z0-9_]*$/ : new RegExp(`^${module}\\.[A-Za-z_][A-Za-z0-9_]*$`); + if (!expected.test(name)) { + throw new ManualFormatError(`${location(`entry "${name}"`)}: the name does not belong to this section.`); + } + const entryHeadingText = decodeEntities(rawHeading).replace(/[ \t\r\n]+/g, ' ').trim(); + entries.push({ + name, + kind: entryHeadingText.includes('(') ? 'function' : 'value', + section: number, + anchor: `pdf-${name}`, + heading: entryHeadingText, + ...convert(html, location(`entry "${name}"`)), + }); + } + // Every `<hr><h3>` of the section must have been an entry heading. + const headings = rest.split('<hr><h3>').length - 1; + const found = entries.filter((entry) => entry.section === number && entry.kind !== 'module').length; + if (headings !== found) { + throw new ManualFormatError(`${location('entries')}: ${headings} entry headings, but only ${found} have the expected form.`); + } + } + return { title, copyright, baseUrl: BASE_URL, sections, entries }; +} + +function convert(html: string, location: string): { markdown: string; plaintext: string } { + try { + return convertFragment(html, BASE_URL); + } catch (error) { + throw new ManualFormatError(`${location}: ${error instanceof Error ? error.message : String(error)}`); + } +} + +export function serialize(data: ManualData): string { + return `${JSON.stringify(data, null, 2)}\n`; +} + +function fail(message: string, file?: string): never { + // `::error::` renders as an annotation on GitHub Actions and reads fine locally. + console.error(`::error${file ? ` file=${relative(root, file)},` : ' '}title=Lua manual data::${message}`); + process.exit(1); +} + +async function generate(): Promise<string> { + const tarball = await fetchLuaTarball(); + const html = readTarballMember(tarball, MEMBER).toString('latin1'); + return serialize({ source: { url: LUA_URL, sha256: LUA_SHA256, member: MEMBER, encoding: 'iso-8859-1' }, ...extract(html) }); +} + +/** Differences between the entries of the tarball's manual and the online one, as readable lines. */ +async function compareOnline(): Promise<string[]> { + const tarball = await fetchLuaTarball(); + const local = extract(readTarballMember(tarball, MEMBER).toString('latin1')); + const response = await fetch(ONLINE_URL); + if (!response.ok) { + throw new Error(`GET ${ONLINE_URL} failed: HTTP ${response.status} ${response.statusText}`); + } + // Served as text/html without a charset; the page declares iso-8859-1 like the tarball's copy. + const online = extract(Buffer.from(await response.arrayBuffer()).toString('latin1')); + const differences: string[] = []; + for (const key of ['sections', 'entries'] as const) { + const a = JSON.stringify(local[key], null, 2).split('\n'); + const b = JSON.stringify(online[key], null, 2).split('\n'); + for (let i = 0; i < Math.max(a.length, b.length); i++) { + if (a[i] !== b[i]) differences.push(`${key}, line ${i + 1}:\n tarball: ${a[i] ?? '(none)'}\n online: ${b[i] ?? '(none)'}`); + } + } + if (local.title !== online.title) differences.push(`title: tarball "${local.title}", online "${online.title}"`); + if (local.copyright !== online.copyright) differences.push(`copyright: tarball "${local.copyright}", online "${online.copyright}"`); + return differences; +} + +async function main(): Promise<void> { + try { + if (process.argv.includes('--compare-online')) { + const differences = await compareOnline(); + if (differences.length === 0) { + console.log(`The library entries of ${ONLINE_URL} are identical to those of ${MEMBER}.`); + } else { + console.log(`${ONLINE_URL} differs from ${MEMBER}:\n${differences.join('\n')}`); + } + return; + } + const fresh = await generate(); + if (process.argv.includes('--check')) { + if (!existsSync(output)) { + fail(`${relative(root, output)} is missing. Run \`npm run lua-manual\` and commit the result.`, output); + } + if (readFileSync(output, 'utf8') !== fresh) { + fail(`${relative(root, output)} does not match the data generated from ${LUA_URL}. Run \`npm run lua-manual\` and commit the result.`, output); + } + console.log(`${relative(root, output)} matches the data generated from ${LUA_URL}.`); + return; + } + mkdirSync(dirname(output), { recursive: true }); + writeFileSync(output, fresh); + console.log(`Wrote ${relative(root, output)}.`); + } catch (error) { + fail(error instanceof Error ? error.message : String(error)); + } +} + +// Run only as a script, not when the tests import `extract`. +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + await main(); +} diff --git a/test/unit/scripts/lua-manual/generate.test.ts b/test/unit/scripts/lua-manual/generate.test.ts new file mode 100644 index 0000000..b397130 --- /dev/null +++ b/test/unit/scripts/lua-manual/generate.test.ts @@ -0,0 +1,137 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { extract, type ManualData } from '../../../../scripts/lua-manual/generate.mts'; + +// The committed data file; CI (`npm run lua-manual -- --check`) proves it is +// what the generator makes from the official tarball. +const data = JSON.parse(readFileSync(new URL('../../../../data/lua52/manual.json', import.meta.url), 'utf8')) as ManualData; +const entry = (name: string): ManualData['entries'][number] => { + const found = data.entries.find((candidate) => candidate.name === name); + assert.ok(found, `no entry "${name}"`); + return found; +}; +const BASE = 'https://www.lua.org/manual/5.2/manual.html'; + +describe('scripts/lua-manual/generate', () => { + describe('data/lua52/manual.json', () => { + it('records its verified source and the manual copyright', () => { + assert.deepEqual(data.source, { + url: 'https://www.lua.org/ftp/lua-5.2.4.tar.gz', + sha256: 'b9e2e4aad6789b3b63a056d442f7b39f0ecfca3ae0f1fc0ae4e9614401b69f4b', + member: 'lua-5.2.4/doc/manual.html', + encoding: 'iso-8859-1', + }); + assert.equal(data.title, 'Lua 5.2 Reference Manual'); + assert.equal(data.copyright, 'Copyright © 2011–2015 Lua.org, PUC-Rio. Freely available under the terms of the Lua license.'); + assert.equal(data.baseUrl, BASE); + }); + + it('holds exactly the libraries the game engine opens', () => { + assert.deepEqual(data.sections, [ + { number: '6.1', title: 'Basic Functions' }, + { number: '6.4', title: 'String Manipulation', module: 'string' }, + { number: '6.5', title: 'Table Manipulation', module: 'table' }, + { number: '6.6', title: 'Mathematical Functions', module: 'math' }, + { number: '6.7', title: 'Bitwise Operations', module: 'bit32' }, + { number: '6.10', title: 'The Debug Library', module: 'debug' }, + ]); + const perSection = new Map<string, number>(); + for (const { section } of data.entries) perSection.set(section, (perSection.get(section) ?? 0) + 1); + // Entries per section, module table included (counted in the manual's HTML). + assert.deepEqual(Object.fromEntries(perSection), { '6.1': 24, '6.4': 15, '6.5': 7, '6.6': 30, '6.7': 13, '6.10': 17 }); + for (const { name } of data.entries) { + assert.doesNotMatch(name, /^(coroutine|io|os|package)\b/, `${name} is not opened by the engine`); + } + for (const absent of ['require', 'module', 'unpack', 'loadstring']) { + assert.equal(data.entries.some((candidate) => candidate.name === absent), false, absent); + } + }); + + it('gives each entry a kind, anchor and verbatim heading', () => { + assert.deepEqual( + data.entries.filter((candidate) => candidate.kind === 'value').map((candidate) => candidate.name), + ['_G', '_VERSION', 'math.huge', 'math.pi'], + ); + assert.deepEqual( + data.entries.filter((candidate) => candidate.kind === 'module').map((candidate) => [candidate.name, candidate.anchor]), + [['string', '6.4'], ['table', '6.5'], ['math', '6.6'], ['bit32', '6.7'], ['debug', '6.10']], + ); + assert.equal(entry('string.format').heading, 'string.format (formatstring, ···)'); + assert.equal(entry('string.format').anchor, 'pdf-string.format'); + assert.equal(entry('debug.sethook').heading, 'debug.sethook ([thread,] hook, mask [, count])'); + }); + + it('keeps the manual text of entries', () => { + assert.equal(entry('math.huge').markdown, 'The value `HUGE_VAL`, a value larger than or equal to any other numerical value.'); + assert.equal(entry('math.exp').markdown, 'Returns the value *eˣ*.'); + assert.equal(entry('math.exp').plaintext, 'Returns the value eˣ.'); + assert.equal( + entry('select').markdown, + 'If `index` is a number, returns all arguments after argument number `index`; a negative number indexes from the end (-1 is the last argument). ' + + 'Otherwise, `index` must be the string `"#"`, and `select` returns the total number of extra arguments it received.', + ); + assert.equal( + entry('bit32.extract').markdown, + 'Returns the unsigned number formed by the bits `field` to `field + width - 1` from `n`. ' + + 'Bits are numbered from 0 (least significant) to 31 (most significant). All accessed bits must be in the range *\\[0, 31\\]*.\n\n' + + 'The default for `width` is 1.', + ); + assert.equal( + entry('table.sort').markdown, + 'Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. If `comp` is given, then it must be a function that receives two list elements ' + + 'and returns true when the first element must come before the second in the final order (so that `not comp(list[i+1],list[i])` will be true after the sort). ' + + 'If `comp` is not given, then the standard Lua operator `<` is used instead.\n\n' + + 'The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.', + ); + }); + + it('keeps lists, code blocks and links of entries', () => { + const sethook = entry('debug.sethook').markdown; + assert.ok(sethook.includes("\n\n- **'`c`':** the hook is called every time Lua calls a function;\n- **'`r`':**"), sethook); + assert.ok(sethook.includes(`[\`debug.sethook\`](${BASE}#pdf-debug.sethook) turns off the hook.`), sethook); + const collectgarbage = entry('collectgarbage').markdown; + assert.ok( + collectgarbage.includes('so the following equality is always true:\n\n ```\n k, b = collectgarbage("count")\n assert(k*1024 == math.floor(k)*1024 + b)\n ```\n\n (The second result'), + collectgarbage, + ); + assert.ok(entry('string.gsub').markdown.includes('of the form `%`*`d`*, with *d* between 1 and 9')); + assert.ok(entry('string').markdown.startsWith('This library provides generic functions for string manipulation,')); + }); + }); + + describe('extract', () => { + const page = (sections: string): string => + `<title>Manual\nCopyright © 2015 X.\nLicense.\n${sections}

    7 – End

    `; + const section = (number: string, title: string, body: string): string => `

    ${number} – ${title}

    ${body}`; + const minimal = (overrides: Record = {}): string => + page( + [ + ['6.1', '

    \nIntro.\n

    \n


    f (x)

    \nDoes x.\n'], + ...['6.4:string', '6.5:table', '6.6:math', '6.7:bit32', '6.10:debug'].map((spec) => { + const [number = '', module = ''] = spec.split(':'); + return [number, `

    \nTable ${module}.\n

    \n


    ${module}.g

    \nA value.\n`]; + }), + ] + .map(([number = '', body = '']) => section(number, `S${number}`, overrides[number] ?? body)) + .join(''), + ); + + it('reads sections, module introductions and entries', () => { + const result = extract(minimal()); + assert.equal(result.title, 'Manual'); + assert.equal(result.copyright, 'Copyright © 2015 X. License.'); + assert.equal(result.entries.length, 11); + assert.deepEqual(result.entries[0], { name: 'f', kind: 'function', section: '6.1', anchor: 'pdf-f', heading: 'f (x)', markdown: 'Does `x`.', plaintext: 'Does x.' }); + assert.deepEqual(result.entries[1], { name: 'string', kind: 'module', section: '6.4', anchor: '6.4', heading: 'string', markdown: 'Table `string`.', plaintext: 'Table string.' }); + assert.equal(result.entries[2]?.kind, 'value'); + }); + + it('fails on a missing section, a foreign entry, an unexpected heading or unsupported HTML', () => { + assert.throws(() => extract(page('')), /The heading of §6\.1 was not found/); + assert.throws(() => extract(minimal({ '6.4': '

    \ns


    os.time ()

    \n' })), /entry "os\.time": the name does not belong/); + assert.throws(() => extract(minimal({ '6.4': '

    \nNo anchor.


    string.g

    \n' })), /no anchor "pdf-string"/); + assert.throws(() => extract(minimal({ '6.1': '

    \n


    f

    \nx\n

    Other

    \n' })), /2 entry headings, but only 1/); + assert.throws(() => extract(minimal({ '6.1': '

    \n


    f

    \n
    \n' })), /entry "f": Unsupported tag /); + }); + }); +}); From 292bb48a20086e84830b91fdbcd6ea196ce30035 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:53:18 +0100 Subject: [PATCH 04/15] ci: check that the Lua manual data matches the official tarball New job "Lua 5.2 manual data is current" runs `npm run lua-manual -- --check`, so data/lua52/manual.json can only change together with the generator or the pinned tarball. It is cheap: - it runs only when scripts/lua-manual/, data/lua52/, third_party/lua52/tarball.mts or ci.yml change (new `manual` output of the `changes` job; every job runs when there is no usable base); - no `npm ci`: the generator uses only Node built-ins and `tar`; - 5-minute timeout. The Lua tarball now has its own cache, keyed by the hash of tarball.mts (which pins the URL and SHA-256), shared by this job and the `wasm` job. Before, it was stored inside the emsdk cache entry. The emsdk cache now holds only .cache/emsdk; its path changed, so the first run after this commit misses it once. Errors are reported as `::error title=Lua manual data::` annotations naming the file and the command that fixes it. Checked with actionlint 1.7.12 (shellcheck is not installed locally, so the run steps were not shell-linted). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 43 +++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c4dd44..8299b1d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,7 @@ # - One Linux runner per job; jobs that only matter for some paths are skipped # by the `changes` job (workflow-level `paths:` filters are not used because a # skipped workflow never reports, which blocks required status checks). -# - npm, VS Code test builds and emsdk are cached. +# - npm, VS Code test builds, emsdk and the Lua source tarball are cached. # - Superseded pull request runs are cancelled. # Failures are reported as file/line annotations (setup-node's tsc and ESLint # problem matchers, and `::error` lines from scripts/). @@ -33,6 +33,7 @@ jobs: outputs: code: ${{ steps.diff.outputs.code }} wasm: ${{ steps.diff.outputs.wasm }} + manual: ${{ steps.diff.outputs.manual }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -49,6 +50,7 @@ jobs: echo "No usable base commit; running every job." echo "code=true" >> "$GITHUB_OUTPUT" echo "wasm=true" >> "$GITHUB_OUTPUT" + echo "manual=true" >> "$GITHUB_OUTPUT" exit 0 fi changed="$(git diff --name-only "$BASE" HEAD)" @@ -64,6 +66,11 @@ jobs: else echo "wasm=false" >> "$GITHUB_OUTPUT" fi + if printf '%s\n' "$changed" | grep -qE '^(scripts/lua-manual/|data/lua52/|third_party/lua52/tarball\.mts$|\.github/workflows/ci\.yml$)'; then + echo "manual=true" >> "$GITHUB_OUTPUT" + else + echo "manual=false" >> "$GITHUB_OUTPUT" + fi checks: name: Type-check, lint, unit tests, package @@ -191,13 +198,17 @@ jobs: exit 1 fi echo "version=$version" >> "$GITHUB_OUTPUT" - - name: Cache emsdk and Lua sources + - name: Cache emsdk uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: - path: | - .cache/emsdk - .cache/lua + path: .cache/emsdk key: emsdk-${{ runner.os }}-${{ steps.emsdk.outputs.version }} + # Shared with the `manual` job; the key changes when the pinned tarball does. + - name: Cache the Lua source tarball + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache/lua + key: lua-src-${{ hashFiles('third_party/lua52/tarball.mts') }} - name: Install emsdk ${{ steps.emsdk.outputs.version }} env: VERSION: ${{ steps.emsdk.outputs.version }} @@ -211,3 +222,25 @@ jobs: run: | source .cache/emsdk/emsdk_env.sh npm run build:wasm -- --check + + manual: + name: Lua 5.2 manual data is current + needs: changes + if: needs.changes.outputs.manual == 'true' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # No `npm ci`: the generator uses only Node built-ins and `tar`. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: .nvmrc + - name: Cache the Lua source tarball + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache/lua + key: lua-src-${{ hashFiles('third_party/lua52/tarball.mts') }} + - name: Regenerate and compare + run: npm run lua-manual -- --check From c6777d9a8da34094960e35cc9cfe4798eb0d8138 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:54:07 +0100 Subject: [PATCH 05/15] feat(server): record names resolved through a local _ENV MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In Lua 5.2 a free name `x` means `_ENV.x` (manual §2.2). While a local, parameter or `for` variable named `_ENV` is visible, `x` is a field of that table, not of the global environment. Record such identifiers in the new `ScopeAnalysis.environmentFields`, so that hover does not describe `print` or `string` from the standard library when they can be anything. They stay in `globals` by name, so navigation, rename and symbols are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/server/syntax/scope.ts | 35 ++++++++++++++++++++------- test/unit/server/syntax/scope.test.ts | 29 ++++++++++++++++++++++ 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/src/server/syntax/scope.ts b/src/server/syntax/scope.ts index e8cf5cf..b028438 100644 --- a/src/server/syntax/scope.ts +++ b/src/server/syntax/scope.ts @@ -6,7 +6,9 @@ // - Parameters, and the implicit `self` of `function a:m()`, are visible in the // function body; `for` variables in the loop body. // - `repeat … until cond`: `cond` sees the locals of the body. -// - Any other name is a global (a field of _ENV). +// - 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`. import type * as Ast from './ast.ts'; @@ -34,6 +36,12 @@ export interface ScopeAnalysis { * identifiers are not included (see `declarations`). */ readonly writes: ReadonlySet; + /** + * Global-looking identifiers resolved while a local, parameter or `for` + * variable named `_ENV` was visible: fields of that table, not of the + * global environment. Also listed in `globals`. + */ + readonly environmentFields: ReadonlySet; } export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { @@ -41,6 +49,7 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { const resolved = new Map(); const globals = new Map(); const writes = new Set(); + const environmentFields = new Set(); const scopes: Map[] = []; const declare = (kind: DeclarationKind, name: string, identifier: Ast.Identifier | undefined): void => { @@ -50,15 +59,23 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { scopes.at(-1)?.set(name, declaration); }; - const use = (identifier: Ast.Identifier): void => { + const lookup = (name: string): Declaration | undefined => { for (let i = scopes.length - 1; i >= 0; i--) { - const declaration = scopes[i]?.get(identifier.name); - if (declaration) { - declaration.references.push(identifier); - resolved.set(identifier, declaration); - return; - } + const declaration = scopes[i]?.get(name); + if (declaration) return declaration; + } + return undefined; + }; + + const use = (identifier: Ast.Identifier): void => { + const declaration = lookup(identifier.name); + if (declaration) { + declaration.references.push(identifier); + resolved.set(identifier, declaration); + return; } + // The chunk's own _ENV is an upvalue, never in `scopes`: only a local one is found. + if (lookup('_ENV')) environmentFields.add(identifier); const uses = globals.get(identifier.name); if (uses) uses.push(identifier); else globals.set(identifier.name, [identifier]); @@ -220,5 +237,5 @@ export function analyzeScopes(chunk: Ast.Chunk): ScopeAnalysis { scoped(() => { block(chunk.body); }); - return { declarations, resolved, globals, writes }; + return { declarations, resolved, globals, writes, environmentFields }; } diff --git a/test/unit/server/syntax/scope.test.ts b/test/unit/server/syntax/scope.test.ts index b1c2430..4b601f9 100644 --- a/test/unit/server/syntax/scope.test.ts +++ b/test/unit/server/syntax/scope.test.ts @@ -90,6 +90,35 @@ describe('server/syntax/scope', () => { assert.deepEqual(writes, ['a@8', 'b@16', 'g@31', 'a@39']); }); + describe('environmentFields', () => { + const fields = (source: string): string[] => [...analyze(source).environmentFields].map((identifier) => `${identifier.name}@${String(identifier.start)}`); + + it('is empty while only the chunk\'s own _ENV is in effect', () => { + assert.deepEqual(fields('print(x) _ENV.y = 1'), []); + }); + + it('records globals resolved while a local _ENV is visible, and only then', () => { + // 0 1 2 3 + // 0123456789012345678901234567890123456789 + const source = 'a = 1 do local _ENV = {} b = c end d()'; + assert.deepEqual(fields(source), ['b@25', 'c@29']); + // They stay globals by name, as navigation expects. + assert.deepEqual(globalNames(source), ['a', 'b', 'c', 'd']); + }); + + it('treats a parameter or for variable named _ENV the same way', () => { + assert.deepEqual(fields('function f(_ENV) return x end'), ['x@24']); + assert.deepEqual(fields('for _ENV in e do y() end'), ['y@17']); + }); + + it('applies `local _ENV = _ENV` only after the statement', () => { + // 0 1 2 + // 0123456789012345678901234 + const source = 'local _ENV = x return y'; + assert.deepEqual(fields(source), ['y@22']); + }); + }); + 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], []); }); From 8cf84e36945c204a88142713b1a41dabc5e0ab33 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:57:05 +0100 Subject: [PATCH 06/15] feat(server): index member names and declaration sites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hover needs two things the syntax layer did not provide yet: - members.ts: the field and method names used in expressions (`string.format`, `s:rep()`), sorted by offset, with the expression and chunk they belong to, and `memberAt` to find one by position. Names in `function a.b:c()` and table constructor keys define fields and are not included. - signatures.ts: the statement that declares or assigns each name (`local function f(…)`, `local x = …`, `function x(…)`, `x = …`), with the value in the same position, for describing variables. Both are built lazily once per parsed document (WeakMap, dropped with it), like the variable index of navigation.ts, on a new generic walker (walk.ts) over statements and expressions. `identifierAt`, the binary search behind `targetAt`, is now exported so variables and members share the rule that a cursor just after a name selects it. `parameterList` moves from symbols.ts to signatures.ts; outline details are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/server/syntax/members.ts | 44 ++++++++ src/server/syntax/navigation.ts | 27 +++-- src/server/syntax/signatures.ts | 70 ++++++++++++ src/server/syntax/symbols.ts | 9 +- src/server/syntax/walk.ts | 119 +++++++++++++++++++++ test/unit/server/syntax/members.test.ts | 31 ++++++ test/unit/server/syntax/navigation.test.ts | 13 ++- test/unit/server/syntax/signatures.test.ts | 42 ++++++++ test/unit/server/syntax/walk.test.ts | 35 ++++++ 9 files changed, 373 insertions(+), 17 deletions(-) create mode 100644 src/server/syntax/members.ts create mode 100644 src/server/syntax/signatures.ts create mode 100644 src/server/syntax/walk.ts create mode 100644 test/unit/server/syntax/members.test.ts create mode 100644 test/unit/server/syntax/signatures.test.ts create mode 100644 test/unit/server/syntax/walk.test.ts diff --git a/src/server/syntax/members.ts b/src/server/syntax/members.ts new file mode 100644 index 0000000..64d6e14 --- /dev/null +++ b/src/server/syntax/members.ts @@ -0,0 +1,44 @@ +// Field and method names used in expressions (`base.name`, `base:name(…)`), +// found by position. Pure: no LSP or `vscode` imports. +// +// Names in `function a.b:c()` declarations and keys of table constructors are +// not included: they define fields rather than use them. + +import type * as Ast from './ast.ts'; +import type { ParsedDocument } from './document.ts'; +import { identifierAt } from './navigation.ts'; +import { walk } from './walk.ts'; + +export interface MemberOccurrence { + /** The field or method name. */ + readonly identifier: Ast.Identifier; + /** The expression the name belongs to. */ + readonly node: Ast.MemberExpression | Ast.MethodCallExpression; + /** Index in `ParsedDocument.chunks` of the chunk the name is in. */ + readonly chunkIndex: number; +} + +/** Member names of each document, sorted by offset; dropped with the document. */ +const indexes = new WeakMap(); + +/** Every field and method name used in an expression, sorted by offset. */ +export function memberIndex(document: ParsedDocument): readonly MemberOccurrence[] { + let index = indexes.get(document); + if (!index) { + const entries: MemberOccurrence[] = []; + document.chunks.forEach(({ tree }, chunkIndex) => { + walk(tree.body, (node) => { + if (node.kind === 'MemberExpression') entries.push({ identifier: node.member, node, chunkIndex }); + else if (node.kind === 'MethodCallExpression') entries.push({ identifier: node.method, node, chunkIndex }); + }); + }); + index = entries.sort((a, b) => a.identifier.start - b.identifier.start); + indexes.set(document, index); + } + return index; +} + +/** The field or method name at `offset`; a cursor just after the name still selects it. */ +export function memberAt(document: ParsedDocument, offset: number): MemberOccurrence | undefined { + return identifierAt(memberIndex(document), offset); +} diff --git a/src/server/syntax/navigation.ts b/src/server/syntax/navigation.ts index ae8078e..dbc399c 100644 --- a/src/server/syntax/navigation.ts +++ b/src/server/syntax/navigation.ts @@ -51,20 +51,19 @@ export function variableIndex(document: ParsedDocument): readonly VariableOccurr } /** - * The variable at `offset`, or `undefined` when there is none (keyword, field - * name, string, comment, menu syntax). A cursor just after a name still - * selects it, as editors place the cursor there after typing. + * The entry of `sorted` (sorted by identifier offset) whose identifier is at + * `offset`. A cursor just after a name still selects it, as editors place the + * cursor there after typing. */ -export function targetAt(document: ParsedDocument, offset: number): TargetHit | undefined { - const index = variableIndex(document); +export function identifierAt(sorted: readonly T[], offset: number): T | undefined { // Last identifier starting at or before `offset`. Identifiers never touch, so // one starting exactly at `offset` wins over one ending there. let low = 0; - let high = index.length - 1; - let found: VariableOccurrence | undefined; + let high = sorted.length - 1; + let found: T | undefined; while (low <= high) { const middle = (low + high) >> 1; - const entry = index[middle]; + const entry = sorted[middle]; if (entry && entry.identifier.start <= offset) { found = entry; low = middle + 1; @@ -72,7 +71,17 @@ export function targetAt(document: ParsedDocument, offset: number): TargetHit | high = middle - 1; } } - if (!found || offset > found.identifier.end) { + return found && offset <= found.identifier.end ? found : undefined; +} + +/** + * The variable at `offset`, or `undefined` when there is none (keyword, field + * name, string, comment, menu syntax). A cursor just after a name still + * selects it, as editors place the cursor there after typing. + */ +export function targetAt(document: ParsedDocument, offset: number): TargetHit | undefined { + const found = identifierAt(variableIndex(document), offset); + if (!found) { return undefined; } const { identifier, chunkIndex } = found; diff --git a/src/server/syntax/signatures.ts b/src/server/syntax/signatures.ts new file mode 100644 index 0000000..a089296 --- /dev/null +++ b/src/server/syntax/signatures.ts @@ -0,0 +1,70 @@ +// How a variable gets its value where it is declared or assigned, for +// describing it (hover). Pure: no LSP or `vscode` imports. + +import type * as Ast from './ast.ts'; +import type { ParsedDocument } from './document.ts'; +import { walk } from './walk.ts'; + +/** The statement that declares or assigns a name. */ +export type DeclarationSite = + /** `local function f(…)`. */ + | { readonly kind: 'localFunction'; readonly func: Ast.FunctionExpression } + /** `local x, y = …`; `value` is the expression in the same position, if any. */ + | { readonly kind: 'local'; readonly value: Ast.Expression | undefined } + /** `function x(…)` (one name, no fields or method). */ + | { readonly kind: 'functionDeclaration'; readonly func: Ast.FunctionExpression } + /** `x, y = …`; `value` is the expression in the same position, if any. */ + | { readonly kind: 'assignment'; readonly value: Ast.Expression | undefined }; + +/** `(a, b, ...)`: the parameter list of a function as written. */ +export function parameterList(func: Ast.FunctionExpression): string { + const names = func.parameters.map((parameter) => parameter.name); + if (func.isVararg) names.push('...'); + return `(${names.join(', ')})`; +} + +/** Declaration sites of each document, by declaring or assigned identifier; dropped with the document. */ +const indexes = new WeakMap>(); + +function siteIndex(document: ParsedDocument): ReadonlyMap { + let index = indexes.get(document); + if (!index) { + const sites = new Map(); + for (const { tree } of document.chunks) { + walk(tree.body, (node) => { + switch (node.kind) { + case 'LocalFunctionStatement': + sites.set(node.name, { kind: 'localFunction', func: node.func }); + break; + case 'LocalStatement': + node.names.forEach((name, i) => sites.set(name, { kind: 'local', value: node.values[i] })); + break; + case 'FunctionDeclaration': { + const [name] = node.path; + if (name && node.path.length === 1 && node.method === undefined) sites.set(name, { kind: 'functionDeclaration', func: node.func }); + break; + } + case 'AssignmentStatement': + node.targets.forEach((target, i) => { + if (target.kind === 'Identifier') sites.set(target, { kind: 'assignment', value: node.values[i] }); + }); + break; + default: + break; + } + }); + } + index = sites; + indexes.set(document, index); + } + return index; +} + +/** + * The statement in which `identifier` is declared (`local x`, `local function + * f`) or assigned (`x = …`, `function x()`); `undefined` for any other + * identifier (parameters, `for` variables, reads). + */ +export function declarationSite(document: ParsedDocument, identifier: Ast.Identifier): DeclarationSite | undefined { + return siteIndex(document).get(identifier); +} diff --git a/src/server/syntax/symbols.ts b/src/server/syntax/symbols.ts index 80c5940..0c616ae 100644 --- a/src/server/syntax/symbols.ts +++ b/src/server/syntax/symbols.ts @@ -19,6 +19,7 @@ import type * as Ast from './ast.ts'; import type { ParsedChunk, ParsedDocument } from './document.ts'; import type { ScopeAnalysis } from './scope.ts'; +import { parameterList } from './signatures.ts'; export type OutlineKind = 'function' | 'method' | 'variable' | 'field' | 'namespace'; @@ -51,12 +52,6 @@ interface Context { const nested = (context: Context, container: OutlineSymbol[]): Context => ({ ...context, container, topLevel: false }); const inFunction = (context: Context, container: OutlineSymbol[]): Context => ({ ...nested(context, container), listGlobals: false }); -function parameters(func: Ast.FunctionExpression): string { - const names = func.parameters.map((p) => p.name); - if (func.isVararg) names.push('...'); - return `(${names.join(', ')})`; -} - /** `a`, `a.b.c` for identifiers and `.` chains on an identifier; `undefined` otherwise. */ function dottedName(expression: Ast.Expression): string | undefined { if (expression.kind === 'Identifier') return expression.name; @@ -76,7 +71,7 @@ function functionSymbol( context: Context, ): OutlineSymbol { const symbol: OutlineSymbol = { - name, kind, detail: parameters(func), start: range.start, end: range.end, + name, kind, detail: parameterList(func), start: range.start, end: range.end, selectionStart: selection.start, selectionEnd: selection.end, children: [], }; block(func.body, inFunction(context, symbol.children)); diff --git a/src/server/syntax/walk.ts b/src/server/syntax/walk.ts new file mode 100644 index 0000000..c2d5482 --- /dev/null +++ b/src/server/syntax/walk.ts @@ -0,0 +1,119 @@ +// Generic traversal of a Lua syntax tree. Pure: no LSP or `vscode` imports. +import type * as Ast from './ast.ts'; + +export type WalkedNode = Ast.Statement | Ast.Expression; + +/** + * Calls `visit` for every statement and expression in `block`, in source + * order, parents before children, including function bodies and table + * fields. Identifiers that are not expressions (declared names, parameters, + * field and method names, labels) are not visited. + */ +export function walk(block: Ast.Block, visit: (node: WalkedNode) => void): void { + const statements = (nodes: readonly Ast.Statement[]): void => { + for (const node of nodes) statement(node); + }; + const expressions = (nodes: readonly Ast.Expression[]): void => { + for (const node of nodes) expression(node); + }; + + function statement(node: Ast.Statement): void { + visit(node); + switch (node.kind) { + case 'LocalStatement': + expressions(node.values); + break; + case 'AssignmentStatement': + expressions(node.targets); + expressions(node.values); + break; + case 'CallStatement': + expression(node.call); + break; + case 'DoStatement': + statements(node.body.body); + break; + case 'WhileStatement': + expression(node.condition); + statements(node.body.body); + break; + case 'RepeatStatement': + statements(node.body.body); + if (node.condition) expression(node.condition); + break; + case 'IfStatement': + for (const clause of node.clauses) { + if (clause.condition) expression(clause.condition); + statements(clause.body.body); + } + break; + case 'NumericForStatement': + expression(node.initial); + expression(node.limit); + if (node.step) expression(node.step); + statements(node.body.body); + break; + case 'GenericForStatement': + expressions(node.iterators); + statements(node.body.body); + break; + case 'FunctionDeclaration': + case 'LocalFunctionStatement': + expression(node.func); + break; + case 'ReturnStatement': + expressions(node.values); + break; + case 'BreakStatement': + case 'GotoStatement': + case 'LabelStatement': + break; + } + } + + function expression(node: Ast.Expression): void { + visit(node); + switch (node.kind) { + case 'FunctionExpression': + statements(node.body.body); + break; + case 'TableConstructor': + for (const field of node.fields) { + if (field.form === 'keyed' && field.key) expression(field.key); + expression(field.value); + } + break; + case 'BinaryExpression': + expression(node.left); + expression(node.right); + break; + case 'UnaryExpression': + expression(node.argument); + break; + case 'ParenthesizedExpression': + expression(node.expression); + break; + case 'MemberExpression': + expression(node.base); + break; + case 'IndexExpression': + expression(node.base); + expression(node.index); + break; + case 'CallExpression': + case 'MethodCallExpression': + expression(node.base); + expressions(node.arguments.values); + break; + case 'Identifier': + case 'NilLiteral': + case 'BooleanLiteral': + case 'NumberLiteral': + case 'StringLiteral': + case 'VarargLiteral': + break; + } + } + + statements(block.body); +} diff --git a/test/unit/server/syntax/members.test.ts b/test/unit/server/syntax/members.test.ts new file mode 100644 index 0000000..a6b20f9 --- /dev/null +++ b/test/unit/server/syntax/members.test.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { memberAt, memberIndex } from '../../../../src/server/syntax/members.ts'; + +describe('server/syntax/members', () => { + // 0 1 2 3 + // 0123456789012345678901234567890123456 + const text = 'string.format(s:rep(2)) function t.f() end'; + const document = parseDocument(text, 'lua'); + + it('lists field and method names used in expressions, in source order', () => { + assert.deepEqual( + memberIndex(document).map(({ identifier, node }) => `${identifier.name}@${String(identifier.start)}:${node.kind}`), + ['format@7:MemberExpression', 'rep@16:MethodCallExpression'], + ); + }); + + it('finds the name under the cursor, also just after it, but not the base', () => { + assert.equal(memberAt(document, 7)?.identifier.name, 'format'); + assert.equal(memberAt(document, 13)?.identifier.name, 'format'); + assert.equal(memberAt(document, 16)?.identifier.name, 'rep'); + assert.equal(memberAt(document, 3), undefined); + // `f` in `function t.f()` names a field being defined. + assert.equal(memberAt(document, 35), undefined); + }); + + it('records the chunk of each name in a .menu file', () => { + const menu = parseDocument('menu { onOpen "a.b()" } menu { onOpen "c.d()" }', 'menu'); + assert.deepEqual(memberIndex(menu).map(({ identifier, chunkIndex }) => `${identifier.name}:${String(chunkIndex)}`), ['b:0', 'd:1']); + }); +}); diff --git a/test/unit/server/syntax/navigation.test.ts b/test/unit/server/syntax/navigation.test.ts index 03ecdd3..17eae5f 100644 --- a/test/unit/server/syntax/navigation.test.ts +++ b/test/unit/server/syntax/navigation.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { parseDocument, type ParsedDocument } from '../../../../src/server/syntax/document.ts'; -import { definitions, references, targetAt } from '../../../../src/server/syntax/navigation.ts'; +import { definitions, identifierAt, references, targetAt } from '../../../../src/server/syntax/navigation.ts'; /** `name@offset` for each identifier. */ const at = (identifiers: readonly { name: string; start: number }[]): string[] => identifiers.map((i) => `${i.name}@${String(i.start)}`); @@ -21,6 +21,17 @@ function definitionsAt(document: ParsedDocument, offset: number): string[] | und } describe('server/syntax/navigation', () => { + describe('identifierAt', () => { + const entries = [{ identifier: { kind: 'Identifier', name: 'ab', start: 2, end: 4 } }, { identifier: { kind: 'Identifier', name: 'c', start: 6, end: 7 } }] as const; + + it('finds the identifier containing or just before the offset', () => { + assert.deepEqual([0, 1, 2, 3, 4, 5, 6, 7, 8].map((offset) => identifierAt(entries, offset)?.identifier.name), [ + undefined, undefined, 'ab', 'ab', 'ab', undefined, 'c', 'c', undefined, + ]); + assert.equal(identifierAt<(typeof entries)[number]>([], 0), undefined); + }); + }); + describe('targetAt', () => { // 0 1 2 // 0123456789012345678901234 diff --git a/test/unit/server/syntax/signatures.test.ts b/test/unit/server/syntax/signatures.test.ts new file mode 100644 index 0000000..6c7a5ba --- /dev/null +++ b/test/unit/server/syntax/signatures.test.ts @@ -0,0 +1,42 @@ +import assert from 'node:assert/strict'; +import type * as Ast from '../../../../src/server/syntax/ast.ts'; +import { parseDocument, type ParsedDocument } from '../../../../src/server/syntax/document.ts'; +import { targetAt } from '../../../../src/server/syntax/navigation.ts'; +import { declarationSite, parameterList } from '../../../../src/server/syntax/signatures.ts'; + +function siteAt(document: ParsedDocument, text: string, needle: string): ReturnType { + const hit = targetAt(document, text.indexOf(needle)); + assert.ok(hit, needle); + return declarationSite(document, hit.identifier); +} + +const params = (func: Ast.FunctionExpression): string => parameterList(func); + +describe('server/syntax/signatures', () => { + const text = 'local function lf(a, b, ...) end local lv, lw = function(c) end function G(d) end H, I = 1 local J'; + const document = parseDocument(text, 'lua'); + + it('describes local functions and function declarations with their parameter lists', () => { + const lf = siteAt(document, text, 'lf'); + assert.equal(lf?.kind === 'localFunction' && params(lf.func), '(a, b, ...)'); + const g = siteAt(document, text, 'G('); + assert.equal(g?.kind === 'functionDeclaration' && params(g.func), '(d)'); + }); + + it('pairs each declared or assigned name with the value in the same position', () => { + const lv = siteAt(document, text, 'lv'); + assert.equal(lv?.kind === 'local' && lv.value?.kind, 'FunctionExpression'); + assert.deepEqual(siteAt(document, text, 'lw'), { kind: 'local', value: undefined }); + assert.equal(siteAt(document, text, 'H,')?.kind, 'assignment'); + assert.deepEqual(siteAt(document, text, 'I ='), { kind: 'assignment', value: undefined }); + assert.deepEqual(siteAt(document, text, 'J'), { kind: 'local', value: undefined }); + }); + + it('has no site for parameters, reads, or names with fields or a method', () => { + const source = 'function t.f(p) return p end function t:m() end print(q)'; + const parsed = parseDocument(source, 'lua'); + for (const needle of ['t.f', 'p)', 't:m', 'q']) { + assert.equal(siteAt(parsed, source, needle), undefined, needle); + } + }); +}); diff --git a/test/unit/server/syntax/walk.test.ts b/test/unit/server/syntax/walk.test.ts new file mode 100644 index 0000000..6b24bdd --- /dev/null +++ b/test/unit/server/syntax/walk.test.ts @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import { parseChunk } from '../../../../src/server/syntax/parser.ts'; +import { walk } from '../../../../src/server/syntax/walk.ts'; + +function kinds(source: string): string[] { + const chunk = parseChunk(source); + assert.deepEqual(chunk.errors, [], source); + const visited: string[] = []; + walk(chunk.body, (node) => visited.push(node.kind === 'Identifier' ? `Identifier:${node.name}` : node.kind)); + return visited; +} + +describe('server/syntax/walk', () => { + it('visits statements and expressions in source order, parents first', () => { + assert.deepEqual(kinds('local x = a.b(1) x = -x'), [ + 'LocalStatement', 'CallExpression', 'MemberExpression', 'Identifier:a', 'NumberLiteral', + 'AssignmentStatement', 'Identifier:x', 'UnaryExpression', 'Identifier:x', + ]); + }); + + it('enters function bodies, table constructors and every kind of block', () => { + const visited = kinds( + 'function f() return { k = g, [h] = 1, i } end local function l() end ' + + 'do j() end while w do end repeat until u if c then elseif d then else end ' + + 'for n = s, e, p do end for k in it do end', + ); + for (const name of ['g', 'h', 'i', 'j', 'w', 'u', 'c', 'd', 's', 'e', 'p', 'it']) { + assert.ok(visited.includes(`Identifier:${name}`), name); + } + // Declared names, parameters and field names are not expressions. + for (const name of ['f', 'l', 'n', 'k']) { + assert.equal(visited.includes(`Identifier:${name}`), false, name); + } + }); +}); From e6bdb4965ff9b790741bc3096b573d178b8735ab Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:59:46 +0100 Subject: [PATCH 07/15] feat(server): localize server messages from the client's locale MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hover will show a few labels of the server's own (maintainer decision: localized on the server, from `InitializeParams.locale`, so that every LSP client benefits, not only VS Code). The server runs outside VS Code and cannot use `vscode.l10n`, so: - l10n/server/messages.json (English) and messages..json for the 14 VS Code display languages are bundled into the server by esbuild through JSON import attributes (checked with tsc, ESLint, Node's type stripping for the unit tests, and esbuild); - src/server/l10n.ts resolves the requested locale (exact match, else the bare language: `de-AT` → `de`; regional variants are never substituted, so `pt-PT` and `zh-Hans` get English), substitutes `{n}` placeholders, and falls back to English per key; - the list of locales moves from scripts/check-l10n.mts to src/shared/locales.ts, so the server and the check share it; - `npm run check-l10n` gains step 6 (each server table has exactly the English keys, with code spans and placeholders unchanged, and exists) and step 7 (every English key is used in src/server). Both were checked to fail on a missing file, a missing or changed key and an unused key. The tables are empty in this commit; hover adds its keys. .vscodeignore now ships only l10n/bundle.l10n*.json, which the client loads at run time; the server tables are already inside server.js (`vsce ls` and the CI allow-list are unchanged). Co-Authored-By: Claude Opus 5.5 --- .vscodeignore | 2 +- l10n/server/messages.cs.json | 1 + l10n/server/messages.de.json | 1 + l10n/server/messages.es.json | 1 + l10n/server/messages.fr.json | 1 + l10n/server/messages.hu.json | 1 + l10n/server/messages.it.json | 1 + l10n/server/messages.ja.json | 1 + l10n/server/messages.json | 1 + l10n/server/messages.ko.json | 1 + l10n/server/messages.pl.json | 1 + l10n/server/messages.pt-br.json | 1 + l10n/server/messages.ru.json | 1 + l10n/server/messages.tr.json | 1 + l10n/server/messages.zh-cn.json | 1 + l10n/server/messages.zh-tw.json | 1 + scripts/check-l10n.mts | 49 ++++++++++++++++++---- src/server/l10n.ts | 73 +++++++++++++++++++++++++++++++++ src/shared/locales.ts | 7 ++++ test/unit/server/l10n.test.ts | 43 +++++++++++++++++++ 20 files changed, 180 insertions(+), 9 deletions(-) create mode 100644 l10n/server/messages.cs.json create mode 100644 l10n/server/messages.de.json create mode 100644 l10n/server/messages.es.json create mode 100644 l10n/server/messages.fr.json create mode 100644 l10n/server/messages.hu.json create mode 100644 l10n/server/messages.it.json create mode 100644 l10n/server/messages.ja.json create mode 100644 l10n/server/messages.json create mode 100644 l10n/server/messages.ko.json create mode 100644 l10n/server/messages.pl.json create mode 100644 l10n/server/messages.pt-br.json create mode 100644 l10n/server/messages.ru.json create mode 100644 l10n/server/messages.tr.json create mode 100644 l10n/server/messages.zh-cn.json create mode 100644 l10n/server/messages.zh-tw.json create mode 100644 src/server/l10n.ts create mode 100644 src/shared/locales.ts create mode 100644 test/unit/server/l10n.test.ts diff --git a/.vscodeignore b/.vscodeignore index ea823e3..230ccc2 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -7,7 +7,7 @@ !package.json !package.nls.json !package.nls.*.json -!l10n/** +!l10n/bundle.l10n*.json !language-configuration/** !syntaxes/** !images/icon.png diff --git a/l10n/server/messages.cs.json b/l10n/server/messages.cs.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.cs.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.de.json b/l10n/server/messages.de.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.de.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.es.json b/l10n/server/messages.es.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.es.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.fr.json b/l10n/server/messages.fr.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.fr.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.hu.json b/l10n/server/messages.hu.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.hu.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.it.json b/l10n/server/messages.it.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.it.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.ja.json b/l10n/server/messages.ja.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.ja.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.json b/l10n/server/messages.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.ko.json b/l10n/server/messages.ko.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.ko.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.pl.json b/l10n/server/messages.pl.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.pl.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.pt-br.json b/l10n/server/messages.pt-br.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.pt-br.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.ru.json b/l10n/server/messages.ru.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.ru.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.tr.json b/l10n/server/messages.tr.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.tr.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.zh-cn.json b/l10n/server/messages.zh-cn.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.zh-cn.json @@ -0,0 +1 @@ +{} diff --git a/l10n/server/messages.zh-tw.json b/l10n/server/messages.zh-tw.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/l10n/server/messages.zh-tw.json @@ -0,0 +1 @@ +{} diff --git a/scripts/check-l10n.mts b/scripts/check-l10n.mts index 0ab6715..a59e5de 100644 --- a/scripts/check-l10n.mts +++ b/scripts/check-l10n.mts @@ -2,23 +2,27 @@ // one GitHub annotation per problem, naming the file and key at fault. // // Checks: -// 1. Every VS Code display language has package.nls..json and -// l10n/bundle.l10n..json. +// 1. Every VS Code display language (src/shared/locales.ts) has +// package.nls..json, l10n/bundle.l10n..json and +// l10n/server/messages..json. // 2. Each locale has exactly the keys of the English source, all non-empty. // 3. Code spans (`…`, which include setting links), {0}-style placeholders and // **IE Lua: ** references survive translation unchanged // (references must use that locale's own command title). // 4. Every %key% used in package.json exists in package.nls.json and vice versa. // 5. l10n/bundle.l10n.json equals a fresh `@vscode/l10n-dev export` of src/client. +// The language server is not part of the export: it uses `messages.t()` +// (src/server/l10n.ts), not `vscode.l10n.t()`. +// 6. The server tables l10n/server/messages..json have exactly the keys +// of l10n/server/messages.json, with code spans and placeholders unchanged. +// 7. Every key of l10n/server/messages.json is used in src/server/ (as a +// quoted string); unknown keys are compile errors there (`MessageKey`). import { execFileSync } from 'node:child_process'; -import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; - -// The display languages VS Code offers as language packs, besides English: -// https://code.visualstudio.com/docs/configure/locales#_available-locales -export const LOCALES = ['cs', 'de', 'es', 'fr', 'hu', 'it', 'ja', 'ko', 'pl', 'pt-br', 'ru', 'tr', 'zh-cn', 'zh-tw'] as const; +import { LOCALES } from '../src/shared/locales.ts'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const errors: string[] = []; @@ -130,6 +134,32 @@ if (packageNls && bundle) { } } +// 6. Language server tables. +const serverDir = join(root, 'l10n', 'server'); +const serverFile = join(serverDir, 'messages.json'); +const server = readJson(serverFile); +if (server) { + for (const locale of LOCALES) { + const localeFile = join(serverDir, `messages.${locale}.json`); + const translated = readJson(localeFile); + if (translated) { + compare(server, serverFile, translated, localeFile); + } + } + + // 7. Every server key is used by the server. + const sources = (dir: string): string[] => + readdirSync(dir, { withFileTypes: true }).flatMap((entry) => + entry.isDirectory() ? sources(join(dir, entry.name)) : entry.name.endsWith('.ts') ? [readFileSync(join(dir, entry.name), 'utf8')] : [], + ); + const serverSource = sources(join(root, 'src', 'server')).join('\n'); + for (const key of Object.keys(server)) { + if (!serverSource.includes(`'${key}'`)) { + error(serverFile, `"${key}" is not used in src/server; remove it from every l10n/server/messages*.json.`); + } + } +} + if (errors.length > 0) { for (const line of errors) { console.error(line); @@ -137,4 +167,7 @@ if (errors.length > 0) { console.error(`Localization check failed with ${errors.length} problem(s).`); process.exit(1); } -console.log(`Localization check passed: ${LOCALES.length} locales, ${Object.keys(packageNls ?? {}).length} manifest strings, ${Object.keys(bundle ?? {}).length} runtime strings.`); +console.log( + `Localization check passed: ${LOCALES.length} locales, ${Object.keys(packageNls ?? {}).length} manifest strings, ` + + `${Object.keys(bundle ?? {}).length} client strings, ${Object.keys(server ?? {}).length} server strings.`, +); diff --git a/src/server/l10n.ts b/src/server/l10n.ts new file mode 100644 index 0000000..613ce6d --- /dev/null +++ b/src/server/l10n.ts @@ -0,0 +1,73 @@ +// Localized messages of the language server, in the language the client asks +// for (`InitializeParams.locale`; VS Code sends its display language). The +// server runs outside VS Code, so it cannot use `vscode.l10n`; the tables in +// l10n/server/ are bundled into the server and checked by `npm run check-l10n` +// (same keys in every locale, code spans and `{n}` placeholders unchanged). +// +// Only the server's own wording is localized. Text quoted from upstream +// documentation (the Lua manual) stays as published. +import cs from '../../l10n/server/messages.cs.json' with { type: 'json' }; +import de from '../../l10n/server/messages.de.json' with { type: 'json' }; +import es from '../../l10n/server/messages.es.json' with { type: 'json' }; +import fr from '../../l10n/server/messages.fr.json' with { type: 'json' }; +import hu from '../../l10n/server/messages.hu.json' with { type: 'json' }; +import it from '../../l10n/server/messages.it.json' with { type: 'json' }; +import ja from '../../l10n/server/messages.ja.json' with { type: 'json' }; +import en from '../../l10n/server/messages.json' with { type: 'json' }; +import ko from '../../l10n/server/messages.ko.json' with { type: 'json' }; +import pl from '../../l10n/server/messages.pl.json' with { type: 'json' }; +import ptBr from '../../l10n/server/messages.pt-br.json' with { type: 'json' }; +import ru from '../../l10n/server/messages.ru.json' with { type: 'json' }; +import tr from '../../l10n/server/messages.tr.json' with { type: 'json' }; +import zhCn from '../../l10n/server/messages.zh-cn.json' with { type: 'json' }; +import zhTw from '../../l10n/server/messages.zh-tw.json' with { type: 'json' }; +import { LOCALES, type Locale } from '../shared/locales.ts'; + +/** Keys of the English table, the source of every translation. */ +export type MessageKey = keyof typeof en; + +export type MessageTable = Readonly>; + +const TRANSLATIONS: Readonly> = { + cs, de, es, fr, hu, it, ja, ko, pl, 'pt-br': ptBr, ru, tr, 'zh-cn': zhCn, 'zh-tw': zhTw, +}; + +/** + * The supported locale for a requested one (BCP 47, any letter case): an + * exact match, else the requested language without its region or script + * (`de-AT` → `de`). Regional variants are never substituted for each other + * (`pt-PT` does not get `pt-br`, `zh-Hans` does not get `zh-cn`): `undefined` + * means English. + */ +export function resolveLocale(requested: string | undefined): Locale | undefined { + const wanted = requested?.trim().toLowerCase().replaceAll('_', '-'); + if (!wanted) return undefined; + const language = wanted.split('-')[0]; + return LOCALES.find((locale) => locale === wanted) ?? LOCALES.find((locale) => locale === language); +} + +/** Replaces `{0}`, `{1}`, … with the arguments; other text is kept. */ +export function format(template: string, args: readonly string[]): string { + return template.replace(/\{(\d+)\}/g, (placeholder, index: string) => args[Number(index)] ?? placeholder); +} + +export interface Messages { + /** The supported locale in use; `undefined` for English. */ + readonly locale: Locale | undefined; + /** The message for `key` in the locale, falling back to English, with `{n}` replaced by `args[n]`. */ + t(key: MessageKey, ...args: string[]): string; +} + +/** Messages from explicit tables (for tests); see `createMessages`. */ +export function messagesFrom(english: MessageTable, translation: MessageTable | undefined, locale: Locale | undefined): Messages { + return { + locale, + t: (key, ...args) => format(translation?.[key] ?? english[key] ?? key, args), + }; +} + +/** The server's messages for the client's requested locale. */ +export function createMessages(requested: string | undefined): Messages { + const locale = resolveLocale(requested); + return messagesFrom(en, locale && TRANSLATIONS[locale], locale); +} diff --git a/src/shared/locales.ts b/src/shared/locales.ts new file mode 100644 index 0000000..3b8729a --- /dev/null +++ b/src/shared/locales.ts @@ -0,0 +1,7 @@ +// The display languages VS Code offers as language packs, besides English: +// https://code.visualstudio.com/docs/configure/locales#_available-locales +// Every localized file (package.nls..json, l10n/bundle.l10n..json, +// l10n/server/messages..json) exists for each; `npm run check-l10n` verifies it. +export const LOCALES = ['cs', 'de', 'es', 'fr', 'hu', 'it', 'ja', 'ko', 'pl', 'pt-br', 'ru', 'tr', 'zh-cn', 'zh-tw'] as const; + +export type Locale = (typeof LOCALES)[number]; diff --git a/test/unit/server/l10n.test.ts b/test/unit/server/l10n.test.ts new file mode 100644 index 0000000..68d350a --- /dev/null +++ b/test/unit/server/l10n.test.ts @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { createMessages, format, messagesFrom, resolveLocale, type MessageKey } from '../../../src/server/l10n.ts'; + +describe('server/l10n', () => { + it('resolves a requested locale exactly, case-insensitively', () => { + assert.equal(resolveLocale('de'), 'de'); + assert.equal(resolveLocale('pt-BR'), 'pt-br'); + assert.equal(resolveLocale('zh_TW'), 'zh-tw'); + }); + + it('falls back to the bare language, never to another regional variant, and otherwise to English', () => { + assert.equal(resolveLocale('de-AT'), 'de'); + assert.equal(resolveLocale('fr-CA'), 'fr'); + assert.equal(resolveLocale('pt-PT'), undefined); + assert.equal(resolveLocale('pt'), undefined); + assert.equal(resolveLocale('zh-Hans'), undefined); + assert.equal(resolveLocale('en'), undefined); + assert.equal(resolveLocale('en-US'), undefined); + assert.equal(resolveLocale('xx'), undefined); + assert.equal(resolveLocale(''), undefined); + assert.equal(resolveLocale(undefined), undefined); + }); + + it('replaces numbered placeholders and keeps unmatched ones', () => { + assert.equal(format('See {0} and {1}; {0}.', ['a', 'b']), 'See a and b; a.'); + assert.equal(format('Missing {2}', ['a']), 'Missing {2}'); + }); + + it('uses the translation, then English, then the key', () => { + const messages = messagesFrom({ greet: 'Hello {0}', only: 'English only' }, { greet: 'Hallo {0}' }, 'de'); + // The keys are not in the bundled English table; the cast only satisfies MessageKey. + const t = (key: string, ...args: string[]): string => messages.t(key as MessageKey, ...args); + assert.equal(messages.locale, 'de'); + assert.equal(t('greet', 'Welt'), 'Hallo Welt'); + assert.equal(t('only'), 'English only'); + assert.equal(t('unknown'), 'unknown'); + }); + + it('creates messages for the resolved locale', () => { + assert.equal(createMessages('ja').locale, 'ja'); + assert.equal(createMessages('en-GB').locale, undefined); + }); +}); From b2cd048a9ca88e3b4e4d1e6ae008ff14a82ef848 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:03:21 +0100 Subject: [PATCH 08/15] feat(server): resolve hover targets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decide what a hover describes, without rendering it yet. knowledge.ts loads what the server knows about names it does not see defined: - the Lua 5.2 manual entries (data/lua52/manual.json), with their section and a link into https://www.lua.org/manual/5.2/manual.html; - the engine's replacement of `print` (IESDP "Engine Lua globals", commit 38e7532: "Replacement for Lua's print, registered by the engine's Lua bootstrap", with no behaviour given); - EEex-Docs names and links (data/eeex/eeex-functions.json and game-lua-functions.json; no text, as EEex-Docs has no license). Game structures are C++ types that Lua code never names, so they are not looked up and not bundled. resolve.ts maps the name under the cursor to a target: - a local: its declaration and how it gets its value; - a global, shared by the chunks of a .menu file: the document's own first assignment wins (an EEex-Docs link is kept); otherwise the engine's `print` note, the manual, EEex-Docs, or a bare global. io, os, require and coroutine get no documentation: the engine does not open those libraries; - a field or method: `string.format`, `_G.string.format`, `("x"):rep()` (strings index the string table, manual §6.4), `C:AddGold()` and `C.AddGold`, `EEex_Options_Option.new`. Fields of locals and of tables the document builds get no hover, as does any name resolved through a local `_ENV`, and `_ENV` itself. `TargetHit` from navigation.ts now also carries the chunk index that targetAt already knew. Co-Authored-By: Claude Opus 5.5 --- src/server/hover/knowledge.ts | 104 +++++++++++++++++ src/server/hover/resolve.ts | 143 +++++++++++++++++++++++ src/server/syntax/navigation.ts | 3 + test/unit/server/hover/knowledge.test.ts | 38 ++++++ test/unit/server/hover/resolve.test.ts | 127 ++++++++++++++++++++ 5 files changed, 415 insertions(+) create mode 100644 src/server/hover/knowledge.ts create mode 100644 src/server/hover/resolve.ts create mode 100644 test/unit/server/hover/knowledge.test.ts create mode 100644 test/unit/server/hover/resolve.test.ts diff --git a/src/server/hover/knowledge.ts b/src/server/hover/knowledge.ts new file mode 100644 index 0000000..4351a3b --- /dev/null +++ b/src/server/hover/knowledge.ts @@ -0,0 +1,104 @@ +// What the server knows about names it did not see defined: the Lua 5.2 +// libraries the game engine opens, the engine's replacements of standard +// functions, and the EEex and game functions documented by EEex-Docs. +// Pure: no LSP or `vscode` imports. +import eeexFunctions from '../../../data/eeex/eeex-functions.json' with { type: 'json' }; +import gameLuaFunctions from '../../../data/eeex/game-lua-functions.json' with { type: 'json' }; +import manual from '../../../data/lua52/manual.json' with { type: 'json' }; + +// ------------------------------------------------------------ Lua manual + +export interface ManualSection { + /** `6.4`. */ + readonly number: string; + /** `String Manipulation`. */ + readonly title: string; +} + +/** An entry of the Lua 5.2 manual (data/lua52/manual.json, generated by scripts/lua-manual/). */ +export interface ManualEntry { + /** `print`, `string.format`, or the module name for a module table. */ + readonly name: string; + readonly kind: 'function' | 'value' | 'module'; + readonly section: ManualSection; + /** The heading as the manual prints it: `string.format (formatstring, ···)`. */ + readonly heading: string; + readonly markdown: string; + readonly plaintext: string; + /** Link to the entry in the online manual. */ + readonly url: string; +} + +export const MANUAL_TITLE: string = manual.title; + +const ENTRY_KINDS: ReadonlySet = new Set(['function', 'value', 'module']); + +/** Manual entries by name. The data is generated and checked in CI; a malformed file fails at load. */ +const manualEntries: ReadonlyMap = (() => { + const sections = new Map(manual.sections.map((section) => [section.number, { number: section.number, title: section.title }])); + const entries = new Map(); + for (const entry of manual.entries) { + const section = sections.get(entry.section); + if (!section || !ENTRY_KINDS.has(entry.kind)) { + throw new Error(`data/lua52/manual.json: entry "${entry.name}" has an unknown section or kind.`); + } + entries.set(entry.name, { + name: entry.name, + kind: entry.kind as ManualEntry['kind'], + section, + heading: entry.heading, + markdown: entry.markdown, + plaintext: entry.plaintext, + url: `${manual.baseUrl}#${encodeURI(entry.anchor)}`, + }); + } + return entries; +})(); + +/** The manual entry named `name` (`print`, `string`, `string.format`); only the libraries the engine opens are included. */ +export function manualEntry(name: string): ManualEntry | undefined { + return manualEntries.get(name); +} + +// ------------------------------------------------- engine replacements + +/** A standard function the engine replaces, so the manual does not describe it. */ +export interface EngineReplacement { + readonly name: string; + /** Title of the page that documents the replacement. */ + readonly sourceTitle: string; + readonly url: string; +} + +// IESDP, "Engine Lua globals" (https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm, +// commit 38e7532; checked against the 2.6.6.0 and 2.7.3.0 executables): `bootstrapLua` "replaces `print`"; +// its entry reads "Replacement for Lua's print, registered by the engine's Lua bootstrap." and gives no behaviour. +const ENGINE_REPLACEMENTS: ReadonlyMap = new Map([ + ['print', { name: 'print', sourceTitle: 'Engine Lua globals', url: 'https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm' }], +]); + +export function engineReplacement(name: string): EngineReplacement | undefined { + return ENGINE_REPLACEMENTS.get(name); +} + +// --------------------------------------------------------------- EEex-Docs + +/** A function documented by EEex-Docs. Only the name and link are stored: EEex-Docs has no license. */ +export interface ExternalEntry { + /** As documented: `EEex_Sprite_GetName`, `Infinity_DisplayString`, `C:AddGold`, `EEex_Options_Option.new`. */ + readonly name: string; + readonly url: string; + /** The documentation section: `EEex Functions` or `EE Game Lua Functions`. */ + readonly sourceTitle: string; +} + +// Game structures (game-structures-x64.json) are C++ types that Lua code never +// names as variables, so they are not looked up. +const externalEntries: ReadonlyMap = new Map( + [eeexFunctions, gameLuaFunctions].flatMap(({ title, entries }) => entries.map(({ name, url }) => [name, { name, url, sourceTitle: title }] as const)), +); + +/** The EEex-Docs entry for `name` as it is documented (`x`, `x.y` or `x:y`). */ +export function externalEntry(name: string): ExternalEntry | undefined { + return externalEntries.get(name); +} diff --git a/src/server/hover/resolve.ts b/src/server/hover/resolve.ts new file mode 100644 index 0000000..cb76fb3 --- /dev/null +++ b/src/server/hover/resolve.ts @@ -0,0 +1,143 @@ +// What a hover describes: the name under the cursor and what it refers to. +// Pure: no LSP or `vscode` imports. +// +// - A local: its declaration (`local function f(a)`, a parameter, …). +// - A global: shared by all chunks of a .menu file, as in navigation.ts. +// 1. Assigned in this document: described by its first assignment; the +// document's own definition wins over the libraries (an EEex-Docs link is +// still given, since a link makes no claim about behaviour). +// 2. Replaced by the engine (`print`): a note instead of the manual text. +// 3. In the manual (basic functions and the module tables string, table, +// math, bit32, debug), then EEex-Docs. +// 4. Otherwise just a global, without documentation: also io, os, require +// and coroutine, which the engine does not provide. +// - A field or method name: library and EEex-Docs names only (`string.format`, +// `_G.string.format`, `("x"):rep()`, `C:AddGold()`, `EEex_Options_Option.new`). +// Fields of anything else (locals, tables built in Lua) have no hover. +// +// Names resolved through a local `_ENV` are fields of that table, so they get +// no hover. Without type inference that is the only safe answer. + +import type * as Ast from '../syntax/ast.ts'; +import type { ParsedDocument } from '../syntax/document.ts'; +import { memberAt, type MemberOccurrence } from '../syntax/members.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'; +import { engineReplacement, externalEntry, manualEntry, type EngineReplacement, type ExternalEntry, type ManualEntry } from './knowledge.ts'; + +export type HoverTarget = + | { readonly kind: 'local'; readonly declaration: Declaration; readonly site: DeclarationSite | undefined } + /** A global without documentation; `site` is its first assignment in the document, if any. */ + | { readonly kind: 'global'; readonly name: string; readonly site: DeclarationSite | undefined; readonly link: ExternalEntry | undefined } + | { readonly kind: 'library'; readonly entry: ManualEntry } + | { readonly kind: 'engineReplaced'; readonly replacement: EngineReplacement; readonly entry: ManualEntry | undefined } + | { readonly kind: 'external'; readonly entry: ExternalEntry }; + +export interface HoverHit { + readonly target: HoverTarget; + /** The name under the cursor. */ + readonly identifier: Ast.Identifier; +} + +/** The first assignment to the global `name` in the document, if any. */ +function firstWrite(document: ParsedDocument, name: string): Ast.Identifier | undefined { + return definitions(document, { kind: 'global', name })[0]; +} + +/** A global that is not assigned in the document, looked up in what the server knows. */ +function knownGlobal(name: string): HoverTarget | undefined { + const replacement = engineReplacement(name); + if (replacement) return { kind: 'engineReplaced', replacement, entry: manualEntry(name) }; + const entry = manualEntry(name); + if (entry) return { kind: 'library', entry }; + const external = externalEntry(name); + return external && { kind: 'external', entry: external }; +} + +function globalTarget(document: ParsedDocument, name: string): HoverTarget { + const write = firstWrite(document, name); + if (write) { + return { kind: 'global', name, site: declarationSite(document, write), link: externalEntry(name) }; + } + return knownGlobal(name) ?? { kind: 'global', name, site: undefined, link: undefined }; +} + +function variableTarget(document: ParsedDocument, { target, identifier, chunkIndex }: TargetHit): HoverTarget | undefined { + if (target.kind === 'local') { + const declaring = target.declaration.identifier; + return { kind: 'local', declaration: target.declaration, site: declaring && declarationSite(document, declaring) }; + } + // A field of a local `_ENV` table, or `_ENV` itself (the chunk's upvalue, not a global). + const scopes = document.chunks[chunkIndex]?.scopes; + if (!scopes || scopes.environmentFields.has(identifier) || identifier.name === '_ENV') { + return undefined; + } + 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]; +} + +const isStringLiteral = (expression: Ast.Expression): boolean => + expression.kind === 'StringLiteral' || (expression.kind === 'ParenthesizedExpression' && isStringLiteral(expression.expression)); + +function memberTarget(document: ParsedDocument, { node, chunkIndex }: MemberOccurrence): HoverTarget | undefined { + if (node.kind === 'MethodCallExpression') { + // Strings have the string table as their metatable's __index (manual §6.4). + if (isStringLiteral(node.base)) { + const entry = manualEntry(`string.${node.method.name}`); + return entry && { kind: 'library', entry }; + } + const path = globalPath(document, chunkIndex, node.base); + const entry = path?.length === 1 ? externalEntry(`${path.join('.')}:${node.method.name}`) : undefined; + return entry && { kind: 'external', entry }; + } + const path = globalPath(document, chunkIndex, node.base); + if (!path) return undefined; + const names = [...path, node.member.name]; + // `_G.x` is the global `x` (manual §6.1, `_G`). + while (names.length > 1 && names[0] === '_G') names.shift(); + const [head = ''] = names; + if (names.length === 1) { + return globalTarget(document, head); + } + const dotted = names.join('.'); + // Library members are documented one level deep (`string.format`); a module + // table the document assigns itself is not the library's. + const library = names.length === 2 && !firstWrite(document, head) ? manualEntry(dotted) : undefined; + if (library) return { kind: 'library', entry: library }; + // EEex-Docs documents methods of game objects as `C:AddGold`; `C.AddGold` is the same function. + const external = externalEntry(dotted) ?? (names.length === 2 ? externalEntry(names.join(':')) : undefined); + return external && { kind: 'external', entry: external }; +} + +/** What to describe for the name at `offset`, or `undefined` when there is nothing to say. */ +export function hoverTargetAt(document: ParsedDocument, offset: number): HoverHit | undefined { + // A variable and a member name never touch (a `.` or `:` separates them), + // so at most one of them is at `offset`. + const member = memberAt(document, offset); + if (member) { + const target = memberTarget(document, member); + return target && { target, identifier: member.identifier }; + } + const variable = targetAt(document, offset); + if (variable) { + const target = variableTarget(document, variable); + return target && { target, identifier: variable.identifier }; + } + return undefined; +} diff --git a/src/server/syntax/navigation.ts b/src/server/syntax/navigation.ts index dbc399c..8a2fd41 100644 --- a/src/server/syntax/navigation.ts +++ b/src/server/syntax/navigation.ts @@ -22,6 +22,8 @@ export interface TargetHit { readonly target: NavigationTarget; /** The identifier under the cursor. */ readonly identifier: Ast.Identifier; + /** Index in `ParsedDocument.chunks` of the chunk the identifier is in. */ + readonly chunkIndex: number; } export interface VariableOccurrence { @@ -88,6 +90,7 @@ export function targetAt(document: ParsedDocument, offset: number): TargetHit | const declaration = document.chunks[chunkIndex]?.scopes.resolved.get(identifier); return { identifier, + chunkIndex, target: declaration ? { kind: 'local', chunkIndex, declaration } : { kind: 'global', name: identifier.name }, }; } diff --git a/test/unit/server/hover/knowledge.test.ts b/test/unit/server/hover/knowledge.test.ts new file mode 100644 index 0000000..56957da --- /dev/null +++ b/test/unit/server/hover/knowledge.test.ts @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict'; +import { engineReplacement, externalEntry, MANUAL_TITLE, manualEntry } from '../../../../src/server/hover/knowledge.ts'; + +describe('server/hover/knowledge', () => { + it('looks up manual entries with their section and link', () => { + const entry = manualEntry('string.format'); + assert.equal(entry?.kind, 'function'); + assert.equal(entry.heading, 'string.format (formatstring, ···)'); + assert.deepEqual(entry.section, { number: '6.4', title: 'String Manipulation' }); + assert.equal(entry.url, 'https://www.lua.org/manual/5.2/manual.html#pdf-string.format'); + assert.equal(manualEntry('string')?.url, 'https://www.lua.org/manual/5.2/manual.html#6.4'); + assert.equal(manualEntry('_G')?.kind, 'value'); + assert.equal(MANUAL_TITLE, 'Lua 5.2 Reference Manual'); + }); + + it('has no manual entries for libraries the engine does not open', () => { + for (const name of ['io', 'io.write', 'os.time', 'coroutine', 'coroutine.wrap', 'require', 'package.path']) { + assert.equal(manualEntry(name), undefined, name); + } + }); + + it('knows that the engine replaces print, citing IESDP', () => { + assert.deepEqual(engineReplacement('print'), { + name: 'print', + sourceTitle: 'Engine Lua globals', + url: 'https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm', + }); + assert.equal(engineReplacement('tostring'), undefined); + }); + + it('looks up EEex and game functions by their documented name', () => { + assert.equal(externalEntry('EEex_AIBase_GetScriptLevel')?.sourceTitle, 'EEex Functions'); + assert.equal(externalEntry('Infinity_DisplayString')?.sourceTitle, 'EE Game Lua Functions'); + assert.match(externalEntry('C:AddGold')?.url ?? '', /^https:\/\/eeex-docs\.readthedocs\.io\/en\/latest\/EE%20Game%20Lua%20Functions\//); + // Game structures are types, not Lua names. + assert.equal(externalEntry('CGameSprite'), undefined); + }); +}); diff --git a/test/unit/server/hover/resolve.test.ts b/test/unit/server/hover/resolve.test.ts new file mode 100644 index 0000000..e509afd --- /dev/null +++ b/test/unit/server/hover/resolve.test.ts @@ -0,0 +1,127 @@ +import assert from 'node:assert/strict'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; +import { hoverTargetAt, type HoverTarget } from '../../../../src/server/hover/resolve.ts'; + +/** A compact description of a hover target, for comparison. */ +function summary(target: HoverTarget): string { + switch (target.kind) { + case 'local': + return `local ${target.declaration.kind} ${target.declaration.name} ${target.site?.kind ?? '-'}`; + case 'global': + return `global ${target.name} ${target.site?.kind ?? '-'} ${target.link?.name ?? '-'}`; + case 'library': + return `library ${target.entry.name}`; + case 'engineReplaced': + return `engine ${target.replacement.name}`; + case 'external': + return `external ${target.entry.name}`; + } +} + +/** + * Hover at the `occurrence`-th `needle` of `text`, `offset` characters into it: + * `name -> summary`, or `undefined` when there is no hover. + */ +function hover(text: string, needle: string, { occurrence = 0, offset = 0, kind = 'lua' }: { occurrence?: number; offset?: number; kind?: 'lua' | 'menu' } = {}): string | undefined { + let at = -1; + for (let i = 0; i <= occurrence; i++) { + at = text.indexOf(needle, at + 1); + assert.ok(at >= 0, `"${needle}" #${String(i)} not found`); + } + const hit = hoverTargetAt(parseDocument(text, kind), at + offset); + return hit && `${hit.identifier.name} -> ${summary(hit.target)}`; +} + +describe('server/hover/resolve', () => { + describe('variables', () => { + it('describes locals by their declaration', () => { + const text = 'local function f(a, ...) for i = 1, a do local x, y = i end end return f'; + assert.equal(hover(text, 'f', { occurrence: 1 }), 'f -> local localFunction f localFunction'); + assert.equal(hover(text, 'return f', { offset: 7 }), 'f -> local localFunction f localFunction'); + assert.equal(hover(text, 'a,'), 'a -> local parameter a -'); + assert.equal(hover(text, 'i ='), 'i -> local forVariable i -'); + assert.equal(hover(text, 'x,'), 'x -> local local x local'); + assert.equal(hover('function t:m() return self end', 'self'), 'self -> local self self -'); + }); + + it('describes a global the document assigns by its first assignment, also across .menu chunks', () => { + assert.equal(hover('function G(a) end G()', 'G', { occurrence: 1 }), 'G -> global G functionDeclaration -'); + const menu = 'menu { onOpen "Total = Total + 1" } menu { onOpen "print(Total)" }'; + assert.equal(hover(menu, 'Total', { occurrence: 2, kind: 'menu' }), 'Total -> global Total assignment -'); + }); + + it('lets the document\'s own definition win over the libraries, keeping EEex-Docs links', () => { + assert.equal(hover('function print() end print()', 'print', { occurrence: 1 }), 'print -> global print functionDeclaration -'); + assert.equal(hover('string = {} string.format()', 'format'), undefined); + assert.equal( + hover('Infinity_DisplayString = nil Infinity_DisplayString()', 'Infinity_DisplayString', { occurrence: 1 }), + 'Infinity_DisplayString -> global Infinity_DisplayString assignment Infinity_DisplayString', + ); + }); + + it('documents library and EEex-Docs globals, and the engine\'s print', () => { + assert.equal(hover('pairs(t)', 'pairs'), 'pairs -> library pairs'); + assert.equal(hover('local s = string', 'string'), 'string -> library string'); + assert.equal(hover('print(1)', 'print'), 'print -> engine print'); + assert.equal(hover('EEex_AIBase_GetScriptLevel()', 'EEex'), 'EEex_AIBase_GetScriptLevel -> external EEex_AIBase_GetScriptLevel'); + }); + + it('gives no documentation for libraries the engine does not open', () => { + for (const name of ['io', 'os', 'require', 'coroutine', 'unknownGlobal']) { + assert.equal(hover(`${name}()`, name), `${name} -> global ${name} - -`); + } + }); + + it('selects a name when the cursor is just after it', () => { + assert.equal(hover('pairs(t)', 'pairs', { offset: 5 }), 'pairs -> library pairs'); + }); + }); + + describe('fields and methods', () => { + it('documents library members, also through _G and on string literals', () => { + assert.equal(hover('string.format("%d", 1)', 'format'), 'format -> library string.format'); + assert.equal(hover('return math.pi', 'pi'), 'pi -> library math.pi'); + assert.equal(hover('_G.string.format()', 'format'), 'format -> library string.format'); + assert.equal(hover('_G.string.format()', 'string'), 'string -> library string'); + assert.equal(hover('_G.print()', 'print'), 'print -> engine print'); + assert.equal(hover('("x"):rep(3)', 'rep'), 'rep -> library string.rep'); + assert.equal(hover('local s = "x" .. ("y"):upper()', 'upper'), 'upper -> library string.upper'); + }); + + it('documents EEex-Docs methods and dotted names', () => { + assert.equal(hover('C:AddGold(10)', 'AddGold'), 'AddGold -> external C:AddGold'); + assert.equal(hover('C.AddGold(C, 10)', 'AddGold'), 'AddGold -> external C:AddGold'); + assert.equal(hover('worldScreen:CheckIfPaused()', 'CheckIfPaused'), 'CheckIfPaused -> external worldScreen:CheckIfPaused'); + assert.equal(hover('EEex_Options_Option.new({})', 'new'), 'new -> external EEex_Options_Option.new'); + }); + + it('gives no hover for members of locals, unknown tables or other libraries', () => { + assert.equal(hover('local string = {} string.format()', 'format'), undefined); + assert.equal(hover('local s = "" s:rep(2)', 'rep'), undefined); + assert.equal(hover('io.write("x")', 'write'), undefined); + assert.equal(hover('os.time()', 'time'), undefined); + assert.equal(hover('t.x = 1', 'x'), undefined); + assert.equal(hover('string.format.x()', 'x'), undefined); + assert.equal(hover('f().format()', 'format'), undefined); + }); + }); + + describe('_ENV', () => { + it('gives no hover for names resolved through a local _ENV, nor for _ENV itself', () => { + assert.equal(hover('local _ENV = {} print(1)', 'print'), undefined); + assert.equal(hover('local function f(_ENV) return string.format end', 'format'), undefined); + assert.equal(hover('local function f(_ENV) return string.format end', 'string'), undefined); + assert.equal(hover('return _ENV', '_ENV'), undefined); + // Outside the local's scope, globals are globals again. + assert.equal(hover('do local _ENV = {} end print(1)', 'print'), 'print -> engine print'); + }); + }); + + it('gives no hover outside names', () => { + const cases: [string, string][] = [['local x = 1', 'local'], ['x = "print"', 'print'], ['-- print', 'print'], ['x = 1 + 2', '+']]; + for (const [text, needle] of cases) { + assert.equal(hover(text, needle), undefined, text); + } + assert.equal(hover('menu { name "print" }', 'name', { kind: 'menu' }), undefined); + }); +}); From 7edea90f438c7d7a6d2a67d34025d2551bfdcd43 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:06:10 +0100 Subject: [PATCH 09/15] feat(server): render hovers in Markdown and plain text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Turn a hover target into text, in the format the client asks for: - the name as Lua: a ```lua block in Markdown (`local function f(a, b, ...)`, `local g = function(c)`, `(parameter) a`, `(for variable) i`, `(global) function G(a)`), or the manual's heading verbatim (`string.format (formatstring, ···)`); - the manual text, verbatim (Markdown or plain text from data/lua52/manual.json); - the source: `Lua 5.2 Reference Manual, §6.4 – String Manipulation`, or the EEex-Docs section title (`EEex Functions`, `EE Game Lua Functions`), linked to the entry. For `print`, the manual text is replaced by a note that the engine replaces the function, linking IESDP's "Engine Lua globals" page. The server's own four strings (`parameter`, `for variable`, `global` and that note) are added to l10n/server/ in English and the 14 VS Code display languages (machine-produced, like the existing translations; review welcome). `npm run check-l10n` passes. Co-Authored-By: Claude Opus 5.5 --- l10n/server/messages.cs.json | 7 +- l10n/server/messages.de.json | 7 +- l10n/server/messages.es.json | 7 +- l10n/server/messages.fr.json | 7 +- l10n/server/messages.hu.json | 7 +- l10n/server/messages.it.json | 7 +- l10n/server/messages.ja.json | 7 +- l10n/server/messages.json | 7 +- l10n/server/messages.ko.json | 7 +- l10n/server/messages.pl.json | 7 +- l10n/server/messages.pt-br.json | 7 +- l10n/server/messages.ru.json | 7 +- l10n/server/messages.tr.json | 7 +- l10n/server/messages.zh-cn.json | 7 +- l10n/server/messages.zh-tw.json | 7 +- src/server/hover/render.ts | 86 ++++++++++++++++++++++++ test/unit/server/hover/render.test.ts | 95 +++++++++++++++++++++++++++ 17 files changed, 271 insertions(+), 15 deletions(-) create mode 100644 src/server/hover/render.ts create mode 100644 test/unit/server/hover/render.test.ts diff --git a/l10n/server/messages.cs.json b/l10n/server/messages.cs.json index 0967ef4..fef2b14 100644 --- a/l10n/server/messages.cs.json +++ b/l10n/server/messages.cs.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "parametr", + "hover.kind.forVariable": "proměnná for", + "hover.kind.global": "globální", + "hover.engineReplaced": "Herní engine nahrazuje {0} vlastní funkcí, takže popis v příručce Lua 5.2 neplatí. Viz {1}." +} diff --git a/l10n/server/messages.de.json b/l10n/server/messages.de.json index 0967ef4..b9d35a2 100644 --- a/l10n/server/messages.de.json +++ b/l10n/server/messages.de.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "Parameter", + "hover.kind.forVariable": "for-Variable", + "hover.kind.global": "global", + "hover.engineReplaced": "Die Spiel-Engine ersetzt {0} durch eine eigene Funktion, daher gilt die Beschreibung im Lua 5.2-Handbuch nicht. Siehe {1}." +} diff --git a/l10n/server/messages.es.json b/l10n/server/messages.es.json index 0967ef4..bdf6523 100644 --- a/l10n/server/messages.es.json +++ b/l10n/server/messages.es.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "parámetro", + "hover.kind.forVariable": "variable for", + "hover.kind.global": "global", + "hover.engineReplaced": "El motor del juego reemplaza {0} por una función propia, por lo que la descripción del manual de Lua 5.2 no se aplica. Consulte {1}." +} diff --git a/l10n/server/messages.fr.json b/l10n/server/messages.fr.json index 0967ef4..6eacce5 100644 --- a/l10n/server/messages.fr.json +++ b/l10n/server/messages.fr.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "paramètre", + "hover.kind.forVariable": "variable for", + "hover.kind.global": "globale", + "hover.engineReplaced": "Le moteur du jeu remplace {0} par sa propre fonction : la description du manuel Lua 5.2 ne s'applique donc pas. Voir {1}." +} diff --git a/l10n/server/messages.hu.json b/l10n/server/messages.hu.json index 0967ef4..474e42c 100644 --- a/l10n/server/messages.hu.json +++ b/l10n/server/messages.hu.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "paraméter", + "hover.kind.forVariable": "for-változó", + "hover.kind.global": "globális", + "hover.engineReplaced": "A játékmotor saját függvényre cseréli a(z) {0} függvényt, ezért a Lua 5.2 kézikönyv leírása nem érvényes. Lásd: {1}." +} diff --git a/l10n/server/messages.it.json b/l10n/server/messages.it.json index 0967ef4..18cd307 100644 --- a/l10n/server/messages.it.json +++ b/l10n/server/messages.it.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "parametro", + "hover.kind.forVariable": "variabile for", + "hover.kind.global": "globale", + "hover.engineReplaced": "Il motore di gioco sostituisce {0} con una propria funzione, quindi la descrizione del manuale di Lua 5.2 non si applica. Vedere {1}." +} diff --git a/l10n/server/messages.ja.json b/l10n/server/messages.ja.json index 0967ef4..b248938 100644 --- a/l10n/server/messages.ja.json +++ b/l10n/server/messages.ja.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "パラメーター", + "hover.kind.forVariable": "for 変数", + "hover.kind.global": "グローバル", + "hover.engineReplaced": "ゲーム エンジンは {0} を独自の関数に置き換えるため、Lua 5.2 マニュアルの説明は当てはまりません。{1} を参照してください。" +} diff --git a/l10n/server/messages.json b/l10n/server/messages.json index 0967ef4..ff04bbc 100644 --- a/l10n/server/messages.json +++ b/l10n/server/messages.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "parameter", + "hover.kind.forVariable": "for variable", + "hover.kind.global": "global", + "hover.engineReplaced": "The game engine replaces {0} with its own function, so the description in the Lua 5.2 manual does not apply. See {1}." +} diff --git a/l10n/server/messages.ko.json b/l10n/server/messages.ko.json index 0967ef4..83b0160 100644 --- a/l10n/server/messages.ko.json +++ b/l10n/server/messages.ko.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "매개 변수", + "hover.kind.forVariable": "for 변수", + "hover.kind.global": "전역", + "hover.engineReplaced": "게임 엔진이 {0}을(를) 자체 함수로 대체하므로 Lua 5.2 설명서의 설명은 적용되지 않습니다. {1}을(를) 참조하세요." +} diff --git a/l10n/server/messages.pl.json b/l10n/server/messages.pl.json index 0967ef4..2510399 100644 --- a/l10n/server/messages.pl.json +++ b/l10n/server/messages.pl.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "parametr", + "hover.kind.forVariable": "zmienna for", + "hover.kind.global": "globalna", + "hover.engineReplaced": "Silnik gry zastępuje {0} własną funkcją, więc opis z podręcznika Lua 5.2 nie ma zastosowania. Zobacz {1}." +} diff --git a/l10n/server/messages.pt-br.json b/l10n/server/messages.pt-br.json index 0967ef4..c8d52c0 100644 --- a/l10n/server/messages.pt-br.json +++ b/l10n/server/messages.pt-br.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "parâmetro", + "hover.kind.forVariable": "variável for", + "hover.kind.global": "global", + "hover.engineReplaced": "O mecanismo do jogo substitui {0} por uma função própria, portanto a descrição do manual do Lua 5.2 não se aplica. Consulte {1}." +} diff --git a/l10n/server/messages.ru.json b/l10n/server/messages.ru.json index 0967ef4..29538c3 100644 --- a/l10n/server/messages.ru.json +++ b/l10n/server/messages.ru.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "параметр", + "hover.kind.forVariable": "переменная for", + "hover.kind.global": "глобальная", + "hover.engineReplaced": "Игровой движок заменяет {0} собственной функцией, поэтому описание из руководства по Lua 5.2 не применимо. См. {1}." +} diff --git a/l10n/server/messages.tr.json b/l10n/server/messages.tr.json index 0967ef4..7c0f086 100644 --- a/l10n/server/messages.tr.json +++ b/l10n/server/messages.tr.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "parametre", + "hover.kind.forVariable": "for değişkeni", + "hover.kind.global": "global", + "hover.engineReplaced": "Oyun motoru {0} işlevini kendi işleviyle değiştirir; bu nedenle Lua 5.2 kılavuzundaki açıklama geçerli değildir. Bkz. {1}." +} diff --git a/l10n/server/messages.zh-cn.json b/l10n/server/messages.zh-cn.json index 0967ef4..225af1c 100644 --- a/l10n/server/messages.zh-cn.json +++ b/l10n/server/messages.zh-cn.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "参数", + "hover.kind.forVariable": "for 变量", + "hover.kind.global": "全局", + "hover.engineReplaced": "游戏引擎将 {0} 替换为自己的函数,因此 Lua 5.2 手册中的说明不适用。请参阅 {1}。" +} diff --git a/l10n/server/messages.zh-tw.json b/l10n/server/messages.zh-tw.json index 0967ef4..3c183af 100644 --- a/l10n/server/messages.zh-tw.json +++ b/l10n/server/messages.zh-tw.json @@ -1 +1,6 @@ -{} +{ + "hover.kind.parameter": "參數", + "hover.kind.forVariable": "for 變數", + "hover.kind.global": "全域", + "hover.engineReplaced": "遊戲引擎會以自己的函式取代 {0},因此 Lua 5.2 手冊中的說明不適用。請參閱 {1}。" +} diff --git a/src/server/hover/render.ts b/src/server/hover/render.ts new file mode 100644 index 0000000..74739aa --- /dev/null +++ b/src/server/hover/render.ts @@ -0,0 +1,86 @@ +// Hover text for a hover target, in Markdown or plain text. Pure: no LSP or +// `vscode` imports. +// +// Layout: the name as Lua (a code block in Markdown), then the documentation, +// then where it comes from. Documentation quoted from the Lua manual is +// verbatim; only the server's own words (`parameter`, `global`, the note on +// engine replacements) are localized. + +import type { Messages } from '../l10n.ts'; +import type * as Ast from '../syntax/ast.ts'; +import { parameterList, type DeclarationSite } from '../syntax/signatures.ts'; +import { MANUAL_TITLE, type ExternalEntry, type ManualEntry } from './knowledge.ts'; +import type { HoverTarget } from './resolve.ts'; + +export type HoverFormat = 'markdown' | 'plaintext'; + +/** `= function(a, b)` when `value` is a function expression, else nothing. */ +function functionValue(value: Ast.Expression | undefined): string { + return value?.kind === 'FunctionExpression' ? ` = function${parameterList(value)}` : ''; +} + +function localSignature(target: Extract, messages: Messages): string { + const { declaration, site } = target; + switch (declaration.kind) { + case 'localFunction': + return site?.kind === 'localFunction' ? `local function ${declaration.name}${parameterList(site.func)}` : `local function ${declaration.name}`; + case 'local': + return `local ${declaration.name}${site?.kind === 'local' ? functionValue(site.value) : ''}`; + case 'parameter': + case 'self': + return `(${messages.t('hover.kind.parameter')}) ${declaration.name}`; + case 'forVariable': + return `(${messages.t('hover.kind.forVariable')}) ${declaration.name}`; + } +} + +function globalSignature(name: string, site: DeclarationSite | undefined, messages: Messages): string { + const label = `(${messages.t('hover.kind.global')})`; + if (site?.kind === 'functionDeclaration') return `${label} function ${name}${parameterList(site.func)}`; + if (site?.kind === 'assignment') return `${label} ${name}${functionValue(site.value)}`; + return `${label} ${name}`; +} + +interface Link { + readonly text: string; + readonly url: string; +} + +const manualLink = (entry: ManualEntry): Link => ({ text: `${MANUAL_TITLE}, §${entry.section.number} – ${entry.section.title}`, url: entry.url }); +const externalLink = (entry: ExternalEntry): Link => ({ text: entry.sourceTitle, url: entry.url }); + +/** The parts of a hover, before formatting: code, documentation paragraphs (already in the format), source link. */ +interface Parts { + readonly code: string; + readonly documentation?: string; + readonly link?: Link; +} + +function parts(target: HoverTarget, format: HoverFormat, messages: Messages): Parts { + const linkText = (link: Link): string => (format === 'markdown' ? `[${link.text}](${link.url})` : `${link.text} (${link.url})`); + switch (target.kind) { + case 'local': + return { code: localSignature(target, messages) }; + case 'global': + return { code: globalSignature(target.name, target.site, messages), ...(target.link ? { link: externalLink(target.link) } : {}) }; + case 'library': + return { code: target.entry.heading, documentation: format === 'markdown' ? target.entry.markdown : target.entry.plaintext, link: manualLink(target.entry) }; + case 'engineReplaced': { + const { replacement, entry } = target; + const source = linkText({ text: `IESDP: ${replacement.sourceTitle}`, url: replacement.url }); + const name = format === 'markdown' ? `\`${replacement.name}\`` : replacement.name; + return { code: entry?.heading ?? replacement.name, documentation: messages.t('hover.engineReplaced', name, source) }; + } + case 'external': + return { code: target.entry.name, link: externalLink(target.entry) }; + } +} + +/** 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'); +} diff --git a/test/unit/server/hover/render.test.ts b/test/unit/server/hover/render.test.ts new file mode 100644 index 0000000..a2b302b --- /dev/null +++ b/test/unit/server/hover/render.test.ts @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict'; +import { createMessages } from '../../../../src/server/l10n.ts'; +import { renderHover, type HoverFormat } from '../../../../src/server/hover/render.ts'; +import { hoverTargetAt } from '../../../../src/server/hover/resolve.ts'; +import { parseDocument } from '../../../../src/server/syntax/document.ts'; + +const english = createMessages(undefined); + +/** The hover text at the first `needle` of `text`, `offset` characters into it. */ +function render(text: string, needle: string, format: HoverFormat = 'markdown', { offset = 0, locale = undefined as string | undefined } = {}): string { + const at = text.indexOf(needle); + assert.ok(at >= 0, needle); + const hit = hoverTargetAt(parseDocument(text, 'lua'), at + offset); + assert.ok(hit, `no hover at "${needle}"`); + return renderHover(hit.target, format, locale === undefined ? english : createMessages(locale)); +} + +const fence = (code: string): string => `\`\`\`lua\n${code}\n\`\`\``; + +describe('server/hover/render', () => { + describe('locals', () => { + const text = 'local function f(a, b, ...) for i = 1, 2 do end end local g = function(c) end local x, y = 1 function t:m() return self end'; + + it('shows how each local is declared', () => { + assert.equal(render(text, 'f('), fence('local function f(a, b, ...)')); + assert.equal(render(text, 'g ='), fence('local g = function(c)')); + assert.equal(render(text, 'x,'), fence('local x')); + assert.equal(render(text, 'y ='), fence('local y')); + assert.equal(render(text, 'a,'), fence('(parameter) a')); + assert.equal(render(text, 'self'), fence('(parameter) self')); + assert.equal(render(text, 'i ='), fence('(for variable) i')); + }); + + it('localizes the server\'s own labels', () => { + assert.equal(render(text, 'a,', 'markdown', { locale: 'de' }), fence('(Parameter) a')); + assert.equal(render(text, 'i =', 'markdown', { locale: 'fr-CA' }), fence('(variable for) i')); + }); + + it('renders plain text without fences', () => { + assert.equal(render(text, 'f(', 'plaintext'), 'local function f(a, b, ...)'); + }); + }); + + describe('globals', () => { + it('shows the first assignment of a global the document defines', () => { + assert.equal(render('function G(a) end', 'G'), fence('(global) function G(a)')); + assert.equal(render('H = function(...) end', 'H'), fence('(global) H = function(...)')); + assert.equal(render('K = 1', 'K'), fence('(global) K')); + assert.equal(render('unknownGlobal()', 'unknown'), fence('(global) unknownGlobal')); + assert.equal(render('io.write()', 'io', 'markdown', { locale: 'ja' }), fence('(グローバル) io')); + }); + + it('links an EEex-Docs name the document redefines', () => { + const markdown = render('Infinity_DisplayString = nil', 'Infinity'); + assert.match(markdown, /^```lua\n\(global\) Infinity_DisplayString\n```\n\n---\n\n\[EE Game Lua Functions\]\(https:\/\/eeex-docs\.readthedocs\.io\/[^)]+\)$/); + }); + }); + + describe('libraries', () => { + it('quotes the manual entry with its heading and a link to its section', () => { + assert.equal( + render('return math.huge', 'huge'), + `${fence('math.huge')}\n\n---\n\nThe value \`HUGE_VAL\`, a value larger than or equal to any other numerical value.\n\n---\n\n` + + '[Lua 5.2 Reference Manual, §6.6 – Mathematical Functions](https://www.lua.org/manual/5.2/manual.html#pdf-math.huge)', + ); + assert.equal( + render('return math.huge', 'huge', 'plaintext'), + 'math.huge\n\nThe value HUGE_VAL, a value larger than or equal to any other numerical value.\n\n' + + 'Lua 5.2 Reference Manual, §6.6 – Mathematical Functions: https://www.lua.org/manual/5.2/manual.html#pdf-math.huge', + ); + assert.ok(render('string.format()', 'format').startsWith(fence('string.format (formatstring, ···)'))); + assert.ok(render('return string', 'string').endsWith('[Lua 5.2 Reference Manual, §6.4 – String Manipulation](https://www.lua.org/manual/5.2/manual.html#6.4)')); + }); + + it('replaces the manual text of print with a note on the engine, in the display language', () => { + const iesdp = 'https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm'; + assert.equal( + render('print(1)', 'print'), + `${fence('print (···)')}\n\n---\n\n` + + `The game engine replaces \`print\` with its own function, so the description in the Lua 5.2 manual does not apply. See [IESDP: Engine Lua globals](${iesdp}).`, + ); + assert.equal( + render('print(1)', 'print', 'plaintext'), + `print (···)\n\nThe game engine replaces print with its own function, so the description in the Lua 5.2 manual does not apply. See IESDP: Engine Lua globals (${iesdp}).`, + ); + assert.match(render('print(1)', 'print', 'markdown', { locale: 'de' }), /Die Spiel-Engine ersetzt `print` durch eine eigene Funktion/); + }); + + it('links EEex-Docs functions by their documented name', () => { + const markdown = render('C:AddGold(1)', 'AddGold'); + assert.match(markdown, /^```lua\nC:AddGold\n```\n\n---\n\n\[EE Game Lua Functions\]\(https:\/\/eeex-docs\.readthedocs\.io\/[^)]+\)$/); + assert.match(render('EEex_AIBase_GetScriptLevel()', 'EEex', 'plaintext'), /^EEex_AIBase_GetScriptLevel\n\nEEex Functions: https:\/\/eeex-docs\.readthedocs\.io\//); + }); + }); +}); From 996eeff78d3cf48d14eb008f9ff4be2f7c64ec4a Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:06:55 +0100 Subject: [PATCH 10/15] build(notices): credit the Lua 5.2 manual when its text is bundled Hovers will quote the Lua 5.2 reference manual, whose copyright line reads "Freely available under the terms of the Lua license". When the esbuild metafiles show data/lua52/manual.json in a bundle, the notices gain a section with the manual's title, source, copyright line (read from the data file) and the Lua license text already kept in third_party/lua52/licenses/lua.txt. Nothing bundles the file yet, so THIRD_PARTY_NOTICES.md is unchanged (`npm run notices -- --check` passes); the hover commit regenerates it. Co-Authored-By: Claude Opus 5.5 --- scripts/third-party-notices.mts | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/scripts/third-party-notices.mts b/scripts/third-party-notices.mts index 80bf10d..3e33fd0 100644 --- a/scripts/third-party-notices.mts +++ b/scripts/third-party-notices.mts @@ -6,7 +6,8 @@ // Sources: dist/{client/extension,server/server}.meta.json (esbuild metafiles). // Every npm package with at least one bundled file is listed with the license // text it ships. Code under third_party/ is listed with the texts kept in -// third_party//licenses/. +// third_party//licenses/, and so is the Lua 5.2 manual text that +// data/lua52/manual.json quotes, when it is bundled. import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -73,6 +74,8 @@ const packages = [...packageDirs] const fence = (text: string): string => `\`\`\`text\n${text}\n\`\`\``; const usesLua52 = [...inputs].some((input) => input.startsWith('third_party/lua52/dist/')); const lua52License = (name: string): string => readFileSync(join(root, 'third_party', 'lua52', 'licenses', name), 'utf8').trim(); +const manualData = 'data/lua52/manual.json'; +const usesManual = inputs.has(manualData); const sections: string[] = [ '', @@ -115,19 +118,39 @@ if (usesLua52) { ); } +if (usesManual) { + const { title, copyright, source } = JSON.parse(readFileSync(join(root, manualData), 'utf8')) as { + title: string; + copyright: string; + source: { url: string; member: string }; + }; + sections.push( + '', + `## ${title}`, + '', + `Hovers quote the library reference of the ${title} (${source.member} in`, + `<${source.url}>), converted to Markdown by`, + '[`scripts/lua-manual/`](scripts/lua-manual/). The manual reads:', + `"${copyright}" The Lua license:`, + '', + fence(lua52License('lua.txt')), + ); +} + sections.push('', '## npm packages', ''); for (const pkg of packages) { sections.push(`### ${pkg.name} ${pkg.version}`, '', `License: ${pkg.license}${pkg.homepage ? ` — <${pkg.homepage}>` : ''}`, '', fence(pkg.text), ''); } const content = `${sections.join('\n').trimEnd()}\n`; +const summary = `${packages.length} npm packages${usesLua52 ? ' + Lua 5.2.4' : ''}${usesManual ? ' + Lua 5.2 manual' : ''}`; if (process.argv.includes('--check')) { const current = existsSync(output) ? readFileSync(output, 'utf8') : ''; if (current !== content) { fail('THIRD_PARTY_NOTICES.md does not match the bundled dependencies. Run `npm run package && node scripts/third-party-notices.mts` and commit the result.'); } - console.log(`THIRD_PARTY_NOTICES.md is up to date (${packages.length} npm packages${usesLua52 ? ' + Lua 5.2.4' : ''}).`); + console.log(`THIRD_PARTY_NOTICES.md is up to date (${summary}).`); } else { writeFileSync(output, content); - console.log(`Wrote THIRD_PARTY_NOTICES.md (${packages.length} npm packages${usesLua52 ? ' + Lua 5.2.4' : ''}).`); + console.log(`Wrote THIRD_PARTY_NOTICES.md (${summary}).`); } From a5566e71c1e4c0e1934ae6b162533b09b022daf1 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:13:30 +0100 Subject: [PATCH 11/15] feat(server): add hover MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Register `textDocument/hover` and advertise `hoverProvider`. The handler follows the other features: it uses the shared parse cache, checks cancellation before its synchronous work, and logs and returns null on any error. It answers in the first format of the client's `hover.contentFormat` it can produce (Markdown or plain text; plain text when the client lists none), with the server messages of the client's `locale`, and gives the range of the name. Integration tests (original fixtures hover.lua and HOVER.MENU) cover the manual text and link of string.format, a local function, a parameter, a `for` variable, a global function, the print note, an EEex-Docs link, a shadowed `string`, no hover on a keyword, and a .menu global assigned in another chunk. THIRD_PARTY_NOTICES.md now credits the Lua 5.2 manual, which the server bundle quotes. Measured on the game's UI.MENU (588 KB, 16,425 names; local, not committed), Node 24.22.1, five runs: - first hover of a parsed document (builds the member index and the declaration sites): 4.7 ms; - each name after that: 0.09–0.11 ms median, 4.4 ms at worst, against the 50 ms budget; - loading the hover modules and their data: 14.7 ms, once at startup. Size: dist/server/server.js 420,851 → 662,479 bytes (manual text 81.4 KB, EEex-Docs names and links 146.7 KB, code and messages the rest); VSIX 273.1 → 308.5 KB; installed size 950.05 KB → 1.16 MB. Stripping the shared URL prefixes of the EEex-Docs links would save about 58 KB but change the data format the EEex sync workflows write, so it is not done here. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 23 +++++++- THIRD_PARTY_NOTICES.md | 31 ++++++++++ docs/CHANGELOG.vsix.md | 5 ++ src/server/features/hover.ts | 48 +++++++++++++++ src/server/server.ts | 8 +++ test/fixtures/workspace/HOVER.MENU | 13 +++++ test/fixtures/workspace/hover.lua | 19 ++++++ test/integration/hover.test.ts | 77 +++++++++++++++++++++++++ test/unit/server/features/hover.test.ts | 16 +++++ 9 files changed, 238 insertions(+), 2 deletions(-) create mode 100644 src/server/features/hover.ts create mode 100644 test/fixtures/workspace/HOVER.MENU create mode 100644 test/fixtures/workspace/hover.lua create mode 100644 test/integration/hover.test.ts create mode 100644 test/unit/server/features/hover.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f140d17..37ec771 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,10 +69,29 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). `**/*.[mM][eE][nN][uU]`, and creates and deletes of folders), workspace folder changes and document closes. `files.exclude` is honored as VS Code's explorer applies it, with an original matcher checked against VS Code's own; changing it rescans. +- Hover (`textDocument/hover`), in Markdown or plain text as the client prefers: + - Lua 5.2 library functions, values and module tables, with the text of the + [Lua 5.2 manual](https://www.lua.org/manual/5.2/manual.html) verbatim and a link to the entry: + the basic functions and the `string`, `table`, `math`, `bit32` and `debug` libraries, the ones + the engine opens (IESDP), also as `_G.string.format` and `("x"):rep()`. The text is generated + from `doc/manual.html` of the checksum-verified Lua 5.2.4 tarball (`npm run lua-manual`, checked + in CI) and is identical to the online manual's. `io`, `os`, `package` (`require`) and + `coroutine` are not documented, as the engine does not provide them. + - `print`: a note that the engine replaces it, linking IESDP's *Engine Lua globals*, instead of + the manual's description. + - EEex and game functions (`EEex_*`, `Infinity_*`, `C:AddGold`, also called as `C.AddGold`): + the name and a link to EEex-Docs; no EEex-Docs text is copied. + - Locals and globals of the document: how they are declared (`local function f(a, b)`, + `(parameter) a`, `(for variable) i`, `(global) function G(x)`), from the first assignment for + a global, shared across the Lua chunks of a `.menu` file. + - No library text for names a local shadows (`local string = {}`), globals the document assigns + itself, or names 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. - Error-tolerant Lua 5.2 parser and scope analysis (`src/server/syntax/`), checked against the official compiler by a differential test; it publishes no diagnostics of its own. -- Localization of the manifest and UI strings into all 14 VS Code display languages - (machine-produced; review welcome). +- Localization of the manifest, UI strings and the language server's hover labels into all 14 VS + Code display languages (machine-produced; review welcome). - Setup guides for Sublime Text, Neovim, Emacs, JetBrains IDEs, Helix, Zed, Kate, Notepad++ and Geany. - EEex documentation index (`data/eeex/`): names and deep links only, synced from the published Read the Docs build. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 5d83ffa..e076dd4 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -350,6 +350,37 @@ obstacle to adoption, that text has been removed. compiled object forms to be redistributed without the attribution conditions of sections 4(a), 4(b) and 4(d) of the Apache License 2.0. +## Lua 5.2 Reference Manual + +Hovers quote the library reference of the Lua 5.2 Reference Manual (lua-5.2.4/doc/manual.html in +), converted to Markdown by +[`scripts/lua-manual/`](scripts/lua-manual/). The manual reads: +"Copyright © 2011–2015 Lua.org, PUC-Rio. Freely available under the terms of the Lua license." The Lua license: + +```text +Source: lua-5.2.4.tar.gz, doc/readme.html, section "License" (https://www.lua.org/ftp/lua-5.2.4.tar.gz). + +Copyright © 1994–2015 Lua.org, PUC-Rio. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + ## npm packages ### balanced-match 4.0.4 diff --git a/docs/CHANGELOG.vsix.md b/docs/CHANGELOG.vsix.md index 5f6fb78..e47274f 100644 --- a/docs/CHANGELOG.vsix.md +++ b/docs/CHANGELOG.vsix.md @@ -33,6 +33,11 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea - **Go to Symbol in Workspace** (Ctrl+T) finds functions, variables and menus in every Lua and `.menu` file of your workspace, even files you haven't opened. Files hidden with *Files: Exclude* are left out. +- **Documentation on hover.** Hover over a Lua function such as `string.format` to read its + description from the Lua 5.2 manual, over an EEex or game function such as + `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. - **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/hover.ts b/src/server/features/hover.ts new file mode 100644 index 0000000..78ebb87 --- /dev/null +++ b/src/server/features/hover.ts @@ -0,0 +1,48 @@ +import type { Connection, Hover, TextDocuments } from 'vscode-languageserver/node'; +import { MarkupKind } from 'vscode-languageserver/node'; +import type { TextDocument } from 'vscode-languageserver-textdocument'; +import type { ParsedDocumentCache } from '../documentCache.ts'; +import { renderHover, type HoverFormat } from '../hover/render.ts'; +import { hoverTargetAt } from '../hover/resolve.ts'; +import type { Messages } from '../l10n.ts'; + +export interface HoverDeps { + readonly cache: ParsedDocumentCache; + readonly format: HoverFormat; + /** Messages in the client's locale. */ + 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 => { + 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 hit = hoverTargetAt(deps.cache.get(document), document.offsetAt(position)); + if (!hit) { + return null; + } + return { + contents: { kind: deps.format === 'markdown' ? MarkupKind.Markdown : MarkupKind.PlainText, value: renderHover(hit.target, deps.format, deps.messages) }, + range: { start: document.positionAt(hit.identifier.start), end: document.positionAt(hit.identifier.end) }, + }; + } catch (error) { + connection.console.error(`Hover for ${textDocument.uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`); + return null; + } + }); +} diff --git a/src/server/server.ts b/src/server/server.ts index 9a5baff..4d546a7 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -19,9 +19,11 @@ 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 * as references from './features/references.ts'; import * as rename from './features/rename.ts'; import * as workspaceSymbols from './features/workspaceSymbols.ts'; +import { createMessages } from './l10n.ts'; import { SettingsStore } from './settingsStore.ts'; import { loadLua52 } from './validation/lua52.ts'; import { nodeFileSystem } from './workspace/nodeFileSystem.ts'; @@ -97,6 +99,11 @@ connection.onInitialize((params) => { references.register(connection, documents, { cache: parsed }); rename.register(connection, documents, { cache: parsed, documentChanges: workspace?.workspaceEdit?.documentChanges === true }); 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), + }); // One handler per notification: settings changes go to every feature that needs them. connection.onDidChangeConfiguration(({ settings }) => { diagnosticsFeature.configurationChanged(settings); @@ -117,6 +124,7 @@ connection.onInitialize((params) => { // Without prepareSupport the client must not be sent `prepareProvider` (LSP 3.17). renameProvider: prepareRename ? { prepareProvider: true } : true, workspaceSymbolProvider: true, + hoverProvider: true, ...(workspaceFolderChanges ? { workspace: { workspaceFolders: { supported: true, changeNotifications: true } } } : {}), }, serverInfo: { name: 'IE Lua Language Server' }, diff --git a/test/fixtures/workspace/HOVER.MENU b/test/fixtures/workspace/HOVER.MENU new file mode 100644 index 0000000..a3b0db3 --- /dev/null +++ b/test/fixtures/workspace/HOVER.MENU @@ -0,0 +1,13 @@ +-- Original fixture: hover over the Lua of a .menu file. +` +hoverCount = 0 +` +menu +{ + name 'HOVER_MAIN' + onOpen + " + hoverCount = hoverCount + 1 + Infinity_DisplayString(string.rep('-', hoverCount)) + " +} diff --git a/test/fixtures/workspace/hover.lua b/test/fixtures/workspace/hover.lua new file mode 100644 index 0000000..88e6fe1 --- /dev/null +++ b/test/fixtures/workspace/hover.lua @@ -0,0 +1,19 @@ +-- Original fixture: hover. +local function greet(name, ...) + local message = string.format("Hello, %s", name) + print(message) + return message +end + +for index = 1, 3 do + greet(tostring(index)) +end + +function Refresh(force) + Infinity_DisplayString("refresh") +end + +local function shadowed() + local string = { format = greet } + return string.format("x") +end diff --git a/test/integration/hover.test.ts b/test/integration/hover.test.ts new file mode 100644 index 0000000..57d20eb --- /dev/null +++ b/test/integration/hover.test.ts @@ -0,0 +1,77 @@ +import * as assert from 'node:assert/strict'; +import * as vscode from 'vscode'; +import { activateExtension, closeAllEditors, openFixture } from './helpers.ts'; + +/** + * The hover text at the `occurrence`-th (0-based) `needle` of a fixture, or + * `undefined` when no provider has anything to say. + */ +async function hoverAt(file: string, needle: string, occurrence = 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 hovers = await vscode.commands.executeCommand('vscode.executeHoverProvider', uri, document.positionAt(offset)); + // The server sends MarkupContent, which the client turns into a MarkdownString. + const values = hovers.flatMap((hover) => + hover.contents.map((content) => { + assert.ok(content instanceof vscode.MarkdownString, 'expected Markdown hover content'); + return content.value; + }), + ); + return values.length === 0 ? undefined : values.join('\n'); +} + +suite('Hover', () => { + suiteSetup(async () => { + await activateExtension(); + }); + + teardown(async () => { + await closeAllEditors(); + }); + + test('quotes the Lua 5.2 manual for a library function, with a link to it', async () => { + const value = await hoverAt('hover.lua', 'format'); + assert.ok(value, 'no hover'); + assert.ok(value.startsWith('```lua\nstring.format (formatstring, ···)\n```'), value); + assert.ok(value.includes('Returns a formatted version of its variable number of arguments'), value); + assert.ok(value.endsWith('[Lua 5.2 Reference Manual, §6.4 – String Manipulation](https://www.lua.org/manual/5.2/manual.html#pdf-string.format)'), value); + }); + + test('describes locals by their declaration', async () => { + assert.equal(await hoverAt('hover.lua', 'greet', 1), '```lua\nlocal function greet(name, ...)\n```'); + assert.equal(await hoverAt('hover.lua', 'name', 1), '```lua\n(parameter) name\n```'); + assert.equal(await hoverAt('hover.lua', 'index', 1), '```lua\n(for variable) index\n```'); + assert.equal(await hoverAt('hover.lua', 'Refresh'), '```lua\n(global) function Refresh(force)\n```'); + }); + + test('says that the engine replaces print instead of quoting the manual', async () => { + const value = await hoverAt('hover.lua', 'print'); + assert.ok(value, 'no hover'); + assert.ok(value.includes('The game engine replaces `print` with its own function'), value); + assert.ok(value.includes('(https://gibberlings3.github.io/iesdp/file_formats/ie_formats/lua_globals.htm)'), value); + }); + + test('links game functions to EEex-Docs', async () => { + const value = await hoverAt('hover.lua', 'Infinity_DisplayString'); + assert.match(value ?? '', /^```lua\nInfinity_DisplayString\n```\n\n---\n\n\[EE Game Lua Functions\]\(https:\/\/eeex-docs\.readthedocs\.io\//); + }); + + test('gives no library documentation for a shadowed library table, nor any hover on keywords', async () => { + assert.equal(await hoverAt('hover.lua', 'format', 2), undefined); + assert.equal(await hoverAt('hover.lua', 'string', 2), '```lua\nlocal string\n```'); + assert.equal(await hoverAt('hover.lua', 'local'), undefined); + }); + + test('describes a .menu global by its assignment in another chunk', async () => { + assert.equal(await hoverAt('HOVER.MENU', 'hoverCount', 2), '```lua\n(global) hoverCount\n```'); + const value = await hoverAt('HOVER.MENU', 'rep'); + assert.ok(value, 'no hover'); + assert.ok(value.startsWith('```lua\nstring.rep (s, n [, sep])\n```'), value); + }); +}); diff --git a/test/unit/server/features/hover.test.ts b/test/unit/server/features/hover.test.ts new file mode 100644 index 0000000..c9425bc --- /dev/null +++ b/test/unit/server/features/hover.test.ts @@ -0,0 +1,16 @@ +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'); + }); +}); From 0d1275c5da490264afe7900b8c8d0ac797691e9e Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:15:58 +0100 Subject: [PATCH 12/15] docs: document hover - README: hover in the feature list and the early-version note (no longer "planned"). - Editor guide: the hover row in "What you get", and what other editors need: `hover.contentFormat` for Markdown, `locale` for the server's own words (and how a locale is matched). - CONTRIBUTING: layout (src/server/hover/, data/lua52/, l10n/server/), `npm run lua-manual`, server strings under Localization, and a section on the Lua 5.2 manual data (regenerate, --check, --compare-online). - CLAUDE.md: purpose line, layout and the lua-manual command. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 +++++- CONTRIBUTING.md | 23 +++++++++++++++++++++++ README.md | 14 +++++++++++--- docs/editors/README.md | 10 +++++++++- 4 files changed, 48 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 98992de..63973de 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ |---|---| | Name | `IE Lua Language Server` | | Publisher | `infinity-engine-tools` | -| Purpose | Lua 5.2 language support (diagnostics, document 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, 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) | @@ -32,6 +32,8 @@ │ ├── server/ # Language server (separate Node process) │ │ ├── server.ts # Connection, capabilities, handlers │ │ ├── features/ # completion.ts, diagnostics.ts, hover.ts, ... +│ │ ├── hover/ # Hover targets, library knowledge and rendering (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 │ │ └── workspace/ # Workspace index, files.exclude glob matching (fs injected; no LSP) @@ -42,6 +44,7 @@ │ └── fixtures/workspace/ # Original fixtures only — never copy game files ├── third_party/lua52/ # Official Lua 5.2.4 → WASM (reproducible build; dist/ is generated) ├── data/eeex/ # Generated EEex docs index (names + links only; see scripts/eeex-docs/) +├── data/lua52/ # Lua 5.2 manual library text, generated by scripts/lua-manual/ (CI-checked) ├── scripts/ # Repo tooling in TypeScript (`.mts`, run by Node's type stripping) ├── docs/editors/ # Setup guides for non-VS Code editors ├── dist/ # esbuild output — generated, never edit @@ -71,6 +74,7 @@ The server runs in a separate process where the `vscode` module does not exist. | Localization check | `npm run check-l10n` | | Third-party notices | `npm run notices` (after `npm run package`; `-- --check` in CI) | | Rebuild Lua WASM | `npm run build:wasm` (needs pinned emsdk; see CONTRIBUTING.md) | +| Regenerate Lua manual data | `npm run lua-manual` (`-- --check` in CI) | | Build VSIX | `npx @vscode/vsce package --no-dependencies --changelog-path docs/CHANGELOG.vsix.md` | **Definition of done for any change:** `check-types`, `lint` and `test:unit` all pass. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4987248..dc18930 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,11 +29,14 @@ server (port 6009). | `src/client/` | VS Code extension host code: activation, command, settings, language client | | `src/server/` | Language server (separate Node process; no `vscode` import) | | `src/server/validation/` | Pure validation logic, unit-tested without LSP or VS Code | +| `src/server/hover/` | What a hover describes and its text (pure; library data from `data/lua52/` and `data/eeex/`) | | `src/server/syntax/` | Error-tolerant Lua 5.2 parser, scope analysis, document symbols and folding (pure; checked against the official compiler by `test/unit/server/syntax/differential.test.ts`) | | `src/server/workspace/` | Index of the workspace's Lua and `.menu` files, and `files.exclude` matching as VS Code applies it (file system injected, unit-tested with an in-memory one) | | `src/shared/` | Types and constants used by both sides | | `third_party/lua52/` | Reproducible build of the official Lua 5.2.4 compiler to WebAssembly | | `data/eeex/` | Generated EEex documentation index (names and links) | +| `data/lua52/` | Lua 5.2 library reference generated from the official manual (see below) | +| `l10n/server/` | The language server's own messages, per locale | | `scripts/` | Repository tooling (TypeScript run directly by Node.js) | | `test/unit/`, `test/integration/` | Mocha unit tests; VS Code integration tests | | `docs/editors/` | Setup guides for other editors | @@ -53,6 +56,7 @@ See [`CLAUDE.md`](CLAUDE.md) for the architecture rules. | `npm run package` | Production bundle | | `npm run notices` | Regenerate `THIRD_PARTY_NOTICES.md` (after `npm run package`) | | `npm run build:wasm` | Rebuild the Lua 5.2 WebAssembly module (needs Emscripten, see below) | +| `npm run lua-manual` | Regenerate `data/lua52/manual.json` from the official Lua 5.2 manual (see below) | **Definition of done:** `check-types`, `lint` and `test:unit` pass. Run `npm test` too when you touch activation, commands, settings or the language client/server wiring. @@ -91,6 +95,9 @@ The extension is translated into the 14 display languages VS Code offers - Manifest strings: `package.nls.json` (English) and `package.nls..json`. - Runtime strings: `vscode.l10n.t('…')` in `src/client/`. After adding or changing one, run `npx @vscode/l10n-dev export --outDir l10n src/client` and update every `l10n/bundle.l10n..json`. +- Language server strings: `messages.t('key', …)` in `src/server/` (`src/server/l10n.ts`), with the + English text in `l10n/server/messages.json` and one `l10n/server/messages..json` per + locale. The server picks the table from the client's `locale`, so they work in every editor. - Keep code spans, setting links (`` `#ieLua.validate.mode#` ``) and `{0}` placeholders unchanged, and refer to commands by the locale's translated title. `npm run check-l10n` enforces all of this. @@ -112,6 +119,22 @@ npm run build:wasm -- --check # verify the committed files are reproducible The Emscripten version is pinned in `third_party/lua52/build.mts` (`EMSCRIPTEN_VERSION`); CI reads it from there. The Lua tarball is verified against the SHA-256 published on . +## The Lua 5.2 manual data + +Hovers quote the library reference of the Lua 5.2 manual from `data/lua52/manual.json`, which is +generated and committed. `npm run lua-manual` rebuilds it from `doc/manual.html` in the same +checksum-verified Lua 5.2.4 tarball as the WebAssembly module (downloaded once into `.cache/lua`): + +```sh +npm run lua-manual # regenerate +npm run lua-manual -- --check # verify the committed file (CI does this) +npm run lua-manual -- --compare-online # audit: compare with https://www.lua.org/manual/5.2/ +``` + +Only the libraries the game engine opens are included (see CLAUDE.md, section 7). The converter +in `scripts/lua-manual/convert.mts` accepts exactly the HTML the manual uses and fails on anything +else; its header lists the three places where Markdown cannot show the manual's formatting. + ## Releases Releases are private: VSIX files are attached to [GitHub Releases](https://github.com/4Luke4/IE-Lua-Language-Server/releases). diff --git a/README.md b/README.md index c08e741..c55c911 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,10 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the `.menu` files such as `UI.MENU`. > [!NOTE] -> This is an early version. It currently provides **syntax diagnostics**, **document symbols**, -> **workspace symbols**, **folding**, and **go to definition**, **find references** and **rename** -> within a file; completion, hover, cross-file navigation, formatting and more are planned. +> 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. ## Features @@ -36,6 +37,13 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the you haven't opened; files hidden with *Files: Exclude* are left out. - **Folding that follows the code:** functions, loops, each `if`/`elseif`/`else` branch, tables, comments, and every `{ … }` block and Lua script of a `.menu` file. +- **Documentation on hover.** Lua functions such as `string.format` show their description from + the [Lua 5.2 manual](https://www.lua.org/manual/5.2/manual.html), word for word, with a link to + it. Only the libraries the game provides are documented (`io`, `os`, `require` and coroutines + are not), and `print` tells you that the game replaces it. EEex and game functions such as + `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. - **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 078c4c4..e0ef1b7 100644 --- a/docs/editors/README.md +++ b/docs/editors/README.md @@ -68,6 +68,7 @@ node /path/to/server.js --stdio | Go to definition | `textDocument/definition` | The declaration of a local, or every assignment to a global, in the same file. | | Find references | `textDocument/references` | Every use of a local or global in the same file. | | Rename | `textDocument/prepareRename`, `textDocument/rename` | Same file only; refused, with the reason as the error message, when the rename could change what the code does. | +| 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. | | 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; @@ -80,6 +81,13 @@ through `workspace/configuration` (your guide says whether it does), you can add `ieLua`, for example `{ "files": { "exclude": { "**/backup": true } } }`. Only folders on the local disk are scanned. -Symbols, folding and navigation always reflect the current text, whatever `validate.mode` is. +Hover shows the [Lua 5.2 manual](https://www.lua.org/manual/5.2/manual.html) text for the +libraries the game provides, a link to the EEex documentation for EEex and game functions, and +how your own variables are declared. Editors that render Markdown get code blocks and links; +others get plain text with the links written out. The few words of the server's own (such as +`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. 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. From a795760567ce6f70c391662130c4d32ba76ec780 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:18:54 +0100 Subject: [PATCH 13/15] fix(server): do not quote the manual for library members the document redefines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found by the project review. The document's own definition already won over the libraries for globals (`string = {}`), but not for members: after `string.format = myFormat` or `function string.format() end`, hovering `string.format` still showed the manual's description, which no longer applies. The resolver now collects, once per parsed document, the `table.field` names the document assigns on global tables (`t.f = …`, `_G.t.f = …`, `function t.f()`, `function t:f()`; not on locals or fields of a local `_ENV`), and skips the manual entry for those members, including `("x"):rep()` when `string.rep` is redefined. Other members of the same library are still documented. UI.MENU timings are unchanged within noise: first hover 5.0 ms (was 4.7), median 0.09–0.10 ms, worst 4.9 ms (was 4.4), five runs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++- src/server/hover/resolve.ts | 60 +++++++++++++++++++++++--- test/unit/server/hover/resolve.test.ts | 11 +++++ 3 files changed, 68 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37ec771..fe5c6a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,8 +84,9 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md). - Locals and globals of the document: how they are declared (`local function f(a, b)`, `(parameter) a`, `(for variable) i`, `(global) function G(x)`), from the first assignment for a global, shared across the Lua chunks of a `.menu` file. - - No library text for names a local shadows (`local string = {}`), globals the document assigns - itself, or names resolved through a local `_ENV`. + - No library text for names a local shadows (`local string = {}`), globals or library members the + document assigns itself (`string = …`, `string.format = …`, `function string.trim()`), or names + 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. - Error-tolerant Lua 5.2 parser and scope analysis (`src/server/syntax/`), checked against the diff --git a/src/server/hover/resolve.ts b/src/server/hover/resolve.ts index cb76fb3..9c93bb2 100644 --- a/src/server/hover/resolve.ts +++ b/src/server/hover/resolve.ts @@ -13,7 +13,9 @@ // and coroutine, which the engine does not provide. // - A field or method name: library and EEex-Docs names only (`string.format`, // `_G.string.format`, `("x"):rep()`, `C:AddGold()`, `EEex_Options_Option.new`). -// Fields of anything else (locals, tables built in Lua) have no hover. +// Fields of anything else (locals, tables built in Lua) have no hover. As for +// globals, a library member the document defines itself (`string.format = f`, +// `function string.trim()`) is not described by the manual. // // Names resolved through a local `_ENV` are fields of that table, so they get // no hover. Without type inference that is the only safe answer. @@ -21,6 +23,7 @@ import type * as Ast from '../syntax/ast.ts'; import type { ParsedDocument } from '../syntax/document.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'; @@ -92,6 +95,53 @@ function globalPath(document: ParsedDocument, chunkIndex: number, expression: As 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); +} + const isStringLiteral = (expression: Ast.Expression): boolean => expression.kind === 'StringLiteral' || (expression.kind === 'ParenthesizedExpression' && isStringLiteral(expression.expression)); @@ -99,7 +149,7 @@ function memberTarget(document: ParsedDocument, { node, chunkIndex }: MemberOccu if (node.kind === 'MethodCallExpression') { // Strings have the string table as their metatable's __index (manual §6.4). if (isStringLiteral(node.base)) { - const entry = manualEntry(`string.${node.method.name}`); + const entry = libraryMember(document, `string.${node.method.name}`); return entry && { kind: 'library', entry }; } const path = globalPath(document, chunkIndex, node.base); @@ -108,9 +158,7 @@ function memberTarget(document: ParsedDocument, { node, chunkIndex }: MemberOccu } const path = globalPath(document, chunkIndex, node.base); if (!path) return undefined; - const names = [...path, node.member.name]; - // `_G.x` is the global `x` (manual §6.1, `_G`). - while (names.length > 1 && names[0] === '_G') names.shift(); + const names = withoutG([...path, node.member.name]); const [head = ''] = names; if (names.length === 1) { return globalTarget(document, head); @@ -118,7 +166,7 @@ function memberTarget(document: ParsedDocument, { node, chunkIndex }: MemberOccu const dotted = names.join('.'); // Library members are documented one level deep (`string.format`); a module // table the document assigns itself is not the library's. - const library = names.length === 2 && !firstWrite(document, head) ? manualEntry(dotted) : undefined; + const library = names.length === 2 && !firstWrite(document, head) ? libraryMember(document, dotted) : undefined; if (library) return { kind: 'library', entry: library }; // EEex-Docs documents methods of game objects as `C:AddGold`; `C.AddGold` is the same function. const external = externalEntry(dotted) ?? (names.length === 2 ? externalEntry(names.join(':')) : undefined); diff --git a/test/unit/server/hover/resolve.test.ts b/test/unit/server/hover/resolve.test.ts index e509afd..b066e95 100644 --- a/test/unit/server/hover/resolve.test.ts +++ b/test/unit/server/hover/resolve.test.ts @@ -88,6 +88,17 @@ describe('server/hover/resolve', () => { assert.equal(hover('local s = "x" .. ("y"):upper()', 'upper'), 'upper -> library string.upper'); }); + it('lets the document\'s own definition of a library member win over the manual', () => { + assert.equal(hover('string.format = nil string.format()', 'format', { occurrence: 1 }), undefined); + assert.equal(hover('_G.string.format = nil string.format()', 'format', { occurrence: 1 }), undefined); + assert.equal(hover('function string.format() end string.format()', 'format', { occurrence: 1 }), undefined); + assert.equal(hover('function string:rep() end ("x"):rep()', 'rep', { occurrence: 1 }), undefined); + // Only that member, and only on the global table. + assert.equal(hover('string.format = nil string.rep()', 'rep'), 'rep -> library string.rep'); + assert.equal(hover('local string = {} string.format = nil', 'format'), undefined); + assert.equal(hover('do local string = {} string.format = nil end string.format()', 'format', { occurrence: 1 }), 'format -> library string.format'); + }); + it('documents EEex-Docs methods and dotted names', () => { assert.equal(hover('C:AddGold(10)', 'AddGold'), 'AddGold -> external C:AddGold'); assert.equal(hover('C.AddGold(C, 10)', 'AddGold'), 'AddGold -> external C:AddGold'); From 807c2a1d6b081436fa21d36a541ff3b33e57cd21 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:19:34 +0100 Subject: [PATCH 14/15] fix(build): escape `!` in Markdown generated from the Lua manual Found by the project review. In Markdown, `!` directly before a link makes it an image (`![text](url)`). No entry of the manual has text ending in `!` before a link today, but the converter did not guard against it. `!` is now escaped in text like the other characters Markdown interprets. The only change to data/lua52/manual.json is in `assert` ("assertion failed\!"), which renders the same. Co-Authored-By: Claude Opus 5.5 --- data/lua52/manual.json | 2 +- scripts/lua-manual/convert.mts | 7 +++++-- test/unit/scripts/lua-manual/convert.test.ts | 2 ++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/data/lua52/manual.json b/data/lua52/manual.json index 152f700..68fa756 100644 --- a/data/lua52/manual.json +++ b/data/lua52/manual.json @@ -46,7 +46,7 @@ "section": "6.1", "anchor": "pdf-assert", "heading": "assert (v [, message])", - "markdown": "Issues an error when the value of its argument `v` is false (i.e., **nil** or **false**); otherwise, returns all its arguments. `message` is an error message; when absent, it defaults to \"assertion failed!\"", + "markdown": "Issues an error when the value of its argument `v` is false (i.e., **nil** or **false**); otherwise, returns all its arguments. `message` is an error message; when absent, it defaults to \"assertion failed\\!\"", "plaintext": "Issues an error when the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. message is an error message; when absent, it defaults to \"assertion failed!\"" }, { diff --git a/scripts/lua-manual/convert.mts b/scripts/lua-manual/convert.mts index 1be67d8..ea9dba2 100644 --- a/scripts/lua-manual/convert.mts +++ b/scripts/lua-manual/convert.mts @@ -264,9 +264,12 @@ export interface Converted { /** HTML collapses runs of ASCII whitespace; U+00A0 ( ) is not whitespace. */ const collapse = (text: string): string => text.replace(/[ \t\r\n]+/g, ' '); -/** Backslash-escapes the characters that Markdown (CommonMark + GFM) would interpret in text. */ +/** + * Backslash-escapes the characters that Markdown (CommonMark + GFM) would + * interpret in text; `!` too, which would turn a following link into an image. + */ function escapeMarkdown(text: string): string { - return text.replace(/[\\`*_[\]<>&~|]/g, '\\$&'); + return text.replace(/[\\`*_[\]<>&~|!]/g, '\\$&'); } /** Escapes a paragraph or list item start that Markdown would read as a heading, list, quote or rule. */ diff --git a/test/unit/scripts/lua-manual/convert.test.ts b/test/unit/scripts/lua-manual/convert.test.ts index d918976..8686847 100644 --- a/test/unit/scripts/lua-manual/convert.test.ts +++ b/test/unit/scripts/lua-manual/convert.test.ts @@ -75,6 +75,8 @@ describe('scripts/lua-manual/convert', () => { it('escapes text Markdown would interpret', () => { assert.equal(convert('a*b_c [d] <e> & ~f~ \\ `').markdown, 'a\\*b\\_c \\[d\\] \\ \\& \\~f\\~ \\\\ \\`'); + assert.equal(convert('Wow! link').markdown, `Wow\\! [link](${BASE}#x)`); + assert.equal(convert('Wow!link').markdown, `Wow\\![link](${BASE}#x)`); assert.equal(convert('# not a heading').markdown, '\\# not a heading'); assert.equal(convert('- not a list').markdown, '\\- not a list'); assert.equal(convert('1. not a list').markdown, '1\\. not a list'); From 091a8b69083f0ad8b37b6f68bb6f2379c1adf1a7 Mon Sep 17 00:00:00 2001 From: 4Luke4 <39967126+4Luke4@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:25:58 +0100 Subject: [PATCH 15/15] fix(wasm): cache the Lua tarball only after verifying it, without a race CodeQL flagged the download code on this pull request (js/http-to-file-access and js/file-system-race at third_party/lua52/tarball.mts:35). The same code was already flagged in build.mts on main (alerts #2 and #4, open); moving it made the alerts count as new. Both findings were real: - the downloaded bytes were written to .cache/lua before their SHA-256 was checked, so unverified data reached the disk and was deleted only afterwards; - `existsSync` followed by `writeFileSync` raced with anything else creating or removing the file in between. Now the cache file is read directly (a missing file is ENOENT, no separate existence check), and a download is hashed in memory and written only when it matches the published SHA-256; a mismatch writes nothing. A cached file with the wrong checksum is still deleted with the same message. The source (URL, checksum, cache path, downloader) can be injected, so the new unit tests cover every path without network: download and cache, tampered download, verified cache hit, corrupt cache, and a failed download. Checked by hand: `build:wasm -- --check` and `lua-manual -- --check` pass, including with an empty .cache/lua (fresh download, byte-identical to the previously cached file). Co-Authored-By: Claude Opus 5.5 --- test/unit/third_party/lua52/tarball.test.ts | 63 ++++++++++++++++++ third_party/lua52/tarball.mts | 71 ++++++++++++++++----- 2 files changed, 117 insertions(+), 17 deletions(-) create mode 100644 test/unit/third_party/lua52/tarball.test.ts diff --git a/test/unit/third_party/lua52/tarball.test.ts b/test/unit/third_party/lua52/tarball.test.ts new file mode 100644 index 0000000..ef56374 --- /dev/null +++ b/test/unit/third_party/lua52/tarball.test.ts @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fetchLuaTarball, sha256, type TarballSource } from '../../../../third_party/lua52/tarball.mts'; + +describe('third_party/lua52/tarball fetchLuaTarball', () => { + const good = Buffer.from('the official tarball'); + let dir: string; + let downloads: number; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'tarball-test-')); + downloads = 0; + }); + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + const source = (body: Buffer, path = join(dir, 'cache', 'lua.tar.gz')): TarballSource => ({ + url: 'https://example.invalid/lua.tar.gz', + sha256: sha256(good), + path, + download: () => { + downloads++; + return Promise.resolve(body); + }, + }); + + it('downloads, verifies and caches the tarball when it is not cached', async () => { + const from = source(good); + assert.equal(await fetchLuaTarball(from), from.path); + assert.deepEqual(readFileSync(from.path), good); + assert.equal(downloads, 1); + }); + + it('never writes a download whose checksum is wrong', async () => { + const from = source(Buffer.from('tampered')); + await assert.rejects(fetchLuaTarball(from), /https:\/\/example\.invalid\/lua\.tar\.gz has SHA-256 [0-9a-f]{64}, expected [0-9a-f]{64}\. Nothing was cached\./); + assert.equal(existsSync(from.path), false); + }); + + it('uses a verified cached file without downloading', async () => { + const from = source(good, join(dir, 'lua.tar.gz')); + writeFileSync(from.path, good); + assert.equal(await fetchLuaTarball(from), from.path); + assert.equal(downloads, 0); + }); + + it('deletes a cached file whose checksum is wrong', async () => { + const from = source(good, join(dir, 'lua.tar.gz')); + writeFileSync(from.path, 'corrupt'); + await assert.rejects(fetchLuaTarball(from), /The cached file was deleted; re-run to download it again\./); + assert.equal(existsSync(from.path), false); + assert.equal(downloads, 0); + }); + + it('passes download failures on', async () => { + const from: TarballSource = { ...source(good), download: () => Promise.reject(new Error('HTTP 503')) }; + await assert.rejects(fetchLuaTarball(from), /HTTP 503/); + assert.equal(existsSync(from.path), false); + }); +}); diff --git a/third_party/lua52/tarball.mts b/third_party/lua52/tarball.mts index 4ae491e..e432bcb 100644 --- a/third_party/lua52/tarball.mts +++ b/third_party/lua52/tarball.mts @@ -3,7 +3,7 @@ // (build.mts) and the Lua manual data generator (scripts/lua-manual/). import { createHash } from 'node:crypto'; import { execFileSync } from 'node:child_process'; -import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -13,33 +13,70 @@ export const LUA_URL = `https://www.lua.org/ftp/lua-${LUA_VERSION}.tar.gz`; export const LUA_SHA256 = 'b9e2e4aad6789b3b63a056d442f7b39f0ecfca3ae0f1fc0ae4e9614401b69f4b'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'); -const cacheDir = join(root, '.cache', 'lua'); -const tarball = join(cacheDir, `lua-${LUA_VERSION}.tar.gz`); export function sha256(data: Buffer | string): string { return createHash('sha256').update(data).digest('hex'); } +/** Where the tarball comes from and where it is cached; injectable for tests. */ +export interface TarballSource { + readonly url: string; + readonly sha256: string; + /** Cache file. */ + readonly path: string; + readonly download: (url: string) => Promise; +} + +async function httpGet(url: string): Promise { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`Downloading ${url} failed: HTTP ${response.status} ${response.statusText}`); + } + return new Uint8Array(await response.arrayBuffer()); +} + +const OFFICIAL: TarballSource = { + url: LUA_URL, + sha256: LUA_SHA256, + path: join(root, '.cache', 'lua', `lua-${LUA_VERSION}.tar.gz`), + download: httpGet, +}; + +/** The file's bytes, or `undefined` when it does not exist (read directly: no exists-then-read race). */ +function readIfPresent(path: string): Buffer | undefined { + try { + return readFileSync(path); + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined; + throw error; + } +} + /** * Path of the verified tarball, downloading it first when it is not cached. - * Throws an `Error` with an actionable message when the download fails or the - * file does not have the published SHA-256 (the bad file is then deleted). + * A download is checked against the published SHA-256 in memory and written + * to the cache only when it matches. Throws an `Error` with an actionable + * message when the download fails or a checksum does not match (a bad cached + * file is then deleted). */ -export async function fetchLuaTarball(): Promise { - if (!existsSync(tarball)) { - mkdirSync(cacheDir, { recursive: true }); - const response = await fetch(LUA_URL); - if (!response.ok) { - throw new Error(`Downloading ${LUA_URL} failed: HTTP ${response.status} ${response.statusText}`); +export async function fetchLuaTarball(source: TarballSource = OFFICIAL): Promise { + const cached = readIfPresent(source.path); + if (cached) { + const actual = sha256(cached); + if (actual !== source.sha256) { + rmSync(source.path, { force: true }); + throw new Error(`${source.path} has SHA-256 ${actual}, expected ${source.sha256}. The cached file was deleted; re-run to download it again.`); } - writeFileSync(tarball, Buffer.from(await response.arrayBuffer())); + return source.path; } - const actual = sha256(readFileSync(tarball)); - if (actual !== LUA_SHA256) { - rmSync(tarball); - throw new Error(`${LUA_URL} has SHA-256 ${actual}, expected ${LUA_SHA256}. The cached file was deleted; re-run to download it again.`); + const data = Buffer.from(await source.download(source.url)); + const actual = sha256(data); + if (actual !== source.sha256) { + throw new Error(`${source.url} has SHA-256 ${actual}, expected ${source.sha256}. Nothing was cached.`); } - return tarball; + mkdirSync(dirname(source.path), { recursive: true }); + writeFileSync(source.path, data); + return source.path; } /** The bytes of one member of the tarball (`member` as listed by `tar -t`, e.g. `lua-5.2.4/doc/manual.html`). */