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
22 changes: 20 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,19 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below.
`pcall` hands back inside Lua. Code matching on a string reason should
switch to the struct (or call `Exception.message/1` on it).
- `Lua.parse_chunk/1` returns `{:error, %Lua.CompilerException{}}` instead of
`{:error, [String.t()]}`. The formatted diagnostics are on the
exception's `:errors` field; `Exception.message/1` renders them.
`{:error, [String.t()]}`. Call `Exception.message/1` to render the full,
human-readable report; the `:errors` field carries the bare, ANSI-free
messages for programmatic inspection.
- Lua exceptions render their message lazily at `Exception.message/1` call
time, so the `:message` **struct field** is removed from
`Lua.VM.RuntimeError`, `Lua.VM.TypeError`, and `Lua.VM.AssertionError`, and
is `nil` on the `Lua.RuntimeException` wrapper when it wraps a VM exception.
Read the message through `Exception.message/1` (the idiomatic accessor)
rather than the `e.message` field. Likewise `Lua.CompilerException`'s
`:errors` field now holds bare, ANSI-free messages rather than the fully
formatted (and previously ANSI-colored) diagnostics — the rich report moved
to `Exception.message/1`. This is what lets the ANSI gate hold at output time
(#384).

### Changed
- `Lua.new/1`'s `:max_string_bytes` now accepts `:infinity` for no limit,
Expand All @@ -94,6 +105,13 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below.
populated (always `nil`); `:errors` carries all the formatted diagnostics.

### Fixed
- Lua exception messages no longer leak ANSI escape codes (and multi-line rich
rendering) into non-terminal sinks such as log files, container stdout, or a
Sentry/AppSignal title. Messages were formatted eagerly during VM execution —
where `IO.ANSI.enabled?/0` is true — freezing escape codes into the struct
that survived long after the TTY gate. They now render at `Exception.message/1`
call time, so the ANSI gate is evaluated where the message is actually written
(#384).
- `Lua.eval!/3` now accepts a `:source` option when evaluating a pre-compiled
`Lua.Chunk`, matching the string-script clause. Previously
`eval!(lua, chunk, source: "x")` raised via `Keyword.validate!`. For a chunk
Expand Down
12 changes: 6 additions & 6 deletions lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ defmodule Lua do
def eval!(%__MODULE__{state: state} = lua, script, opts) when is_binary(script) do
opts = Keyword.validate!(opts, decode: true, source: "<eval>")

case Lua.Parser.parse(script) do
case Lua.Parser.parse_structured(script) do
{:ok, ast} ->
case Lua.Compiler.compile(ast, source: opts[:source]) do
{:ok, proto} ->
Expand All @@ -520,8 +520,8 @@ defmodule Lua do
raise Lua.CompilerException, msg
end

{:error, msg} ->
raise Lua.CompilerException, msg
{:error, parse_errors} ->
raise Lua.CompilerException, {:parse_errors, parse_errors, script}
end
rescue
e in [Lua.RuntimeException, Lua.CompilerException] ->
Expand Down Expand Up @@ -641,7 +641,7 @@ defmodule Lua do
"""
@spec parse_chunk(String.t()) :: {:ok, Lua.Chunk.t()} | {:error, Lua.CompilerException.t()}
def parse_chunk(code) do
case Lua.Parser.parse(code) do
case Lua.Parser.parse_structured(code) do
{:ok, ast} ->
case Lua.Compiler.compile(ast) do
{:ok, proto} ->
Expand All @@ -651,8 +651,8 @@ defmodule Lua do
{:error, Lua.CompilerException.exception(msg)}
end

{:error, msg} ->
{:error, Lua.CompilerException.exception(msg)}
{:error, parse_errors} ->
{:error, Lua.CompilerException.exception({:parse_errors, parse_errors, code})}
end
end

Expand Down
50 changes: 43 additions & 7 deletions lib/lua/compiler_exception.ex
Original file line number Diff line number Diff line change
@@ -1,13 +1,35 @@
defmodule Lua.CompilerException do
@moduledoc """
Raised when Lua source cannot be lexed, parsed, or compiled. Carries
a list of formatted error messages in `:errors`.
Raised when Lua source cannot be lexed, parsed, or compiled.

Use `Exception.message/1` to render the full, human-readable report (location,
source context, pointer, and suggestions). ANSI color is applied only when
`IO.ANSI.enabled?/0` is true *at render time*, so the same exception logs
cleanly to a file and renders in color on a TTY (issue #384).

The `:errors` field carries the bare, ANSI-free error messages (no location
header or source context) for programmatic inspection and clean logging.
"""
alias Lua.Parser.Error
alias Lua.Util

@type t :: %__MODULE__{}

defexception [:errors]
# `:diagnostics` holds structured `Lua.Parser.Error` structs and `:source` the
# original code, so `message/1` can render the rich report lazily. They stay
# `nil` for non-parser inputs (compiler/lexer errors), which fall back to
# joining the `:errors` strings.
defexception errors: [], diagnostics: nil, source: nil

# Structured parse errors — defer formatting to `message/1` so the ANSI gate
# is evaluated when the message is written, not frozen at construction.
def exception({:parse_errors, diagnostics, source}) when is_list(diagnostics) do
%__MODULE__{
diagnostics: diagnostics,
source: source,
errors: Enum.map(diagnostics, &clean_message/1)
}
end

def exception(formatted: errors) when is_list(errors) do
%__MODULE__{errors: errors}
Expand All @@ -30,15 +52,29 @@ defmodule Lua.CompilerException do
end

# Compile-time errors don't have a meaningful runtime stack trace — they're
# produced by the lexer/parser before any code is executed. The rich source
# context (line, column, pointer to the offending token) is embedded in
# `errors` by `Lua.Parser.Error.format/2` (and the lexer's equivalent), so
# we just join those messages under a clear "Failed to compile" header.
# produced by the lexer/parser/compiler before any code is executed. The rich
# source context (line, column, pointer to the offending token) is rendered
# here from the structured diagnostics, so we join it under a clear
# "Failed to compile" header.
@impl true
def message(%__MODULE__{diagnostics: [_ | _] = diagnostics, source: source}) do
rendered = Enum.map_join(diagnostics, "\n", &Error.format(&1, source))

"""
Failed to compile Lua!

#{rendered}
"""
end

def message(%__MODULE__{errors: errors}) do
"""
Failed to compile Lua!

#{Enum.join(errors, "\n")}
"""
end

defp clean_message(%Error{message: message}) when is_binary(message), do: String.trim(message)
defp clean_message(%Error{}), do: ""
end
37 changes: 28 additions & 9 deletions lib/lua/runtime_exception.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,15 @@ defmodule Lua.RuntimeException do
arithmetic on a non-number, indexing a nil, an explicit `error()`
call from Lua, or any other dynamic failure inside the VM.

Use `Exception.message/1` to render the message — do not read the `:message`
field directly. When this wraps a VM exception the field is `nil` and the
message is rendered lazily so ANSI color is gated on `IO.ANSI.enabled?/0` at
output time rather than frozen at construction (issue #384).

Fields:

* `:message` — formatted error string
* `:message` — pre-rendered string for terminal-independent errors, or
`nil` when rendered lazily from `:original`
* `:original` — the underlying VM error term
* `:state` — the internal VM state at the point of failure
* `:line` — line number where the error was raised
Expand Down Expand Up @@ -50,27 +56,40 @@ defmodule Lua.RuntimeException do
end

def exception(error) do
message =
if is_exception(error) do
Exception.message(error)
else
inspect(error)
end

# Copy structured fields off VM exceptions (TypeError, RuntimeError,
# AssertionError) so consumers can pattern-match on `:line` / `:source`
# without having to re-parse the message string.
{line, source, call_stack} = extract_context(error)

# `:message` is left nil so `message/1` renders the wrapped error lazily.
# The inner VM exceptions gate ANSI on `IO.ANSI.enabled?/0` at render time
# (issue #384); freezing their rendered message here would bake in escape
# codes from the TTY-attached VM process and leak them into log sinks.
%__MODULE__{
original: error,
message: prefix_message(message),
line: line,
source: source,
call_stack: call_stack
}
end

# The `:lua_error`, `:api_error`, keyword-list, and binary clauses build
# ANSI-free strings that don't depend on the terminal, so they memoize into
# `:message`. The generic clause defers to keep the ANSI gate honest.
@impl true
def message(%__MODULE__{message: message}) when is_binary(message), do: message

def message(%__MODULE__{original: original}) do
rendered =
if is_exception(original) do
Exception.message(original)
else
inspect(original)
end

prefix_message(rendered)
end

defp prefix_message(@runtime_prefix <> _ = msg), do: msg
defp prefix_message(msg), do: @runtime_prefix <> msg

Expand Down
25 changes: 13 additions & 12 deletions lib/lua/vm/assertion_error.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,29 @@ defmodule Lua.VM.AssertionError do
# rolling back to their entry snapshot. It is out-of-band metadata: it never
# participates in `message` and stays `nil` when no state was in scope.
@derive {Inspect, except: [:state]}
defexception [:value, :source, :message, :call_stack, :line, :state]
defexception [:value, :source, :call_stack, :line, :state]

@impl true
def exception(opts) do
{auto_line, auto_source} = Lua.VM.Executor.current_position()

value = Keyword.get(opts, :value)
source = Keyword.get(opts, :source) || auto_source
call_stack = Keyword.get(opts, :call_stack, [])
line = Keyword.get(opts, :line) || auto_line
message = Keyword.get(opts, :message) || format_message(value, source, line, call_stack)

%__MODULE__{
value: value,
source: source,
message: message,
call_stack: call_stack,
line: line,
value: Keyword.get(opts, :value),
source: Keyword.get(opts, :source) || auto_source,
call_stack: Keyword.get(opts, :call_stack, []),
line: Keyword.get(opts, :line) || auto_line,
state: Keyword.get(opts, :state)
}
end

# Rendered lazily so `IO.ANSI.enabled?/0` is evaluated when the message is
# actually written rather than frozen at construction time. See issue #384;
# mirrors `Lua.VM.ArgumentError.message/1`.
@impl true
def message(%__MODULE__{} = error) do
format_message(error.value, error.source, error.line, error.call_stack)
end

@doc """
Returns a wire-safe structured map for this error. See
`Lua.VM.ErrorFormatter.to_map/3` for the shape.
Expand Down
26 changes: 14 additions & 12 deletions lib/lua/vm/runtime_error.ex
Original file line number Diff line number Diff line change
Expand Up @@ -30,29 +30,31 @@ defmodule Lua.VM.RuntimeError do
# raw `:value`, so host-facing rendering (which adds its own
# `at source:line:` header) never doubles the location.
@derive {Inspect, except: [:state]}
defexception [:value, :lua_value, :source, :message, :call_stack, :line, :state]
defexception [:value, :lua_value, :source, :call_stack, :line, :state]

@impl true
def exception(opts) do
{auto_line, auto_source} = Lua.VM.Executor.current_position()

value = Keyword.get(opts, :value)
source = Keyword.get(opts, :source) || auto_source
call_stack = Keyword.get(opts, :call_stack, [])
line = Keyword.get(opts, :line) || auto_line
message = Keyword.get(opts, :message) || format_message(value, source, line, call_stack)

%__MODULE__{
value: value,
value: Keyword.get(opts, :value),
lua_value: Keyword.get(opts, :lua_value),
source: source,
message: message,
call_stack: call_stack,
line: line,
source: Keyword.get(opts, :source) || auto_source,
call_stack: Keyword.get(opts, :call_stack, []),
line: Keyword.get(opts, :line) || auto_line,
state: Keyword.get(opts, :state)
}
end

# Rendered lazily so `IO.ANSI.enabled?/0` is evaluated when the message is
# actually written (log sink, TTY, Sentry) rather than frozen at construction
# time — where it would run inside a Lua execution and always see a TTY. See
# issue #384; mirrors `Lua.VM.ArgumentError.message/1`.
@impl true
def message(%__MODULE__{} = error) do
format_message(error.value, error.source, error.line, error.call_stack)
end

@doc """
Returns a wire-safe structured map for this error. See
`Lua.VM.ErrorFormatter.to_map/3` for the shape.
Expand Down
41 changes: 22 additions & 19 deletions lib/lua/vm/type_error.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,35 +21,38 @@ defmodule Lua.VM.TypeError do
# rolling back to their entry snapshot. It is out-of-band metadata: it never
# participates in `message` and stays `nil` when no state was in scope.
@derive {Inspect, except: [:state]}
defexception [:value, :source, :message, :call_stack, :line, :error_kind, :value_type, :state]
defexception [:value, :source, :call_stack, :line, :error_kind, :value_type, :state]

@impl true
def exception(opts) do
{auto_line, auto_source} = Lua.VM.Executor.current_position()

value = Keyword.get(opts, :value)
source = Keyword.get(opts, :source) || auto_source
call_stack = Keyword.get(opts, :call_stack, [])
line = Keyword.get(opts, :line) || auto_line
error_kind = Keyword.get(opts, :error_kind)
value_type = Keyword.get(opts, :value_type)

message =
Keyword.get(opts, :message) ||
format_message(value, source, line, call_stack, error_kind, value_type)

%__MODULE__{
value: value,
source: source,
message: message,
call_stack: call_stack,
line: line,
error_kind: error_kind,
value_type: value_type,
value: Keyword.get(opts, :value),
source: Keyword.get(opts, :source) || auto_source,
call_stack: Keyword.get(opts, :call_stack, []),
line: Keyword.get(opts, :line) || auto_line,
error_kind: Keyword.get(opts, :error_kind),
value_type: Keyword.get(opts, :value_type),
state: Keyword.get(opts, :state)
}
end

# Rendered lazily so `IO.ANSI.enabled?/0` is evaluated when the message is
# actually written rather than frozen at construction time. See issue #384;
# mirrors `Lua.VM.ArgumentError.message/1`.
@impl true
def message(%__MODULE__{} = error) do
format_message(
error.value,
error.source,
error.line,
error.call_stack,
error.error_kind,
error.value_type
)
end

@doc """
Returns a wire-safe structured map for this error. See
`Lua.VM.ErrorFormatter.to_map/3` for the shape.
Expand Down
Loading
Loading