Lua.Parser (Lua v1.0.0-rc.3)

View Source

Hand-written recursive descent parser for Lua 5.3.

Uses Pratt parsing for operator precedence in expressions.

Summary

Functions

Parses Lua source code into an AST.

Parses a chunk (top-level block) from a token list.

Parses an expression with minimum precedence.

Parses Lua source code and returns raw error information.

Parses Lua source code and returns structured errors.

Types

parse_result(t)

@type parse_result(t) :: {:ok, t, [token()]} | {:error, term()}

token()

@type token() :: Lua.Lexer.token()

Functions

parse(code)

@spec parse(String.t()) :: {:ok, Lua.AST.Chunk.t()} | {:error, String.t()}

Parses Lua source code into an AST.

Returns {:ok, chunk} on success or {:error, formatted_error} on failure. The error is a beautifully formatted string with context and suggestions.

Examples

iex> Lua.Parser.parse("local x = 42")
{:ok, %Lua.AST.Chunk{...}}

iex> {:error, error_msg} = Lua.Parser.parse("if x then")
iex> String.contains?(error_msg, "Parse Error")
true

parse_chunk(tokens)

@spec parse_chunk([token()]) :: {:ok, Lua.AST.Chunk.t()} | {:error, term()}

Parses a chunk (top-level block) from a token list.

parse_expr(tokens, min_prec \\ 0)

@spec parse_expr([token()], non_neg_integer()) :: parse_result(Lua.AST.Expr.t())

Parses an expression with minimum precedence.

parse_raw(code)

@spec parse_raw(String.t()) :: {:ok, Lua.AST.Chunk.t()} | {:error, term()}

Parses Lua source code and returns raw error information.

Use this when you want to handle errors programmatically instead of displaying them to users.

parse_structured(code)

@spec parse_structured(String.t()) ::
  {:ok, Lua.AST.Chunk.t()} | {:error, [Lua.Parser.Error.t()]}

Parses Lua source code and returns structured errors.

Unlike parse/1, which returns a pre-formatted display string, this returns the Lua.Parser.Error.t/0 structs directly so consumers can render errors in their own UI (editors, LSPs, web frontends) without scraping the formatted output. Use Lua.Parser.Error.to_map/2 to obtain a JSON-serializable shape.

The error list always holds a single error today; the list shape leaves room for multi-error recovery without a breaking change.

Examples

iex> {:ok, %Lua.AST.Chunk{}} = Lua.Parser.parse_structured("local x = 42")

iex> {:error, [error]} = Lua.Parser.parse_structured("if x then")
iex> error.type
:unexpected_token