ast

package
v1.1.10 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2025 License: MIT Imports: 2 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OpPlus = iota + 1
	OpMinus
	OpMul
	OpDiv
	OpMod
	OpEq
	OpNeq
	OpLt
	OpLte
	OpGt
	OpGte
	OpAnd
	OpOr
	OpNot // unary
	OpNeg // unary minus
)

Operator codes for BinaryExpr and UnaryExpr.Op. Keep these AST-local to avoid import cycles.

Variables

View Source
var (
	ANY = &Type{Name: "Any", Aliases: []string{"any"}, GoParallel: false, IsBuiltin: true}
	NIL = &Type{Name: "nil", Aliases: []string{"null", "Nil", "Null"}, GoParallel: false, IsBuiltin: true}
)

Predefined built-in types

View Source
var (
	// Pre-allocated common number literals
	NumberZero = &NumberLit{Value: 0}
	NumberOne  = &NumberLit{Value: 1}
	NumberTwo  = &NumberLit{Value: 2}
	NumberTen  = &NumberLit{Value: 10}

	// Pre-allocated boolean literals
	BoolTrue  = &BoolLit{Value: true}
	BoolFalse = &BoolLit{Value: false}

	// Pre-allocated nil literal
	NilValue = &NilLit{}
)

Commonly used constants to reduce allocations

Functions

func ClearTypeCache added in v1.1.4

func ClearTypeCache()

ClearTypeCache clears the type cache. Useful for testing or memory management.

func GetTypeNameString added in v1.0.0

func GetTypeNameString(t *Type) string

GetTypeName returns the string name of a type This is a compatibility helper for code migration Optimized with caching and index-based loops for better performance

func IsBuiltinTypeName added in v1.0.0

func IsBuiltinTypeName(typeName string) bool

IsBuiltinTypeName checks if a type name refers to a built-in type

func ReleaseAssignStmt added in v1.1.4

func ReleaseAssignStmt(n *AssignStmt)

ReleaseAssignStmt returns an AssignStmt to the pool

func ReleaseBinaryExpr added in v1.1.4

func ReleaseBinaryExpr(n *BinaryExpr)

ReleaseBinaryExpr returns a BinaryExpr to the pool

func ReleaseBoolLit added in v1.1.4

func ReleaseBoolLit(n *BoolLit)

ReleaseBoolLit returns a BoolLit to the pool

func ReleaseCallExpr added in v1.1.4

func ReleaseCallExpr(n *CallExpr)

ReleaseCallExpr returns a CallExpr to the pool

func ReleaseExprStmt added in v1.1.4

func ReleaseExprStmt(n *ExprStmt)

ReleaseExprStmt returns an ExprStmt to the pool

func ReleaseFieldExpr added in v1.1.4

func ReleaseFieldExpr(n *FieldExpr)

ReleaseFieldExpr returns a FieldExpr to the pool

func ReleaseIdent added in v1.1.4

func ReleaseIdent(n *Ident)

ReleaseIdent returns an Ident to the pool

func ReleaseIndexExpr added in v1.1.4

func ReleaseIndexExpr(n *IndexExpr)

ReleaseIndexExpr returns an IndexExpr to the pool

func ReleaseLetStmt added in v1.1.4

func ReleaseLetStmt(n *LetStmt)

ReleaseLetStmt returns a LetStmt to the pool

func ReleaseNilLit added in v1.1.4

func ReleaseNilLit(n *NilLit)

ReleaseNilLit returns a NilLit to the pool

func ReleaseNumberLit added in v1.1.4

func ReleaseNumberLit(n *NumberLit)

ReleaseNumberLit returns a NumberLit to the pool

func ReleaseReturnStmt added in v1.1.4

func ReleaseReturnStmt(n *ReturnStmt)

ReleaseReturnStmt returns a ReturnStmt to the pool

func ReleaseStringLit added in v1.1.4

func ReleaseStringLit(n *StringLit)

ReleaseStringLit returns a StringLit to the pool

func ReleaseType added in v1.1.4

func ReleaseType(t *Type)

ReleaseType returns a Type to the pool

func ReleaseUnaryExpr added in v1.1.4

func ReleaseUnaryExpr(n *UnaryExpr)

ReleaseUnaryExpr returns a UnaryExpr to the pool

Types

type Annotation

type Annotation struct {
	Raw        string // original casing as written in source
	Normalized string // canonical lowercase form for comparisons
	Known      bool   // true if the annotation is registered in the runtime
}

