ast

package
v1.5.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 12, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package ast defines the abstract syntax tree for Lua source code.

The AST represents the syntactic structure of Lua programs, including expressions, statements, and type annotations. Each node carries source position information for error reporting.

Key node types:

  • Stmt: statements (assignment, function def, control flow, etc.)
  • Expr: expressions (literals, identifiers, operators, calls, etc.)
  • TypeExpr: type annotations for the optional type system

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func KeyName

func KeyName(key Expr) string

KeyName extracts a string key name from an expression. Returns the string value for StringExpr and IdentExpr, empty string otherwise.

func SpanOf

func SpanOf(p PositionHolder) diag.Span

SpanOf extracts a diagnostic span from a PositionHolder.

Types

type AnnotationExpr

type AnnotationExpr struct {
	Name string // "min", "max", "pattern", etc.
	Args []Expr // literal argument values
}

AnnotationExpr represents a type annotation like @min(0) or @pattern("^.+$")

type ArithmeticOpExpr

type ArithmeticOpExpr struct {
	ExprBase
	Operator string // Arithmetic operator
	Lhs      Expr   // Left operand
	Rhs      Expr   // Right operand
}

ArithmeticOpExpr represents an arithmetic operator (+, -, *, /, //, %, ^, &, |, ~, <<, >>).

type ArrayTypeExpr

type ArrayTypeExpr struct {
	TypeExprBase
	Element            TypeExpr
	Readonly           bool
	ElementAnnotations []AnnotationExpr // annotations on element type (before [])
	ArrayAnnotations   []AnnotationExpr // annotations on array itself (after [])
}

ArrayTypeExpr represents an array type: {T}

type AssertsTypeExpr

type AssertsTypeExpr struct {
	TypeExprBase
	ParamName string   // the parameter being asserted
	NarrowTo  TypeExpr // the type to narrow to (nil means truthy/non-nil)
}

AssertsTypeExpr represents a type assertion in return position: asserts x is T

type AssignStmt

type AssignStmt struct {
	StmtBase
	Lhs []Expr // Left-hand side expressions
	Rhs []Expr // Right-hand side expressions
}

AssignStmt represents an assignment statement (a, b = x, y).

type AttrGetExpr

type AttrGetExpr struct {
	ExprBase
	Object Expr // Table expression
	Key    Expr // Key expression
}

AttrGetExpr represents a table field access (obj.key or obj[key]).

type BreakStmt

type BreakStmt struct {
	StmtBase
}

BreakStmt represents a break statement.

type CastExpr

type CastExpr struct {
	ExprBase
	Expr Expr
	Type TypeExpr
}

CastExpr represents an unsafe type cast: expr :: Type

type Comma3Expr

type Comma3Expr struct {
	ExprBase
	AdjustRet bool // Whether return count should be adjusted
}

Comma3Expr represents the vararg expression (...).

type ConditionalTypeExpr

type ConditionalTypeExpr struct {
	TypeExprBase
	Check   TypeExpr // the type to check
	Extends TypeExpr // the constraint type
	Then    TypeExpr // result if Check extends Extends
	Else    TypeExpr // result if not
}

ConditionalTypeExpr represents T extends U ? A : B - type-level conditional.

type IsString<T> = T extends string ? true : false

When T is a union, the conditional distributes over each member.

type ConstExpr

type ConstExpr interface {
	Expr
	// contains filtered or unexported methods
}

ConstExpr is the interface for compile-time constant expressions.

type ConstExprBase

type ConstExprBase struct {
	ExprBase
}

ConstExprBase is the base struct for constant expression nodes.

type DoBlockStmt

type DoBlockStmt struct {
	StmtBase
	Stmts []Stmt // Statements within the block
}

DoBlockStmt represents a do...end block.

type Expr

type Expr interface {
	PositionHolder
	// contains filtered or unexported methods
}

Expr is the interface implemented by all expression nodes.

type ExprBase

type ExprBase struct {
	Node
}

ExprBase is the base struct embedded in all expression nodes.

type FalseExpr

type FalseExpr struct {
	ConstExprBase
}

FalseExpr represents the boolean literal false.

type Field

type Field struct {
	Key   Expr
	Value Expr
}

Field represents a key-value pair in a table constructor.

type FuncCallExpr

type FuncCallExpr struct {
	ExprBase
	Func      Expr       // Function to call
	Receiver  Expr       // Method receiver (nil for regular calls)
	Method    string     // Method name (empty for regular calls)
	Args      []Expr     // Call arguments
	TypeArgs  []TypeExpr // Explicit type arguments for generic calls
	AdjustRet bool       // Whether return count should be adjusted
}

FuncCallExpr represents a function call expression.

type FuncCallStmt

type FuncCallStmt struct {
	StmtBase
	Expr Expr // The function call expression
}

FuncCallStmt represents a function call used as a statement.

type FuncDefStmt

type FuncDefStmt struct {
	StmtBase
	Name *FuncName     // Function name (may include receiver for methods)
	Func *FunctionExpr // Function body
}

FuncDefStmt represents a function definition statement.

type FuncName

type FuncName struct {
	Func     Expr
	Receiver Expr
	Method   string
}

FuncName represents a function name in a function definition statement.

type FunctionExpr

type FunctionExpr struct {
	ExprBase
	TypeParams  []TypeParamExpr // Generic type parameters <T, U>
	ParList     *ParList        // Parameter list
	ReturnTypes []TypeExpr      // Declared return types (nil = inferred)
	Stmts       []Stmt          // Function body
}

FunctionExpr represents a function expression (function(...) ... end).

type FunctionParamExpr

type FunctionParamExpr struct {
	Name string   // parameter name (may be empty for anonymous)
	Type TypeExpr // parameter type
}

FunctionParamExpr represents a function parameter with optional name and type.

type FunctionTypeExpr

type FunctionTypeExpr struct {
	TypeExprBase
	TypeParams []TypeParamExpr
	Params     []FunctionParamExpr
	Variadic   TypeExpr // nil if not variadic
	Returns    []TypeExpr
}

FunctionTypeExpr represents a function type: (A, B) -> (C, D)

type GenericForStmt

type GenericForStmt struct {
	StmtBase
	Names         []string   // Loop variable names
	NamePositions []Position // Per-name token positions, parallel to Names
	Exprs         []Expr     // Iterator expressions
	Stmts         []Stmt     // Loop body
}

GenericForStmt represents a generic for loop (for k, v in iter do ... end).

type GenericTypeExpr

type GenericTypeExpr struct {
	TypeExprBase
	Base *TypeRefExpr
	Args []TypeExpr
}

GenericTypeExpr represents an instantiated generic type: Array<T>, Map<K, V>

type GotoStmt

type GotoStmt struct {
	StmtBase
	Label string // Target label name
}

GotoStmt represents a goto statement.

type IdentExpr

type IdentExpr struct {
	ExprBase
	Value string // Identifier name
}

IdentExpr represents an identifier reference.

type IfStmt

type IfStmt struct {
	StmtBase
	Condition Expr   // Branch condition
	Then      []Stmt // Statements when condition is true
	Else      []Stmt // Statements when condition is false (may contain nested IfStmt for elseif)
}

IfStmt represents an if statement with optional else branch.

type IndexAccessExpr

type IndexAccessExpr struct {
	TypeExprBase
	Object TypeExpr // the type being indexed
	Index  TypeExpr // the key (usually a literal type)
}

IndexAccessExpr represents T[K] - extracts the type of a field by key.

type Person = {name: string, age: number}
type NameType = Person["name"]  -- string

Supports records, tuples (numeric index), and arrays.

type InterfaceDefStmt

type InterfaceDefStmt struct {
	StmtBase
	Name    string
	Extends []*TypeRefExpr
	Fields  []RecordFieldExpr
	Methods []InterfaceMethodExpr
}

InterfaceDefStmt represents an interface declaration: interface Serializable ... end

type InterfaceMethodExpr

type InterfaceMethodExpr struct {
	Name string
	Type *FunctionTypeExpr
}

InterfaceMethodExpr represents a method signature in an interface.

type IntersectionTypeExpr

type IntersectionTypeExpr struct {
	TypeExprBase
	Types []TypeExpr
}

IntersectionTypeExpr represents an intersection type: A & B

type KeyOfExpr

type KeyOfExpr struct {
	TypeExprBase
	Inner TypeExpr
}

KeyOfExpr represents keyof T - extracts record keys as a union of string literals.

type Person = {name: string, age: number}
type Keys = keyof Person  -- "name" | "age"

For non-record types, keyof returns never.

type LabelStmt

type LabelStmt struct {
	StmtBase
	Name string // Label name
}

LabelStmt represents a label definition (::name::).

type LiteralTypeExpr

type LiteralTypeExpr struct {
	TypeExprBase
	Value interface{} // string, float64, bool
}

LiteralTypeExpr represents a literal type: "red" | 42 | true

type LocalAssignStmt

type LocalAssignStmt struct {
	StmtBase
	Names         []string   // Variable names
	NamePositions []Position // Per-name token positions, parallel to Names
	Types         []TypeExpr // Type annotations, parallel to Names (nil entries = inferred)
	Exprs         []Expr     // Initializer expressions
}

LocalAssignStmt represents a local variable declaration (local a, b = x, y).

type LogicalOpExpr

type LogicalOpExpr struct {
	ExprBase
	Operator string // "and" or "or"
	Lhs      Expr   // Left operand
	Rhs      Expr   // Right operand
}

LogicalOpExpr represents a logical operator (and, or).

type MapTypeExpr

type MapTypeExpr struct {
	TypeExprBase
	Key      TypeExpr
	Value    TypeExpr
	Readonly bool
}

MapTypeExpr represents a map type: {K: V}

type MetaTypeExpr

type MetaTypeExpr struct {
	TypeExprBase
	Inner TypeExpr
}

MetaTypeExpr represents a metatype: type<User>

type NilExpr

type NilExpr struct {
	ConstExprBase
}

NilExpr represents the nil literal.

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node is the base struct embedded in all AST nodes.

func (*Node) Column

func (n *Node) Column() int

Column returns the starting column number.

func (*Node) CopyLastPos

func (n *Node) CopyLastPos(src PositionHolder)

CopyLastPos copies lastline and lastcol from another PositionHolder.

func (*Node) CopyPos

func (n *Node) CopyPos(src PositionHolder)

CopyPos copies line and column from another PositionHolder.

func (*Node) LastColumn

func (n *Node) LastColumn() int

LastColumn returns the ending column number.

func (*Node) LastLine

func (n *Node) LastLine() int

LastLine returns the ending line number.

func (*Node) Line

func (n *Node) Line() int

Line returns the starting line number.

func (*Node) SetColumn

func (n *Node) SetColumn(col int)

SetColumn sets the starting column number.

func (*Node) SetLastColumn

func (n *Node) SetLastColumn(col int)

SetLastColumn sets the ending column number.

func (*Node) SetLastLine

func (n *Node) SetLastLine(line int)

SetLastLine sets the ending line number.

func (*Node) SetLastPosFromToken

func (n *Node) SetLastPosFromToken(pos Position)

SetLastPosFromToken sets lastline and lastcol from a token position.

func (*Node) SetLine

func (n *Node) SetLine(line int)

SetLine sets the starting line number.

func (*Node) SetPosFromToken

func (n *Node) SetPosFromToken(pos Position)

SetPosFromToken sets line and column from a token position.

type NonNilAssertExpr

type NonNilAssertExpr struct {
	ExprBase
	Expr Expr
}

NonNilAssertExpr represents a non-nil assertion: expr!

type NumberExpr

type NumberExpr struct {
	ConstExprBase
	Value string // Raw numeric string from source
}

NumberExpr represents a numeric literal.

type NumberForStmt

type NumberForStmt struct {
	StmtBase
	Name         string   // Loop variable name
	NamePosition Position // Token position for the loop variable
	Init         Expr     // Initial value
	Limit        Expr     // Upper bound
	Step         Expr     // Step increment (nil means 1)
	Stmts        []Stmt   // Loop body
}

NumberForStmt represents a numeric for loop (for i = start, limit, step do ... end).

type OptionalTypeExpr

type OptionalTypeExpr struct {
	TypeExprBase
	Inner TypeExpr
}

OptionalTypeExpr represents an optional type: T?

type ParList

type ParList struct {
	HasVargs   bool
	VarargType TypeExpr // Type annotation for variadic (...: T)
	Names      []string
	Types      []TypeExpr // Type annotations, parallel to Names (nil entries = inferred)
}

ParList represents a function parameter list.

type Position

type Position struct {
	Source    string // Source file name
	Line      int    // Start line number (1-based)
	Column    int    // Start column number (1-based)
	EndLine   int    // End line number (0 means same as Line)
	EndColumn int    // End column number (0 means same as Column)
}

Position represents a location in source code.

type PositionHolder

type PositionHolder interface {
	Line() int
	SetLine(int)
	LastLine() int
	SetLastLine(int)
	Column() int
	SetColumn(int)
	LastColumn() int
	SetLastColumn(int)
	SetPosFromToken(Position)
	SetLastPosFromToken(Position)
	CopyPos(PositionHolder)
	CopyLastPos(PositionHolder)
}

PositionHolder provides source location info for AST nodes.

type PrimitiveTypeExpr

type PrimitiveTypeExpr struct {
	TypeExprBase
	Name        string           // "number", "string", "boolean", "nil", "any", "unknown", "never", "integer"
	Annotations []AnnotationExpr // runtime validation annotations
}

PrimitiveTypeExpr represents primitive types: number, string, boolean, nil, any, unknown, never, integer

type RecordFieldExpr

type RecordFieldExpr struct {
	Name        string
	Type        TypeExpr
	Optional    bool
	Annotations []AnnotationExpr // runtime validation annotations on field
}

RecordFieldExpr represents a field in a record type.

type RecordTypeExpr

type RecordTypeExpr struct {
	TypeExprBase
	Fields   []RecordFieldExpr
	Readonly bool
}

RecordTypeExpr represents a record/table type: {name: string, age: number}

type RelationalOpExpr

type RelationalOpExpr struct {
	ExprBase
	Operator string // Comparison operator
	Lhs      Expr   // Left operand
	Rhs      Expr   // Right operand
}

RelationalOpExpr represents a relational operator (<, >, <=, >=, ==, ~=).

type RepeatStmt

type RepeatStmt struct {
	StmtBase
	Condition Expr   // Loop termination condition
	Stmts     []Stmt // Loop body
}

RepeatStmt represents a repeat-until loop (repeat ... until cond).

type ReturnStmt

type ReturnStmt struct {
	StmtBase
	Exprs []Expr // Return values
}

ReturnStmt represents a return statement.

type SelfTypeExpr

type SelfTypeExpr struct {
	TypeExprBase
}

SelfTypeExpr represents the self type in method declarations.

type Stmt

type Stmt interface {
	PositionHolder
	// contains filtered or unexported methods
}

Stmt is the interface implemented by all statement nodes.

type StmtBase

type StmtBase struct {
	Node
}

StmtBase is the base struct embedded in all statement nodes.

type StringConcatOpExpr

type StringConcatOpExpr struct {
	ExprBase
	Lhs Expr // Left operand
	Rhs Expr // Right operand
}

StringConcatOpExpr represents string concatenation (..).

type StringExpr

type StringExpr struct {
	ConstExprBase
	Value string // Parsed string value
}

StringExpr represents a string literal.

type TableExpr

type TableExpr struct {
	ExprBase
	Fields []*Field // Table fields
}

TableExpr represents a table constructor ({...}).

type Token

type Token struct {
	Type int      // Token type identifier
	Name string   // Human-readable token name
	Str  string   // Token string value
	Pos  Position // Source position
}

Token represents a lexical token from the scanner.

func (*Token) String

func (t *Token) String() string

String returns a debug representation of the token.

type TrueExpr

type TrueExpr struct {
	ConstExprBase
}

TrueExpr represents the boolean literal true.

type TupleTypeExpr

type TupleTypeExpr struct {
	TypeExprBase
	Elements []TypeExpr
}

TupleTypeExpr represents a tuple type: (A, B, C)

type TypeAnnotation

type TypeAnnotation struct {
	Type TypeExpr
}

TypeAnnotation holds optional type information for variables/parameters.

type TypeDefStmt

type TypeDefStmt struct {
	StmtBase
	Name       string
	TypeParams []TypeParamExpr
	Type       TypeExpr
}

TypeDefStmt represents a type alias declaration: type User = {name: string}

type TypeExpr

type TypeExpr interface {
	PositionHolder
	// contains filtered or unexported methods
}

TypeExpr represents a type annotation in the AST. Type expressions are used for type annotations, type declarations, and type-related operations in the typed Lua extension.

type TypeExprBase

type TypeExprBase struct {
	Node
}

TypeExprBase provides the base implementation for all type expressions.

type TypeOfExpr

type TypeOfExpr struct {
	TypeExprBase
	Expr Expr // the expression whose type to capture
}

TypeOfExpr represents typeof(expr) - captures the inferred type of an expression.

Unlike TypeScript which restricts typeof to identifiers, we follow Luau's approach allowing any expression. This enables patterns like:

type Config = typeof(defaultConfig)           -- capture variable type
type Person = typeof({ name = "", age = 0 })  -- capture table literal type
type API = typeof(require("api"))             -- capture module type

During type checking, the Expr is synthesized and its type becomes the result.

type TypeParamExpr

type TypeParamExpr struct {
	Name       string
	Constraint TypeExpr // nil = any
}

TypeParamExpr represents a type parameter in generic types.

type TypeRefExpr

type TypeRefExpr struct {
	TypeExprBase
	Path []string // ["User"] or ["http", "Request"]
}

TypeRefExpr represents a type reference: User, http.Request

type UnaryBNotOpExpr

type UnaryBNotOpExpr struct {
	ExprBase
	Expr Expr // Operand
}

UnaryBNotOpExpr represents bitwise negation (~x).

type UnaryLenOpExpr

type UnaryLenOpExpr struct {
	ExprBase
	Expr Expr // Operand
}

UnaryLenOpExpr represents the length operator (#x).

type UnaryMinusOpExpr

type UnaryMinusOpExpr struct {
	ExprBase
	Expr Expr // Operand
}

UnaryMinusOpExpr represents unary negation (-x).

type UnaryNotOpExpr

type UnaryNotOpExpr struct {
	ExprBase
	Expr Expr // Operand
}

UnaryNotOpExpr represents logical negation (not x).

type UnionTypeExpr

type UnionTypeExpr struct {
	TypeExprBase
	Types []TypeExpr
}

UnionTypeExpr represents a union type: A | B | C

type WhileStmt

type WhileStmt struct {
	StmtBase
	Condition Expr   // Loop condition
	Stmts     []Stmt // Loop body
}

WhileStmt represents a while loop (while cond do ... end).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL