diff --git a/client/space_lua/arithmetic_test.lua b/client/space_lua/arithmetic_test.lua index 33edcae7..5173173c 100644 --- a/client/space_lua/arithmetic_test.lua +++ b/client/space_lua/arithmetic_test.lua @@ -4,7 +4,7 @@ local function assert_eq(actual, expected, message) end end -local function assert_throws(msg_substr, fn) +local function assertThrows(msg_substr, fn) local ok, err = pcall(fn) if ok then @@ -320,7 +320,7 @@ assert_eq('1'+2, 3, 'str-num: "1"+2 == 3') assert_eq(' -2 ' * '3', -6, 'str-num: " -2 " * "3" == -6') assert_eq('0x10' + 1, 17, 'str-num: hex int string + 1 == 17') assert_eq('0x1p4' + 0, 16, 'str-num: hex float string + 0 == 16') -assert_throws('attempt to perform arithmetic on a non-number', +assertThrows("attempt to add a 'string' with a 'number'", function() return 'x1'+1 end @@ -342,7 +342,7 @@ assert_eq(1/-rec_zero(5) == 1/0, true, 'recursive: -(rec_zero) (+Inf)') -- 16. Modulo and integer division by zero -- 16.1. Modulo by zero -assert_throws('modulo by zero', +assertThrows("attempt to perform 'n%0'", function() return 1%0 end @@ -370,7 +370,7 @@ val = pcall( assert_eq(val, true, 'mixed (int,float) mod by zero ok (NaN)') -- 16.2. Integer division by zero -assert_throws('divide by zero', +assertThrows('divide by zero', function() return 1//0 end @@ -467,83 +467,237 @@ assert_eq(0^0 == 1, true, 'pow: 0^0 == 1') assert_eq((-0.0)^0 == 1, true, 'pow: (-0.0)^0 == 1') -- 19. Error tests -assert_throws('has no integer representation', +assertThrows('has no integer representation', function() return ~0.5 end ) -assert_throws('attempt to perform arithmetic on a non-number', +assertThrows("attempt to add a 'string' with a 'number'", function() return 'a'+1 end ) -assert_throws('attempt to perform arithmetic on a non-number', +assertThrows('attempt to perform arithmetic on a table value', function() return -{} end ) -- 19.1. Bitwise on non-integers should error -assert_throws('has no integer representation', +assertThrows('has no integer representation', function() return 1.5&1 end ) -assert_throws('attempt to perform arithmetic on a non-number', +assertThrows( + "attempt to perform bitwise operation on a string value (constant '3')", function() return '3'|1 end ) -assert_throws('has no integer representation', +assertThrows('has no integer representation', function() return 1~1.2 end ) -assert_throws('has no integer representation', +assertThrows('has no integer representation', function() return 1<<0.1 end ) -- 19.2. Relational type error -assert_throws('attempt to compare number with string', +assertThrows('attempt to compare number with string', function() return 1<'1' end ) -- 19.3. Additional negative tests -assert_throws('attempt to perform arithmetic on a non-number', +assertThrows('attempt to perform arithmetic on a table value', function() return 1+{} end ) -assert_throws('attempt to perform arithmetic on a non-number', +assertThrows("attempt to unm a 'string' with a 'string'", function() return -'x' end ) -assert_throws('attempt to perform arithmetic on a non-number', +assertThrows( + "attempt to perform bitwise operation on a string value (constant '1')", function() return ~'1' end ) -assert_throws('attempt to compare string with number', +assertThrows('attempt to compare string with number', function() return '1'<1 end ) -assert_throws('attempt to compare number with object', +assertThrows('attempt to compare number with table', function() return 1<{} end ) + +-- 19.4. String arithmetic: exact verb mapping +assertThrows("attempt to sub a 'string' with a 'number'", + function() + return 'x' - 1 + end +) + +assertThrows("attempt to mul a 'string' with a 'number'", + function() + return 'x' * 2 + end +) + +assertThrows("attempt to div a 'string' with a 'number'", + function() + return 'x' / 2 + end +) + +assertThrows("attempt to idiv a 'string' with a 'number'", + function() + return 'x' // 2 + end +) + +assertThrows("attempt to mod a 'string' with a 'number'", + function() + return 'x' % 2 + end +) + +assertThrows("attempt to pow a 'string' with a 'number'", + function() + return 'x' ^ 2 + end +) + +-- 19.4.1. String arithmetic: type pairing and string-vs-string cases +assertThrows("attempt to add a 'string' with a 'string'", + function() + return 'x' + 'y' + end +) + +assertThrows("attempt to mul a 'number' with a 'string'", + function() + return 2 * 'x' + end +) + +-- 19.5. Bitwise: exact type errors +assertThrows("attempt to perform bitwise operation on a table value", + function() + return {} & 1 + end +) + +assertThrows("attempt to perform bitwise operation on a nil value", + function() + return nil | 1 + end +) + +assertThrows("attempt to perform bitwise operation on a boolean value", + function() + return true ~ 1 + end +) + +-- 19.6. Bitwise shifts: non-integer RHS +assertThrows("number has no integer representation", + function() + return 1 << 0.5 + end +) + +assertThrows("number has no integer representation", + function() + return 8 >> 0.25 + end +) + +-- 19.7. Concatenation: exact messages +assertThrows("attempt to concatenate a nil value", + function() + return nil .. "x" + end +) + +assertThrows("attempt to concatenate a nil value", + function() + return "x" .. nil + end +) + +assertThrows("attempt to concatenate a table value", + function() + return "x" .. {} + end +) + +-- 19.8. Length operator: exact message +assertThrows("attempt to get length of a number value", + function() + return #1 + end +) + +assertThrows("attempt to get length of a nil value", + function() + return #nil + end +) + +-- 19.9. Relational mismatches +assertThrows("attempt to compare number with string", + function() + return 1 <= '1' + end +) + +assertThrows("attempt to compare number with string", + function() + return '1' >= 1 + end +) + +assertThrows("attempt to compare table with number", + function() + return 1 > {} + end +) + +assertThrows("attempt to compare table with number", + function() + return {} < 1 + end +) + +-- 19.10. Explicit int-path division/modulo by zero through expr +assertThrows("attempt to perform 'n%0'", + function() + return 1 % (1-1) + end +) + +assertThrows("attempt to divide by zero", + function() + return 1 // (1-1) + end +) diff --git a/client/space_lua/context_errors.test.ts b/client/space_lua/context_errors.test.ts index d2a30678..47e6a6ec 100644 --- a/client/space_lua/context_errors.test.ts +++ b/client/space_lua/context_errors.test.ts @@ -77,7 +77,7 @@ Deno.test("Context error: modulo by zero includes message and ref", async () => `, "mod_zero.lua", ); - assertCtxErrorContains(e, code, ref, "attempt to perform modulo by zero"); + assertCtxErrorContains(e, code, ref, "attempt to perform 'n%0'"); }); Deno.test("Context error: type mismatch in comparison includes message and ref", async () => { diff --git a/client/space_lua/eval.ts b/client/space_lua/eval.ts index 3e743210..3e172148 100644 --- a/client/space_lua/eval.ts +++ b/client/space_lua/eval.ts @@ -33,6 +33,7 @@ import { LuaTable, luaTruthy, type LuaType, + luaTypeName, luaTypeOf, type LuaValue, luaValueToJS, @@ -46,6 +47,7 @@ import { boxZero, coerceNumeric, coerceNumericPair, + luaStringCoercionError, type OpHints, } from "./numeric.ts"; import { isPromise, rpAll, rpThen } from "./rp.ts"; @@ -127,6 +129,52 @@ function isQueryable(x: unknown): x is Queryable { return !!x && typeof (x as any).query === "function"; } +function arithVerbFromOperator(op: string): string | null { + switch (op) { + case "+": + return "add"; + case "-": + return "sub"; + case "*": + return "mul"; + case "/": + return "div"; + case "//": + return "idiv"; + case "%": + return "mod"; + case "^": + return "pow"; + default: + return null; + } +} + +function maybeLuaArithStringError( + op: string, + a: any, + b: any, + ctx: ASTCtx, + sf: LuaStackFrame, +): LuaRuntimeError | null { + const verb = arithVerbFromOperator(op); + if (!verb) { + return null; + } + + const ta = luaTypeName(a); + const tb = luaTypeName(b); + + if (ta === "string" || tb === "string") { + return new LuaRuntimeError( + `attempt to ${verb} a '${ta}' with a '${tb}'`, + sf.withCtx(ctx), + ); + } + + return null; +} + function luaFloorDiv( a: unknown, b: unknown, @@ -162,7 +210,7 @@ function luaMod( const { ax, bx, bothInt } = coerceNumericPair(a, b, hints); if (bothInt && bx === 0) { throw new LuaRuntimeError( - `attempt to perform modulo by zero`, + `attempt to perform 'n%0'`, sf.withCtx(ctx), ); } @@ -347,7 +395,19 @@ export function evalExpression( "__unm", u.ctx, sf, - () => luaUnaryMinus(arg), + () => { + if (typeof arg === "string") { + try { + coerceNumeric(arg); + } catch (_e: any) { + throw new LuaRuntimeError( + "attempt to unm a 'string' with a 'string'", + sf.withCtx(u.ctx), + ); + } + } + return luaUnaryMinus(arg); + }, ); } case "+": { @@ -766,8 +826,8 @@ function luaRelOperands( av: any; bv: any; } { - const ta = (a instanceof Number) ? "number" : typeof a; - const tb = (b instanceof Number) ? "number" : typeof b; + const ta = luaTypeName(a); + const tb = luaTypeName(b); const av = (a instanceof Number) ? Number(a) : a; const bv = (b instanceof Number) ? Number(b) : b; @@ -882,7 +942,6 @@ const operatorsMetaMethods: Record { - // Accepts only strings or numbers (coerced to strings) const coerce = (v: any): string => { if (v === null || v === undefined) { throw new LuaRuntimeError( @@ -896,8 +955,9 @@ const operatorsMetaMethods: Record luaLessEqual(a, b, ctx, sf), }, + // Lua does not define `>`/`>=` as logical negations of `<`/`<=` but + // as swapped operands (`a>b` evaluated as `b=b` as `b<=a`). ">": { - nativeImplementation: (a, b, ctx, sf) => !luaOp("<=", a, b, ctx, sf), + nativeImplementation: (a, b, ctx, sf) => luaOp("<", b, a, ctx, sf), }, ">=": { - nativeImplementation: (a, b, ctx, sf) => !luaOp("<", a, b, ctx, sf), + nativeImplementation: (a, b, ctx, sf) => luaOp("<=", b, a, ctx, sf), }, }; @@ -952,7 +1014,28 @@ function luaOp( } } - return handler.nativeImplementation(left, right, ctx, sf, hints); + try { + return handler.nativeImplementation(left, right, ctx, sf, hints); + } catch (e: any) { + // If numeric coercion failed on a string produce the Lua message + if (e === luaStringCoercionError) { + const mapped = maybeLuaArithStringError(op, left, right, ctx, sf); + if (mapped) { + throw mapped; + } + // Fallback + throw new LuaRuntimeError( + "attempt to perform arithmetic on a string value", + sf.withCtx(ctx), + ); + } + + const mapped = maybeLuaArithStringError(op, left, right, ctx, sf); + if (mapped) { + throw mapped; + } + throw e; + } } /** @@ -2149,18 +2232,24 @@ function exactInt( n = num; } else if (num instanceof Number) { n = Number(num); - } else { + } else if (typeof num === "string") { throw new LuaRuntimeError( - `attempt to perform arithmetic on a non-number`, + `attempt to perform bitwise operation on a string value (constant '${num}')`, + sf.withCtx(ctx), + ); + } else { + const t = luaTypeName(num); + throw new LuaRuntimeError( + `attempt to perform bitwise operation on a ${t} value`, sf.withCtx(ctx), ); } if (!Number.isInteger(n)) { throw new LuaRuntimeError( - `Number ${n} has no integer representation (consider math.floor or math.ceil)`, + `number has no integer representation`, sf.withCtx(ctx), ); } return n; -} \ No newline at end of file +} diff --git a/client/space_lua/len_test.lua b/client/space_lua/len_test.lua index b1a71130..e738301b 100644 --- a/client/space_lua/len_test.lua +++ b/client/space_lua/len_test.lua @@ -4,7 +4,7 @@ local function assert_eq(actual, expected, msg) end end -local function assert_throws(substr, fn) +local function assertThrows(substr, fn) local ok, err = pcall(fn) if ok then error("expected error containing: " .. substr) @@ -76,28 +76,28 @@ do end -- 3. Non-strings and non-tables -assert_throws( +assertThrows( "attempt to get length of a nil value", function() return #nil end ) -assert_throws( +assertThrows( "attempt to get length of a number value", function() return #1 end ) -assert_throws( +assertThrows( "attempt to get length of a boolean value", function() return #false end ) -assert_throws( +assertThrows( "attempt to get length of a function value", function() local f = function() end diff --git a/client/space_lua/numeric.ts b/client/space_lua/numeric.ts index d1f368e6..2f54a2e4 100644 --- a/client/space_lua/numeric.ts +++ b/client/space_lua/numeric.ts @@ -1,5 +1,6 @@ import type { NumericType } from "./ast.ts"; import { luaToNumberDetailed } from "./tonumber.ts"; +import { luaTypeName } from "./runtime.ts"; export const ZeroBoxKind = Symbol("ZeroBox"); @@ -24,6 +25,11 @@ export type OpHints = { rightKind?: NumericType; }; +// Marker error used to let the evaluator decide the final message. +export const luaStringCoercionError: Error = new Error( + "LuaStringCoercionError", +); + export function coerceNumeric( val: unknown, ): { @@ -75,7 +81,8 @@ export function coerceNumeric( if (typeof val === "string") { const det = luaToNumberDetailed(val); if (!det) { - throw new Error(`attempt to perform arithmetic on a non-number`); + // Let evaluator produce the final error message + throw luaStringCoercionError; } const n = det.value; @@ -101,7 +108,9 @@ export function coerceNumeric( }; } - throw new Error(`attempt to perform arithmetic on a non-number`); + throw new Error( + `attempt to perform arithmetic on a ${luaTypeName(val)} value`, + ); } export function coerceNumericPair( diff --git a/client/space_lua/runtime.ts b/client/space_lua/runtime.ts index f13eb491..2ebaf338 100644 --- a/client/space_lua/runtime.ts +++ b/client/space_lua/runtime.ts @@ -64,6 +64,39 @@ type LuaThreadState = { closeStack?: LuaCloseEntry[]; }; +export function luaTypeName(val: any): LuaType { + const t = luaTypeOf(val); + + if (typeof t === "string") { + return t; + } + if (val === null || val === undefined) { + return "nil"; + } + + const ty = typeof val; + if (ty === "number" || val instanceof Number) { + return "number"; + } + if (ty === "string") { + return "string"; + } + if (ty === "boolean") { + return "boolean"; + } + if (ty === "function") { + return "function"; + } + if (Array.isArray(val)) { + return "table"; + } + if (ty === "object" && (val as any).constructor === Object) { + return "table"; + } + + return "userdata"; +} + // Check whether a value is callable without invoking it. export function luaIsCallable( v: LuaValue, diff --git a/client/space_lua/stdlib.ts b/client/space_lua/stdlib.ts index b415e93e..6d5454a4 100644 --- a/client/space_lua/stdlib.ts +++ b/client/space_lua/stdlib.ts @@ -139,7 +139,15 @@ const tostringFunction = new LuaBuiltinFunction((_sf, value: any) => { }); const tonumberFunction = new LuaBuiltinFunction( - (_sf, value: LuaValue, base?: number) => { + (sf, value: LuaValue, base?: number) => { + if (base !== undefined) { + if (!(typeof base === "number" && base >= 2 && base <= 36)) { + throw new LuaRuntimeError( + "bad argument #2 to 'tonumber' (base out of range)", + sf, + ); + } + } return luaToNumber(value, base); }, ); diff --git a/client/space_lua/tonumber.ts b/client/space_lua/tonumber.ts index 80430036..c84f9ac2 100644 --- a/client/space_lua/tonumber.ts +++ b/client/space_lua/tonumber.ts @@ -321,6 +321,7 @@ function parseHexFloat(s: string): { ok: boolean; value: number } { let fracVal = 0; let fracScale = 1; let anyHex = false; + let sawDot = false; // integer hex digits while (i < n) { @@ -346,6 +347,7 @@ function parseHexFloat(s: string): { ok: boolean; value: number } { // optional fractional part if (i < n) { if (s.charCodeAt(i) === 46) { // '.' + sawDot = true; i++; while (i < n) { const c = s.charCodeAt(i); @@ -370,43 +372,64 @@ function parseHexFloat(s: string): { ok: boolean; value: number } { } } - // exponent (required) - if (i >= n) { - return { ok: false, value: 0 }; - } - const ec = s.charCodeAt(i); - if (!(ec === 112 || ec === 80)) { // 'p' or 'P' - return { ok: false, value: 0 }; - } - i++; - + // exponent: + // - required if there is no dot (so `0x10` stays an integer), + // - optional if there was a dot (`0x1.2` means `0x1.2p0`). let expSign = 1; - if (i < n) { - const sc = s.charCodeAt(i); - if (sc === 45) { // '-' - expSign = -1; - i++; - } else if (sc === 43) { // '+' - i++; - } - } - if (i >= n) { - return { ok: false, value: 0 }; - } - - let anyExp = false; let exp = 0; - while (i < n) { - const c = s.charCodeAt(i); - if (c < 48 || c > 57) { // not '0'..'9' - break; + + if (i < n) { + const ec = s.charCodeAt(i); + if (ec === 112 || ec === 80) { // 'p' or 'P' + i++; + if (i < n) { + const sc = s.charCodeAt(i); + if (sc === 45) { // '-' + expSign = -1; + i++; + } else if (sc === 43) { // '+' + i++; + } + } + if (i >= n) { + return { ok: false, value: 0 }; + } + + let anyExp = false; + while (i < n) { + const c = s.charCodeAt(i); + if (c < 48 || c > 57) { // not '0'..'9' + break; + } + exp = exp * 10 + (c - 48); + anyExp = true; + i++; + } + if (!anyHex || !anyExp) { + return { ok: false, value: 0 }; + } + } else { + // no exponent marker + if (!sawDot) { + // without dot we must reject so parseInt can claim it as integer + return { ok: false, value: 0 }; + } + if (!anyHex) { + return { ok: false, value: 0 }; + } + expSign = 1; + exp = 0; // implicit p0 } - exp = exp * 10 + (c - 48); - anyExp = true; - i++; - } - if (!anyHex || !anyExp) { - return { ok: false, value: 0 }; + } else { + // end of string + if (!sawDot) { + return { ok: false, value: 0 }; + } + if (!anyHex) { + return { ok: false, value: 0 }; + } + expSign = 1; + exp = 0; } i = skipSpace(s, i); @@ -426,6 +449,8 @@ export function luaToNumberDetailed( base?: number, ): { value: number; numericType: NumericType } | null { if (base !== undefined) { + // Base range errors are handled by the stdlib `tonumber` builtin, + // to match Lua's "bad argument #2 ..." error message. if (!(typeof base === "number" && base >= 2 && base <= 36)) { return null; } diff --git a/client/space_lua/tonumber_test.lua b/client/space_lua/tonumber_test.lua index bf727146..b8f8de6c 100644 --- a/client/space_lua/tonumber_test.lua +++ b/client/space_lua/tonumber_test.lua @@ -5,6 +5,24 @@ local function assert_eq(a, b, message) end end +local function assertThrows(msg_substr, fn) + local ok, err = pcall(fn) + + if ok then + error('Assertion failed: expected error containing "' + .. msg_substr .. '"') + end + + if type(err) ~= 'string' then + err = tostring(err) + end + + if not string.find(err, msg_substr, 1, true) then + error('Assertion failed: expected error message to contain "' + .. msg_substr .. '", got: "' .. err .. '"') + end +end + -- helper for whitespace handling tests local chr = string.char -- no base: whitespace handling @@ -58,6 +76,7 @@ assert_eq(tonumber('-0x10p0'), -16.0) assert_eq(tonumber('0x10.2p0'), 16.125) assert_eq(tonumber('0x10.3P-1'), 8.09375) assert_eq(tonumber('-0X10.3P-1'), -8.09375) +assert_eq(tonumber('0x1.2'), 1.125) -- no base: invalid assert_eq(tonumber(''), nil) @@ -70,7 +89,6 @@ assert_eq(tonumber('1e'), nil) assert_eq(tonumber('1e+'), nil) assert_eq(tonumber('0x'), nil) assert_eq(tonumber('0xG'), nil) -assert_eq(tonumber('0x1.2'), nil) assert_eq(tonumber('+ 10'), nil) assert_eq(tonumber('- 10'), nil) assert_eq(tonumber('123x'), nil) @@ -92,8 +110,18 @@ assert_eq(tonumber(' ff ', 16), 255) assert_eq(tonumber('1010', 10), 1010) -- with base: invalid -assert_eq(tonumber('1010', 1), nil) -assert_eq(tonumber('1010', 37), nil) +assertThrows("bad argument #2 to 'tonumber' (base out of range)", + function() + return tonumber('1010', 1) + end +) + +assertThrows("bad argument #2 to 'tonumber' (base out of range)", + function() + return tonumber('1010', 37) + end +) + assert_eq(tonumber('FF', 10), nil) assert_eq(tonumber('8', 8), nil) assert_eq(tonumber('2', 2), nil)