Annotation captures metadata attached to declarations such as methods.

type ArrayLit

type ArrayLit struct{ Elems []Expr }

Composite literals

type AssignStmt

type AssignStmt struct {
	Target Expr     // left side of assignment (could be identifier or field access)
	Value  Expr     // right side of assignment
	Pos    Position // position of the assignment operator
}

func NewAssignStmt added in v1.1.4

func NewAssignStmt(target, value Expr) *AssignStmt

NewAssignStmt gets an AssignStmt from the pool

type BinaryExpr

type BinaryExpr struct {
	Op       int
	Lhs, Rhs Expr
}

func NewBinaryExpr added in v1.1.4

func NewBinaryExpr(op int, lhs, rhs Expr) *BinaryExpr

NewBinaryExpr gets a BinaryExpr from the pool

type BoolLit

type BoolLit struct{ Value bool }

func GetCommonBoolLit added in v1.1.4

func GetCommonBoolLit(value bool) *BoolLit

GetCommonBoolLit returns a pre-allocated BoolLit

func NewBoolLit added in v1.1.4

func NewBoolLit(value bool) *BoolLit

NewBoolLit gets a BoolLit from the pool

type BreakStmt

type BreakStmt struct{}

type BytesLit added in v1.1.0

type BytesLit struct{ Value []byte }

type CallExpr

type CallExpr struct {
	Callee Expr
	Args   []Expr
}

Call

func NewCallExpr added in v1.1.4

func NewCallExpr(callee Expr, args []Expr) *CallExpr

NewCallExpr gets a CallExpr from the pool

type CatchClause

type CatchClause struct {
	VarName    string // variable name to bind the exception
	Modifier   string // modifier like "final", "const"
	ExceptType string // type of exception to catch (optional)
	Body       []Stmt
}

Try-catch statement: try { ... } catch e: Type { ... } finally { ... }

type ChannelExpr added in v1.0.0

type ChannelExpr struct {
	ElemType string // Type of elements in the channel
}

Channel creation: channel[Type]()

type ClassDecl

type ClassDecl struct {
	Name             string
	Parent           string           // parent class name for inheritance
	ParentTypeParams []TypeParam      // parent's generic type parameters (e.g., Container<T> has [T])
	Implements       []string         // interface names
	IsAbstract       bool             // whether the class is abstract
	AccessLevel      string           // "public", "private", "protected"
	IsSealed         bool             // whether the class is sealed
	Permits          []string         // names permitted to inherit
	Fields           []FieldDecl      // class fields
	Methods          []MethodDecl     // class methods
	Constructor      *ConstructorDecl // class constructor
	TypeParams       []TypeParam      // generic type parameters (e.g., [T, K, V])
}

Class declaration with full OOP support

type ConstructorDecl

type ConstructorDecl struct {
	Params []Parameter
	Body   []Stmt
}

Constructor declaration

type ContinueStmt

type ContinueStmt struct{}

type DefStmt

type DefStmt struct {
	Name        string
	Params      []Parameter // updated to support typed and variadic parameters
	Body        []Stmt
	ReturnType  *Type       // Return type using unified type system
	AccessLevel string      // "public", "private", "protected"
	Modifiers   []string    // all modifiers including access level
	TypeParams  []TypeParam // generic type parameters (e.g., [T, K, V])
}

type DeferStmt added in v1.0.0

type DeferStmt struct {
	Call Expr
	Pos  Position
}

Defer statement: defer expr (usually a function call)

type DoLoopStmt added in v1.1.0

type DoLoopStmt struct {
	Condition Expr // required: loop condition
	Body      []Stmt
}

DoLoopStmt represents a do-loop statement (do-while) do ... loop condition

type EnumDecl

type EnumDecl struct {
	Name        string
	AccessLevel string // "public", "private", "protected"
	IsSealed    bool
	Permits     []string
	Values      []EnumValue
	Fields      []FieldDecl      // enum can have fields
	Methods     []MethodDecl     // enum can have methods
	Constructor *ConstructorDecl // enum constructor
}

Enum declaration similar to Java enums

type EnumValue

type EnumValue struct {
	Name string
	Args []Expr // constructor arguments
}

Enum value with optional constructor arguments

type Expr

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

Expr represents an expression.

type ExprStmt

type ExprStmt struct{ X Expr }

