Help us shape the future of Go! Take the 2026 Go Developer Survey

syntax

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: BSD-3-Clause Imports: 6 Imported by: 0

Documentation

Overview

Package syntax turns Lua 5.4 source text into an abstract syntax tree. It knows nothing about the VM: the compiler in the glua package walks the tree it produces.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsMultiValue

func IsMultiValue(e Expr) bool

IsMultiValue reports whether e can produce several values: a call or '...' that is not wrapped in parentheses.

func IsReserved

func IsReserved(s string) bool

IsReserved reports whether s is a reserved word of Lua.

func ParseNumber

func ParseNumber(s string) (i int64, f float64, isInt, ok bool)

ParseNumber converts a Lua numeral, without sign or surrounding space, as C Lua's luaO_str2num does: a decimal integer that fits in 64 bits, a hexadecimal integer (wrapping around), or else a float, decimal or hexadecimal.

Types

type AssignStmt

type AssignStmt struct {
	Line            int
	Targets, Values []Expr
	TargetLines     []int
}

AssignStmt is Targets = Values. Each target is a NameExpr or IndexExpr. TargetLines has, per target, the line of the ',' or '=' after it, where C Lua reports an assignment to a const variable.

func (*AssignStmt) Pos

func (s *AssignStmt) Pos() int

type BinaryExpr

type BinaryExpr struct {
	Line int
	Op   Kind
	L, R Expr
}

BinaryExpr is L Op R. Op is one of the operator kinds, And or Or.

func (*BinaryExpr) Pos

func (e *BinaryExpr) Pos() int

type Block

type Block struct {
	Stmts   []Stmt
	EndLine int
}

Block is a list of statements; a ReturnStmt can only be last. EndLine is the line of the token that closes it.

type BreakStmt

type BreakStmt struct{ Line int }

func (*BreakStmt) Pos

func (s *BreakStmt) Pos() int

type CallExpr

type CallExpr struct {
	Line int
	Fn   Expr
	Args []Expr
}

func (*CallExpr) Pos

func (e *CallExpr) Pos() int

type CallStmt

type CallStmt struct {
	Line int
	Call Expr // CallExpr or MethodCallExpr
}

CallStmt is a call used as a statement.

func (*CallStmt) Pos

func (s *CallStmt) Pos() int

type DoStmt

type DoStmt struct {
	Line int
	Body *Block
}

func (*DoStmt) Pos

func (s *DoStmt) Pos() int

type Error

type Error struct {
	Source    string
	Line, Col int
	Msg       string
}

Error is a syntax error. Its message has C Lua's form, such as "unexpected symbol near 'x'".

func (*Error) Error

func (e *Error) Error() string

type Expr

type Expr interface {
	Pos() int
	// contains filtered or unexported methods
}

Expr is an expression node. Line is where the node's code should be reported: the start of a call's prefix, the operator of a binary expression, the first token otherwise.

type ExprEnv

type ExprEnv struct {
	Param  string
	Fields map[string]bool
	Known  func(name string) bool
}

ExprEnv makes a chunk an expression over a Go struct: its main function takes the struct as the parameter Param, and a free name that is one of Fields is a field of it. Any other free name must be Known. Fields maps each name to whether it may be assigned.

type FalseExpr

type FalseExpr struct{ Line int }

func (*FalseExpr) Pos

func (e *FalseExpr) Pos() int

type Field

type Field struct {
	Key, Value Expr
}

Field is one entry of a table constructor. Key is nil for a positional entry.

type FloatExpr

type FloatExpr struct {
	Line  int
	Value float64
}

func (*FloatExpr) Pos

func (e *FloatExpr) Pos() int

type FuncInfo

type FuncInfo struct {
	Node   *FunctionExpr // nil for the pseudo function that holds the main chunk's _ENV
	Parent *FuncInfo
	Upvals []*Upval // in order of first use
}

FuncInfo is what resolution found out about one function.

type FunctionExpr

type FunctionExpr struct {
	Line, EndLine int
	CloseLine     int      // line of the token after the closing 'end', where C Lua reports pending gotos
	Params        []string // a method's "self" comes first
	IsVararg      bool
	Body          *Block
	Name          string // for messages: "f", "a.b:c", "<anonymous>"
}

func Parse

func Parse(source, src string) (fn *FunctionExpr, err error)

Parse parses a chunk into the body of its main function, which takes '...'.

func ParseFile

func ParseFile(source, src string) (fn *FunctionExpr, err error)

ParseFile is Parse for the contents of a file: a first line starting with '#' is skipped.

func ParseFixed

func ParseFixed(source, src string) (fn *FunctionExpr, err error)

ParseFixed is Parse for a chunk whose main function is not vararg, such as an expression over a Go struct: '...' in it is an error.

func (*FunctionExpr) Pos

func (e *FunctionExpr) Pos() int

type FunctionStmt

type FunctionStmt struct {
	Line   int
	Target Expr
	Func   *FunctionExpr
}

