diff --git a/AGENTS.md b/AGENTS.md index 2f4cd986..9ed54c30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,6 +82,10 @@ mix usage_rules.search_docs "Enum.zip" --query-by title - Only use macros if explicitly requested - There are many useful standard library functions, prefer to use them where possible +## Code Style +- Use `alias Module.Submodule` instead of `alias Module.{Submodule}` - avoid curly braces for single aliases +- When aliasing multiple modules from the same namespace, use separate `alias` statements on individual lines + ## Function Design - Use guard clauses: `when is_binary(name) and byte_size(name) > 0` - Prefer multiple function clauses over complex conditional logic diff --git a/lib/lua/vm/argument_error.ex b/lib/lua/vm/argument_error.ex new file mode 100644 index 00000000..7f2863c3 --- /dev/null +++ b/lib/lua/vm/argument_error.ex @@ -0,0 +1,127 @@ +defmodule Lua.VM.ArgumentError do + @moduledoc """ + Raised when a function is called with invalid arguments. + + This exception provides standardized error messages for bad arguments across + all Lua standard library functions. + + ## Fields + + - `:function_name` - The fully qualified function name (e.g., "string.rep") + - `:arg_num` - The argument number (1-based) + - `:expected` - What type or value was expected (e.g., "number", "string") + - `:got` - What was actually received (optional, e.g., "nil", "boolean") + - `:details` - Additional details about the error (optional) + + ## Examples + + # Basic type error + raise ArgumentError, + function_name: "string.rep", + arg_num: 2, + expected: "number" + + # With actual type received + raise ArgumentError, + function_name: "string.sub", + arg_num: 2, + expected: "number", + got: "string" + + # With additional details + raise ArgumentError, + function_name: "string.char", + arg_num: 1, + expected: "number", + details: "value out of range" + """ + + defexception [:function_name, :arg_num, :expected, :got, :details] + + @impl true + def exception(opts) do + function_name = Keyword.fetch!(opts, :function_name) + arg_num = Keyword.get(opts, :arg_num) + expected = Keyword.get(opts, :expected) + got = Keyword.get(opts, :got) + details = Keyword.get(opts, :details) + + %__MODULE__{ + function_name: function_name, + arg_num: arg_num, + expected: expected, + got: got, + details: details + } + end + + @impl true + def message(%__MODULE__{ + function_name: function_name, + arg_num: arg_num, + expected: expected, + got: got, + details: details + }) do + build_message(function_name, arg_num, expected, got, details) + end + + defp build_message(function_name, arg_num, expected, got, details) do + base = + if arg_num do + "bad argument ##{arg_num} to '#{function_name}'" + else + "bad argument to '#{function_name}'" + end + + expectation = + case {expected, got} do + {nil, nil} -> + nil + + {exp, nil} -> + "(#{exp} expected)" + + {exp, got_val} -> + "(#{exp} expected, got #{got_val})" + end + + case {expectation, details} do + {nil, nil} -> base + {exp, nil} -> "#{base} #{exp}" + {nil, detail} -> "#{base} (#{detail})" + {_exp, detail} -> "#{base} (#{detail})" + end + end + + @doc """ + Creates an ArgumentError when no value is provided for a required argument. + + ## Example + + ArgumentError.value_expected("string.lower", 1) + """ + def value_expected(function_name, arg_num) do + exception( + function_name: function_name, + arg_num: arg_num, + expected: "value" + ) + end + + @doc """ + Creates an ArgumentError for type mismatches. + + ## Example + + ArgumentError.type_error("string.rep", 2, "number", "string") + """ + def type_error(function_name, arg_num, expected, got) do + exception( + function_name: function_name, + arg_num: arg_num, + expected: expected, + got: got + ) + end +end diff --git a/lib/lua/vm/stdlib.ex b/lib/lua/vm/stdlib.ex index f36ac7ef..88ad0f76 100644 --- a/lib/lua/vm/stdlib.ex +++ b/lib/lua/vm/stdlib.ex @@ -29,6 +29,7 @@ defmodule Lua.VM.Stdlib do |> State.register_function("next", &lua_next/2) |> State.register_function("pairs", &lua_pairs/2) |> State.register_function("ipairs", &lua_ipairs/2) + |> Lua.VM.Stdlib.String.install() end # type(v) — returns the type of v as a string diff --git a/lib/lua/vm/stdlib/library.ex b/lib/lua/vm/stdlib/library.ex new file mode 100644 index 00000000..3c587c61 --- /dev/null +++ b/lib/lua/vm/stdlib/library.ex @@ -0,0 +1,41 @@ +defmodule Lua.VM.Stdlib.Library do + @moduledoc """ + Behaviour for Lua standard library modules. + + All standard library modules (string, math, table, os, etc.) should implement + this behaviour to provide a consistent interface for installation into the VM state. + + ## Example + + defmodule Lua.VM.Stdlib.String do + @behaviour Lua.VM.Stdlib.Library + + @impl true + def install(state) do + # Create and register the string library + string_table = %{...} + {tref, state} = State.alloc_table(state, string_table) + State.set_global(state, "string", tref) + end + end + + """ + + alias Lua.VM.State + + @doc """ + Installs the library into the given VM state. + + This function should register all library functions in the appropriate global + namespace (e.g., "string", "math", "table") and return the updated state. + + ## Parameters + + - `state` - The VM state to install the library into + + ## Returns + + The updated VM state with the library installed + """ + @callback install(State.t()) :: State.t() +end diff --git a/lib/lua/vm/stdlib/string.ex b/lib/lua/vm/stdlib/string.ex new file mode 100644 index 00000000..e466ddbd --- /dev/null +++ b/lib/lua/vm/stdlib/string.ex @@ -0,0 +1,444 @@ +defmodule Lua.VM.Stdlib.String do + @moduledoc """ + String standard library functions for Lua 5.3. + + This module implements the Lua string library, providing functions for string + manipulation. All functions are registered in the global `string` table when + the standard library is installed. + + ## Implemented Functions + + - `string.lower(s)` - converts string to lowercase + - `string.upper(s)` - converts string to uppercase + - `string.len(s)` - returns length of string in bytes + - `string.sub(s, i [, j])` - extracts substring (1-based indexing) + - `string.rep(s, n [, sep])` - repeats string with optional separator + - `string.reverse(s)` - reverses a string + - `string.byte(s [, i [, j]])` - returns byte values of characters + - `string.char(...)` - creates string from byte values + - `string.format(fmt, ...)` - C-style string formatting + + ## Pattern Matching (Not Yet Implemented) + + The following functions require Lua's pattern matching engine and are deferred: + - `string.find/4`, `string.match/3`, `string.gmatch/2`, `string.gsub/4` + """ + + @behaviour Lua.VM.Stdlib.Library + + alias Lua.VM.ArgumentError + alias Lua.VM.State + alias Lua.VM.Stdlib.Util + + @impl true + def install(%State{} = state) do + # Create string table with all functions + string_table = %{ + "lower" => {:native_func, &string_lower/2}, + "upper" => {:native_func, &string_upper/2}, + "len" => {:native_func, &string_len/2}, + "sub" => {:native_func, &string_sub/2}, + "rep" => {:native_func, &string_rep/2}, + "reverse" => {:native_func, &string_reverse/2}, + "byte" => {:native_func, &string_byte/2}, + "char" => {:native_func, &string_char/2}, + "format" => {:native_func, &string_format/2} + } + + # Create the string table in VM state + {tref, state} = State.alloc_table(state, string_table) + + # Register as global + State.set_global(state, "string", tref) + end + + # string.lower(s) - converts string to lowercase + defp string_lower([str | _], state) when is_binary(str) do + {[String.downcase(str)], state} + end + + defp string_lower([other | _], _state) do + raise_string_expected(1, "lower", other) + end + + defp string_lower([], _state) do + raise_arg_expected(1, "lower") + end + + # string.upper(s) - converts string to uppercase + defp string_upper([str | _], state) when is_binary(str) do + {[String.upcase(str)], state} + end + + defp string_upper([other | _], _state) do + raise_string_expected(1, "upper", other) + end + + defp string_upper([], _state) do + raise_arg_expected(1, "upper") + end + + # string.len(s) - returns length of string + defp string_len([str | _], state) when is_binary(str) do + {[byte_size(str)], state} + end + + defp string_len([other | _], _state) do + raise_string_expected(1, "len", other) + end + + defp string_len([], _state) do + raise_arg_expected(1, "len") + end + + # string.sub(s, i [, j]) - returns substring from position i to j + defp string_sub([str | rest], state) when is_binary(str) do + i = Enum.at(rest, 0) + j = Enum.at(rest, 1) + + unless is_integer(i) do + raise ArgumentError, + function_name: "string.sub", + arg_num: 2, + expected: "number" + end + + # Convert Lua 1-based indices to 0-based, handle negative indices + len = byte_size(str) + start_idx = normalize_index(i, len) + end_idx = if j == nil, do: len - 1, else: normalize_index(j, len) + + result = + if start_idx > end_idx or start_idx >= len do + "" + else + start_byte = max(0, start_idx) + end_byte = min(len - 1, end_idx) + length = end_byte - start_byte + 1 + binary_part(str, start_byte, length) + end + + {[result], state} + end + + defp string_sub([other | _], _state) do + raise_string_expected(1, "sub", other) + end + + defp string_sub([], _state) do + raise_arg_expected(1, "sub") + end + + # string.rep(s, n [, sep]) - repeats string s n times with optional separator + defp string_rep([str, n | rest], state) when is_binary(str) and is_integer(n) do + sep = Enum.at(rest, 0, "") + + unless is_binary(sep) do + raise ArgumentError, + function_name: "string.rep", + arg_num: 3, + expected: "string", + got: Util.typeof(sep) + end + + result = + if n <= 0 do + "" + else + 1..n + |> Enum.map(fn _ -> str end) + |> Enum.join(sep) + end + + {[result], state} + end + + defp string_rep([str, n | _], _state) when is_binary(str) do + raise ArgumentError, + function_name: "string.rep", + arg_num: 2, + expected: "number", + got: Util.typeof(n) + end + + defp string_rep([other, _ | _], _state) do + raise_string_expected(1, "rep", other) + end + + defp string_rep([_], _state) do + raise ArgumentError, + function_name: "string.rep", + arg_num: 2, + expected: "number" + end + + defp string_rep([], _state) do + raise_arg_expected(1, "rep") + end + + # string.reverse(s) - reverses a string + defp string_reverse([str | _], state) when is_binary(str) do + {[String.reverse(str)], state} + end + + defp string_reverse([other | _], _state) do + raise_string_expected(1, "reverse", other) + end + + defp string_reverse([], _state) do + raise_arg_expected(1, "reverse") + end + + # string.byte(s [, i [, j]]) - returns byte values of characters at positions i to j + defp string_byte([str | rest], state) when is_binary(str) do + i = Enum.at(rest, 0, 1) + j = Enum.at(rest, 1, i) + + unless is_integer(i) do + raise ArgumentError, + function_name: "string.byte", + arg_num: 2, + expected: "number" + end + + unless is_integer(j) do + raise ArgumentError, + function_name: "string.byte", + arg_num: 3, + expected: "number" + end + + len = byte_size(str) + start_idx = normalize_index(i, len) + end_idx = normalize_index(j, len) + + bytes = + if start_idx > end_idx or start_idx >= len do + [] + else + start_byte = max(0, start_idx) + end_byte = min(len - 1, end_idx) + + start_byte..end_byte + |> Enum.map(fn idx -> :binary.at(str, idx) end) + end + + {bytes, state} + end + + defp string_byte([other | _], _state) do + raise_string_expected(1, "byte", other) + end + + defp string_byte([], _state) do + raise_arg_expected(1, "byte") + end + + # string.char(...) - converts byte values to characters + defp string_char(args, state) do + result = + args + |> Enum.with_index(1) + |> Enum.reduce_while("", fn {arg, idx}, acc -> + cond do + not is_integer(arg) -> + {:halt, {:error, idx, "number expected"}} + + arg < 0 or arg > 255 -> + {:halt, {:error, idx, "value out of range"}} + + true -> + {:cont, acc <> <>} + end + end) + + case result do + {:error, arg_num, "number expected"} -> + raise ArgumentError, + function_name: "string.char", + arg_num: arg_num, + expected: "number" + + {:error, arg_num, "value out of range"} -> + raise ArgumentError, + function_name: "string.char", + arg_num: arg_num, + details: "value out of range" + + str -> + {[str], state} + end + end + + # string.format(formatstring, ...) - formats strings with C-style format specifiers + defp string_format([fmt | args], state) when is_binary(fmt) do + result = format_string(fmt, args, "") + {[result], state} + rescue + e in Lua.VM.RuntimeError -> + reraise e, __STACKTRACE__ + end + + defp string_format([other | _], _state) do + raise_string_expected(1, "format", other) + end + + defp string_format([], _state) do + raise_arg_expected(1, "format") + end + + # Format string parser + defp format_string("", _args, acc), do: acc + + defp format_string("%" <> rest, args, acc) do + case rest do + "%" <> rest -> + format_string(rest, args, acc <> "%") + + "s" <> rest -> + [arg | remaining_args] = args + str = Util.to_lua_string(arg) + format_string(rest, remaining_args, acc <> str) + + "d" <> rest -> + [arg | remaining_args] = args + str = format_integer(arg) + format_string(rest, remaining_args, acc <> str) + + "i" <> rest -> + [arg | remaining_args] = args + str = format_integer(arg) + format_string(rest, remaining_args, acc <> str) + + "f" <> rest -> + [arg | remaining_args] = args + str = format_float(arg) + format_string(rest, remaining_args, acc <> str) + + "x" <> rest -> + [arg | remaining_args] = args + str = format_hex(arg, :lower) + format_string(rest, remaining_args, acc <> str) + + "X" <> rest -> + [arg | remaining_args] = args + str = format_hex(arg, :upper) + format_string(rest, remaining_args, acc <> str) + + "o" <> rest -> + [arg | remaining_args] = args + str = format_octal(arg) + format_string(rest, remaining_args, acc <> str) + + "c" <> rest -> + [arg | remaining_args] = args + str = format_char(arg) + format_string(rest, remaining_args, acc <> str) + + "q" <> rest -> + [arg | remaining_args] = args + str = format_quoted(arg) + format_string(rest, remaining_args, acc <> str) + + _ -> + raise ArgumentError, + function_name: "string.format", + details: "invalid option '%#{String.first(rest)}'" + end + end + + defp format_string(<>, args, acc) do + format_string(rest, args, acc <> <>) + end + + # Format helpers + defp format_integer(val) when is_integer(val), do: Integer.to_string(val) + defp format_integer(val) when is_float(val), do: Integer.to_string(trunc(val)) + + defp format_integer(_) do + raise ArgumentError, + function_name: "string.format", + expected: "number" + end + + defp format_float(val) when is_number(val) do + :io_lib.format("~.6f", [val / 1]) |> IO.iodata_to_binary() + end + + defp format_float(_) do + raise ArgumentError, + function_name: "string.format", + expected: "number" + end + + defp format_hex(val, case_style) when is_integer(val) do + str = Integer.to_string(val, 16) + if case_style == :lower, do: String.downcase(str), else: String.upcase(str) + end + + defp format_hex(val, case_style) when is_float(val) do + format_hex(trunc(val), case_style) + end + + defp format_hex(_, _) do + raise ArgumentError, + function_name: "string.format", + expected: "number" + end + + defp format_octal(val) when is_integer(val), do: Integer.to_string(val, 8) + defp format_octal(val) when is_float(val), do: Integer.to_string(trunc(val), 8) + + defp format_octal(_) do + raise ArgumentError, + function_name: "string.format", + expected: "number" + end + + defp format_char(val) when is_integer(val) and val >= 0 and val <= 255, do: <> + + defp format_char(_) do + raise ArgumentError, + function_name: "string.format", + details: "invalid value for %c" + end + + defp format_quoted(val) when is_binary(val) do + escaped = + val + |> String.replace("\\", "\\\\") + |> String.replace("\"", "\\\"") + |> String.replace("\n", "\\n") + |> String.replace("\r", "\\r") + |> String.replace("\t", "\\t") + + "\"#{escaped}\"" + end + + defp format_quoted(_) do + raise ArgumentError, + function_name: "string.format", + expected: "string", + details: "for %q" + end + + # Helper: convert Lua 1-based index to 0-based, handle negative indices + defp normalize_index(idx, _len) when idx > 0, do: idx - 1 + defp normalize_index(idx, len) when idx < 0, do: len + idx + defp normalize_index(0, _len), do: 0 + + # Error helpers + defp raise_string_expected(arg_num, func_name, value) do + type = Util.typeof(value) + + raise ArgumentError, + function_name: "string.#{func_name}", + arg_num: arg_num, + expected: "string", + got: type + end + + defp raise_arg_expected(arg_num, func_name) do + raise ArgumentError.value_expected("string.#{func_name}", arg_num) + end +end diff --git a/lib/lua/vm/stdlib/util.ex b/lib/lua/vm/stdlib/util.ex new file mode 100644 index 00000000..3523e99f --- /dev/null +++ b/lib/lua/vm/stdlib/util.ex @@ -0,0 +1,26 @@ +defmodule Lua.VM.Stdlib.Util do + @moduledoc false + + @doc """ + Returns the Lua type name for a value as a string. + + This is useful for error messages in standard library functions. + """ + def typeof(nil), do: "nil" + def typeof(v) when is_boolean(v), do: "boolean" + def typeof(v) when is_number(v), do: "number" + def typeof(v) when is_binary(v), do: "string" + def typeof({:tref, _}), do: "table" + def typeof({:lua_closure, _, _}), do: "function" + def typeof({:native_func, _}), do: "function" + def typeof(_), do: "unknown" + + @doc """ + Converts a Lua value to a string representation for formatting. + """ + def to_lua_string(nil), do: "nil" + def to_lua_string(val) when is_binary(val), do: val + def to_lua_string(val) when is_boolean(val), do: to_string(val) + def to_lua_string(val) when is_number(val), do: Lua.VM.Value.to_string(val) + def to_lua_string(_), do: "table" +end diff --git a/mix.exs b/mix.exs index e064735e..03a68c21 100644 --- a/mix.exs +++ b/mix.exs @@ -57,7 +57,8 @@ defmodule Lua.MixProject do [ {:usage_rules, "~> 0.1", only: [:dev]}, {:ex_doc, "~> 0.38", only: :dev, runtime: false}, - {:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false} + {:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false}, + {:stream_data, "~> 1.1", only: [:test]} ] end end diff --git a/mix.lock b/mix.lock index 3d9c126e..44283a47 100644 --- a/mix.lock +++ b/mix.lock @@ -21,6 +21,7 @@ "rewrite": {:hex, :rewrite, "1.2.0", "80220eb14010e175b67c939397e1a8cdaa2c32db6e2e0a9d5e23e45c0414ce21", [:mix], [{:glob_ex, "~> 0.1", [hex: :glob_ex, repo: "hexpm", optional: false]}, {:sourceror, "~> 1.0", [hex: :sourceror, repo: "hexpm", optional: false]}, {:text_diff, "~> 0.1", [hex: :text_diff, repo: "hexpm", optional: false]}], "hexpm", "a1cd702bbb9d51613ab21091f04a386d750fc6f4516b81900df082d78b2d8c50"}, "sourceror": {:hex, :sourceror, "1.10.1", "325753ed460fe9fa34ebb4deda76d57b2e1507dcd78a5eb9e1c41bfb78b7cdfe", [:mix], [], "hexpm", "288f3079d93865cd1e3e20df5b884ef2cb440e0e03e8ae393624ee8a770ba588"}, "spitfire": {:hex, :spitfire, "0.3.2", "476b7b5151fd053a864dae7b5eaeed01811e8b2ff3f24f3c048af1c9dfee5e3d", [:mix], [], "hexpm", "014f7b8c6dd45d1e3b08103c7e61515a590efc872441cf3e933a20efa4b5c46c"}, + "stream_data": {:hex, :stream_data, "1.2.0", "58dd3f9e88afe27dc38bef26fce0c84a9e7a96772b2925c7b32cd2435697a52b", [:mix], [], "hexpm", "eb5c546ee3466920314643edf68943a5b14b32d1da9fe01698dc92b73f89a9ed"}, "telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"}, "text_diff": {:hex, :text_diff, "0.1.0", "1caf3175e11a53a9a139bc9339bd607c47b9e376b073d4571c031913317fecaa", [:mix], [], "hexpm", "d1ffaaecab338e49357b6daa82e435f877e0649041ace7755583a0ea3362dbd7"}, "usage_rules": {:hex, :usage_rules, "0.1.26", "19d38c8b9b5c35434eae44f7e4554caeb5f08037a1d45a6b059a9782543ac22e", [:mix], [{:igniter, ">= 0.6.6 and < 1.0.0-0", [hex: :igniter, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:req, "~> 0.5", [hex: :req, repo: "hexpm", optional: false]}], "hexpm", "9f0d203aa288e1b48318929066778ec26fc423fd51f08518c5b47f58ad5caca9"}, diff --git a/test/lua/vm/stdlib/util_test.exs b/test/lua/vm/stdlib/util_test.exs new file mode 100644 index 00000000..6c81f0ec --- /dev/null +++ b/test/lua/vm/stdlib/util_test.exs @@ -0,0 +1,159 @@ +defmodule Lua.VM.Stdlib.UtilTest do + use ExUnit.Case, async: true + use ExUnitProperties + + alias Lua.VM.Stdlib.Util + alias Lua.VM.State + + describe "typeof/1" do + test "returns 'nil' for nil" do + assert Util.typeof(nil) == "nil" + end + + test "returns 'boolean' for booleans" do + assert Util.typeof(true) == "boolean" + assert Util.typeof(false) == "boolean" + end + + test "returns 'number' for integers" do + assert Util.typeof(0) == "number" + assert Util.typeof(42) == "number" + assert Util.typeof(-100) == "number" + end + + test "returns 'number' for floats" do + assert Util.typeof(0.0) == "number" + assert Util.typeof(3.14) == "number" + assert Util.typeof(-2.5) == "number" + end + + test "returns 'string' for binaries" do + assert Util.typeof("") == "string" + assert Util.typeof("hello") == "string" + assert Util.typeof("multi\nline") == "string" + end + + test "returns 'table' for table references" do + state = State.new() + {tref, _state} = State.alloc_table(state) + assert Util.typeof(tref) == "table" + end + + test "returns 'function' for lua closures" do + closure = {:lua_closure, %{}, []} + assert Util.typeof(closure) == "function" + end + + test "returns 'function' for native functions" do + native_func = {:native_func, fn _, s -> {[], s} end} + assert Util.typeof(native_func) == "function" + end + + test "returns 'unknown' for other values" do + assert Util.typeof({:unknown_type, :data}) == "unknown" + assert Util.typeof(%{custom: :map}) == "unknown" + end + + property "typeof always returns a string" do + check all( + value <- + one_of([ + constant(nil), + boolean(), + integer(), + float(), + string(:printable), + constant({:tref, 0}), + constant({:lua_closure, %{}, []}), + constant({:native_func, fn _, s -> {[], s} end}) + ]) + ) do + result = Util.typeof(value) + assert is_binary(result) + assert result in ["nil", "boolean", "number", "string", "table", "function", "unknown"] + end + end + end + + describe "to_lua_string/1" do + test "converts nil to 'nil'" do + assert Util.to_lua_string(nil) == "nil" + end + + test "converts booleans to strings" do + assert Util.to_lua_string(true) == "true" + assert Util.to_lua_string(false) == "false" + end + + test "converts strings to themselves" do + assert Util.to_lua_string("hello") == "hello" + assert Util.to_lua_string("") == "" + assert Util.to_lua_string("with spaces") == "with spaces" + end + + test "converts integers using Value.to_string" do + assert Util.to_lua_string(0) == "0" + assert Util.to_lua_string(42) == "42" + assert Util.to_lua_string(-100) == "-100" + end + + test "converts floats using Value.to_string" do + result = Util.to_lua_string(3.14) + assert is_binary(result) + assert result =~ "3.14" + end + + test "converts tables to 'table'" do + state = State.new() + {tref, _state} = State.alloc_table(state) + assert Util.to_lua_string(tref) == "table" + end + + test "converts functions to 'table'" do + # Note: In the current implementation, functions fall through to the catch-all + closure = {:lua_closure, %{}, []} + assert Util.to_lua_string(closure) == "table" + + native_func = {:native_func, fn _, s -> {[], s} end} + assert Util.to_lua_string(native_func) == "table" + end + + test "converts unknown types to 'table'" do + assert Util.to_lua_string({:unknown, :data}) == "table" + assert Util.to_lua_string(%{custom: :map}) == "table" + end + + property "to_lua_string always returns a string" do + check all( + value <- + one_of([ + constant(nil), + boolean(), + integer(), + float(), + string(:printable), + constant({:tref, 0}), + constant({:lua_closure, %{}, []}) + ]) + ) do + result = Util.to_lua_string(value) + assert is_binary(result) + end + end + + property "to_lua_string for strings is identity" do + check all(str <- string(:printable)) do + assert Util.to_lua_string(str) == str + end + end + + property "to_lua_string for integers produces parseable result" do + check all(int <- integer()) do + result = Util.to_lua_string(int) + assert is_binary(result) + # Should be parseable back to integer + assert String.to_integer(result) == int + end + end + end +end diff --git a/test/lua/vm/string_test.exs b/test/lua/vm/string_test.exs new file mode 100644 index 00000000..ce51d08e --- /dev/null +++ b/test/lua/vm/string_test.exs @@ -0,0 +1,422 @@ +defmodule Lua.VM.StringTest do + use ExUnit.Case, async: true + use ExUnitProperties + + alias Lua.{Parser, Compiler, VM} + alias Lua.VM.State + + describe "string.lower and string.upper" do + test "string.lower converts to lowercase" do + code = "return string.lower(\"HELLO World\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["hello world"], _state} = VM.execute(proto, state) + end + + test "string.upper converts to uppercase" do + code = "return string.upper(\"hello World\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["HELLO WORLD"], _state} = VM.execute(proto, state) + end + + test "string.lower raises on non-string" do + code = "return string.lower(123)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + + assert_raise Lua.VM.ArgumentError, ~r/string expected/, fn -> + VM.execute(proto, state) + end + end + end + + describe "string.len" do + test "string.len returns length of string" do + code = "return string.len(\"hello\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [5], _state} = VM.execute(proto, state) + end + + test "string.len works with empty string" do + code = "return string.len(\"\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [0], _state} = VM.execute(proto, state) + end + end + + describe "string.sub" do + test "string.sub extracts substring" do + code = "return string.sub(\"hello world\", 7, 11)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["world"], _state} = VM.execute(proto, state) + end + + test "string.sub with negative indices" do + code = "return string.sub(\"hello\", -4, -2)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["ell"], _state} = VM.execute(proto, state) + end + + test "string.sub without end index" do + code = "return string.sub(\"hello world\", 7)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["world"], _state} = VM.execute(proto, state) + end + + test "string.sub with out of range indices returns empty string" do + code = "return string.sub(\"hello\", 10, 20)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [""], _state} = VM.execute(proto, state) + end + end + + describe "string.rep" do + test "string.rep repeats string" do + code = "return string.rep(\"ha\", 3)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["hahaha"], _state} = VM.execute(proto, state) + end + + test "string.rep with separator" do + code = "return string.rep(\"ha\", 3, \"-\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["ha-ha-ha"], _state} = VM.execute(proto, state) + end + + test "string.rep with zero returns empty string" do + code = "return string.rep(\"ha\", 0)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [""], _state} = VM.execute(proto, state) + end + end + + describe "string.reverse" do + test "string.reverse reverses string" do + code = "return string.reverse(\"hello\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["olleh"], _state} = VM.execute(proto, state) + end + + test "string.reverse works with empty string" do + code = "return string.reverse(\"\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [""], _state} = VM.execute(proto, state) + end + end + + describe "string.byte" do + test "string.byte returns single byte value" do + code = "return string.byte(\"A\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [65], _state} = VM.execute(proto, state) + end + + test "string.byte with index" do + code = "return string.byte(\"hello\", 2)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [101], _state} = VM.execute(proto, state) + end + + test "string.byte with range returns multiple values" do + code = "return string.byte(\"hello\", 1, 3)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [104, 101, 108], _state} = VM.execute(proto, state) + end + + test "string.byte with negative index" do + code = "return string.byte(\"hello\", -1)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [111], _state} = VM.execute(proto, state) + end + end + + describe "string.char" do + test "string.char creates string from byte values" do + code = "return string.char(72, 101, 108, 108, 111)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["Hello"], _state} = VM.execute(proto, state) + end + + test "string.char with no arguments returns empty string" do + code = "return string.char()" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [""], _state} = VM.execute(proto, state) + end + + test "string.char raises on out of range value" do + code = "return string.char(256)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + + assert_raise Lua.VM.ArgumentError, ~r/out of range/, fn -> + VM.execute(proto, state) + end + end + end + + describe "string.format" do + test "string.format with %s specifier" do + code = "return string.format(\"Hello, %s!\", \"world\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["Hello, world!"], _state} = VM.execute(proto, state) + end + + test "string.format with %d specifier" do + code = "return string.format(\"Number: %d\", 42)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["Number: 42"], _state} = VM.execute(proto, state) + end + + test "string.format with %f specifier" do + code = "return string.format(\"Float: %f\", 3.14)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert result =~ "3.14" + end + + test "string.format with %x specifier" do + code = "return string.format(\"Hex: %x\", 255)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["Hex: ff"], _state} = VM.execute(proto, state) + end + + test "string.format with %X specifier" do + code = "return string.format(\"Hex: %X\", 255)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["Hex: FF"], _state} = VM.execute(proto, state) + end + + test "string.format with %o specifier" do + code = "return string.format(\"Octal: %o\", 8)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["Octal: 10"], _state} = VM.execute(proto, state) + end + + test "string.format with %c specifier" do + code = "return string.format(\"Char: %c\", 65)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["Char: A"], _state} = VM.execute(proto, state) + end + + test "string.format with %q specifier" do + code = "return string.format(\"Quoted: %q\", \"hello\\nworld\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert result == "Quoted: \"hello\\nworld\"" + end + + test "string.format with %% escapes percent" do + code = "return string.format(\"100%% done\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["100% done"], _state} = VM.execute(proto, state) + end + + test "string.format with multiple specifiers" do + code = "return string.format(\"%s: %d (%x)\", \"Value\", 255, 255)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["Value: 255 (ff)"], _state} = VM.execute(proto, state) + end + end + + describe "string table access" do + test "string functions are accessible via string table" do + code = """ + local s = string + return s.upper("hello") + """ + + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, ["HELLO"], _state} = VM.execute(proto, state) + end + end + + describe "property tests" do + property "string.lower always returns a string" do + check all(str <- string(:printable)) do + code = "return string.lower(\"#{escape_string(str)}\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert is_binary(result) + assert result == String.downcase(str) + end + end + + property "string.upper always returns a string" do + check all(str <- string(:printable)) do + code = "return string.upper(\"#{escape_string(str)}\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert is_binary(result) + assert result == String.upcase(str) + end + end + + property "string.len returns non-negative integer" do + check all(str <- string(:printable)) do + code = "return string.len(\"#{escape_string(str)}\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert is_integer(result) + assert result >= 0 + assert result == byte_size(str) + end + end + + property "string.reverse twice gives original (ASCII)" do + # Note: Lua operates on bytes, not graphemes, so we test with ASCII only + # Multi-byte UTF-8 characters would be reversed incorrectly by Lua's string.reverse + check all(str <- string(:ascii)) do + code = "return string.reverse(string.reverse(\"#{escape_string(str)}\"))" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert result == str + end + end + + property "string.rep with 0 returns empty string" do + check all(str <- string(:printable)) do + code = "return string.rep(\"#{escape_string(str)}\", 0)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [""], _state} = VM.execute(proto, state) + end + end + + property "string.rep with 1 returns original" do + check all(str <- string(:printable, max_length: 10)) do + code = "return string.rep(\"#{escape_string(str)}\", 1)" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert result == str + end + end + + property "string.byte/char round-trip for single bytes" do + check all(byte <- integer(0..255)) do + code = "return string.char(string.byte(string.char(#{byte})))" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert result == <> + end + end + + property "string.sub with full range returns original" do + check all(str <- string(:printable, max_length: 10)) do + len = byte_size(str) + code = "return string.sub(\"#{escape_string(str)}\", 1, #{len})" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert result == str + end + end + + property "string.format %s always produces string" do + check all(str <- string(:printable, max_length: 20)) do + code = "return string.format(\"Result: %s\", \"#{escape_string(str)}\")" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert is_binary(result) + assert String.starts_with?(result, "Result: ") + end + end + + property "string.format %d works with integers" do + check all(int <- integer(-1000..1000)) do + code = "return string.format(\"Number: %d\", #{int})" + assert {:ok, ast} = Parser.parse(code) + assert {:ok, proto} = Compiler.compile(ast, source: "test.lua") + state = State.new() |> Lua.VM.Stdlib.install() + assert {:ok, [result], _state} = VM.execute(proto, state) + assert result == "Number: #{int}" + end + end + end + + # Helper to escape strings for Lua code + defp escape_string(str) do + str + |> String.replace("\\", "\\\\") + |> String.replace("\"", "\\\"") + |> String.replace("\n", "\\n") + |> String.replace("\r", "\\r") + |> String.replace("\t", "\\t") + end +end