func NewExprStmt added in v1.1.4

func NewExprStmt(x Expr) *ExprStmt

NewExprStmt gets an ExprStmt from the pool

type FieldDecl

type FieldDecl struct {
	Name      string
	Type      *Type    // Type annotation using unified type system
	Modifiers []string // public, private, protected, static, final
	InitValue Expr     // optional initial value
}

Field declaration within a class

type FieldExpr

type FieldExpr struct {
	X    Expr
	Name string
}

Field access: obj.field

func NewFieldExpr added in v1.1.4

func NewFieldExpr(x Expr, name string) *FieldExpr

NewFieldExpr gets a FieldExpr from the pool

type ForInStmt

type ForInStmt struct {
	Name     string   // deprecated: use Names for single or multiple vars
	Names    []string // iteration variable names (supports destructuring)
	Iterable Expr
	Where    Expr // optional where clause for filtering
	Body     []Stmt
}

type GenericCallExpr added in v1.0.0

type GenericCallExpr struct {
	Name       string      // Base type name (e.g., "List", "Set", "Map", "Lambda")
	TypeParams []TypeParam // Type parameters (e.g., [TypeParam{Name: "Int"}] for List<Int>)
	Args       []Expr      // Constructor arguments
}

Generic Call: List<Int>(), Map<String, Int>()

type Ident

type Ident struct {
	Name string
}

Identifier

func NewIdent added in v1.1.4

func NewIdent(name string) *Ident

NewIdent gets an Ident from the pool

type IfClause

type IfClause struct {
	Cond Expr
	Body []Stmt
}

type IfStmt

type IfStmt struct {
	Clauses []IfClause
	Else    []Stmt
}

type ImportStmt

type ImportStmt struct {
	Path  []string // e.g., ["math","vector"]
	Names []string // specific symbols to import; if empty, import as namespace (future)
}

Import statement: import path.with.dots { Name, Name2 }

type IndexExpr

type IndexExpr struct {
	X     Expr
	Index Expr
}

Indexing: arr[idx] or map[key]

func NewIndexExpr added in v1.1.4

func NewIndexExpr(x, index Expr) *IndexExpr

NewIndexExpr gets an IndexExpr from the pool

type InstanceOfExpr

type InstanceOfExpr struct {
	Expr     Expr   // the object to check
	TypeName string // the type to check against
	Variable string // optional variable to assign (e.g., "foo" in "10 instanceof int final foo")
	Modifier string // optional modifier like "final"
}

Instance of expression: obj instanceof Type with optional variable assignment

type InterfaceDecl

type InterfaceDecl struct {
	Name        string
	Methods     []MethodSignature
	TypeParams  []TypeParam // generic type parameters (e.g., [T, K, V])
	IsSealed    bool        // whether the interface is sealed
	Permits     []string    // names permitted to implement
	Fields      []FieldDecl // static fields
	AccessLevel string      // "public", "private", "protected"
}

Interface declaration with method signatures

type InterpolatedStringLit

type InterpolatedStringLit struct {
	Parts []Expr // alternating string literals and expressions
}

type LambdaExpr

type LambdaExpr struct {
	Params     []Parameter // updated to support typed and variadic parameters
	Body       Expr        // expression body (single expression)
	BlockBody  []Stmt      // statement block body (multi-line lambda with do...end)
	ReturnType *Type       // Return type using unified type system
	IsBlock    bool        // true if this is a multi-line lambda
}

Lambda expression: (params) => expr or (params) => do ... end

type LetStmt

type LetStmt struct {
	Name      string   // Single variable name (for backward compatibility)
	Names     []string // Multiple variable names for destructuring (e.g., let a, b = [1,2])
	Value     Expr
	Type      *Type    // Type annotation using unified type system
	Modifiers []string // optional modifiers: public/private/protected/static
	Kind      string   // "let", "var", "const", "final"
	Inferred  bool     // true if declared with ':=' (type inference)
}

Statements

func NewLetStmt added in v1.1.4

func NewLetStmt() *LetStmt

NewLetStmt gets a LetStmt from the pool

type LoopStmt

type LoopStmt struct {
	Condition Expr // optional: if nil, infinite loop
	Body      []Stmt
}

LoopStmt represents a loop statement with optional condition loop ... end (infinite loop) loop condition ... end (while-like loop)

type MapEntry added in v1.0.0

type MapEntry struct {
	Key   any
	Value any
}

