Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 37 additions & 37 deletions lib/lua/compiler/scope.ex
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,18 @@ defmodule Lua.Compiler.Scope do
Enum.reduce(stmts, state, &resolve_statement/2)
end

# Per Lua 5.3 §3.3.4, each control-flow block (then/else, while/repeat
# body, for body) is its own lexical scope: locals declared inside it
# must not leak past the block's end.
defp with_block_scope(state, fun) do
saved_locals = state.locals
saved_next_register = state.next_register

state = fun.(state)

%{state | locals: saved_locals, next_register: saved_next_register}
end

defp resolve_statement(%Statement.Return{values: values}, state) do
Enum.reduce(values, state, &resolve_expr/2)
end
Expand Down Expand Up @@ -169,75 +181,66 @@ defmodule Lua.Compiler.Scope do
%Statement.If{condition: condition, then_block: then_block, elseifs: elseifs, else_block: else_block},
state
) do
# Resolve the main condition
# Per Lua 5.3 §3.3.4, each branch of an `if` is its own block, so locals
# declared inside it do not leak past `end`.
state = resolve_expr(condition, state)
state = with_block_scope(state, &resolve_block(then_block, &1))

# Resolve the then block
state = resolve_block(then_block, state)

# Resolve all elseif clauses
state =
Enum.reduce(elseifs, state, fn {elseif_cond, elseif_block}, state ->
state = resolve_expr(elseif_cond, state)
resolve_block(elseif_block, state)
with_block_scope(state, &resolve_block(elseif_block, &1))
end)

# Resolve the else block if present
if else_block do
resolve_block(else_block, state)
with_block_scope(state, &resolve_block(else_block, &1))
else
state
end
end

defp resolve_statement(%Statement.While{condition: condition, body: body}, state) do
# Resolve the condition
state = resolve_expr(condition, state)
# Resolve the body
resolve_block(body, state)
with_block_scope(state, &resolve_block(body, &1))
end

defp resolve_statement(%Statement.Repeat{body: body, condition: condition}, state) do
# Resolve the body first (in Lua, the condition can reference variables declared in the body)
# In Lua, repeat-until's condition is part of the body's scope so it can
# reference locals declared inside the loop. Restore the outer scope only
# after the condition has been resolved.
saved_locals = state.locals
saved_next_register = state.next_register

state = resolve_block(body, state)
# Resolve the condition
resolve_expr(condition, state)
state = resolve_expr(condition, state)

%{state | locals: saved_locals, next_register: saved_next_register}
end

defp resolve_statement(
%Statement.ForNum{var: var, start: start_expr, limit: limit_expr, step: step_expr, body: body} = for_stmt,
state
) do
# Resolve start, limit, and step expressions with current scope
state = resolve_expr(start_expr, state)
state = resolve_expr(limit_expr, state)
state = if step_expr, do: resolve_expr(step_expr, state), else: state

# The loop variable is a local within the loop body
# Assign it a register
saved_locals = state.locals
saved_next_register = state.next_register

loop_var_reg = state.next_register
state = %{state | locals: Map.put(state.locals, var, loop_var_reg)}
# Reserve 3 registers: the loop variable shares with the internal counter,
# plus limit and step registers (codegen allocates base, base+1, base+2)
state = %{state | next_register: loop_var_reg + 3}

# Store this loop's variable register in var_map so codegen can find the
# correct register even when consecutive `for` statements share a variable
# name (each loop binds the same name to a fresh register, but
# `state.locals[var]` only retains the most recent binding).
state = %{state | var_map: Map.put(state.var_map, {:for_num_var_reg, for_stmt}, loop_var_reg)}

# Update max_register
func_scope = state.functions[state.current_function]
func_scope = %{func_scope | max_register: max(func_scope.max_register, state.next_register)}
state = %{state | functions: Map.put(state.functions, state.current_function, func_scope)}

# Resolve the body with the loop variable in scope
state = resolve_block(body, state)

# Remove the loop variable from scope after the loop
# (In real implementation, we'd need scope stack management, but for now this is fine)
state
%{state | locals: saved_locals, next_register: saved_next_register}
end