FunctionStmt is "function a.b.c() end" or "function a.b:c() end": Target = Func. Target is a NameExpr or IndexExpr; for a method, Func's first parameter is self.

func (*FunctionStmt) Pos

func (s *FunctionStmt) Pos() int

type GenericForStmt

type GenericForStmt struct {
	Line     int
	ExprLine int // line of the token after 'in', where C Lua places the iterator call
	Names    []string
	Exprs    []Expr
	Body     *Block
}

func (*GenericForStmt) Pos

func (s *GenericForStmt) Pos() int

type GotoStmt

type GotoStmt struct {
	Line  int
	Label string
}

func (*GotoStmt) Pos

func (s *GotoStmt) Pos() int

type IfStmt

type IfStmt struct {
	Line   int
	Conds  []Expr
	Blocks []*Block
	Else   *Block
}

IfStmt has one condition and block per if and elseif. Else may be nil.

func (*IfStmt) Pos

func (s *IfStmt) Pos() int

type IndexExpr

type IndexExpr struct {
	Line     int
	Obj, Key Expr
}

IndexExpr is Obj[Key]. Obj.name has a StringExpr key.

func (*IndexExpr) Pos

func (e *IndexExpr) Pos() int

type Info

type Info struct {
	Main  *FuncInfo
	Funcs map[*FunctionExpr]*FuncInfo
	Names map[*NameExpr]Ref
	// Decls holds the variables each declaration introduces, in order: for a LocalStmt,
	// LocalFunctionStmt, NumericForStmt, GenericForStmt, or a FunctionExpr's parameters.
	Decls map[any][]*Var
	// ExplicitEnv is set when the chunk declares or assigns _ENV. Free names are then
	// fields of whichever _ENV is visible, and EnvVar is the main chunk's own _ENV.
	ExplicitEnv bool
	EnvVar      *Var
}

Info is the result of resolution.

func Resolve

func Resolve(source string, fn *FunctionExpr) (info *Info, err error)

Resolve binds every name in the chunk fn and checks what C Lua checks while parsing: gotos and labels, break outside a loop, assignments to const variables, and the limits on locals and upvalues.

func ResolveExpr

func ResolveExpr(source string, fn *FunctionExpr, xenv *ExprEnv) (info *Info, err error)

ResolveExpr is Resolve for a chunk whose free names env resolves. fn must take env.Param as its first parameter. A name neither a field nor known, an assignment to a read-only field and an assignment to a global are errors.

type IntExpr

type IntExpr struct {
	Line  int
	Value int64
}

func (*IntExpr) Pos

func (e *IntExpr) Pos() int

type Kind

type Kind uint8

Kind is the kind of a token.

const (
	EOF Kind = iota

	// literals and names
	Name
	String
	Int
	Float

	// reserved words
	And
	Break
	Do
	Else
	Elseif
	End
	False
	For
	Function
	Goto
	If
	In
	Local
	Nil
	Not
	Or
	Repeat
	Return
	Then
	True
	Until
	While

	// operators and punctuation
	Plus     // +
	Minus    // -
	Star     // *
	Slash    // /
	DSlash   // //
	Percent  // %
	Caret    // ^
	Hash     // #
	Amp      // &
	Tilde    // ~
	Pipe     // |
	Shl      // <<
	Shr      // >>
	Concat   // ..
	Dots     // ...
	Eq       // ==
	Ne       // ~=
	Le       // <=
	Ge       // >=
	Lt       // <
	Gt       // >
	Assign   // =
	LParen   // (
	RParen   // )
	LBrace   // {
	RBrace   // }
	LBracket // [
	RBracket // ]
	DColon   // ::
	Semi     // ;
	Colon    // :
	Comma    // ,
	Dot      // .
)
const Other Kind = 255

Other is the kind of a byte that starts no token, such as '@'. C Lua hands such bytes to the parser, which reports "unexpected symbol near '@'".

func (Kind) String

func (k Kind) String() string

type LabelStmt

type LabelStmt struct {
	Line      int
	Name      string
	AfterLine int
}

LabelStmt is ::Name::. AfterLine is the line of the token after it, where C Lua reports a duplicate label or a goto that jumps into a local's scope.

func (*LabelStmt) Pos

func (s *LabelStmt) Pos() int

type Lexer

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

Lexer splits Lua source into tokens. It reports errors by panicking with *Error, which the parser recovers.

func NewLexer

func NewLexer(source, src string, skipComment bool) *Lexer

NewLexer returns a lexer for src. A first line starting with '#' is skipped, as C Lua's loaders do for files, when skipComment is set.

func (*Lexer) Next

func (l *Lexer) Next() Token

Next returns the next token.

type LocalFunctionStmt

type LocalFunctionStmt struct {
	Line int
	Name string
	Func *FunctionExpr
}

LocalFunctionStmt is "local function name() end"; the name is in scope in the body.

func (*LocalFunctionStmt) Pos

func (s *LocalFunctionStmt) Pos() int

type LocalStmt

type LocalStmt struct {
	Line    int
	Names   []string
	Attribs []string
	Values  []Expr
}