type MapLit

type MapLit struct{ Pairs []MapPair }

type MapPair

type MapPair struct {
	Key   string
	Value Expr
}

type MethodDecl

type MethodDecl struct {
	Name        string
	Params      []Parameter
	ReturnType  *Type // Return type using unified type system
	Body        []Stmt
	Modifiers   []string // public, private, protected, static, abstract, final
	IsAbstract  bool
	IsOverride  bool         // whether this method is marked with @override
	Annotations []Annotation // annotations like @override, @deprecated, etc.
}

Method declaration within a class

type MethodSignature

type MethodSignature struct {
	Name        string
	Params      []Parameter
	ReturnType  *Type  // Return type using unified type system
	HasDefault  bool   // whether this method has a default implementation
	DefaultBody []Stmt // default implementation body
}

Method signature for interfaces

type NilLit

type NilLit struct{}

func NewNilLit added in v1.1.4

func NewNilLit() *NilLit

NewNilLit gets a NilLit from the pool

type Node

type Node interface {
	// contains filtered or unexported methods
}

Node is the common interface implemented by all AST nodes.

type NumberLit

type NumberLit struct{ Value any } // Can be int or float64

Literals

func GetCommonNumberLit added in v1.1.4

func GetCommonNumberLit(value int) *NumberLit

GetCommonNumberLit returns a pre-allocated NumberLit for common values This reduces allocations for frequently used numbers

func NewNumberLit added in v1.1.4

func NewNumberLit(value any) *NumberLit

NewNumberLit gets a NumberLit from the pool

type Parameter

type Parameter struct {
	Name       string
	Type       *Type // Type annotation using unified type system
	IsVariadic bool  // true if this parameter is variadic (args...)
}

Parameter with optional type annotation

type Position

type Position struct {
	Offset int // 0-based byte offset
	Line   int // 1-based line number
	Col    int // 1-based column number (in runes)
}

Position describes a location in a source file.

type Program

type Program struct {
	Stmts []Stmt
}

Program is the root node for a source file.

type RangeExpr added in v1.0.0

type RangeExpr struct {
	Start     Expr
	End       Expr
	Inclusive bool // true for ..., false for ..
}

RangeExpr represents range expressions like 1...10 or arr[1...3]

type RecordComponent

type RecordComponent struct {
	Name string
	Type *Type // Type annotation using unified type system
}

Record component (immutable field with accessor)

type RecordDecl

type RecordDecl struct {
	Name        string
	AccessLevel string            // "public", "private", "protected"
	Components  []RecordComponent // record components
	Methods     []MethodDecl      // additional methods
}

Record declaration similar to Java records

type ReturnStmt

type ReturnStmt struct{ Value Expr }

func NewReturnStmt added in v1.1.4

func NewReturnStmt(value Expr) *ReturnStmt

NewReturnStmt gets a ReturnStmt from the pool

type SelectCase added in v1.0.0

type SelectCase struct {
	IsRecv  bool   // true for recv case, false for closed case
	RecvVar string // variable name for received value (optional)
	Channel Expr   // channel expression
	Body    []Stmt // statements to execute if this case is selected
}

SelectCase represents a case in a select statement

type SelectStmt added in v1.0.0

type SelectStmt struct {
	Cases []SelectCase
	Pos   Position
}

Select statement for channel operations

type Stmt

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

Stmt represents a statement.

type StringLit

type StringLit struct{ Value string }

func NewStringLit added in v1.1.4

func NewStringLit(value string) *StringLit

NewStringLit gets a StringLit from the pool

type SuperExpr

type SuperExpr struct {
	Args []Expr
}

Super call expression: super(args)

type SwitchCase added in v1.0.0

type SwitchCase struct {
	// For value matching: case value:
	Values []Expr // values to match (can have multiple values per case)

	// For type matching: case (x: Type):
	TypeName string // type name for type matching
	VarName  string // variable name for type matching (optional)

	Body []Stmt // statements to execute if this case matches
}

SwitchCase represents a case in a switch statement

type SwitchStmt added in v1.0.0

type SwitchStmt struct {
	Expr    Expr         // expression to switch on (can be nil for type switches)
	Cases   []SwitchCase // switch cases
	Default []Stmt       // default case body (optional)
	Pos     Position
}

Switch statement for value/type/enum matching

type TernaryExpr

