From c12d67f6e5f091735095735c29ead3be09188822 Mon Sep 17 00:00:00 2001 From: Adrien Cohen <18153974+adriencohen@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:53:00 +0100 Subject: [PATCH] fix(lexer): convert long numerals in linear time without raising A very long numeric literal makes Lua.parse_chunk/1 raise a host ArithmeticError, and tonumber on a long string does quadratic bignum work outside the instruction budget before failing. --- CHANGELOG.md | 6 + lib/lua/lexer.ex | 228 +++++--------------- lib/lua/numeral.ex | 273 ++++++++++++++++++++++++ lib/lua/parser.ex | 9 + lib/lua/vm/stdlib.ex | 19 +- lib/lua/vm/stdlib/string/pack.ex | 9 +- lib/lua/vm/value.ex | 137 +----------- test/lua/lexer_test.exs | 38 ++++ test/lua/numeral_scaling_test.exs | 82 +++++++ test/lua/numeral_test.exs | 76 +++++++ test/lua/parser/error_position_test.exs | 3 +- test/lua/vm/stdlib/math_test.exs | 21 ++ test/lua/vm/stdlib/string_pack_test.exs | 8 + test/lua53_skips.exs | 4 +- 14 files changed, 580 insertions(+), 333 deletions(-) create mode 100644 lib/lua/numeral.ex create mode 100644 test/lua/numeral_scaling_test.exs create mode 100644 test/lua/numeral_test.exs diff --git a/CHANGELOG.md b/CHANGELOG.md index c26f0cab..37dfb50f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,12 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below. past the ceiling in a single allocation. Each raises the same catchable `"resulting string too large"` error as `string.rep` and `..`, before the result is built (#425). +- Long numerals convert in linear time. A long integer literal made + `Lua.parse_chunk/1` raise `ArithmeticError`, and `tonumber`, string + arithmetic and `string.pack` did quadratic bignum work before failing. +- Malformed hexadecimal numerals (`0x.`, `0x1p`) are a "Malformed number" + parse error instead of evaluating to `0.0` or `1.0`, and hexadecimal floats + are correctly rounded. ## [1.0.2] - 2026-07-28 diff --git a/lib/lua/lexer.ex b/lib/lua/lexer.ex index 9440ddd8..8622126a 100644 --- a/lib/lua/lexer.ex +++ b/lib/lua/lexer.ex @@ -20,6 +20,8 @@ defmodule Lua.Lexer do import Bitwise + alias Lua.Numeral + @type position :: %{line: pos_integer(), column: pos_integer(), byte_offset: non_neg_integer()} @type token :: {:keyword, atom(), position()} @@ -31,11 +33,6 @@ defmodule Lua.Lexer do | {:comment, :single | :multi, String.t(), position()} | {:eof, position()} - # Signed 64-bit wrap-around constants for integer literals. - @uint64_mask 0xFFFFFFFFFFFFFFFF - @uint64_modulus 0x10000000000000000 - @sign_bit 0x8000000000000000 - @compile {:inline, position: 3, utf8_width: 1, chunked_text: 4} @doc """ @@ -197,7 +194,7 @@ defmodule Lua.Lexer do # Numbers: hex (0x, 0X) defp do_tokenize(<<"0", x, rest::binary>>, acc, src, line, line_start, offset) when x in [?x, ?X] do - scan_hex_int(rest, acc, src, line, line_start, offset + 2, offset + 2, offset) + scan_hex_digits(rest, acc, src, line, line_start, offset + 2, offset) end # Numbers: decimal or float @@ -803,229 +800,100 @@ defmodule Lua.Lexer do defp keyword_atom("while"), do: {:ok, :while} defp keyword_atom(_), do: :error - # Scan decimal number. `token_start` is the byte offset of the first - # character of the literal; the digit runs are measured against it and the - # value is converted straight from the source bytes. + # Numerals are only delimited here; `Lua.Numeral.parse/1` rejects malformed + # ones such as `1e` or `0x1p`. defp scan_int_digits(<>, acc, src, line, line_start, offset, token_start) when c in ?0..?9 do scan_int_digits(rest, acc, src, line, line_start, offset + 1, token_start) end # ".." is the concat operator, not a decimal point: 0..5 → 0 .. 5 defp scan_int_digits(<<"..", _rest::binary>> = bin, acc, src, line, line_start, offset, token_start) do - emit_integer(bin, acc, src, line, line_start, offset, token_start) + emit_number(bin, acc, src, line, line_start, offset, token_start) end defp scan_int_digits(<<".", rest::binary>>, acc, src, line, line_start, offset, token_start) do - scan_frac_digits(rest, acc, src, line, line_start, offset + 1, token_start, offset - token_start, offset + 1) + scan_frac_digits(rest, acc, src, line, line_start, offset + 1, token_start) end - # Scientific notation without a decimal point: 1e5 defp scan_int_digits(<>, acc, src, line, line_start, offset, token_start) when c in [?e, ?E] do - mantissa = binary_part(src, token_start, offset - token_start) <> ".0" - scan_exponent(rest, acc, src, line, line_start, offset + 1, token_start, mantissa) + scan_exponent(rest, acc, src, line, line_start, offset + 1, token_start) end defp scan_int_digits(bin, acc, src, line, line_start, offset, token_start) do - emit_integer(bin, acc, src, line, line_start, offset, token_start) + emit_number(bin, acc, src, line, line_start, offset, token_start) end - # Scan the fractional digits after a decimal point. - defp scan_frac_digits(<>, acc, src, line, line_start, offset, token_start, int_len, frac_start) - when c in ?0..?9 do - scan_frac_digits(rest, acc, src, line, line_start, offset + 1, token_start, int_len, frac_start) + defp scan_frac_digits(<>, acc, src, line, line_start, offset, token_start) when c in ?0..?9 do + scan_frac_digits(rest, acc, src, line, line_start, offset + 1, token_start) end - defp scan_frac_digits(<>, acc, src, line, line_start, offset, token_start, int_len, frac_start) - when c in [?e, ?E] do - mantissa = mantissa_binary(src, token_start, int_len, frac_start, offset - frac_start) - scan_exponent(rest, acc, src, line, line_start, offset + 1, token_start, mantissa) + defp scan_frac_digits(<>, acc, src, line, line_start, offset, token_start) when c in [?e, ?E] do + scan_exponent(rest, acc, src, line, line_start, offset + 1, token_start) end - defp scan_frac_digits(bin, acc, src, line, line_start, offset, token_start, int_len, frac_start) do - mantissa = mantissa_binary(src, token_start, int_len, frac_start, offset - frac_start) - emit_float(bin, acc, src, line, line_start, offset, token_start, mantissa) + defp scan_frac_digits(bin, acc, src, line, line_start, offset, token_start) do + emit_number(bin, acc, src, line, line_start, offset, token_start) end - # Scan the exponent of a decimal float. `mantissa` is already normalized to - # a form Erlang's binary_to_float/1 accepts (digits on both sides of a dot). - defp scan_exponent(<>, acc, src, line, line_start, offset, token_start, mantissa) - when sign in [?+, ?-] do - scan_exponent_digits(rest, acc, src, line, line_start, offset + 1, token_start, mantissa <> <>, offset + 1) + defp scan_hex_digits(<>, acc, src, line, line_start, offset, token_start) + when c in ?0..?9 or c in ?a..?f or c in ?A..?F do + scan_hex_digits(rest, acc, src, line, line_start, offset + 1, token_start) end - defp scan_exponent(bin, acc, src, line, line_start, offset, token_start, mantissa) do - scan_exponent_digits(bin, acc, src, line, line_start, offset, token_start, mantissa <> "e", offset) + defp scan_hex_digits(<<".", rest::binary>>, acc, src, line, line_start, offset, token_start) do + scan_hex_frac(rest, acc, src, line, line_start, offset + 1, token_start) end - defp scan_exponent_digits(<>, acc, src, line, line_start, offset, token_start, mantissa, digit_start) - when c in ?0..?9 do - scan_exponent_digits(rest, acc, src, line, line_start, offset + 1, token_start, mantissa, digit_start) + defp scan_hex_digits(<>, acc, src, line, line_start, offset, token_start) when p in [?p, ?P] do + scan_exponent(rest, acc, src, line, line_start, offset + 1, token_start) end - # An exponent marker with no digits after it is a malformed number. - defp scan_exponent_digits(_bin, _acc, _src, line, line_start, offset, token_start, _mantissa, digit_start) - when offset == digit_start do - {:error, {:invalid_number, position(line, line_start, token_start)}} + defp scan_hex_digits(bin, acc, src, line, line_start, offset, token_start) do + emit_number(bin, acc, src, line, line_start, offset, token_start) end - defp scan_exponent_digits(bin, acc, src, line, line_start, offset, token_start, mantissa, digit_start) do - literal = mantissa <> binary_part(src, digit_start, offset - digit_start) - emit_float(bin, acc, src, line, line_start, offset, token_start, literal) + defp scan_hex_frac(<>, acc, src, line, line_start, offset, token_start) + when c in ?0..?9 or c in ?a..?f or c in ?A..?F do + scan_hex_frac(rest, acc, src, line, line_start, offset + 1, token_start) end - # Normalize the mantissa so Erlang's strict float syntax accepts it: digits - # are required on both sides of the decimal point. - defp mantissa_binary(src, token_start, int_len, _frac_start, 0) when int_len > 0 do - binary_part(src, token_start, int_len) <> ".0" + defp scan_hex_frac(<>, acc, src, line, line_start, offset, token_start) when p in [?p, ?P] do + scan_exponent(rest, acc, src, line, line_start, offset + 1, token_start) end - defp mantissa_binary(src, _token_start, 0, frac_start, frac_len) when frac_len > 0 do - "0." <> binary_part(src, frac_start, frac_len) + defp scan_hex_frac(bin, acc, src, line, line_start, offset, token_start) do + emit_number(bin, acc, src, line, line_start, offset, token_start) end - defp mantissa_binary(src, token_start, int_len, _frac_start, frac_len) when int_len > 0 and frac_len > 0 do - binary_part(src, token_start, int_len + 1 + frac_len) + defp scan_exponent(<>, acc, src, line, line_start, offset, token_start) when sign in [?+, ?-] do + scan_exponent_digits(rest, acc, src, line, line_start, offset + 1, token_start) end - defp mantissa_binary(_src, _token_start, _int_len, _frac_start, _frac_len), do: "0.0" + defp scan_exponent(bin, acc, src, line, line_start, offset, token_start) do + scan_exponent_digits(bin, acc, src, line, line_start, offset, token_start) + end - defp emit_integer(bin, acc, src, line, line_start, offset, token_start) do - value = :erlang.binary_to_integer(binary_part(src, token_start, offset - token_start)) + defp scan_exponent_digits(<>, acc, src, line, line_start, offset, token_start) when c in ?0..?9 do + scan_exponent_digits(rest, acc, src, line, line_start, offset + 1, token_start) + end - # Lua 5.3.3 §3.1: a decimal integer literal that overflows the signed - # 64-bit range converts to a float (a leading sign is a separate token, - # so `value` here is always the non-negative magnitude). Hex integer - # literals instead wrap via wrap_int64; this branch is decimal only. - # @sign_bit is 2^63, i.e. max_int + 1, so `>= @sign_bit` means overflow. - number = if value >= @sign_bit, do: value * 1.0, else: value - token = {:number, number, position(line, line_start, token_start)} - do_tokenize(bin, [token | acc], src, line, line_start, offset) + defp scan_exponent_digits(bin, acc, src, line, line_start, offset, token_start) do + emit_number(bin, acc, src, line, line_start, offset, token_start) end - defp emit_float(bin, acc, src, line, line_start, offset, token_start, literal) do - case parse_float(literal) do + defp emit_number(bin, acc, src, line, line_start, offset, token_start) do + numeral = binary_part(src, token_start, offset - token_start) + + case Numeral.parse(numeral) do {:ok, value} -> token = {:number, value, position(line, line_start, token_start)} do_tokenize(bin, [token | acc], src, line, line_start, offset) :error -> - {:error, {:invalid_number, position(line, line_start, token_start)}} + {:error, {malformed_number_kind(numeral), position(line, line_start, token_start)}} end end - # The literal is always well-formed by construction; the only way this can - # fail is a magnitude outside the double range, e.g. `1e400`. - defp parse_float(literal) do - {:ok, :erlang.binary_to_float(literal)} - rescue - ArgumentError -> :error - end - - # Scan hexadecimal number (0x...) — supports integers, hex floats (0xF0.0), and exponents (0xABCp-3) - defp scan_hex_int(<>, acc, src, line, line_start, offset, digit_start, token_start) - when c in ?0..?9 or c in ?a..?f or c in ?A..?F do - scan_hex_int(rest, acc, src, line, line_start, offset + 1, digit_start, token_start) - end - - # Hex float: dot followed by hex digits - defp scan_hex_int(<<".", rest::binary>>, acc, src, line, line_start, offset, digit_start, token_start) do - int_hex = binary_part(src, digit_start, offset - digit_start) - scan_hex_frac(rest, acc, src, line, line_start, offset + 1, offset + 1, int_hex, token_start) - end - - # Hex float: binary exponent (p/P) - defp scan_hex_int(<>, acc, src, line, line_start, offset, digit_start, token_start) - when p in [?p, ?P] do - int_hex = binary_part(src, digit_start, offset - digit_start) - scan_hex_exponent(rest, acc, src, line, line_start, offset + 1, int_hex, "", token_start) - end - - defp scan_hex_int(bin, acc, src, line, line_start, offset, digit_start, token_start) when offset > digit_start do - # Per Lua 5.3 §3.1: hex integer literals overflow-wrap into the - # signed 64-bit range. e.g. 0xFFFFFFFFFFFFFFFF == -1. - value = wrap_int64(:erlang.binary_to_integer(binary_part(src, digit_start, offset - digit_start), 16)) - token = {:number, value, position(line, line_start, token_start)} - do_tokenize(bin, [token | acc], src, line, line_start, offset) - end - - defp scan_hex_int(_bin, _acc, _src, line, line_start, _offset, _digit_start, token_start) do - {:error, {:invalid_hex_number, position(line, line_start, token_start)}} - end - - # Wrap an unsigned hex integer to the signed 64-bit range. Inlined here so - # the lexer doesn't depend on Lua.VM.Numeric (kept VM-internal). - defp wrap_int64(n) when is_integer(n) do - masked = band(n, @uint64_mask) - if masked >= @sign_bit, do: masked - @uint64_modulus, else: masked - end - - # Scan hex fractional digits after the dot - defp scan_hex_frac(<>, acc, src, line, line_start, offset, frac_start, int_hex, token_start) - when c in ?0..?9 or c in ?a..?f or c in ?A..?F do - scan_hex_frac(rest, acc, src, line, line_start, offset + 1, frac_start, int_hex, token_start) - end - - # Hex float fractional part followed by exponent - defp scan_hex_frac(<>, acc, src, line, line_start, offset, frac_start, int_hex, token_start) - when p in [?p, ?P] do - frac_hex = binary_part(src, frac_start, offset - frac_start) - scan_hex_exponent(rest, acc, src, line, line_start, offset + 1, int_hex, frac_hex, token_start) - end - - # Hex float fractional part without exponent - defp scan_hex_frac(bin, acc, src, line, line_start, offset, frac_start, int_hex, token_start) do - frac_hex = binary_part(src, frac_start, offset - frac_start) - token = {:number, build_hex_float(int_hex, frac_hex, 0), position(line, line_start, token_start)} - do_tokenize(bin, [token | acc], src, line, line_start, offset) - end - - # Scan binary exponent (p/P followed by optional sign and decimal digits) - defp scan_hex_exponent(<>, acc, src, line, line_start, offset, int_hex, frac_hex, token_start) - when sign in [?+, ?-] do - scan_hex_exponent_digits(rest, acc, src, line, line_start, offset + 1, offset, int_hex, frac_hex, token_start) - end - - defp scan_hex_exponent(bin, acc, src, line, line_start, offset, int_hex, frac_hex, token_start) do - scan_hex_exponent_digits(bin, acc, src, line, line_start, offset, offset, int_hex, frac_hex, token_start) - end - - defp scan_hex_exponent_digits( - <>, - acc, - src, - line, - line_start, - offset, - exp_start, - int_hex, - frac_hex, - token_start - ) - when c in ?0..?9 do - scan_hex_exponent_digits(rest, acc, src, line, line_start, offset + 1, exp_start, int_hex, frac_hex, token_start) - end - - defp scan_hex_exponent_digits(bin, acc, src, line, line_start, offset, exp_start, int_hex, frac_hex, token_start) do - exp = hex_exponent_value(binary_part(src, exp_start, offset - exp_start)) - token = {:number, build_hex_float(int_hex, frac_hex, exp), position(line, line_start, token_start)} - do_tokenize(bin, [token | acc], src, line, line_start, offset) - end - - defp hex_exponent_value(digits) when digits in ["", "+", "-"], do: 0 - defp hex_exponent_value(digits), do: :erlang.binary_to_integer(digits) - - # Build a hex float value from integer hex digits, fractional hex digits, and binary exponent - defp build_hex_float(int_hex, frac_hex, exp) do - int_val = if int_hex == "", do: 0, else: :erlang.binary_to_integer(int_hex, 16) - - frac_val = - if frac_hex == "" do - 0.0 - else - frac_int = :erlang.binary_to_integer(frac_hex, 16) - frac_int / :math.pow(16, byte_size(frac_hex)) - end - - (int_val + frac_val) * :math.pow(2, exp) - end + defp malformed_number_kind(<<"0", x, _rest::binary>>) when x in [?x, ?X], do: :invalid_hex_number + defp malformed_number_kind(_numeral), do: :invalid_number end diff --git a/lib/lua/numeral.ex b/lib/lua/numeral.ex new file mode 100644 index 00000000..dbf76c5a --- /dev/null +++ b/lib/lua/numeral.ex @@ -0,0 +1,273 @@ +defmodule Lua.Numeral do + @moduledoc """ + Converts Lua 5.3 numerals to numbers in time linear in their length, for the + lexer and every string-to-number coercion. + + A decimal integer numeral that overflows the signed 64-bit range becomes a + float, a hexadecimal integer wraps modulo 2^64, and a float past the double + range becomes `1.0e308`, the VM's stand-in for infinity. + """ + + import Bitwise + + @uint32_mask 0xFFFFFFFF + @uint64_mask 0xFFFFFFFFFFFFFFFF + @uint64_modulus 0x10000000000000000 + @sign_bit 0x8000000000000000 + @max_int 0x7FFFFFFFFFFFFFFF + @min_int -0x8000000000000000 + @int64_max_decimal_digits 19 + @uint64_hex_digits 16 + + @huge 1.0e308 + @infinity_bits 0x7FF0000000000000 + @double_precision 53 + @double_fraction_bits @double_precision - 1 + @smallest_subnormal_exponent -1074 + + # Exponents of `0.e` past which the value overflows or + # underflows a double whatever the digits. + @max_decimal_exponent 310 + @min_decimal_exponent -330 + + # A midpoint between two adjacent doubles has at most 767 significant + # decimal digits, so one nonzero sticky digit stands in for all later ones. + @max_decimal_mantissa_digits 800 + # Sixteen hex digits hold at least 61 significant bits: a 53-bit mantissa + # plus its rounding bit, then the sticky digit. + @max_hex_mantissa_digits 16 + @max_kept_mantissa_bits 4 * (@max_hex_mantissa_digits + 1) + + # Past any numeral's digit count, so a saturated exponent still over- or + # underflows whatever the digits. + @exponent_cap 1_000_000_000_000_000 + + @nonzero_digits ~w(1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F) + @not_a_digit 36 + + @doc "Converts a numeral with an optional sign to a number." + @spec parse(binary()) :: {:ok, number()} | :error + def parse(<>), do: parse_unsigned(numeral, :negative) + def parse(<>), do: parse_unsigned(numeral, :positive) + def parse(numeral) when is_binary(numeral), do: parse_unsigned(numeral, :positive) + + @doc "Converts digits in `base` with an optional sign to an integer, wrapping modulo 2^64." + @spec parse_integer(binary(), 2..36) :: {:ok, integer()} | :error + def parse_integer(<>, base), do: parse_base_digits(digits, base, :negative) + def parse_integer(<>, base), do: parse_base_digits(digits, base, :positive) + def parse_integer(digits, base) when is_binary(digits), do: parse_base_digits(digits, base, :positive) + + defp parse_unsigned(<>, sign) when x in [?x, ?X], do: parse_digits(numeral, :hex, sign) + defp parse_unsigned(numeral, sign), do: parse_digits(numeral, :decimal, sign) + + defp parse_digits(numeral, radix, sign) do + {integer_digits, rest} = take_digits(numeral, radix) + parse_after_integer_digits(integer_digits, rest, radix, sign) + end + + defp parse_after_integer_digits(integer_digits, "", radix, sign) when integer_digits != "" do + {:ok, integer_value(integer_digits, radix, sign)} + end + + defp parse_after_integer_digits(integer_digits, "." <> rest, radix, sign) do + {fraction_digits, exponent_part} = take_digits(rest, radix) + parse_float(integer_digits, fraction_digits, exponent_part, radix, sign) + end + + defp parse_after_integer_digits(integer_digits, exponent_part, radix, sign) do + parse_float(integer_digits, "", exponent_part, radix, sign) + end + + defp parse_float(integer_digits, fraction_digits, exponent_part, radix, sign) + when integer_digits != "" or fraction_digits != "" do + with {:ok, exponent} <- exponent(exponent_part, radix) do + digits = trim_leading_zeros(integer_digits <> fraction_digits) + {:ok, signed(float_value(digits, byte_size(fraction_digits), exponent, radix), sign)} + end + end + + defp parse_float(_integer_digits, _fraction_digits, _exponent_part, _radix, _sign), do: :error + + defp integer_value(digits, :decimal, sign) do + significant_digits = trim_leading_zeros(digits) + + case to_int64(significant_digits, sign) do + {:ok, integer} -> integer + :overflow -> signed(decimal_float(significant_digits, 0), sign) + end + end + + defp integer_value(digits, :hex, sign) do + low_digit_count = min(byte_size(digits), @uint64_hex_digits) + + digits + |> binary_part(byte_size(digits) - low_digit_count, low_digit_count) + |> :erlang.binary_to_integer(16) + |> signed(sign) + |> wrap_int64() + end + + defp to_int64("", _sign), do: {:ok, 0} + + defp to_int64(digits, sign) when byte_size(digits) <= @int64_max_decimal_digits do + case signed(:erlang.binary_to_integer(digits), sign) do + integer when integer >= @min_int and integer <= @max_int -> {:ok, integer} + _integer -> :overflow + end + end + + defp to_int64(_digits, _sign), do: :overflow + + defp float_value(digits, fraction_size, exponent, :decimal), do: decimal_float(digits, exponent - fraction_size) + + defp float_value(digits, fraction_size, exponent, :hex) do + kept = truncate_with_sticky_digit(digits, @max_hex_mantissa_digits) + binary_exponent = exponent + 4 * (byte_size(digits) - fraction_size - byte_size(kept)) + round_to_double(hex_to_integer(kept), binary_exponent) + end + + # `digits` has no leading zero and stands for `digits * 10^scale`. + defp decimal_float("", _scale), do: 0.0 + defp decimal_float(digits, scale), do: scientific_float(digits, byte_size(digits) + scale) + + defp scientific_float(_digits, exponent) when exponent > @max_decimal_exponent, do: @huge + defp scientific_float(_digits, exponent) when exponent < @min_decimal_exponent, do: 0.0 + + defp scientific_float(digits, exponent) do + kept = truncate_with_sticky_digit(digits, @max_decimal_mantissa_digits) + binary_to_float_or_huge("0." <> kept <> "e" <> Integer.to_string(exponent)) + end + + # The literal is well formed, so Erlang refuses it only when it overflows. + defp binary_to_float_or_huge(literal) do + :erlang.binary_to_float(literal) + rescue + ArgumentError -> @huge + end + + defp hex_to_integer(""), do: 0 + defp hex_to_integer(digits), do: :erlang.binary_to_integer(digits, 16) + + # Rounds `mantissa * 2^exponent` half to even onto the double grid. A carry + # out of the mantissa moves into the exponent field, as IEEE 754 rounding does. + defp round_to_double(0, _exponent), do: 0.0 + + defp round_to_double(mantissa, exponent) do + shift = max(bit_length(mantissa, 0) - @double_precision, @smallest_subnormal_exponent - exponent) + biased_exponent = exponent + shift - @smallest_subnormal_exponent + float_from_bits(bsl(biased_exponent, @double_fraction_bits) + shift_right_rounded(mantissa, shift)) + end + + defp float_from_bits(bits) when bits >= @infinity_bits, do: @huge + + defp float_from_bits(bits) do + <> = <> + float + end + + defp shift_right_rounded(mantissa, shift) when shift <= 0, do: bsl(mantissa, -shift) + # Rounds to zero without building 2^shift, which a saturated exponent makes huge. + defp shift_right_rounded(_mantissa, shift) when shift > @max_kept_mantissa_bits, do: 0 + + defp shift_right_rounded(mantissa, shift) do + quotient = bsr(mantissa, shift) + round_half_even(quotient, mantissa - bsl(quotient, shift), bsl(1, shift - 1)) + end + + defp round_half_even(quotient, remainder, half) when remainder > half, do: quotient + 1 + defp round_half_even(quotient, half, half) when band(quotient, 1) == 1, do: quotient + 1 + defp round_half_even(quotient, _remainder, _half), do: quotient + + defp bit_length(0, count), do: count + defp bit_length(value, count), do: bit_length(bsr(value, 1), count + 1) + + # A nonzero digit among the dropped ones becomes a trailing 1, which keeps + # the value strictly between the same two rounding boundaries. + defp truncate_with_sticky_digit(digits, max_digits) when byte_size(digits) <= max_digits, do: digits + + defp truncate_with_sticky_digit(digits, max_digits) do + <> = digits + + case :binary.match(dropped, @nonzero_digits) do + :nomatch -> kept + _found -> kept <> "1" + end + end + + defp exponent("", _radix), do: {:ok, 0} + defp exponent(<>, :decimal) when marker in [?e, ?E], do: signed_exponent(rest) + defp exponent(<>, :hex) when marker in [?p, ?P], do: signed_exponent(rest) + defp exponent(_exponent_part, _radix), do: :error + + defp signed_exponent(<>), do: exponent_digits(digits, :negative) + defp signed_exponent(<>), do: exponent_digits(digits, :positive) + defp signed_exponent(digits), do: exponent_digits(digits, :positive) + + defp exponent_digits(<> = digits, sign) when digit in ?0..?9 do + accumulate_exponent(digits, 0, sign) + end + + defp exponent_digits(_digits, _sign), do: :error + + defp accumulate_exponent(<>, exponent, sign) when digit in ?0..?9 do + accumulate_exponent(rest, min(exponent * 10 + digit - ?0, @exponent_cap), sign) + end + + defp accumulate_exponent("", exponent, sign), do: {:ok, signed(exponent, sign)} + defp accumulate_exponent(_rest, _exponent, _sign), do: :error + + defp parse_base_digits("", _base, _sign), do: :error + defp parse_base_digits(digits, base, sign), do: accumulate_base_digits(digits, base, 0, 0, sign) + + # The value modulo 2^64 is kept as two 32-bit halves, so every step is + # small-integer arithmetic. + defp accumulate_base_digits("", _base, high_half, low_half, sign) do + {:ok, (bsl(high_half, 32) + low_half) |> signed(sign) |> wrap_int64()} + end + + defp accumulate_base_digits(<>, base, high_half, low_half, sign) do + case digit_value(char) do + digit when digit < base -> + low_half = low_half * base + digit + high_half = high_half * base + bsr(low_half, 32) + accumulate_base_digits(rest, base, band(high_half, @uint32_mask), band(low_half, @uint32_mask), sign) + + _not_a_digit_in_base -> + :error + end + end + + defp digit_value(char) when char in ?0..?9, do: char - ?0 + defp digit_value(char) when char in ?a..?z, do: char - ?a + 10 + defp digit_value(char) when char in ?A..?Z, do: char - ?A + 10 + defp digit_value(_char), do: @not_a_digit + + defp take_digits(binary, radix) do + count = count_digits(binary, radix, 0) + <> = binary + {digits, rest} + end + + defp count_digits(<>, :decimal, count) when digit in ?0..?9 do + count_digits(rest, :decimal, count + 1) + end + + defp count_digits(<>, :hex, count) when digit in ?0..?9 or digit in ?a..?f or digit in ?A..?F do + count_digits(rest, :hex, count + 1) + end + + defp count_digits(_rest, _radix, count), do: count + + defp trim_leading_zeros(<>), do: trim_leading_zeros(rest) + defp trim_leading_zeros(digits), do: digits + + defp signed(value, :positive), do: value + defp signed(value, :negative), do: -value + + defp wrap_int64(value) do + case band(value, @uint64_mask) do + wrapped when wrapped >= @sign_bit -> wrapped - @uint64_modulus + wrapped -> wrapped + end + end +end diff --git a/lib/lua/parser.ex b/lib/lua/parser.ex index 64d9a33a..d2a94d6b 100644 --- a/lib/lua/parser.ex +++ b/lib/lua/parser.ex @@ -1547,6 +1547,15 @@ defmodule Lua.Parser do ) end + defp convert_lexer_error({kind, pos}, _code) when kind in [:invalid_number, :invalid_hex_number] do + Error.new(:invalid_syntax, "Malformed number", pos, + suggestion: """ + An exponent (e or p) needs at least one digit after it, and a + hexadecimal number at least one hex digit after 0x. + """ + ) + end + defp convert_lexer_error(other, _code) do Error.new(:lexer_error, "Lexer error: #{inspect(other)}", nil) end diff --git a/lib/lua/vm/stdlib.ex b/lib/lua/vm/stdlib.ex index 69676929..22a26271 100644 --- a/lib/lua/vm/stdlib.ex +++ b/lib/lua/vm/stdlib.ex @@ -6,11 +6,11 @@ defmodule Lua.VM.Stdlib do scope when the standard library is installed. """ + alias Lua.Numeral alias Lua.VM.ArgumentError alias Lua.VM.AssertionError alias Lua.VM.Executor alias Lua.VM.Limits - alias Lua.VM.Numeric alias Lua.VM.ProtectedCall alias Lua.VM.RuntimeError alias Lua.VM.State @@ -147,21 +147,10 @@ defmodule Lua.VM.Stdlib do defp lua_tonumber([], state), do: {[nil], state} - # tonumber(s, base) per Lua 5.3 §6.1: surrounding whitespace is ignored, an - # optional sign is allowed, digits a-z/A-Z map to 10-35 (case-insensitive), - # and the result is always an integer (wrapping into the signed 64-bit range - # like an integer literal). The whole trimmed string must be valid digits. defp parse_in_base(str, base) do - {sign, body} = - case String.trim(str) do - "-" <> rest -> {-1, rest} - "+" <> rest -> {1, rest} - other -> {1, other} - end - - case Integer.parse(body, base) do - {n, ""} when body != "" -> Numeric.to_signed_int64(sign * n) - _ -> nil + case Numeral.parse_integer(String.trim(str), base) do + {:ok, integer} -> integer + :error -> nil end end diff --git a/lib/lua/vm/stdlib/string/pack.ex b/lib/lua/vm/stdlib/string/pack.ex index 3bfe29f8..c819bdf5 100644 --- a/lib/lua/vm/stdlib/string/pack.ex +++ b/lib/lua/vm/stdlib/string/pack.ex @@ -18,6 +18,7 @@ defmodule Lua.VM.Stdlib.String.Pack do alias Lua.VM.Limits alias Lua.VM.RuntimeError + alias Lua.VM.Value # Platform constants. We run on the 64-bit BEAM, so these match the # standard 64-bit C ABI that Lua 5.3 was specced against. @@ -669,10 +670,10 @@ defmodule Lua.VM.Stdlib.String.Pack do end end - defp to_integer(s, _) when is_binary(s) do - case Integer.parse(s) do - {n, ""} -> n - _ -> raise_runtime("bad argument (number expected)") + defp to_integer(s, fname) when is_binary(s) do + case Value.parse_number(s) do + nil -> raise_runtime("bad argument (number expected)") + number -> to_integer(number, fname) end end diff --git a/lib/lua/vm/value.ex b/lib/lua/vm/value.ex index cd55225d..de31b49a 100644 --- a/lib/lua/vm/value.ex +++ b/lib/lua/vm/value.ex @@ -7,7 +7,7 @@ defmodule Lua.VM.Value do the executor and stdlib. """ - alias Lua.VM.Numeric + alias Lua.Numeral alias Lua.VM.State @doc """ @@ -70,139 +70,14 @@ defmodule Lua.VM.Value do defp address(id), do: String.pad_leading(Integer.to_string(id, 16), 14, "0") @doc """ - Parses a string to a number (integer or float), supporting hex notation. - - Hex integer literals overflow-wrap into the signed 64-bit range per Lua 5.3 - §3.1 (e.g. `"0xFFFFFFFFFFFFFFFF"` → `-1`). Hex floats with a fractional - part or binary exponent (e.g. `"0xAA.0"`, `"0x1.8p3"`) are also supported. - - Returns `nil` if the string cannot be parsed. + Converts a string to a number the way Lua 5.3 coerces strings, ignoring + surrounding whitespace. Returns `nil` if the string is not a numeral. """ @spec parse_number(String.t()) :: number() | nil def parse_number(str) do - str = String.trim(str) - - # A sign must be adjacent to the numeral; Lua's `l_str2d` does not allow - # whitespace between the sign and the digits (`tonumber("+ 1")` is nil). - {sign, body} = - case str do - "-" <> rest -> {-1, rest} - "+" <> rest -> {1, rest} - _ -> {1, str} - end - - if String.starts_with?(body, "0x") or String.starts_with?(body, "0X") do - # Hex literals wrap modulo 2^64 (Lua 5.3 §3.1); the sign is applied after - # wrapping the magnitude into the signed 64-bit range. - case parse_hex_number(String.slice(body, 2..-1//1)) do - nil -> nil - n when sign == 1 -> n - n when is_integer(n) -> Numeric.to_signed_int64(-n) - n when is_float(n) -> -n - end - else - case Integer.parse(body) do - {n, ""} -> decimal_int(sign * n) - _ -> parse_float(sign, body) - end - end - end - - # Lua 5.3.3 §3.1: a *decimal* integer literal converts to a float only when - # its signed value overflows the 64-bit range (unlike hex literals, which - # wrap). The sign is applied before the range check, so `-2^63` stays the - # integer `minint` while `2^63` and `-2^63 - 1` become floats. - defp decimal_int(n) when is_integer(n) do - if Numeric.signed?(n), do: n, else: n * 1.0 - end - - # Lua's `l_str2d` accepts leading-dot (`.01`) and trailing-dot (`1.`, `1.e2`) - # forms that Elixir's stricter `Float.parse` rejects. Normalise the numeral - # to a fully-formed decimal before delegating; a body with no digit at all - # (`.`, `.e1`) still fails to parse and yields nil. - defp parse_float(sign, body) do - # Reject numerals with no digit in the mantissa (`.`, `.e1`); after - # normalisation these would otherwise parse as 0.0. A digit appearing only - # in the exponent (`.e1`) does not count. - mantissa = body |> String.split(~r/[eE]/, parts: 2) |> hd() - - if Regex.match?(~r/[0-9]/, mantissa) do - normalized = - body - # "1." → "1.0", "1.e2" → "1.0e2" - |> String.replace(~r/\.([eE]|$)/, ".0\\1") - # ".01" → "0.01" - |> then(fn b -> if String.starts_with?(b, "."), do: "0" <> b, else: b end) - - case Float.parse(normalized) do - {f, ""} -> sign * f - _ -> nil - end - end - end - - # Parse the body of a hex literal (after "0x"). Supports: - # * integer: "FF" → 255 (wrapped to signed int64) - # * fractional: "FF.8" → 255.5 - # * exponent only: "FFp4" → 4080.0 - # * fractional+exp: "1.8p3" → 12.0 - # `0x.` with no digit at all is not a number. - defp parse_hex_number("."), do: nil - - # A leading dot (`.FF`, `.ABCDEFp+24`) is a valid hex float with no integer - # part, e.g. `tonumber("0x.1")`. Treat it as integer part 0. - defp parse_hex_number("." <> rest), do: parse_hex_frac(0, rest) - - defp parse_hex_number(body) do - case parse_hex_int(body) do - {int_val, ""} -> - Numeric.to_signed_int64(int_val) - - {int_val, "." <> rest} -> - parse_hex_frac(int_val, rest) - - {int_val, <>} when p in [?p, ?P] -> - parse_hex_exp(int_val + 0.0, rest) - - _ -> - nil - end - end - - defp parse_hex_int(""), do: :error - defp parse_hex_int(body), do: Integer.parse(body, 16) - - # A trailing dot with no fractional digits (`FF.`, `1.p3`) is still a valid - # hex float; the fractional part contributes 0. - defp parse_hex_frac(int_val, ""), do: int_val + 0.0 - - defp parse_hex_frac(int_val, <>) when p in [?p, ?P] do - parse_hex_exp(int_val + 0.0, exp_rest) - end - - defp parse_hex_frac(int_val, frac_and_rest) do - case Integer.parse(frac_and_rest, 16) do - {frac_int, rest} -> - # Determine how many hex digits the fractional part used. - digits = byte_size(frac_and_rest) - byte_size(rest) - frac = if digits == 0, do: 0.0, else: frac_int / :math.pow(16, digits) - base = int_val + frac - - case rest do - "" -> base - <> when p in [?p, ?P] -> parse_hex_exp(base, exp_rest) - _ -> nil - end - - :error -> - nil - end - end - - defp parse_hex_exp(base, exp_str) do - case Integer.parse(exp_str) do - {exp, ""} -> base * :math.pow(2, exp) - _ -> nil + case Numeral.parse(String.trim(str)) do + {:ok, number} -> number + :error -> nil end end diff --git a/test/lua/lexer_test.exs b/test/lua/lexer_test.exs index a1281d1e..e5a25954 100644 --- a/test/lua/lexer_test.exs +++ b/test/lua/lexer_test.exs @@ -136,6 +136,38 @@ defmodule Lua.LexerTest do end end + describe "long and extreme numerals" do + defp number!(source) do + assert {:ok, [{:number, value, _}, {:eof, _}]} = Lexer.tokenize(source) + value + end + + defp digits(digit, count), do: String.duplicate(digit, count) + + test "a decimal integer literal of any length becomes a float instead of raising" do + assert number!(digits("9", 200_000)) === 1.0e308 + assert {:ok, %Lua.Chunk{}} = Lua.parse_chunk("return " <> digits("9", 200_000)) + assert {[1.0e308], _} = Lua.eval!(Lua.new(), "return " <> digits("9", 200_000)) + end + + test "a hexadecimal integer literal of any length wraps modulo 2^64" do + assert number!("0x" <> digits("f", 200_000)) === -1 + assert number!("0x" <> digits("f", 2_000_000)) === -1 + end + + test "huge exponents and mantissas give the infinity stand-in or zero" do + assert number!("1e99999") === 1.0e308 + assert number!("1e" <> digits("9", 50_000)) === 1.0e308 + assert number!("1e-99999") === 0.0 + assert number!(digits("9", 200_000) <> ".5") === 1.0e308 + assert number!("1." <> digits("9", 200_000)) === 2.0 + assert number!("0x1p99999") === 1.0e308 + assert number!("0x.1p-99999") === 0.0 + assert number!("0x" <> digits("f", 200_000) <> ".0") === 1.0e308 + assert number!("0x1." <> digits("f", 200_000)) === 2.0 + end + end + describe "strings" do test "tokenizes double-quoted strings" do assert {:ok, [{:string, "hello", _}, {:eof, _}]} = Lexer.tokenize(~s("hello")) @@ -881,6 +913,12 @@ defmodule Lua.LexerTest do assert {:error, {:invalid_hex_number, _}} = Lexer.tokenize("0xg") end + test "reports error for a hex float with no digits or no exponent digits" do + for source <- ["0x.", "0x.p1", "0x1p", "0x1p+", "0x1.8P-"] do + assert {:error, {:invalid_hex_number, _}} = Lexer.tokenize(source) + end + end + test "handles uppercase X in hex numbers" do assert {:ok, [{:number, 255, _}, {:eof, _}]} = Lexer.tokenize("0XFF") assert {:ok, [{:number, 10, _}, {:eof, _}]} = Lexer.tokenize("0Xa") diff --git a/test/lua/numeral_scaling_test.exs b/test/lua/numeral_scaling_test.exs new file mode 100644 index 00000000..7c30dafb --- /dev/null +++ b/test/lua/numeral_scaling_test.exs @@ -0,0 +1,82 @@ +defmodule Lua.NumeralScalingTest do + @moduledoc """ + Pins that converting a numeral takes time linear in its length: on a numeral + four times as long, a quadratic conversion would take about 16x as long. + + Not async: CPU contention preempts the longer conversions more often, which + skews the ratio. + """ + use ExUnit.Case, async: false + + @max_linear_ratio 8 + @attempts 3 + @runs_per_attempt 25 + + describe "the lexer" do + test "converts a long decimal integer literal in linear time" do + assert_linear(&("return " <> String.duplicate("9", &1)), &assert_parses/1, 100_000) + end + + test "converts a long hexadecimal integer literal in linear time" do + assert_linear(&("return 0x" <> String.duplicate("f", &1)), &assert_parses/1, 100_000) + end + end + + describe "tonumber" do + test "converts a long decimal string in linear time" do + assert_linear(&state_with_s(String.duplicate("9", &1)), &assert_returns_number(&1, "return tonumber(s)"), 250_000) + end + + test "converts a long string in base 36 in linear time" do + assert_linear( + &state_with_s(String.duplicate("z", &1)), + &assert_returns_number(&1, "return tonumber(s, 36)"), + 100_000 + ) + end + + test "converts a long hexadecimal string in linear time" do + assert_linear( + &state_with_s("0x" <> String.duplicate("f", &1)), + &assert_returns_number(&1, "return tonumber(s)"), + 250_000 + ) + end + end + + defp state_with_s(numeral), do: Lua.set!(Lua.new(), [:s], numeral) + + defp assert_parses(source), do: assert({:ok, _chunk} = Lua.parse_chunk(source)) + + defp assert_returns_number(lua, code) do + assert {[number], _lua} = Lua.eval!(lua, code) + assert is_number(number) + end + + # Each attempt keeps the fastest of alternating small and large runs, so a + # stray GC or a busy scheduler does not decide the ratio. + defp assert_linear(build_input, convert, size) do + small_input = build_input.(size) + large_input = build_input.(4 * size) + + ratios = + Enum.reduce_while(1..@attempts, [], fn _attempt, ratios -> + record_ratio(ratio(convert, small_input, large_input), ratios) + end) + + assert hd(ratios) < @max_linear_ratio, + "a numeral 4x as long took #{inspect(Enum.map(ratios, &Float.round(&1, 1)))}x as long to convert" + end + + defp record_ratio(ratio, ratios) when ratio < @max_linear_ratio, do: {:halt, [ratio | ratios]} + defp record_ratio(ratio, ratios), do: {:cont, [ratio | ratios]} + + defp ratio(convert, small_input, large_input) do + {small_times, large_times} = + Enum.unzip(for _run <- 1..@runs_per_attempt, do: {time(convert, small_input), time(convert, large_input)}) + + Enum.min(large_times) / max(Enum.min(small_times), 1) + end + + defp time(convert, input), do: elem(:timer.tc(fn -> convert.(input) end), 0) +end diff --git a/test/lua/numeral_test.exs b/test/lua/numeral_test.exs new file mode 100644 index 00000000..08c1b071 --- /dev/null +++ b/test/lua/numeral_test.exs @@ -0,0 +1,76 @@ +defmodule Lua.NumeralTest do + use ExUnit.Case, async: true + + alias Lua.Numeral + + describe "parse/1" do + test "a decimal integer stays an integer until it overflows the signed 64-bit range" do + assert Numeral.parse("9223372036854775807") === {:ok, 9_223_372_036_854_775_807} + assert Numeral.parse("-9223372036854775808") === {:ok, -9_223_372_036_854_775_808} + assert Numeral.parse("9223372036854775808") === {:ok, 9.223372036854776e18} + assert Numeral.parse("-9223372036854775809") === {:ok, -9.223372036854776e18} + assert Numeral.parse(String.duplicate("0", 1000) <> "42") === {:ok, 42} + end + + test "a hexadecimal integer wraps modulo 2^64" do + assert Numeral.parse("0x1" <> String.duplicate("0", 16)) === {:ok, 0} + assert Numeral.parse("-0x" <> String.duplicate("f", 16)) === {:ok, 1} + assert Numeral.parse("0x" <> String.duplicate("0", 1000) <> "a") === {:ok, 10} + end + + test "a long decimal mantissa rounds as if every digit were kept" do + halfway = "9007199254740993." <> String.duplicate("0", 1000) + + assert Numeral.parse(halfway) === {:ok, 9_007_199_254_740_992.0} + assert Numeral.parse(halfway <> "1") === {:ok, 9_007_199_254_740_994.0} + assert Numeral.parse("0." <> String.duplicate("0", 300) <> "1") === {:ok, 1.0e-301} + assert Numeral.parse("1" <> String.duplicate("0", 400) <> "e-400") === {:ok, 1.0} + end + + test "a hexadecimal float rounds half to even, through subnormals and overflow" do + assert Numeral.parse("0x1.00000000000008") === {:ok, 1.0} + assert Numeral.parse("0x1.00000000000018") === {:ok, 1.0000000000000004} + assert Numeral.parse("0x1.00000000000008" <> String.duplicate("0", 100) <> "1") === {:ok, 1.0000000000000002} + assert Numeral.parse("0x1p-1074") === {:ok, 5.0e-324} + assert Numeral.parse("0x3p-1076") === {:ok, 5.0e-324} + assert Numeral.parse("0x1p-1075") === {:ok, 0.0} + assert Numeral.parse("0x0.fffffffffffff8p-1022") === {:ok, 2.2250738585072014e-308} + assert Numeral.parse("0x1.fffffffffffffp1023") === {:ok, 1.7976931348623157e308} + assert Numeral.parse("0x1.fffffffffffff8p1023") === {:ok, 1.0e308} + end + + test "an exponent of any size gives the infinity stand-in or zero" do + huge_exponent = String.duplicate("9", 50_000) + + assert Numeral.parse("1e99999") === {:ok, 1.0e308} + assert Numeral.parse("-1e99999") === {:ok, -1.0e308} + assert Numeral.parse("1.5e309") === {:ok, 1.0e308} + assert Numeral.parse("1e" <> huge_exponent) === {:ok, 1.0e308} + assert Numeral.parse("1e-99999") === {:ok, 0.0} + assert Numeral.parse("1e-" <> huge_exponent) === {:ok, 0.0} + assert Numeral.parse("0e" <> huge_exponent) === {:ok, 0.0} + assert Numeral.parse("0x1p" <> huge_exponent) === {:ok, 1.0e308} + assert Numeral.parse("0x.1p-99999") === {:ok, 0.0} + end + + test "rejects anything that is not exactly one numeral" do + for malformed <- + ~w(- . e1 .e1 1e 1e+ 1.0e+ 0x 0x. 0x.p1 0x1p 0x1p+ 0x5p+-2 --1 +-1 1..2 0x3.3.3 00x2 23x inf nan) ++ + ["", " 1", "1 ", "1\0"] do + assert Numeral.parse(malformed) == :error, "expected #{inspect(malformed)} to be rejected" + end + end + end + + describe "parse_integer/2" do + test "accumulates modulo 2^64 and rejects digits outside the base" do + assert Numeral.parse_integer("-1z", 36) === {:ok, -71} + assert Numeral.parse_integer(String.duplicate("z", 1000), 36) === {:ok, -1} + assert Numeral.parse_integer("1" <> String.duplicate("0", 64), 2) === {:ok, 0} + + for {malformed, base} <- [{"", 10}, {"-", 10}, {"--5", 10}, {"8", 8}, {"1 0", 10}, {"0x10", 16}] do + assert Numeral.parse_integer(malformed, base) == :error + end + end + end +end diff --git a/test/lua/parser/error_position_test.exs b/test/lua/parser/error_position_test.exs index 71399140..be61492b 100644 --- a/test/lua/parser/error_position_test.exs +++ b/test/lua/parser/error_position_test.exs @@ -55,7 +55,8 @@ defmodule Lua.Parser.ErrorPositionTest do @lexer_errors [ {"unterminated string", "x = \"abc\n", 1, 9, "Unclosed string literal"}, {"unterminated long string", "x = [[abc\n", 2, 1, "Unclosed long string"}, - {"unterminated long comment", "--[[ comment\nx = 1\n", 3, 1, "Unclosed multi-line comment"} + {"unterminated long comment", "--[[ comment\nx = 1\n", 3, 1, "Unclosed multi-line comment"}, + {"exponent without digits", "x = 1 + 0x1p\n", 1, 9, "Malformed number"} ] @missing_end_errors [ diff --git a/test/lua/vm/stdlib/math_test.exs b/test/lua/vm/stdlib/math_test.exs index 861d5041..548d10ce 100644 --- a/test/lua/vm/stdlib/math_test.exs +++ b/test/lua/vm/stdlib/math_test.exs @@ -365,6 +365,7 @@ defmodule Lua.VM.Stdlib.MathTest do assert run!(~s|return tonumber("-1.")|) == [-1.0] assert run!(~s|return tonumber("+ 0.01")|) == [nil] assert run!(~s|return tonumber(".e1")|) == [nil] + assert run!(~s|return tonumber("--1"), tonumber("+-1"), tonumber("--1", 10)|) == [nil, nil, nil] end test "tonumber with a base handles whitespace and signs (math.lua:390)" do @@ -373,6 +374,26 @@ defmodule Lua.VM.Stdlib.MathTest do assert run!(~s|return tonumber(" +1Z ", 36)|) == [71] end + test "an overflowing decimal string of any length converts to the infinity stand-in" do + code = ~s""" + local s = string.rep("9", 1000000) + local n = tonumber(s) + return n == math.huge, s + 1 == math.huge, tostring(n) == tostring(math.huge) + """ + + assert run!(code) == [true, true, true] + end + + test "tonumber with a base wraps modulo 2^64 however long the digits" do + assert run!(~s|return tonumber(string.rep("z", 1000000), 36)|) === [-1] + end + + test "a hexadecimal string of any length wraps modulo 2^64" do + code = ~s|return string.format("%d", tonumber("0x" .. string.rep("f", 1000000)))| + assert run!(code) == ["-1"] + assert run!(~s|return tonumber("0x" .. string.rep("f", 2000000))|) === [-1] + end + test "hex float strings with leading or trailing dots parse (math.lua:491, 498)" do assert run!(~s|return tonumber("0x1.")|) == [1.0] assert run!(~s|return tonumber("0x.1")|) == [0.0625] diff --git a/test/lua/vm/stdlib/string_pack_test.exs b/test/lua/vm/stdlib/string_pack_test.exs index a8b3f215..f71079ca 100644 --- a/test/lua/vm/stdlib/string_pack_test.exs +++ b/test/lua/vm/stdlib/string_pack_test.exs @@ -150,6 +150,14 @@ defmodule Lua.VM.Stdlib.StringPackTest do lua!("return string.pack('>] + + assert_raise RuntimeError, ~r/number has no integer representation/, fn -> + lua!(~S{return string.pack('j', string.rep('9', 1000000))}) + end + end end describe "string.pack/2 — float formats" do diff --git a/test/lua53_skips.exs b/test/lua53_skips.exs index 2c3d75f1..276a9ad8 100644 --- a/test/lua53_skips.exs +++ b/test/lua53_skips.exs @@ -208,10 +208,10 @@ "locals.lua" => [], "math.lua" => [ %{ - lines: 409..422, + lines: 412..413, category: :unimplemented, reason: - "very-long hex/decimal numerals (2^1200, 16^301) exceed the BEAM IEEE-754 float range (~2^1023), so tonumber and 2.0^exp overflow where PUC-Lua produces a finite or inf result", + "`2.0^1200` and `2.0^2000` overflow the double range; `^` yields the :nan sentinel instead of the 1.0e308 infinity stand-in that tonumber returns for the same magnitude", issue: nil }, %{