// THE KERNEL'S REDIS LIBRARY: A LUA-SUBSET INTERPRETER — the engine behind EVAL/EVALSHA (engine.ts). // // ── WHY AN INTERPRETER AND NOT SCRIPT-RECOGNITION (the honest choice, stated up front) ────────── // The build brief allowed either (a) recognising known script SHA1s and dispatching to hand-written // TypeScript equivalents, or (b) actually EXECUTING the Lua. (a) is a fake-success generator: it // passes for the exact bytes it memorised and silently mis-answers for any script one character // different — and the whole point of `EVAL` is that the caller supplies the program. So this file // takes (b): it PARSES and EVALUATES the script text, calling back into the twin's real Redis // command core for every `redis.call`. Nothing about @upstash/ratelimit's scripts is special-cased // anywhere in this pack; they run because the interpreter runs Lua, and their SHA1s are only ever // used the way real Redis uses them (the EVALSHA script cache). // // ── WHAT IS AND IS NOT SUPPORTED (loud failure, never a fake success) ─────────────────────────── // SUPPORTED: local/global assignment (incl. multiple assignment and `local x` with no value), // numeric `for`, generic `for ... in ipairs/pairs`, `while`, `repeat/until`, `if/elseif/else`, // `break`, `return`, table constructors (array-style and `[k]=v`/`k=v`), indexing (`t[i]`, `t.k`), // the full operator set Lua 5.1 has (`+ - * / % ^ .. == ~= < <= > >= and or not #` and unary minus), // user-defined `function` values, and the standard-library subset real Redis scripts actually use: // `tonumber tostring type error assert unpack ipairs pairs rawget rawset select`, // `math.floor/ceil/min/max/abs/huge/random/randomseed/pow/sqrt/fmod/modf`, // `table.insert/remove/getn/concat`, `string.format/len/sub/lower/upper/rep/find/gsub/byte/char`, // plus `redis.call`, `redis.pcall`, `redis.error_reply`, `redis.status_reply`, `redis.sha1hex`, // `redis.breakpoint`/`redis.debug` (no-ops), `redis.LOG_*`, `redis.log` (no-op), `KEYS`, `ARGV`. // // NOT SUPPORTED — and every one of these throws a LOUD `LuaError` naming the construct rather than // degrading to a wrong answer: `goto`/labels, coroutines, metatables/`setmetatable`, varargs `...` // in a user function, `cjson`/`cmsgpack`/`bit`/`struct`/`os`/`io`, string methods called with `:` // syntax on a value (`s:sub(1,2)`), and any identifier the environment does not define. An // unsupported script therefore fails the way an unmodeled operation must — visibly. // // ── LUA SEMANTICS THAT ARE EASY TO GET WRONG AND MATTER HERE ──────────────────────────────────── // 1. ONLY `nil` and `false` are falsy. `0` and `""` are TRUE. (`if requestsInCurrentWindow == false` // in the sliding-window script depends on the Redis nil→false conversion, not on falsiness.) // 2. `==` does NOT coerce across types: `"3" == 3` is FALSE. This is load-bearing — @upstash/ // ratelimit's `cachedFixedWindowLimitScript` compares a number against a raw `ARGV` STRING // (`if r == incrementBy`), which in real Redis never matches and therefore never arms the // PEXPIRE. Coercing here would make this twin MORE "correct" than the vendor and hide the // caller's real behaviour, so the comparison is kept strict. // 3. Arithmetic DOES coerce numeric strings (`"5" + 1 == 6`); a non-numeric string is an error. // 4. `/` is float division; `math.floor` rounds toward -inf; `%` is `a - floor(a/b)*b` (sign of the // divisor), which differs from JavaScript's `%` for negative operands. // 5. Tables are 1-based and `#t` is the array length. // 6. Lua→Redis conversion truncates a number toward ZERO (`3.7` → `3`, `-3.7` → `-3`) and stops // an array reply at the first `nil`. import { createHash } from 'node:crypto'; /** A Lua runtime/parse error. Surfaces to the caller as a Redis script error, never as a result. */ export class LuaError extends Error { constructor(message: string) { super(message); this.name = 'LuaError'; } } /** A library's null that is not nil (lua-cjson's `cjson.null`, a lightuserdata in Redis): a value a table can hold, * and nil when a script returns it to Redis. */ export const LUA_NULL: LuaValue = new (class LuaNull { })() as never; /** A Lua table. Array part + hash part, exactly like the real thing (1-based array indices). */ export class LuaTable { readonly map = new Map(); get(k: LuaValue): LuaValue { if (k === null) return null; return this.map.get(k as string | number | boolean) ?? null; } set(k: LuaValue, v: LuaValue): void { if (k === null) throw new LuaError('table index is nil'); if (v === null) this.map.delete(k as string | number | boolean); else this.store(k, v); } /** A non-nil value at a non-nil key. */ private store(k: LuaValue, v: LuaValue): void { this.map.set(k as string | number | boolean, v); } /** `#t` — the border of the array part: the largest n where t[1..n] are all non-nil. */ get length(): number { let n = 0; while (this.map.has(n + 1)) n++; return n; } static fromArray(values: LuaValue[]): LuaTable { const t = new LuaTable(); values.forEach((v, i) => { if (v !== null) t.map.set(i + 1, v); }); return t; } toArray(): LuaValue[] { const out: LuaValue[] = []; for (let i = 1; this.map.has(i); i++) out.push(this.map.get(i)!); return out; } } export type LuaFunction = (args: LuaValue[]) => LuaValue[]; /** `null` stands for Lua `nil` (JS `undefined` is never used as a value in this interpreter). */ export type LuaValue = null | boolean | number | string | LuaTable | LuaFunction; // ───────────────────────────────────────────────────────────────────────────────────────────── // LEXER // ───────────────────────────────────────────────────────────────────────────────────────────── type TokKind = 'name' | 'number' | 'string' | 'op' | 'keyword' | 'eof'; type Token = { kind: TokKind; value: string; line: number }; const KEYWORDS = new Set([ 'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while', ]); /** Reserved words this interpreter deliberately refuses rather than silently mis-running. */ const UNSUPPORTED_KEYWORDS = new Set(['goto']); // Longest-first: `...` must win over `..`, `==` over `=`, etc. const OPERATORS = [ '...', '..', '==', '~=', '<=', '>=', '+', '-', '*', '/', '%', '^', '#', '<', '>', '=', '(', ')', '{', '}', '[', ']', ';', ':', ',', '.', ]; export function tokenize(src: string): Token[] { const out: Token[] = []; let i = 0; let line = 1; const isDigit = (c: string) => c >= '0' && c <= '9'; const isNameStart = (c: string) => /[A-Za-z_]/.test(c); const isNamePart = (c: string) => /[A-Za-z0-9_]/.test(c); while (i < src.length) { const c = src[i]!; if (c === '\n') { line++; i++; continue; } if (c === ' ' || c === '\t' || c === '\r') { i++; continue; } // long comment --[[ ... ]] / line comment -- ... if (c === '-' && src[i + 1] === '-') { if (src[i + 2] === '[' && src[i + 3] === '[') { const end = src.indexOf(']]', i + 4); if (end < 0) throw new LuaError(`unfinished long comment at line ${line}`); for (let k = i; k < end; k++) if (src[k] === '\n') line++; i = end + 2; continue; } while (i < src.length && src[i] !== '\n') i++; continue; } // long string [[ ... ]] if (c === '[' && src[i + 1] === '[') { const end = src.indexOf(']]', i + 2); if (end < 0) throw new LuaError(`unfinished long string at line ${line}`); const value = src.slice(i + 2, end); for (const ch of value) if (ch === '\n') line++; out.push({ kind: 'string', value, line }); i = end + 2; continue; } if (c === '"' || c === "'") { const quote = c; let value = ''; i++; while (i < src.length && src[i] !== quote) { if (src[i] === '\\') { const esc = src[i + 1]!; const simple: Record = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', f: '\f', v: '\v', '\\': '\\', '"': '"', "'": "'", '\n': '\n' }; if (esc in simple) { value += simple[esc]; i += 2; continue; } if (isDigit(esc)) { let digits = ''; i++; while (digits.length < 3 && isDigit(src[i] ?? '')) { digits += src[i]; i++; } value += String.fromCharCode(Number(digits)); continue; } throw new LuaError(`unsupported string escape \\${esc} at line ${line}`); } if (src[i] === '\n') line++; value += src[i]; i++; } if (i >= src.length) throw new LuaError(`unfinished string at line ${line}`); i++; // closing quote out.push({ kind: 'string', value, line }); continue; } if (isDigit(c) || (c === '.' && isDigit(src[i + 1] ?? ''))) { let j = i; if (c === '0' && (src[i + 1] === 'x' || src[i + 1] === 'X')) { j = i + 2; while (j < src.length && /[0-9a-fA-F]/.test(src[j]!)) j++; out.push({ kind: 'number', value: src.slice(i, j), line }); i = j; continue; } while (j < src.length && /[0-9.]/.test(src[j]!)) j++; if (src[j] === 'e' || src[j] === 'E') { j++; if (src[j] === '+' || src[j] === '-') j++; while (j < src.length && isDigit(src[j]!)) j++; } out.push({ kind: 'number', value: src.slice(i, j), line }); i = j; continue; } if (isNameStart(c)) { let j = i; while (j < src.length && isNamePart(src[j]!)) j++; const word = src.slice(i, j); if (UNSUPPORTED_KEYWORDS.has(word)) throw new LuaError(`unsupported Lua construct '${word}' at line ${line} — this twin runs a documented Lua SUBSET (the kernel's Redis library, lua.ts)`); out.push({ kind: KEYWORDS.has(word) ? 'keyword' : 'name', value: word, line }); i = j; continue; } const op = OPERATORS.find((o) => src.startsWith(o, i)); if (!op) throw new LuaError(`unexpected character '${c}' at line ${line}`); out.push({ kind: 'op', value: op, line }); i += op.length; } out.push({ kind: 'eof', value: '', line }); return out; } // ───────────────────────────────────────────────────────────────────────────────────────────── // AST + PARSER (recursive descent, Lua 5.1 precedence) // ───────────────────────────────────────────────────────────────────────────────────────────── type Expr = | { t: 'nil' } | { t: 'true' } | { t: 'false' } | { t: 'num'; v: number } | { t: 'str'; v: string } | { t: 'name'; v: string } | { t: 'index'; obj: Expr; key: Expr } | { t: 'call'; fn: Expr; args: Expr[]; line?: number } | { t: 'bin'; op: string; l: Expr; r: Expr } | { t: 'un'; op: string; e: Expr } | { t: 'table'; array: Expr[]; pairs: Array<{ k: Expr; v: Expr }> } | { t: 'func'; params: string[]; body: Stat[] }; type Stat = | { t: 'local'; names: string[]; exprs: Expr[] } | { t: 'assign'; targets: Expr[]; exprs: Expr[] } | { t: 'callstat'; call: Expr } | { t: 'if'; branches: Array<{ cond: Expr; body: Stat[] }>; orelse: Stat[] | null } | { t: 'while'; cond: Expr; body: Stat[] } | { t: 'repeat'; body: Stat[]; cond: Expr } | { t: 'fornum'; name: string; from: Expr; to: Expr; step: Expr | null; body: Stat[] } | { t: 'forin'; names: string[]; exprs: Expr[]; body: Stat[] } | { t: 'do'; body: Stat[] } | { t: 'return'; exprs: Expr[] } | { t: 'break' }; class Parser { private pos = 0; constructor(private readonly toks: Token[]) {} private peek(): Token { return this.toks[this.pos]!; } private next(): Token { return this.toks[this.pos++]!; } private check(kind: TokKind, value?: string): boolean { const t = this.peek(); return t.kind === kind && (value === undefined || t.value === value); } private accept(kind: TokKind, value?: string): boolean { if (this.check(kind, value)) { this.pos++; return true; } return false; } private expect(kind: TokKind, value?: string): Token { if (!this.check(kind, value)) { const t = this.peek(); throw new LuaError(`syntax error near '${t.value}' at line ${t.line} — expected ${value ?? kind}`); } return this.next(); } parseChunk(): Stat[] { const body = this.parseBlock(); this.expect('eof'); return body; } private blockEnds(): boolean { const t = this.peek(); return t.kind === 'eof' || (t.kind === 'keyword' && ['end', 'else', 'elseif', 'until'].includes(t.value)); } private parseBlock(): Stat[] { const out: Stat[] = []; while (!this.blockEnds()) { if (this.accept('op', ';')) continue; const stat = this.parseStatement(); out.push(stat); if (stat.t === 'return' || stat.t === 'break') { this.accept('op', ';'); break; // `return`/`break` must be the last statement of a block in Lua 5.1 } } return out; } private parseStatement(): Stat { const t = this.peek(); if (t.kind === 'keyword') { switch (t.value) { case 'local': return this.parseLocal(); case 'if': return this.parseIf(); case 'while': return this.parseWhile(); case 'repeat': return this.parseRepeat(); case 'for': return this.parseFor(); case 'do': { this.next(); const body = this.parseBlock(); this.expect('keyword', 'end'); return { t: 'do', body }; } case 'return': { this.next(); const exprs = this.blockEnds() || this.check('op', ';') ? [] : this.parseExprList(); return { t: 'return', exprs }; } case 'break': this.next(); return { t: 'break' }; case 'function': { this.next(); // `function a.b.c(...)` — sugar for `a.b.c = function(...)` let target: Expr = { t: 'name', v: this.expect('name').value }; while (this.accept('op', '.')) target = { t: 'index', obj: target, key: { t: 'str', v: this.expect('name').value } }; if (this.check('op', ':')) throw new LuaError(`unsupported Lua construct 'function ...:method' at line ${t.line} — this twin runs a documented Lua SUBSET`); const fn = this.parseFunctionBody(); return { t: 'assign', targets: [target], exprs: [fn] }; } default: throw new LuaError(`unexpected '${t.value}' at line ${t.line}`); } } // expression statement: either a call, or an assignment const first = this.parseSuffixed(); if (this.check('op', '=') || this.check('op', ',')) { const targets = [first]; while (this.accept('op', ',')) targets.push(this.parseSuffixed()); this.expect('op', '='); const exprs = this.parseExprList(); for (const target of targets) { if (target.t !== 'name' && target.t !== 'index') throw new LuaError(`cannot assign to this expression at line ${t.line}`); } return { t: 'assign', targets, exprs }; } if (first.t !== 'call') throw new LuaError(`syntax error at line ${t.line} — statement is neither a call nor an assignment`); return { t: 'callstat', call: first }; } private parseLocal(): Stat { this.expect('keyword', 'local'); if (this.check('keyword', 'function')) { this.next(); const name = this.expect('name').value; const fn = this.parseFunctionBody(); return { t: 'local', names: [name], exprs: [fn] }; } const names = [this.expect('name').value]; while (this.accept('op', ',')) names.push(this.expect('name').value); const exprs = this.accept('op', '=') ? this.parseExprList() : []; return { t: 'local', names, exprs }; } private parseIf(): Stat { this.expect('keyword', 'if'); const branches: Array<{ cond: Expr; body: Stat[] }> = []; const cond = this.parseExpr(); this.expect('keyword', 'then'); branches.push({ cond, body: this.parseBlock() }); let orelse: Stat[] | null = null; for (;;) { if (this.accept('keyword', 'elseif')) { const c = this.parseExpr(); this.expect('keyword', 'then'); branches.push({ cond: c, body: this.parseBlock() }); continue; } if (this.accept('keyword', 'else')) orelse = this.parseBlock(); break; } this.expect('keyword', 'end'); return { t: 'if', branches, orelse }; } private parseWhile(): Stat { this.expect('keyword', 'while'); const cond = this.parseExpr(); this.expect('keyword', 'do'); const body = this.parseBlock(); this.expect('keyword', 'end'); return { t: 'while', cond, body }; } private parseRepeat(): Stat { this.expect('keyword', 'repeat'); const body = this.parseBlock(); this.expect('keyword', 'until'); return { t: 'repeat', body, cond: this.parseExpr() }; } private parseFor(): Stat { this.expect('keyword', 'for'); const first = this.expect('name').value; if (this.accept('op', '=')) { const from = this.parseExpr(); this.expect('op', ','); const to = this.parseExpr(); const step = this.accept('op', ',') ? this.parseExpr() : null; this.expect('keyword', 'do'); const body = this.parseBlock(); this.expect('keyword', 'end'); return { t: 'fornum', name: first, from, to, step, body }; } const names = [first]; while (this.accept('op', ',')) names.push(this.expect('name').value); this.expect('keyword', 'in'); const exprs = this.parseExprList(); this.expect('keyword', 'do'); const body = this.parseBlock(); this.expect('keyword', 'end'); return { t: 'forin', names, exprs, body }; } private parseFunctionBody(): Expr { this.expect('op', '('); const params: string[] = []; if (!this.check('op', ')')) { do { if (this.check('op', '...')) throw new LuaError('unsupported Lua construct: varargs `...` in a function definition — this twin runs a documented Lua SUBSET'); params.push(this.expect('name').value); } while (this.accept('op', ',')); } this.expect('op', ')'); const body = this.parseBlock(); this.expect('keyword', 'end'); return { t: 'func', params, body }; } private parseExprList(): Expr[] { const out = [this.parseExpr()]; while (this.accept('op', ',')) out.push(this.parseExpr()); return out; } // Lua 5.1 binary precedence. `..` and `^` are RIGHT-associative. private static readonly BINARY: Record = { or: [1, 1], and: [2, 2], '<': [3, 3], '>': [3, 3], '<=': [3, 3], '>=': [3, 3], '~=': [3, 3], '==': [3, 3], '..': [5, 4], '+': [6, 6], '-': [6, 6], '*': [7, 7], '/': [7, 7], '%': [7, 7], '^': [10, 9], }; private static readonly UNARY_PRIORITY = 8; private parseExpr(limit = 0): Expr { let left: Expr; const t = this.peek(); if ((t.kind === 'op' && (t.value === '-' || t.value === '#')) || (t.kind === 'keyword' && t.value === 'not')) { this.next(); left = { t: 'un', op: t.value, e: this.parseExpr(Parser.UNARY_PRIORITY) }; } else { left = this.parseSimple(); } for (;;) { const op = this.peek(); const isBin = (op.kind === 'op' || op.kind === 'keyword') && Parser.BINARY[op.value] !== undefined; if (!isBin) break; const [leftPri, rightPri] = Parser.BINARY[op.value]!; if (leftPri <= limit) break; this.next(); left = { t: 'bin', op: op.value, l: left, r: this.parseExpr(rightPri) }; } return left; } private parseSimple(): Expr { const t = this.peek(); if (t.kind === 'number') { this.next(); return { t: 'num', v: parseLuaNumber(t.value) }; } if (t.kind === 'string') { this.next(); return { t: 'str', v: t.value }; } if (t.kind === 'keyword') { if (t.value === 'nil') { this.next(); return { t: 'nil' }; } if (t.value === 'true') { this.next(); return { t: 'true' }; } if (t.value === 'false') { this.next(); return { t: 'false' }; } if (t.value === 'function') { this.next(); return this.parseFunctionBody(); } } if (t.kind === 'op' && t.value === '{') return this.parseTable(); if (t.kind === 'op' && t.value === '...') throw new LuaError(`unsupported Lua construct '...' at line ${t.line} — this twin runs a documented Lua SUBSET`); return this.parseSuffixed(); } private parseTable(): Expr { this.expect('op', '{'); const array: Expr[] = []; const pairs: Array<{ k: Expr; v: Expr }> = []; while (!this.check('op', '}')) { if (this.check('op', '[')) { this.next(); const k = this.parseExpr(); this.expect('op', ']'); this.expect('op', '='); pairs.push({ k, v: this.parseExpr() }); } else if (this.check('name') && this.toks[this.pos + 1]?.kind === 'op' && this.toks[this.pos + 1]?.value === '=') { const k = this.next().value; this.next(); // '=' pairs.push({ k: { t: 'str', v: k }, v: this.parseExpr() }); } else { array.push(this.parseExpr()); } if (!this.accept('op', ',') && !this.accept('op', ';')) break; } this.expect('op', '}'); return { t: 'table', array, pairs }; } /** primary + any chain of `.name`, `[expr]`, `(args)`, `"str"`, `{table}` suffixes. */ private parseSuffixed(): Expr { let e: Expr; if (this.accept('op', '(')) { e = this.parseExpr(); this.expect('op', ')'); } else { e = { t: 'name', v: this.expect('name').value }; } for (;;) { if (this.accept('op', '.')) { e = { t: 'index', obj: e, key: { t: 'str', v: this.expect('name').value } }; continue; } if (this.accept('op', '[')) { const k = this.parseExpr(); this.expect('op', ']'); e = { t: 'index', obj: e, key: k }; continue; } if (this.check('op', ':')) throw new LuaError(`unsupported Lua construct 'method call with :' at line ${this.peek().line} — this twin runs a documented Lua SUBSET`); if (this.check('op', '(')) { const line = this.next().line; const args: Expr[] = this.check('op', ')') ? [] : this.parseExprList(); this.expect('op', ')'); e = { t: 'call', fn: e, args, line }; continue; } if (this.check('string')) { e = { t: 'call', fn: e, args: [{ t: 'str', v: this.next().value }] }; continue; } if (this.check('op', '{')) { e = { t: 'call', fn: e, args: [this.parseTable()] }; continue; } break; } return e; } } function parseLuaNumber(text: string): number { const n = /^0[xX]/.test(text) ? Number.parseInt(text, 16) : Number(text); if (!Number.isFinite(n) && text !== 'inf') throw new LuaError(`malformed number near '${text}'`); return n; } /** Parse Lua source into a chunk. Exported so a test can prove a bad script fails at PARSE time. */ export function parseLua(src: string): Stat[] { return new Parser(tokenize(src)).parseChunk(); } // ───────────────────────────────────────────────────────────────────────────────────────────── // EVALUATOR // ───────────────────────────────────────────────────────────────────────────────────────────── class Scope { private readonly vars = new Map(); constructor(private readonly parent: Scope | null) {} declare(name: string, value: LuaValue): void { this.vars.set(name, value); } has(name: string): boolean { return this.vars.has(name) || (this.parent?.has(name) ?? false); } get(name: string): LuaValue { if (this.vars.has(name)) return this.vars.get(name)!; return this.parent ? this.parent.get(name) : null; } /** Assign to the nearest enclosing declaration; otherwise declare at the ROOT (a Lua global). */ set(name: string, value: LuaValue): void { if (this.vars.has(name)) { this.vars.set(name, value); return; } if (this.parent) { this.parent.set(name, value); return; } this.vars.set(name, value); } } const BREAK = Symbol('lua-break'); type Signal = typeof BREAK | { ret: LuaValue[] } | null; // Lua pattern subset used by command-language scripts; unsupported balanced/frontier patterns refuse explicitly. export function luaPattern(pattern: string): string { const classes: Record = { a: 'A-Za-z', d: '0-9', l: 'a-z', u: 'A-Z', w: 'A-Za-z0-9', s: '\\s', x: 'A-Fa-f0-9', p: '!-/:-@[-`{-~', c: '\\x00-\\x1f\\x7f', z: '\\x00' }; let out = '', inClass = false; for (let i = 0; i < pattern.length; i++) { const c = pattern[i]!; if (c === '%') { const next = pattern[++i]!; if (next === 'b' || next === 'f') throw new LuaError('unsupported Lua balanced/frontier pattern'); if (classes[next.toLowerCase()]) { const content = classes[next.toLowerCase()]!; out += inClass ? content : `[${next === next.toUpperCase() ? '^' : ''}${content}]`; } else if (/\d/.test(next)) out += `\\${next}`; else out += next.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'); } else if (c === '[') { inClass = true; out += c; } else if (c === ']') { inClass = false; out += c; } else if (!inClass && c === '-') out += '*?'; else if ('\\{}|'.includes(c)) out += `\\${c}`; else out += c; } return out; } export function luaTruthy(v: LuaValue): boolean { return v !== null && v !== false; } export function luaTypeName(v: LuaValue): string { if (v === null) return 'nil'; if (typeof v === 'boolean') return 'boolean'; if (typeof v === 'number') return 'number'; if (typeof v === 'string') return 'string'; if (v instanceof LuaTable) return 'table'; if (v === LUA_NULL) return 'userdata'; return 'function'; } /** Lua's arithmetic string→number coercion. Throws (as Lua does) on a non-numeric operand. */ function arith(v: LuaValue, op: string): number { if (typeof v === 'number') return v; if (typeof v === 'string') { const n = v.trim() === '' ? Number.NaN : Number(v); if (Number.isFinite(n)) return n; } throw new LuaError(`attempt to perform arithmetic (${op}) on a ${luaTypeName(v)} value`); } /** Lua's `..` coercion: numbers stringify, everything else but a string is an error. */ function concatOperand(v: LuaValue): string { if (typeof v === 'string') return v; if (typeof v === 'number') return numberToLuaString(v); throw new LuaError(`attempt to concatenate a ${luaTypeName(v)} value`); } /** Lua 5.1's `%.14g` number formatting — `3` prints as "3", not "3.0". */ export function numberToLuaString(n: number): string { if (Number.isInteger(n) && Math.abs(n) < 1e15) return String(n); if (!Number.isFinite(n)) return n > 0 ? 'inf' : Number.isNaN(n) ? 'nan' : '-inf'; const g = n.toPrecision(14); return g.includes('e') ? String(Number(g)) : String(Number(g)); } /** One `string.format` conversion, as C's printf renders it (the flags `-+ #0`, a width, a precision). */ function formatOne(verb: string, flags: string, width: number, precision: number | undefined, v: LuaValue): string { const left = flags.includes('-'); const zero = flags.includes('0') && !left; const sign = (neg: boolean) => (neg ? '-' : flags.includes('+') ? '+' : flags.includes(' ') ? ' ' : ''); const pad = (body: string, prefix = '', numeric = false): string => { const len = prefix.length + body.length; if (len >= width) return prefix + body; if (left) return prefix + body + ' '.repeat(width - len); if (zero && numeric) return prefix + '0'.repeat(width - len) + body; return ' '.repeat(width - len) + prefix + body; }; if (verb === 's') { const s = typeof v === 'string' ? v : concatOperand(v); return pad(precision === undefined ? s : s.slice(0, precision)); } if (verb === 'q') { const s = typeof v === 'string' ? v : concatOperand(v); let q = '"'; for (const ch of s) q += ch === '"' ? '\\"' : ch === '\\' ? '\\\\' : ch === '\n' ? '\\\n' : ch === '\r' ? '\\r' : ch === '\u0000' ? '\\000' : ch; return q + '"'; } const n = arith(v, 'string.format'); if (verb === 'c') return pad(String.fromCharCode(Math.trunc(n) & 0xff)); if (verb === 'd' || verb === 'i') { const t = Math.trunc(n); let digits = Math.abs(t).toString(); if (precision !== undefined) digits = digits.padStart(precision, '0'); return pad(digits, sign(t < 0), precision === undefined); } if (verb === 'o' || verb === 'u' || verb === 'x' || verb === 'X') { const t = BigInt.asUintN(64, BigInt(Math.trunc(n))); let digits = verb === 'o' ? t.toString(8) : verb === 'u' ? t.toString(10) : t.toString(16); if (verb === 'X') digits = digits.toUpperCase(); if (precision !== undefined) digits = digits.padStart(precision, '0'); const prefix = flags.includes('#') && t !== 0n ? (verb === 'x' ? '0x' : verb === 'X' ? '0X' : verb === 'o' ? '0' : '') : ''; return pad(digits, prefix, precision === undefined); } if (!Number.isFinite(n)) { const s = Number.isNaN(n) ? 'nan' : 'inf'; return pad(/[EG]/.test(verb) ? s.toUpperCase() : s, sign(n < 0 || Object.is(n, -0) && false)); } const p = precision ?? 6; const abs = Math.abs(n); const exp = (value: number, digits: number): string => { const { int, frac, exponent } = scientific(value, digits); return `${int}${frac ? `.${frac}` : digits > 0 || flags.includes('#') ? '.' : ''}e${exponent < 0 ? '-' : '+'}${String(Math.abs(exponent)).padStart(2, '0')}`; }; let body: string; if (verb === 'f') body = fixed(abs, p, flags.includes('#')); else if (verb === 'e' || verb === 'E') body = exp(abs, p); else { const P = p === 0 ? 1 : p; const X = abs === 0 ? 0 : scientific(abs, P - 1).exponent; body = P > X && X >= -4 ? fixed(abs, P - 1 - X, flags.includes('#')) : exp(abs, P - 1); // %g drops trailing zeros of the FRACTION only (and a point left bare), never an integer's zeros if (!flags.includes('#')) body = body.replace(/^([^e]*\.[^e]*?)0+(e|$)/, '$1$2').replace(/\.(e|$)/, '$1'); } if (verb === 'E' || verb === 'G') body = body.toUpperCase(); return pad(body, sign(n < 0 || Object.is(n, -0)), true); } /** A finite non-negative double's exact decimal digits: value = digits × 10^-scale (every double has one). */ function exactDecimal(value: number): { digits: bigint; scale: number } { if (value === 0) return { digits: 0n, scale: 0 }; const view = new DataView(new ArrayBuffer(8)); view.setFloat64(0, value); const bits = view.getBigUint64(0); const biased = Number((bits >> 52n) & 0x7ffn); let mantissa = bits & ((1n << 52n) - 1n); let e2 = biased - 1075; if (biased === 0) e2 = -1074; else mantissa |= 1n << 52n; if (e2 >= 0) return { digits: mantissa << BigInt(e2), scale: 0 }; return { digits: mantissa * 5n ** BigInt(-e2), scale: -e2 }; } /** digits × 10^-scale rounded to `places` fraction digits, ties to even (C's printf on the exact binary value). */ function roundTo(digits: bigint, scale: number, places: number): bigint { if (places >= scale) return digits * 10n ** BigInt(places - scale); const div = 10n ** BigInt(scale - places); const q = digits / div; const r = digits % div; const twice = r * 2n; return twice > div || (twice === div && q % 2n === 1n) ? q + 1n : q; } function fixed(value: number, places: number, point: boolean): string { const { digits, scale } = exactDecimal(value); const s = roundTo(digits, scale, places).toString().padStart(places + 1, '0'); const int = s.slice(0, s.length - places); const frac = s.slice(s.length - places); return places > 0 ? `${int}.${frac}` : point ? `${int}.` : int; } /** One digit, `places` more, and the power of ten: `%e`'s parts, rounded ties to even. */ function scientific(value: number, places: number): { int: string; frac: string; exponent: number } { if (value === 0) return { int: '0', frac: '0'.repeat(places), exponent: 0 }; const { digits, scale } = exactDecimal(value); let exponent = digits.toString().length - 1 - scale; let rounded = roundTo(digits, scale, places - exponent); if (rounded.toString().length > places + 1) { exponent += 1; rounded = roundTo(digits, scale, places - exponent); } const s = rounded.toString(); return { int: s.slice(0, 1), frac: s.slice(1), exponent }; } /** `tonumber`, exactly: a number passes through, a numeric string converts, anything else is nil. */ export function luaToNumber(v: LuaValue, base?: number): LuaValue { if (base !== undefined && base !== 10) { if (typeof v !== 'string') return null; const n = Number.parseInt(v.trim(), base); return Number.isNaN(n) ? null : n; } if (typeof v === 'number') return v; if (typeof v !== 'string') return null; const s = v.trim(); if (s === '') return null; const n = /^0[xX][0-9a-fA-F]+$/.test(s) ? Number.parseInt(s, 16) : Number(s); return Number.isFinite(n) ? n : null; } /** What the host must supply: a synchronous `redis.call`, plus KEYS/ARGV. */ export type LuaHost = { /** Run one Redis command, called from the script's line `line`. MUST throw to abort the script the way `redis.call` does. */ call: (args: string[], line: number) => LuaValue; keys: string[]; argv: string[]; /** The wire's environment, installed after the standard library so it may replace it: it names the command API * (`commandApi`: call, pcall, error_reply, status_reply, sha1hex, log…) as scripts call it — Redis's scripts * call it `redis` and `server` — and adds the runtime libraries its server loads (lua-libs.ts). */ extend?: (globals: { get(name: string): LuaValue; set(name: string, value: LuaValue): void; commandApi: LuaTable }) => void; /** How a Lua number becomes a `redis.call` argument; truncated toward zero when absent. */ numberArg: (n: number) => string; }; class Interpreter { private steps = 0; /** The script line of the call being evaluated: where a `redis.call` error says it happened. */ private line = 1; /** A runaway script must not hang the twin. Real Redis has `busy-reply-threshold`; this is the * deterministic equivalent — a hard step ceiling that fails LOUDLY rather than spinning. */ private static readonly MAX_STEPS = 2_000_000; constructor(private readonly host: LuaHost) {} private tick(): void { if (++this.steps > Interpreter.MAX_STEPS) throw new LuaError('script exceeded the interpreter step limit (possible infinite loop)'); } run(chunk: Stat[]): LuaValue { const globals = new Scope(null); this.installStdlib(globals); const signal = this.execBlock(chunk, new Scope(globals)); if (signal === BREAK) throw new LuaError("'break' outside a loop"); return signal && 'ret' in signal ? (signal.ret[0] ?? null) : null; } private installStdlib(g: Scope): void { const host = this.host; g.declare('KEYS', LuaTable.fromArray(host.keys)); g.declare('ARGV', LuaTable.fromArray(host.argv)); const one = (v: LuaValue): LuaValue[] => [v]; g.declare('tonumber', (a) => one(luaToNumber(a[0] ?? null, a[1] === undefined || a[1] === null ? undefined : Number(arith(a[1], 'tonumber'))))); function luaTostring(a: LuaValue[]): LuaValue[] { const v = a[0] ?? null; if (typeof v === 'string') return one(v); if (typeof v === 'number') return one(numberToLuaString(v)); if (v === null) return one('nil'); if (typeof v === 'boolean') return one(String(v)); return one(luaTypeName(v)); } g.declare('tostring', luaTostring); g.declare('type', (a) => one(luaTypeName(a[0] ?? null))); function luaError(a: LuaValue[]): LuaValue[] { const v = a[0] ?? null; if (v instanceof LuaTable) { const err = v.get('err'); throw new LuaError(typeof err === 'string' ? err : 'script raised a table error'); } throw new LuaError(typeof v === 'string' ? v : `script error: ${luaTypeName(v)}`); } g.declare('error', luaError); function luaAssert(a: LuaValue[]): LuaValue[] { if (!luaTruthy(a[0] ?? null)) throw new LuaError(typeof a[1] === 'string' ? a[1] : 'assertion failed!'); return a; } g.declare('assert', luaAssert); function luaSelect(a: LuaValue[]): LuaValue[] { const sel = a[0] ?? null; const rest = a.slice(1); if (sel === '#') return one(rest.length); const n = Number(arith(sel, 'select')); return rest.slice(n - 1); } g.declare('select', luaSelect); g.declare('rawget', (a) => one(a[0] instanceof LuaTable ? a[0].get(a[1] ?? null) : null)); g.declare('rawset', (a) => { if (a[0] instanceof LuaTable) a[0].set(a[1] ?? null, a[2] ?? null); return one(a[0] ?? null); }); g.declare('unpack', (a) => (a[0] instanceof LuaTable ? a[0].toArray() : [])); function luaIpairs(a: LuaValue[]): LuaValue[] { const t = a[0]; if (!(t instanceof LuaTable)) throw new LuaError('bad argument #1 to \'ipairs\' (table expected)'); const iter: LuaFunction = (args) => { const i = Number(arith(args[1] ?? 0, 'ipairs')) + 1; const v = t.get(i); return v === null ? [null] : [i, v]; }; return [iter, t, 0]; } g.declare('ipairs', luaIpairs); function luaPairs(a: LuaValue[]): LuaValue[] { const t = a[0]; if (!(t instanceof LuaTable)) throw new LuaError('bad argument #1 to \'pairs\' (table expected)'); const entries = [...t.map.entries()]; let idx = 0; const iter: LuaFunction = () => { if (idx >= entries.length) return [null]; const [k, v] = entries[idx++]!; return [k as LuaValue, v]; }; return [iter, t, null]; } g.declare('pairs', luaPairs); const math = new LuaTable(); const num = (a: LuaValue[], i: number, who: string) => Number(arith(a[i] ?? null, who)); math.set('floor', (a) => one(Math.floor(num(a, 0, 'math.floor')))); math.set('ceil', (a) => one(Math.ceil(num(a, 0, 'math.ceil')))); math.set('abs', (a) => one(Math.abs(num(a, 0, 'math.abs')))); math.set('sqrt', (a) => one(Math.sqrt(num(a, 0, 'math.sqrt')))); math.set('pow', (a) => one(num(a, 0, 'math.pow') ** num(a, 1, 'math.pow'))); math.set('fmod', (a) => one(num(a, 0, 'math.fmod') % num(a, 1, 'math.fmod'))); math.set('modf', (a) => { const v = num(a, 0, 'math.modf'); const i = v < 0 ? Math.ceil(v) : Math.floor(v); return [i, v - i]; }); math.set('min', (a) => one(Math.min(...a.map((_, i) => num(a, i, 'math.min'))))); math.set('max', (a) => one(Math.max(...a.map((_, i) => num(a, i, 'math.max'))))); math.set('huge', Number.POSITIVE_INFINITY); // DETERMINISM: real Redis seeds Lua's RNG identically for every script run so replicas agree. // This twin does the same with a fixed LCG — a script that calls math.random gets a repeatable // sequence rather than the twin's determinism being silently broken by Math.random(). let seed = 0x2545_f491; const nextRandom = (): number => { seed = (seed * 1_103_515_245 + 12_345) >>> 0; return seed / 0x1_0000_0000; }; math.set('randomseed', (a) => { seed = (num(a, 0, 'math.randomseed') >>> 0) || 1; return []; }); function luaMathRandom(a: LuaValue[]): LuaValue[] { if (a.length === 0) return one(nextRandom()); const lo = a.length === 1 ? 1 : num(a, 0, 'math.random'); const hi = a.length === 1 ? num(a, 0, 'math.random') : num(a, 1, 'math.random'); return one(lo + Math.floor(nextRandom() * (hi - lo + 1))); } math.set('random', luaMathRandom); g.declare('math', math); const table = new LuaTable(); function luaTableInsert(a: LuaValue[]): LuaValue[] { const t = a[0]; if (!(t instanceof LuaTable)) throw new LuaError("bad argument #1 to 'table.insert' (table expected)"); if (a.length >= 3) { const at = Number(arith(a[1] ?? null, 'table.insert')); for (let i = t.length; i >= at; i--) t.set(i + 1, t.get(i)); t.set(at, a[2] ?? null); } else { t.set(t.length + 1, a[1] ?? null); } return []; } table.set('insert', luaTableInsert); function luaTableRemove(a: LuaValue[]): LuaValue[] { const t = a[0]; if (!(t instanceof LuaTable)) throw new LuaError("bad argument #1 to 'table.remove' (table expected)"); const n = t.length; const at = a.length >= 2 ? Number(arith(a[1] ?? null, 'table.remove')) : n; const removed = t.get(at); for (let i = at; i < n; i++) t.set(i, t.get(i + 1)); t.set(n, null); return one(removed); } table.set('remove', luaTableRemove); table.set('getn', (a) => one(a[0] instanceof LuaTable ? a[0].length : 0)); function luaTableConcat(a: LuaValue[]): LuaValue[] { const t = a[0]; if (!(t instanceof LuaTable)) throw new LuaError("bad argument #1 to 'table.concat' (table expected)"); const sep = typeof a[1] === 'string' ? a[1] : a[1] === undefined || a[1] === null ? '' : concatOperand(a[1]); return one(t.toArray().map(concatOperand).join(sep)); } table.set('concat', luaTableConcat); g.declare('table', table); const string = new LuaTable(); const str = (a: LuaValue[], i: number, who: string): string => { const v = a[i] ?? null; if (typeof v === 'string') return v; if (typeof v === 'number') return numberToLuaString(v); throw new LuaError(`bad argument #${i + 1} to '${who}' (string expected, got ${luaTypeName(v)})`); }; string.set('len', (a) => one(str(a, 0, 'string.len').length)); string.set('lower', (a) => one(str(a, 0, 'string.lower').toLowerCase())); string.set('upper', (a) => one(str(a, 0, 'string.upper').toUpperCase())); string.set('rep', (a) => one(str(a, 0, 'string.rep').repeat(Math.max(0, Number(arith(a[1] ?? 0, 'string.rep')))))); function luaStringSub(a: LuaValue[]): LuaValue[] { const s = str(a, 0, 'string.sub'); let i = a.length >= 2 ? Number(arith(a[1] ?? 1, 'string.sub')) : 1; let j = a.length >= 3 && a[2] !== null ? Number(arith(a[2]!, 'string.sub')) : -1; if (i < 0) i = Math.max(s.length + i + 1, 1); else if (i === 0) i = 1; if (j < 0) j = s.length + j + 1; else if (j > s.length) j = s.length; return one(i > j ? '' : s.slice(i - 1, j)); } string.set('sub', luaStringSub); string.set('byte', (a) => one(str(a, 0, 'string.byte').charCodeAt(Math.max(0, (a.length >= 2 ? Number(arith(a[1]!, 'string.byte')) : 1) - 1)) || 0)); string.set('char', (a) => one(a.map((v, i) => { const code = Math.trunc(Number(arith(v, 'string.char'))); // a Lua string holds bytes: lstrlib.c str_char refuses anything outside 0..255 if (!(code >= 0 && code <= 255)) throw new LuaError(`bad argument #${i + 1} to 'char' (invalid value)`); return String.fromCharCode(code); }).join(''))); function luaStringFormat(a: LuaValue[]): LuaValue[] { const fmt = str(a, 0, 'string.format'); let argIndex = 1; // lstrlib.c str_format over C's printf: flags, width and precision as C applies them return one(fmt.replace(/%%|%([-+ #0]*)(\d*)(?:\.(\d*))?([cdiouxXeEfgGqs])|%(.?)/g, (spec, flags: string | undefined, width: string | undefined, precision: string | undefined, verb: string | undefined, bad: string | undefined) => { if (spec === '%%') return '%'; if (verb === undefined) throw new LuaError(`invalid option '%${bad ?? ''}' to 'format'`); // lstrlib.c scanformat: at most two digits of width and of precision if ((width ?? '').length > 2 || (precision ?? '').length > 2) throw new LuaError("invalid format (width or precision too long)"); if ((verb === 's' || verb === 'q') && typeof a[argIndex] !== 'string' && typeof a[argIndex] !== 'number') throw new LuaError(`bad argument #${argIndex + 1} to 'format' (string expected, got ${luaTypeName(a[argIndex] ?? null)})`); if (argIndex >= a.length) throw new LuaError(`bad argument #${argIndex + 1} to 'format' (no value)`); const v = a[argIndex++] ?? null; return formatOne(verb, flags ?? '', width ? Number(width) : 0, precision === undefined ? undefined : Number(precision || '0'), v); })); } string.set('format', luaStringFormat); // `find`/`gsub` are supported ONLY in their plain-text form. Lua PATTERNS are a different // language from JS regexes and a silent mistranslation would be exactly the fake success this // pack forbids, so a pattern with any magic character is REFUSED by name. const PLAIN_ONLY = /[.%^$*+?()[\]-]/; function luaStringFind(a: LuaValue[]): LuaValue[] { const s = str(a, 0, 'string.find'); const pattern = str(a, 1, 'string.find'); const plain = a.length >= 4 && luaTruthy(a[3] ?? null); if (!plain && PLAIN_ONLY.test(pattern)) throw new LuaError(`unsupported Lua construct: string.find with a Lua PATTERN ('${pattern}') — this twin supports plain-text find only`); const from = a.length >= 3 && a[2] !== null ? Math.max(1, Number(arith(a[2]!, 'string.find'))) : 1; const idx = s.indexOf(pattern, from - 1); return idx < 0 ? [null] : [idx + 1, idx + pattern.length]; } string.set('find', luaStringFind); function luaStringGsub(a: LuaValue[]): LuaValue[] { const s = str(a, 0, 'string.gsub'); const pattern = str(a, 1, 'string.gsub'); if (PLAIN_ONLY.test(pattern)) throw new LuaError(`unsupported Lua construct: string.gsub with a Lua PATTERN ('${pattern}') — this twin supports plain-text substitution only`); const repl = str(a, 2, 'string.gsub'); const parts = s.split(pattern); return [parts.join(repl), parts.length - 1]; } string.set('gsub', luaStringGsub); g.declare('string', string); // ── the `redis` table: the bridge back into this twin's real command core ────────────────── const api = new LuaTable(); const toArg = (v: LuaValue): string => { if (typeof v === 'string') return v; // Real Redis converts a Lua NUMBER argument to a string by TRUNCATING it toward zero // (lua_cmsgpack-free path in scripting.c) — 3.7 becomes "3", not "3.7". if (typeof v === 'number') return host.numberArg(v); throw new LuaError('Lua redis lib command arguments must be strings or integers'); }; api.set('call', (a) => { if (a.length === 0) throw new LuaError('Please specify at least one argument for redis.call()'); return one(host.call(a.map(toArg), this.line)); }); const redisPcall = (a: LuaValue[]): LuaValue[] => { if (a.length === 0) throw new LuaError('Please specify at least one argument for redis.pcall()'); try { return one(host.call(a.map(toArg), this.line)); } catch (e) { const t = new LuaTable(); t.set('err', e instanceof Error ? e.message : String(e)); return one(t); } }; api.set('pcall', redisPcall); api.set('error_reply', (a) => { const t = new LuaTable(); t.set('err', typeof a[0] === 'string' ? a[0] : 'ERR'); return one(t); }); api.set('status_reply', (a) => { const t = new LuaTable(); t.set('ok', typeof a[0] === 'string' ? a[0] : 'OK'); return one(t); }); api.set('sha1hex', (a) => one(createHash('sha1').update(typeof a[0] === 'string' ? a[0] : concatOperand(a[0] ?? '')).digest('hex'))); api.set('log', () => []); api.set('breakpoint', () => one(false)); api.set('debug', () => []); api.set('setresp', () => []); api.set('replicate_commands', () => one(true)); api.set('LOG_DEBUG', 0); api.set('LOG_VERBOSE', 1); api.set('LOG_NOTICE', 2); api.set('LOG_WARNING', 3); // the API's global name is the wire's (Redis's scripts call it `redis`, and `server` since 7.0): see `extend` host.extend?.({ get: (name) => g.get(name), set: (name, value) => g.declare(name, value), commandApi: api }); } private execBlock(stats: Stat[], scope: Scope): Signal { for (const s of stats) { const sig = this.execStat(s, scope); if (sig) return sig; } return null; } private execStat(s: Stat, scope: Scope): Signal { this.tick(); switch (s.t) { case 'local': { const values = this.evalList(s.exprs, scope, s.names.length); s.names.forEach((n, i) => scope.declare(n, values[i] ?? null)); return null; } case 'assign': { const values = this.evalList(s.exprs, scope, s.targets.length); s.targets.forEach((target, i) => { const v = values[i] ?? null; if (target.t === 'name') { scope.set(target.v, v); return; } if (target.t === 'index') { const obj = this.evalExpr(target.obj, scope); if (!(obj instanceof LuaTable)) throw new LuaError(`attempt to index a ${luaTypeName(obj)} value`); obj.set(this.evalExpr(target.key, scope), v); return; } throw new LuaError('invalid assignment target'); }); return null; } case 'callstat': this.evalMulti(s.call, scope); return null; case 'do': return this.execBlock(s.body, new Scope(scope)); case 'if': { for (const b of s.branches) { if (luaTruthy(this.evalExpr(b.cond, scope))) return this.execBlock(b.body, new Scope(scope)); } return s.orelse ? this.execBlock(s.orelse, new Scope(scope)) : null; } case 'while': { while (luaTruthy(this.evalExpr(s.cond, scope))) { this.tick(); const sig = this.execBlock(s.body, new Scope(scope)); if (sig === BREAK) break; if (sig) return sig; } return null; } case 'repeat': { for (;;) { this.tick(); // Lua scopes the `until` condition INSIDE the loop body's scope. const inner = new Scope(scope); const sig = this.execBlock(s.body, inner); if (sig === BREAK) break; if (sig) return sig; if (luaTruthy(this.evalExpr(s.cond, inner))) break; } return null; } case 'fornum': { const from = arith(this.evalExpr(s.from, scope), "'for' initial value"); const to = arith(this.evalExpr(s.to, scope), "'for' limit"); const step = s.step ? arith(this.evalExpr(s.step, scope), "'for' step") : 1; if (step === 0) throw new LuaError("'for' step is zero"); for (let i = from; step > 0 ? i <= to : i >= to; i += step) { this.tick(); const inner = new Scope(scope); inner.declare(s.name, i); const sig = this.execBlock(s.body, inner); if (sig === BREAK) break; if (sig) return sig; } return null; } case 'forin': { const [iter, state, initial] = this.evalList(s.exprs, scope, 3); if (typeof iter !== 'function') throw new LuaError(`attempt to call a ${luaTypeName(iter ?? null)} value in a generic for`); let control: LuaValue = initial ?? null; for (;;) { this.tick(); const results = iter([state ?? null, control]); if ((results[0] ?? null) === null) break; control = results[0]!; const inner = new Scope(scope); s.names.forEach((n, i) => inner.declare(n, results[i] ?? null)); const sig = this.execBlock(s.body, inner); if (sig === BREAK) break; if (sig) return sig; } return null; } case 'return': return { ret: this.evalList(s.exprs, scope, s.exprs.length) }; case 'break': return BREAK; } } /** Evaluate an expression list, expanding the LAST expression's multiple returns (Lua rule). */ private evalList(exprs: Expr[], scope: Scope, want: number): LuaValue[] { const out: LuaValue[] = []; exprs.forEach((e, i) => { if (i === exprs.length - 1) out.push(...this.evalMulti(e, scope)); else out.push(this.evalExpr(e, scope)); }); while (out.length < want) out.push(null); return out; } /** Evaluate an expression in "multiple results" position. */ private evalMulti(e: Expr, scope: Scope): LuaValue[] { if (e.t !== 'call') return [this.evalExpr(e, scope)]; const fn = this.evalExpr(e.fn, scope); if (typeof fn !== 'function') { const name = e.fn.t === 'name' ? ` (global '${e.fn.v}')` : e.fn.t === 'index' && e.fn.key.t === 'str' ? ` (field '${e.fn.key.v}')` : ''; throw new LuaError(`attempt to call a ${luaTypeName(fn)} value${name} — unsupported or undefined in this twin's Lua subset`); } // a call passes exactly the values its arguments make: a last argument that returns nothing (`unpack({})`) adds none const args = this.evalList(e.args, scope, 0); this.tick(); if (e.line !== undefined) this.line = e.line; return fn(args); } private evalExpr(e: Expr, scope: Scope): LuaValue { this.tick(); switch (e.t) { case 'nil': return null; case 'true': return true; case 'false': return false; case 'num': return e.v; case 'str': return e.v; case 'name': { if (!scope.has(e.v)) { // A Lua global that was never assigned reads as nil. That is correct Lua — but for the // handful of names that are LIBRARIES this interpreter deliberately does not ship, a // silent nil turns into "attempt to call a nil value" three lines later, which reads as // a script bug rather than a twin limitation. Name them here instead. if (['cjson', 'cmsgpack', 'bit', 'struct', 'os', 'io', 'setmetatable', 'getmetatable', 'pcall', 'xpcall', 'loadstring', 'require', 'coroutine'].includes(e.v)) { throw new LuaError(`unsupported Lua library '${e.v}' — this twin runs a documented Lua SUBSET (the kernel's Redis library, lua.ts)`); } return null; } return scope.get(e.v); } case 'index': { const obj = this.evalExpr(e.obj, scope); if (!(obj instanceof LuaTable)) { if (typeof obj === 'string') throw new LuaError('unsupported Lua construct: indexing a string value (string metatable methods are not modeled)'); throw new LuaError(`attempt to index a ${luaTypeName(obj)} value`); } return obj.get(this.evalExpr(e.key, scope)); } case 'call': return this.evalMulti(e, scope)[0] ?? null; case 'table': { const t = new LuaTable(); e.array.forEach((item, i) => { // The LAST array item expands its multiple returns, exactly as Lua does. if (i === e.array.length - 1) this.evalMulti(item, scope).forEach((v, j) => t.set(i + 1 + j, v)); else t.set(i + 1, this.evalExpr(item, scope)); }); for (const p of e.pairs) t.set(this.evalExpr(p.k, scope), this.evalExpr(p.v, scope)); return t; } case 'un': { if (e.op === 'not') return !luaTruthy(this.evalExpr(e.e, scope)); const v = this.evalExpr(e.e, scope); if (e.op === '-') return -arith(v, 'unary -'); if (e.op === '#') { if (typeof v === 'string') return v.length; if (v instanceof LuaTable) return v.length; throw new LuaError(`attempt to get length of a ${luaTypeName(v)} value`); } throw new LuaError(`unsupported unary operator '${e.op}'`); } case 'bin': return this.evalBinary(e, scope); case 'func': { const params = e.params; const body = e.body; const closure: LuaFunction = (args) => { const inner = new Scope(scope); params.forEach((p, i) => inner.declare(p, args[i] ?? null)); const sig = this.execBlock(body, inner); if (sig === BREAK) throw new LuaError("'break' outside a loop"); return sig && 'ret' in sig ? sig.ret : []; }; return closure; } } } private evalBinary(e: Extract, scope: Scope): LuaValue { // `and`/`or` short-circuit and return an OPERAND, not a boolean. if (e.op === 'and') { const l = this.evalExpr(e.l, scope); return luaTruthy(l) ? this.evalExpr(e.r, scope) : l; } if (e.op === 'or') { const l = this.evalExpr(e.l, scope); return luaTruthy(l) ? l : this.evalExpr(e.r, scope); } const l = this.evalExpr(e.l, scope); const r = this.evalExpr(e.r, scope); switch (e.op) { case '+': return arith(l, '+') + arith(r, '+'); case '-': return arith(l, '-') - arith(r, '-'); case '*': return arith(l, '*') * arith(r, '*'); case '/': return arith(l, '/') / arith(r, '/'); case '^': return arith(l, '^') ** arith(r, '^'); case '%': { // Lua's `%` is `a - floor(a/b)*b` — the result takes the SIGN OF THE DIVISOR, unlike JS. const a = arith(l, '%'); const b = arith(r, '%'); return a - Math.floor(a / b) * b; } case '..': return concatOperand(l) + concatOperand(r); // STRICT equality across types — `"3" == 3` is FALSE in Lua. See the file header (2). case '==': return luaEquals(l, r); case '~=': return !luaEquals(l, r); case '<': case '<=': case '>': case '>=': { if (typeof l === 'number' && typeof r === 'number') { return e.op === '<' ? l < r : e.op === '<=' ? l <= r : e.op === '>' ? l > r : l >= r; } if (typeof l === 'string' && typeof r === 'string') { const c = l < r ? -1 : l > r ? 1 : 0; return e.op === '<' ? c < 0 : e.op === '<=' ? c <= 0 : e.op === '>' ? c > 0 : c >= 0; } throw new LuaError(`attempt to compare ${luaTypeName(l)} with ${luaTypeName(r)}`); } default: throw new LuaError(`unsupported binary operator '${e.op}'`); } } } /** Lua `==`: same type required (no string/number coercion); tables compare by identity. */ export function luaEquals(l: LuaValue, r: LuaValue): boolean { if (l === null || r === null) return l === r; if (typeof l !== typeof r) return false; return l === r; } /** Parse + run a script. Returns the Lua value the chunk returned (or `nil`). */ export function runLua(script: string, host: LuaHost): LuaValue { let chunk = parsed.get(script); if (chunk === undefined) { chunk = parseLua(script); if (parsed.size >= 256) parsed.delete(parsed.keys().next().value!); parsed.set(script, chunk); } return new Interpreter(host).run(chunk); } // cache: a script's parse, by its text — the tree is immutable and a script is parsed once, as Redis compiles it once const parsed = new Map(); /** The SHA1 real Redis keys the script cache by — the same hex digest `SCRIPT LOAD` returns. */ export function luaScriptSha1(script: string): string { return createHash('sha1').update(script).digest('hex'); }