type TernaryExpr struct {
	Condition   Expr
	TrueBranch  Expr
	FalseBranch Expr
}

Ternary expression: condition ? trueBranch : falseBranch

type ThreadJoinExpr

type ThreadJoinExpr struct {
	Thread Expr // thread expression to join
}

type ThreadSpawnExpr

type ThreadSpawnExpr struct {
	Body []Stmt // thread body statements
}

Thread expressions for concurrency

type ThrowStmt

type ThrowStmt struct {
	Value Expr
}

Throw statement: throw expr

type TryStmt

type TryStmt struct {
	Body    []Stmt
	Catches []CatchClause // can have multiple catch clauses
	Finally []Stmt        // optional finally block
}

type Type added in v1.0.0

type Type struct {
	Name        string   // Canonical name of the type (e.g., "bool", "int", "String", "Array")
	Aliases     []string // Alternative names for the type (e.g., ["boolean"] for bool)
	TypeParams  []*Type  // Type parameters for generic types (e.g., [Int] for Array<Int>, [String, Int] for Map<String, Int>)
	UnionTypes  []*Type  // Union type members (e.g., [string, int] for string | int)
	GoParallel  bool     // Whether this type supports parallel operations (optional, defaults to false)
	IsBuiltin   bool     // Whether this is a built-in type
	IsClass     bool     // Whether this is a class type
	IsInterface bool     // Whether this is an interface type
	IsEnum      bool     // Whether this is an enum type
	IsRecord    bool     // Whether this is a record type
	IsUnion     bool     // Whether this is a union type
}

Type represents a type in the Polyloft type system This is used for both built-in types and user-defined types (classes, interfaces, enums, records) It also supports generic/parameterized types like Array<Int>, Map<String, Int> And union types like string | int | null

func GenericType added in v1.0.0

func GenericType(baseType *Type, typeParams ...*Type) *Type

GenericType creates a generic type with type parameters Example: GenericType(arrayType, intType) creates Array<Int> The first parameter is the base type, the rest are type parameters

func GetBuiltinTypes added in v1.0.0

func GetBuiltinTypes() []*Type

GetBuiltinTypes returns all built-in types

func NewType added in v1.1.4

func NewType(name string) *Type

NewType gets a Type from the pool

func ResolveTypeName added in v1.0.0

func ResolveTypeName(typeName string) *Type

ResolveTypeName returns the ast.Type for a given type name string It checks built-in types first, then returns nil if not found Optimized with direct checks for common cases

func TypeFromString added in v1.0.0

func TypeFromString(typeName string) *Type

TypeFromString creates an ast.Type from a string type name This is a compatibility helper for code migration It supports generic type syntax like "Array<Int>", "Map<String, Int>" And union types like "string | int | null"

func (*Type) MatchesType added in v1.0.0

func (t *Type) MatchesType(name string) bool

MatchesType checks if a type name matches this type (checking name and aliases) Optimized with early returns to minimize comparisons

type TypeAliasStmt added in v1.1.0

type TypeAliasStmt struct {
	Name      string   // Alias name (e.g., "Age")
	BaseType  string   // Base type name (e.g., "Int")
	IsFinal   bool     // true if declared with 'final type' (nominal type)
	Modifiers []string // optional modifiers: public/private/protected
}

TypeAliasStmt represents type alias declaration: final type Age = Int

type TypeExpr

type TypeExpr struct {
	Expr Expr // the object to get type of
}

Type expression for Sys.type(obj)

type TypeParam added in v1.0.0

type TypeParam struct {
	IsWildcard   bool     // true if this is a wildcard (?)
	IsVariadic   bool     // true if this is a variadic type parameter (T...)
	Name         string   // Type name for concrete types (e.g., "Int", "String")
	WildcardKind string   // "unbounded", "extends", or "super" for wildcards
	Bounds       []string // Multiple bounds for wildcards (e.g., ["Number", "Comparable"] in "? extends Number & Comparable")
	Variance     string   // "in" (contravariance), "out" (covariance), or "" (invariant)
}

TypeParam represents a type parameter in a generic call, which can be a concrete type or a wildcard

type UnaryExpr

type UnaryExpr struct {
	Op int
	X  Expr
}

Unary and binary

func NewUnaryExpr added in v1.1.4

func NewUnaryExpr(op int, x Expr) *UnaryExpr

NewUnaryExpr gets a UnaryExpr from the pool

Jump to

Keyboard shortcuts

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