defp resolve_statement(
Expand Down Expand Up @@ -293,30 +296,27 @@ defmodule Lua.Compiler.Scope do
end

defp resolve_statement(%Statement.ForIn{vars: vars, iterators: iterators, body: body} = for_stmt, state) do
# Resolve iterator expressions with current scope
state = Enum.reduce(iterators, state, &resolve_expr/2)

# Assign registers for loop variables (same pattern as ForNum)
saved_locals = state.locals
saved_next_register = state.next_register

{state, _, var_regs} =
Enum.reduce(vars, {state, state.next_register, []}, fn name, {state, reg, acc} ->
state = %{state | locals: Map.put(state.locals, name, reg)}
state = %{state | next_register: reg + 1}
{state, reg + 1, [reg | acc]}
end)

# Store this loop's variable registers in var_map so codegen can find the
# correct registers even when consecutive `for` statements share variable
# names (each loop binds the same names to fresh registers, but
# `state.locals[name]` only retains the most recent binding).
state = %{state | var_map: Map.put(state.var_map, {:for_in_var_regs, for_stmt}, Enum.reverse(var_regs))}

# Update max_register
func_scope = state.functions[state.current_function]
func_scope = %{func_scope | max_register: max(func_scope.max_register, state.next_register)}
state = %{state | functions: Map.put(state.functions, state.current_function, func_scope)}

# Resolve the body with loop variables in scope
resolve_block(body, state)
state = resolve_block(body, state)

%{state | locals: saved_locals, next_register: saved_next_register}
end

defp resolve_statement(%Statement.LocalFunc{name: name, params: params, body: body} = local_func, state) do
Expand Down
33 changes: 31 additions & 2 deletions lib/lua/lexer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,10 @@ defmodule Lua.Lexer do
defp do_tokenize(<<"[", rest::binary>>, acc, pos) do
case scan_long_bracket(rest, 0) do
{:ok, equals, after_bracket} ->
scan_long_string(after_bracket, "", acc, advance_column(pos, 2 + equals), pos, equals)
start_pos = pos
open_pos = advance_column(pos, 2 + equals)
{body_rest, body_pos} = drop_leading_newline(after_bracket, open_pos)
scan_long_string(body_rest, "", acc, body_pos, start_pos, equals)

:error ->
# Not a long string, treat as delimiter
Expand Down Expand Up @@ -582,7 +585,19 @@ defmodule Lua.Lexer do
end
end

defp scan_long_string(<<?\n, rest::binary>>, str_acc, acc, pos, start_pos, level) do
# Per Lua 5.3 §3.1, long strings normalize end-of-line sequences (`\r`,
# `\n`, `\r\n`, `\n\r`) to a single `\n`.
defp scan_long_string(<<?\r, ?\n, rest::binary>>, str_acc, acc, pos, start_pos, level) do
new_pos = %{line: pos.line + 1, column: 1, byte_offset: pos.byte_offset + 2}
scan_long_string(rest, str_acc <> "\n", acc, new_pos, start_pos, level)
end

defp scan_long_string(<<?\n, ?\r, rest::binary>>, str_acc, acc, pos, start_pos, level) do
new_pos = %{line: pos.line + 1, column: 1, byte_offset: pos.byte_offset + 2}
scan_long_string(rest, str_acc <> "\n", acc, new_pos, start_pos, level)
end

defp scan_long_string(<<c, rest::binary>>, str_acc, acc, pos, start_pos, level) when c == ?\n or c == ?\r do
new_pos = %{line: pos.line + 1, column: 1, byte_offset: pos.byte_offset + 1}
scan_long_string(rest, str_acc <> "\n", acc, new_pos, start_pos, level)
end
Expand All @@ -595,6 +610,20 @@ defmodule Lua.Lexer do
scan_long_string(rest, str_acc <> <<c>>, acc, advance_column(pos, 1), start_pos, level)
end

# Per Lua 5.3 §3.1: "when the opening long bracket is immediately followed
# by a newline, the newline is not included in the string." Applies to any
# line-break sequence (`\n`, `\r`, `\r\n`, `\n\r`).
defp drop_leading_newline(<<?\r, ?\n, rest::binary>>, pos),
do: {rest, %{line: pos.line + 1, column: 1, byte_offset: pos.byte_offset + 2}}

defp drop_leading_newline(<<?\n, ?\r, rest::binary>>, pos),
do: {rest, %{line: pos.line + 1, column: 1, byte_offset: pos.byte_offset + 2}}

defp drop_leading_newline(<<c, rest::binary>>, pos) when c == ?\n or c == ?\r,
do: {rest, %{line: pos.line + 1, column: 1, byte_offset: pos.byte_offset + 1}}

defp drop_leading_newline(rest, pos), do: {rest, pos}

# Scan identifier or keyword
defp scan_identifier(<<c, rest::binary>>, id_acc, acc, pos, start_pos)
when c in ?a..?z or c in ?A..?Z or c in ?0..?9 or c == ?_ do
Expand Down
58 changes: 46 additions & 12 deletions lib/lua/parser.ex
Original file line number Diff line number Diff line change
Expand Up @@ -610,23 +610,48 @@ defmodule Lua.Parser do
end

defp parse_assignment(targets, [{:operator, :assign, pos} | rest]) do
case parse_expr_list(rest) do
{:ok, values, rest2} ->
# Create meta from first target's position
meta =
if hd(targets).meta do
%{hd(targets).meta | start: hd(targets).meta.start || pos}
else
Meta.new(pos)
end
case validate_assign_targets(targets) do
:ok ->
case parse_expr_list(rest) do
{:ok, values, rest2} ->
# Create meta from first target's position
meta =
if hd(targets).meta do
%{hd(targets).meta | start: hd(targets).meta.start || pos}
else
Meta.new(pos)
end

{:ok, %Statement.Assign{targets: targets, values: values, meta: meta}, rest2}
{:ok, %Statement.Assign{targets: targets, values: values, meta: meta}, rest2}

{:error, reason} ->
{:error, reason}
{:error, reason} ->
{:error, reason}
end

{:error, _} = err ->
err
end
end

# Per Lua 5.3 §3.3.3, the lhs of an assignment must be a `var`:
# Name | prefixexp '[' exp ']' | prefixexp '.' Name. Anything else
# (number, string, function call, parenthesised expression) is a
# syntax error.
defp validate_assign_targets(targets) do
Enum.reduce_while(targets, :ok, fn target, :ok ->
case target do
%Expr.Var{} -> {:cont, :ok}
%Expr.Property{} -> {:cont, :ok}
%Expr.Index{} -> {:cont, :ok}
other -> {:halt, {:error, {:invalid_assign_target, target_position(other), other.__struct__}}}
end
end)
end

defp target_position(%{meta: %Meta{start: %{} = pos}}), do: pos
defp target_position(%{meta: %{start: %{} = pos}}), do: pos
defp target_position(_), do: nil

# Helper: parse list of names (for local declarations, for loops)
defp parse_name_list(tokens) do
case expect(tokens, :identifier) do
Expand Down Expand Up @@ -1288,6 +1313,15 @@ defmodule Lua.Parser do
Error.new(:invalid_syntax, message, pos, suggestion: suggestion)
end

defp convert_error({:invalid_assign_target, pos, _expr_struct}, _code) do
Error.new(
:invalid_syntax,
"syntax error near '='",
pos,
suggestion: "Only variables, table fields, and table indexes can appear on the left of '='."
)
end

defp convert_error(other, _code) do
Error.new(:invalid_syntax, "Parse error: #{inspect(other)}", nil)
end
Expand Down
41 changes: 36 additions & 5 deletions lib/lua/vm/executor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2182,17 +2182,30 @@ defmodule Lua.VM.Executor do
invoke_metamethod(metamethod, [a], state, default_fn)
end

# Per Lua 5.3 §3.4.4, __eq is only consulted when both operands have the
# same primitive type and rawequal returns false. Lua looks at the first
# operand's __eq, falling back to the second operand's. The two metamethods
# do *not* need to be the same function (that was Lua 5.1 behaviour).
defp try_equality_metamethod(a, b, state, default_fn) do
eq_a = lookup_metamethod(a, "__eq", state)
eq_b = lookup_metamethod(b, "__eq", state)
if eq_metamethod_eligible?(a, b) do
case lookup_metamethod(a, "__eq", state) do
nil ->
case lookup_metamethod(b, "__eq", state) do
nil -> {default_fn.(), state}
eq -> invoke_metamethod(eq, [a, b], state, default_fn)
end

if not is_nil(eq_a) and eq_a == eq_b do
invoke_metamethod(eq_a, [a, b], state, default_fn)
eq ->
invoke_metamethod(eq, [a, b], state, default_fn)
end
else
{default_fn.(), state}
end
end

defp eq_metamethod_eligible?({:tref, _}, {:tref, _}), do: true
defp eq_metamethod_eligible?(_, _), do: false

# Invokes a metamethod (native or Lua closure) with the given args, falling
# back to default_fn when the metamethod is missing or unsupported. Delegates
# to call_function/3 so vararg metamethods receive operands through proto
Expand Down Expand Up @@ -2361,12 +2374,23 @@ defmodule Lua.VM.Executor do
defp safe_power(a, b, line, source) do
with {:ok, na} <- to_number(a),
{:ok, nb} <- to_number(b) do
:math.pow(na, nb)
pow_ieee(na, nb)
else
{:error, val} -> raise_arith_type_error(val, line, source)
end
end

# `:math.pow` raises ArithmeticError on 0^(negative), inf ^ 0, etc.
# Lua 5.3 follows IEEE 754: 0^(-x) is +inf for positive x; we approximate
# inf with our sentinel float (`1.0e308`) since BEAM has no float inf.
defp pow_ieee(base, exp) when base == 0 and is_number(exp) and exp < 0, do: 1.0e308

defp pow_ieee(base, exp) do
:math.pow(base / 1, exp / 1)
rescue
ArithmeticError -> :nan
end

defp safe_negate(a, line, source) do
case to_number(a) do
{:ok, na} ->
Expand Down Expand Up @@ -2394,6 +2418,10 @@ defmodule Lua.VM.Executor do

# ── Type-safe comparison ───────────────────────────────────────────────────

# IEEE 754 §5.11: any ordered comparison involving NaN is false.
defp safe_compare_lt(:nan, _, _, _), do: false
defp safe_compare_lt(_, :nan, _, _), do: false

defp safe_compare_lt(a, b, line, source) do
cond do
is_number(a) and is_number(b) ->
Expand All @@ -2407,6 +2435,9 @@ defmodule Lua.VM.Executor do
end
end

defp safe_compare_le(:nan, _, _, _), do: false
defp safe_compare_le(_, :nan, _, _), do: false

defp safe_compare_le(a, b, line, source) do
cond do
is_number(a) and is_number(b) ->
Expand Down
12 changes: 6 additions & 6 deletions lib/lua/vm/stdlib.ex
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ defmodule Lua.VM.Stdlib do

# type(v) — returns the type of v as a string
defp lua_type([value | _], state), do: {[Value.type_name(value)], state}
defp lua_type([], state), do: {["nil"], state}
defp lua_type([], _state), do: raise(ArgumentError.value_expected("type", 1))

# tostring(v) — converts a value to its string representation
defp lua_tostring([value | _], state) do
Expand Down Expand Up @@ -352,16 +352,16 @@ defmodule Lua.VM.Stdlib do

# ipairs(table) — returns iterator function, table, 0
defp lua_ipairs([{:tref, _} = tref | _], state) do
# Per Lua 5.3 §6.1, ipairs reads through the indexing operator, so
# __index is honoured. Iteration stops at the first nil.
iterator =
{:native_func,
fn [table_ref, index], state ->
i = index + 1
{:tref, id} = table_ref
table = Map.fetch!(state.tables, id)

case Map.get(table.data, i) do
nil -> {[nil], state}
v -> {[i, v], state}
case Executor.table_index(table_ref, i, state) do
{nil, state} -> {[nil], state}
{v, state} -> {[i, v], state}
end
end}

Expand Down
Loading
Loading