LocalStmt is "local a <const>, b = ...". Attribs has "", "const" or "close" per name.

func (*LocalStmt) Pos

func (s *LocalStmt) Pos() int

type MethodCallExpr

type MethodCallExpr struct {
	Line int
	Obj  Expr
	Name string
	Args []Expr
}

MethodCallExpr is Obj:Name(Args).

func (*MethodCallExpr) Pos

func (e *MethodCallExpr) Pos() int

type NameExpr

type NameExpr struct {
	Line int
	Name string
}

NameExpr is a free or local name; scope resolution decides which.

func (*NameExpr) Pos

func (e *NameExpr) Pos() int

type NilExpr

type NilExpr struct{ Line int }

func (*NilExpr) Pos

func (e *NilExpr) Pos() int

type NumericForStmt

type NumericForStmt struct {
	Line               int
	Var                string
	Start, Limit, Step Expr // Step may be nil
	Body               *Block
}

func (*NumericForStmt) Pos

func (s *NumericForStmt) Pos() int

type ParenExpr

type ParenExpr struct {
	Line int
	X    Expr
}

ParenExpr is (X). It cuts a call or '...' to one value and makes X no longer assignable.

func (*ParenExpr) Pos

func (e *ParenExpr) Pos() int

type Ref

type Ref struct {
	Kind  RefKind
	Var   *Var   // RefLocal, RefUpval
	Upval *Upval // RefUpval
	// Env, for a RefGlobal in a chunk that declares or assigns _ENV, is the binding of the
	// _ENV that is visible there; the name is a field of it. It is nil in the common case,
	// where free names go straight to the closure's globals table.
	Env *Ref
	// Field, in an expression chunk, is the field of the environment parameter a free name
	// names; Var and Upval then bind that parameter.
	Field string
}

Ref is the binding of one NameExpr.

type RefKind

type RefKind uint8

RefKind says what a name refers to.

const (
	RefLocal  RefKind = iota // a local of the current function
	RefUpval                 // an upvalue of the current function
	RefGlobal                // a free name: a field of _ENV
)

type RepeatStmt

type RepeatStmt struct {
	Line int
	Body *Block
	Cond Expr // in the scope of Body's locals
}

func (*RepeatStmt) Pos

func (s *RepeatStmt) Pos() int

type ReturnStmt

type ReturnStmt struct {
	Line   int
	Values []Expr
}

func (*ReturnStmt) Pos

func (s *ReturnStmt) Pos() int

type Stmt

type Stmt interface {
	Pos() int
	// contains filtered or unexported methods
}

Stmt is a statement node.

type StringExpr

type StringExpr struct {
	Line  int
	Value string
}

func (*StringExpr) Pos

func (e *StringExpr) Pos() int

type TableExpr

type TableExpr struct {
	Line, EndLine int
	Fields        []Field
}

func (*TableExpr) Pos

func (e *TableExpr) Pos() int

type Token

type Token struct {
	Kind    Kind
	Line    int     // 1-based
	EndLine int     // the line the lexer is on after the token, which C Lua reports errors at
	Col     int     // 1-based byte column of the first character
	Str     string  // the name, or the string's contents after escapes
	Int     int64   // the value of an Int token
	Num     float64 // the value of a Float token
	// contains filtered or unexported fields
}

Token is one lexical token.

func (Token) Near

func (tok Token) Near() string

Near returns the text C Lua shows after "near" for tok.

type TrueExpr

type TrueExpr struct{ Line int }

func (*TrueExpr) Pos

func (e *TrueExpr) Pos() int

type UnaryExpr

type UnaryExpr struct {
	Line int
	Op   Kind
	X    Expr
}

UnaryExpr is Op X. Op is Minus, Not, Hash or Tilde.

func (*UnaryExpr) Pos

func (e *UnaryExpr) Pos() int

type Upval

type Upval struct {
	Name   string
	Var    *Var
	Parent *Upval // nil when Var is a local of the immediately enclosing function
	Index  int
}

Upval is one captured variable of a function: a local of the enclosing function, or one of its upvalues.

type Var

type Var struct {
	Name     string
	Attrib   string // "", "const" or "close"
	Func     *FuncInfo
	Line     int
	Captured bool // an inner function refers to it
	Assigned bool // it is assigned somewhere other than its declaration
}

Var is a local variable: a parameter, a loop variable or a local declaration.

func (*Var) Cell

func (v *Var) Cell() bool

Cell reports whether the variable needs a cell: inner functions see it, and it changes. A captured variable that never changes is copied into the closures instead, which is Luau's rule. A fresh cell each time the declaration runs gives Lua's per-iteration semantics.

type VarargExpr

type VarargExpr struct{ Line int }

func (*VarargExpr) Pos

func (e *VarargExpr) Pos() int

type WhileStmt

type WhileStmt struct {
	Line int
	Cond Expr
	Body *Block
}

func (*WhileStmt) Pos

func (s *WhileStmt) Pos() int

Jump to

Keyboard shortcuts

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