common

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: 4 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Tipos base
	TypeInt      = "int"
	TypeInteger  = "integer"
	TypeFloat    = "float"
	TypeString   = "string"
	TypeBool     = "bool"
	TypeBoolean  = "boolean"
	TypeArray    = "array"
	TypeMap      = "map"
	TypeObject   = "object"
	TypeFunction = "function"
	TypeNil      = "nil"
	TypeNull     = "null"
)

TypeNames contains standard type name constants

Variables

View Source
var (
	KBound = GenericBound{
		Name: ast.Type{Name: "K"},
	}
	VBound = GenericBound{
		Name: ast.Type{Name: "V"},
	}
	TBound = GenericBound{
		Name: ast.Type{Name: "T"},
	}
)
View Source
var (
	BuiltinTypeBool              = Builtin{Name: "__BoolClass__", IsPrimitive: true}
	BuiltinTypeInt               = Builtin{Name: "__IntegerClass__", IsPrimitive: true}
	BuiltinTypeString            = Builtin{Name: "__StringClass__", IsPrimitive: true}
	BuiltinTypeMap               = Builtin{Name: "__MapClass__", IsPrimitive: false}
	BuiltinTypeFloat             = Builtin{Name: "__FloatClass__", IsPrimitive: false}
	BuiltinTypeNumber            = Builtin{Name: "__NumberInterface__", IsPrimitive: true}
	BuiltinTypeArray             = Builtin{Name: "__ArrayClass__", IsPrimitive: false}
	BuiltinTypeGeneric           = Builtin{Name: "__GenericClass__", IsPrimitive: false}
	BuiltinTypeRange             = Builtin{Name: "__RangeClass__", IsPrimitive: false}
	BuiltinTypeList              = Builtin{Name: "__ListClass__", IsPrimitive: false}
	BuiltinTypeSet               = Builtin{Name: "__SetClass__", IsPrimitive: false}
	BuiltinTypeDeque             = Builtin{Name: "__DequeClass__", IsPrimitive: false}
	BuiltinTypePair              = Builtin{Name: "__PairClass__", IsPrimitive: false}
	BuiltinTypeTuple             = Builtin{Name: "__TupleClass__", IsPrimitive: false}
	BuiltinTypeBytes             = Builtin{Name: "__BytesClass__", IsPrimitive: true}
	BuiltinTypePromise           = Builtin{Name: "__PromiseClass__", IsPrimitive: false}
	BuiltinTypeCompletableFuture = Builtin{Name: "__CompletableFutureClass__", IsPrimitive: false}
	BuiltinTypeHttpServer        = Builtin{Name: "__HttpServerClass__", IsPrimitive: false}
	BuiltinTypeHttpRequest       = Builtin{Name: "__HttpRequestClass__", IsPrimitive: false}
	BuiltinTypeHttpResponse      = Builtin{Name: "__HttpResponseClass__", IsPrimitive: false}
	BuiltinTypeChannel           = Builtin{Name: "__ChannelClass__", IsPrimitive: false}
	BuiltinTypeSocket            = Builtin{Name: "__SocketClass__", IsPrimitive: false}
	BuiltinInterfaceIterable     = Builtin{Name: "__IterableInterface__", IsInterface: true}
	BuiltinInterfaceCollection   = Builtin{Name: "__CollectionInterface__", IsInterface: true}
	BuiltinSliceableInterface    = Builtin{Name: "__SliceableInterface__", IsInterface: true}
	BuiltinIndexableInterface    = Builtin{Name: "__IndexableInterface__", IsInterface: true}
	BuiltinInterfaceUnstructured = Builtin{Name: "__UnstructuredInterface__", IsInterface: true}
)
View Source
var ModifierApplicability = map[Modifier][]string{
	ModifierStatic:   {"class", "method", "field", "enum", "record"},
	ModifierAbstract: {"class", "method"},
	ModifierDefault:  {"method"},
	ModifierFinal:    {"class", "method", "field", "variable", "parameter"},
}

ModifierApplicability defines where each modifier can be used

View Source
var ModifierNames = map[Modifier]string{
	ModifierNone:     "none",
	ModifierStatic:   "static",
	ModifierAbstract: "abstract",
	ModifierDefault:  "default",
	ModifierFinal:    "final",
}
View Source
var PrivacyApplicability = map[PrivacyLevel][]string{
	PrivacyPublic:    {"class", "method", "field", "enum", "record"},
	PrivacyPrivate:   {"method", "field", "class"},
	PrivacyProtected: {"method", "field", "class"},
	PrivacyPackage:   {"class", "method", "field", "enum", "record"},
}

PrivacyApplicability defines where each privacy level can be used

View Source
var PrivacyLevelNames = map[PrivacyLevel]string{
	PrivacyPublic:    "public",
	PrivacyPrivate:   "private",
	PrivacyProtected: "protected",
	PrivacyPackage:   "package",
}

Functions

func CanUseModifier

func CanUseModifier(modifier Modifier, context string) bool

CanUseModifier checks if a modifier can be used in a specific context

func CanUsePrivacyLevel

func CanUsePrivacyLevel(privacy PrivacyLevel, context string) bool

CanUsePrivacyLevel checks if a privacy level can be used in a specific context

func ClearBuiltinClassCache added in v1.1.0

func ClearBuiltinClassCache()

ClearBuiltinClassCache clears the cached ClassDef pointers in all builtin types This should be called when ResetGlobalRegistries is called to avoid stale pointer references

func FormatFunctionType added in v1.1.0

func FormatFunctionType(params []ast.Parameter, returnType *ast.Type) string

FormatFunctionType formats a function type as Function<Param1,Param2,...,ReturnType>

func GetType added in v1.0.0

func GetType(val any) *ast.Type

GetType returns the ast.Type for a value

func InferExprType added in v1.0.0

func InferExprType(expr ast.Expr, env *Env) *ast.Type

InferExprType infers the type of an expression

func InferReturnType added in v1.0.0

func InferReturnType(body []ast.Stmt, env *Env) *ast.Type

InferReturnType analyzes function body statements to infer the return type

func IsBuiltinType

func IsBuiltinType(typeName string) bool

IsBuiltinType checks if a type name is a built-in type

func MapToObject added in v1.0.0

func MapToObject(mapInstance *ClassInstance) map[any]any

func NormalizeAnnotationName

func NormalizeAnnotationName(name string) string

NormalizeAnnotationName converts an annotation identifier into its canonical form.

func NormalizeTypeName

func NormalizeTypeName(typeName string) string

NormalizeTypeName normalizes type names to their canonical form

func RegisterAnnotation

func RegisterAnnotation(name string, flags AnnotationFlags)

RegisterAnnotation stores metadata for an annotation in the registry.

Types

type AnnotationFlags

type AnnotationFlags struct {
	IsOverride bool // marks methods that should override a parent implementation
}

AnnotationFlags captures semantic toggles associated with annotations.

func (AnnotationFlags) Merge

Merge combines two sets of annotation flags.

type AnnotationInfo

type AnnotationInfo struct {
	Name  string
	Flags AnnotationFlags
}

AnnotationInfo describes a registered annotation and its semantic flags.

func LookupAnnotation

func LookupAnnotation(name string) (AnnotationInfo, bool)

LookupAnnotation resolves annotation metadata by name, returning whether it is known.

type ArityError

type ArityError struct {
	Expected int
	Got      int
}

ArityError represents an arity mismatch error

func (ArityError) Error

func (e ArityError) Error() string

type BreakSentinel

type BreakSentinel struct{}

Sentinel types for control flow

type Builtin added in v1.0.0

type Builtin struct {
	Name        string
	IsClass     bool
	IsInterface bool
	IsEnum      bool
	IsRecord    bool
	IsPrimitive bool
	IsFunction  bool
	// Cached definitions to avoid repeated env lookups
	ClassDef     *ClassDefinition
	TypeDef      *ast.Type
	InterfaceDef *InterfaceDefinition
	EnumDef      *EnumDefinition
	RecordDef    *RecordDefinition
	FunctionDef  *FunctionDefinition
}

func (*Builtin) GetClassDefinition added in v1.0.0

func (bt *Builtin) GetClassDefinition(env *Env) *ClassDefinition

func (*Builtin) GetConstructor added in v1.1.0

func (bt *Builtin) GetConstructor(env *Env) *ClassConstructor

func (*Builtin) GetEnumDefinition added in v1.0.0

func (bt *Builtin) GetEnumDefinition(env *Env) *EnumDefinition

func (*Builtin) GetFunctionDefinition added in v1.0.0

func (bt *Builtin) GetFunctionDefinition(env *Env) *FunctionDefinition

func (*Builtin) GetInterfaceDefinition added in v1.0.0

func (bt *Builtin) GetInterfaceDefinition(env *Env) *InterfaceDefinition

func (*Builtin) GetRecordDefinition added in v1.0.0

func (bt *Builtin) GetRecordDefinition(env *Env) *RecordDefinition

func (*Builtin) GetTypeDefinition added in v1.0.0

func (bt *Builtin) GetTypeDefinition(env *Env) *ast.Type

type Channel added in v1.0.0

type Channel struct {
	Ch chan any // Exported for reflection in select
	// contains filtered or unexported fields
}

Channel represents a communication channel for concurrent operations

func NewChannel added in v1.0.0

func NewChannel(bufferSize int) *Channel

NewChannel creates a new channel with optional buffer size

func (*Channel) Close added in v1.0.0

func (c *Channel) Close()

Close closes the channel

func (*Channel) IsClosed added in v1.0.0

func (c *Channel) IsClosed() bool

IsClosed returns whether the channel is closed

func (*Channel) Recv added in v1.0.0

func (c *Channel) Recv() (any, bool)

Recv receives a value from the channel

func (*Channel) Send added in v1.0.0

func (c *Channel) Send(value any) error

Send sends a value to the channel

type ClassConstructor

type ClassConstructor struct {
	Definition *ClassDefinition
	Func       Func
}

ClassConstructor wraps a class constructor function with metadata This allows Sys.type to identify and format class names properly

type ClassDefinition

type ClassDefinition struct {
	Name         string
	Aliases      []string
	Type         *ast.Type // Unified type representation
	Parent       *ClassDefinition
	Implements   []*InterfaceDefinition // Changed from []string to proper references
	IsAbstract   bool
	AccessLevel  string // "public", "private", "protected"
	IsSealed     bool
	Permits      []*ClassDefinition     // Resolved permits (lazy resolution)
	PermitNames  []PrebuildedDefinition // Unresolved permits (stored at declaration time)
	FileName     string                 // file where class is defined
	PackageName  string                 // package/directory where class is defined
	Fields       map[string]FieldInfo
	Methods      map[string][]MethodInfo // Support overloading: multiple methods with same name
	Constructors []ConstructorInfo       // Support overloading: multiple constructors
	StaticFields map[string]any
	// Generic type support
	TypeParams []GenericType // Generic type parameters (e.g., [T, E extends Comparable])
	IsGeneric  bool          // Whether this class is generic
	// Pre-bound method templates for faster instantiation
	// Maps method name to pre-compiled method function
	MethodTemplates map[string]Func // Cached method templates (created once, reused for all instances)
}

ClassDefinition represents a class definition

func (*ClassDefinition) GetMethods added in v1.1.0

func (classDef *ClassDefinition) GetMethods(name string) []MethodInfo

func (*ClassDefinition) ImplementsInterface added in v1.1.0

func (classDef *ClassDefinition) ImplementsInterface(iface *InterfaceDefinition) bool

func (*ClassDefinition) IsSubclassOf added in v1.1.0

func (classDef *ClassDefinition) IsSubclassOf(other *ClassDefinition) bool

type ClassInstance

type ClassInstance struct {
	ClassName    string
	Fields       map[string]any
	Methods      map[string]Func
	ParentClass  *ClassDefinition
	GenericTypes []GenericType
	// Method lookup cache - speeds up repeated method calls by 2-3x
	MethodCache map[string]Func // Caches resolved method functions
}

ClassInstance represents an instance of a class

type ConstructorInfo

type ConstructorInfo struct {
	Params      []ast.Parameter
	Body        []ast.Stmt
	BuiltinImpl Func // Optional builtin implementation
}

ConstructorInfo contains constructor metadata

func SelectConstructorOverload added in v1.1.0

func SelectConstructorOverload(constructors []ConstructorInfo, argCount int) *ConstructorInfo

SelectConstructorOverload selects the appropriate constructor based on argument count. Returns the matching constructor or nil if no match found.

type ContinueSentinel

type ContinueSentinel struct{}

type EnumConstructor

type EnumConstructor struct {
	Definition *EnumDefinition
	EnumObject map[string]any
}

EnumConstructor wraps an enum object with metadata This allows Sys.type to identify and format enum names properly

type EnumDefinition

type EnumDefinition struct {
	Name         string
	Type         *ast.Type // Unified type representation
	AccessLevel  string
	FileName     string
	PackageName  string
	Methods      map[string][]MethodInfo // Support overloading: multiple methods with same name
	Values       map[string]*EnumValueInstance
	Fields       map[string]FieldInfo
	Constructors []ConstructorInfo // Support overloading: multiple constructors
	IsSealed     bool
	Permits      []*ClassDefinition     // Resolved permits (lazy resolution)
	PermitNames  []PrebuildedDefinition // Unresolved permits (stored at declaration time)
}

EnumDefinition represents an enum declaration

type EnumValueInstance

type EnumValueInstance struct {
	Definition *EnumDefinition
	Name       string
	Ordinal    int
	Fields     map[string]any
	Methods    map[string]Func
}

EnumValueInstance represents a single enum constant instance

type Env

type Env struct {
	Parent           *Env
	Vars             map[string]any
	Consts           map[string]bool
	Finals           map[string]bool
	Defers           []func() error      // stack of deferred calls (LIFO)
	FileName         string              // current file being executed
	PackageName      string              // current package/directory
	CurrentLine      int                 // current line number being executed (1-based)
	CurrentColumn    int                 // current column number being executed (1-based)
	CodeContext      []string            // context lines: [line-2, line-1, current line]
	SourceLines      []string            // all source lines (for hint generation)
	PositionStack    []PositionInfo      // stack of positions for better stack traces
	ImportedClasses  map[string]string   // className -> packageName, tracks imported classes
	ImportedPackages map[string]struct{} // packageName -> struct{}, tracks imported packages

	// Fast variable slots for common loop variables (0-9 represent i, j, k, etc.)
	// Uses array access instead of map lookup for ~2-3x faster access
	FastSlots [10]any        // Indexed slots for common variables
	SlotMap   map[string]int // Maps variable name to slot index (empty when not using slots)
}

Env is a simple lexical environment for variables and functions.

func NewEnv

func NewEnv() *Env

NewEnv creates a new environment

func NewEnvWithContext

func NewEnvWithContext(fileName, packageName string) *Env

NewEnvWithContext creates a new environment with file and package context

func (*Env) Child

func (e *Env) Child() *Env

Child creates a child environment

func (*Env) Define

func (e *Env) Define(k string, v any, kind string)

Define defines a new variable, optionally as a constant

func (*Env) EnableFastSlots added in v1.1.4

func (e *Env) EnableFastSlots()

EnableFastSlots initializes slot mapping for fast variable access

func (*Env) Get

func (e *Env) Get(k string) (any, bool)

Get retrieves a variable from the environment chain

func (*Env) GetCodeContext

func (e *Env) GetCodeContext() []string

GetCodeContext returns the code context (previous 2 lines + current line)

func (*Env) GetCurrentLine

func (e *Env) GetCurrentLine() int

GetCurrentLine returns the current line number being executed

func (*Env) GetCurrentPosition added in v1.0.0

func (e *Env) GetCurrentPosition() PositionInfo

GetCurrentPosition returns the current position info

func (*Env) GetFileName

func (e *Env) GetFileName() string

GetFileName returns the current file name

func (*Env) GetPackageName

func (e *Env) GetPackageName() string

GetPackageName returns the current package name

func (*Env) GetRoot added in v1.1.10

func (e *Env) GetRoot() *Env

GetRoot returns the root environment (the one without a parent)

func (*Env) GetSourceLines

func (e *Env) GetSourceLines() []string

GetSourceLines returns all source lines

func (*Env) PopPosition added in v1.0.0

func (e *Env) PopPosition()

PopPosition removes the last position from the stack

func (*Env) PushPosition added in v1.0.0

func (e *Env) PushPosition(file string, line, column int)

PushPosition adds a position to the stack for better error tracking

func (*Env) Set

func (e *Env) Set(k string, v any)

func (*Env) SetCurrentLine

func (e *Env) SetCurrentLine(line int, sourceLines []string)

SetCurrentLine updates the current line number and code context

func (*Env) SetSourceLines

func (e *Env) SetSourceLines(lines []string)

SetSourceLines sets the source lines for this environment

func (*Env) This added in v1.1.0

func (e *Env) This() (any, bool)

func (*Env) UpdateCurrentLine

func (e *Env) UpdateCurrentLine(line int)

UpdateCurrentLine updates just the line number without updating context Useful when context is not available or not needed

type FieldInfo

type FieldInfo struct {
	Name      string
	Type      *ast.Type // Type using unified type system
	Modifiers []string
	InitValue any
	IsStatic  bool
	IsPrivate bool
}

FieldInfo contains field metadata

type Func

type Func func(env *Env, args []any) (any, error)

Func represents a Polyloft function that can be called from the engine This is the canonical function type used throughout the system

func ExtractFunc added in v1.0.0

func ExtractFunc(val any) (Func, bool)

ExtractFunc extracts a Func from various function-like wrappers

type FunctionDefinition added in v0.2.0

type FunctionDefinition struct {
	Name        string
	Func        Func
	Params      []ast.Parameter // Function parameters with types
	ReturnType  *ast.Type       // Return type (can be inferred)
	AccessLevel string          // "public", "private", "protected"
	Modifiers   []string
	FileName    string // file where function is defined
	PackageName string // package/directory where function is defined
}

FunctionDefinition represents a top-level function with metadata

type GenericBound added in v1.1.0

type GenericBound struct {
	Name       ast.Type
	Variance   string // "in" (contravariance), "out" (covariance), or "" (invariant)
	IsVariadic bool
	Extends    *ClassDefinition
	Implements *InterfaceDefinition
}

func (*GenericBound) AsGenericType added in v1.1.0

func (g *GenericBound) AsGenericType() *GenericType

type GenericType added in v1.0.0

type GenericType struct {
	Bounds []GenericBound
}

GenericType represents a generic type parameter (like T, E, K, V)

func InferCollectionType added in v1.1.0

func InferCollectionType(items []*ClassInstance) *GenericType

func InferMapType added in v1.1.0

func InferMapType(items map[*ClassInstance]*ClassInstance) *GenericType

func (*GenericType) AsArray added in v1.1.0

func (gt *GenericType) AsArray() []GenericType

func (*GenericType) Matchs added in v1.1.0

func (gt *GenericType) Matchs(t *ast.Type) bool

type IndexError

type IndexError struct {
	Index int
	Size  int
}

IndexError represents an index out of range error

func (IndexError) Error

func (e IndexError) Error() string

type InterfaceDefinition

type InterfaceDefinition struct {
	Name         string
	Type         *ast.Type                    // Unified type representation
	Methods      map[string][]MethodSignature // Support overloading: multiple methods with same name
	IsSealed     bool
	Permits      []*ClassDefinition     // Resolved permits (lazy resolution)
	PermitNames  []PrebuildedDefinition // Unresolved permits (stored at declaration time)
	StaticFields map[string]any
	AccessLevel  string
	FileName     string // file where interface is defined
	PackageName  string // package/directory where interface is defined
}

Interface definition

type LambdaDefinition added in v1.0.0

type LambdaDefinition struct {
	Func       Func            // The actual lambda function
	Params     []ast.Parameter // Lambda parameters with types
	ReturnType *ast.Type       // Return type (can be inferred)
}

LambdaDefinition represents a lambda expression with type information

type MethodInfo

type MethodInfo struct {
	Name        string
	Params      []ast.Parameter
	ReturnType  *ast.Type // Return type using unified type system
	Body        []ast.Stmt
	Modifiers   []string
	IsAbstract  bool
	IsStatic    bool
	IsPrivate   bool
	BuiltinImpl Func // Optional builtin implementation
}

MethodInfo contains method metadata

func SelectMethodOverload added in v1.1.0

func SelectMethodOverload(methods []MethodInfo, argCount int) *MethodInfo

type MethodSignature

type MethodSignature struct {
	Name        string
	Params      []ast.Parameter
	ReturnType  *ast.Type // Return type using unified type system
	HasDefault  bool
	DefaultBody []ast.Stmt
}

MethodSignature for interface methods

type Modifier

type Modifier int

Modifier represents different modifiers that can be applied to declarations

const (
	ModifierNone Modifier = iota
	ModifierStatic
	ModifierAbstract
	ModifierDefault
	ModifierFinal
)

type ParameterInfo

type ParameterInfo = ast.Parameter

ParameterInfo contains parameter metadata - DEPRECATED: Use ast.Parameter instead

type PositionInfo added in v1.0.0

type PositionInfo struct {
	File   string
	Line   int
	Column int
}

PositionInfo holds position information for stack traces

type PrebuildedDefinition added in v1.0.0

type PrebuildedDefinition struct {
	Name        string
	PackageName string
}

PrebuildedDefinition represents a forward reference to a class or interface Used for permits declarations where the target may not be defined yet

type PrivacyLevel

type PrivacyLevel int

PrivacyLevel represents visibility/access levels

const (
	PrivacyPublic PrivacyLevel = iota
	PrivacyPrivate
	PrivacyProtected
	PrivacyPackage // default package visibility
)

type RecordDefinition

type RecordDefinition struct {
	Name        string
	Type        *ast.Type // Unified type representation
	AccessLevel string
	FileName    string
	PackageName string
	Components  []ast.RecordComponent
	Methods     map[string][]MethodInfo // Support overloading: multiple methods with same name
}

RecordDefinition represents a record declaration

type RecordInstance

type RecordInstance struct {
	Definition *RecordDefinition
	Values     map[string]any
	Methods    map[string]Func
}

RecordInstance represents an instance of a record

type RuntimeError

type RuntimeError struct {
	Message string
	Context string
}

RuntimeError represents a runtime error with more context

func (RuntimeError) Error

func (e RuntimeError) Error() string

type TypeError

type TypeError struct {
	Message string
}

TypeError represents a type error in Polyloft operations

func (TypeError) Error

func (e TypeError) Error() string

type UndefinedError

type UndefinedError struct {
	Name string
}

UndefinedError represents an undefined identifier error

func (UndefinedError) Error

func (e UndefinedError) Error() string

type VarKind

type VarKind string

VarKind represents variable declaration kinds

const (
	VarKindLet   VarKind = "let"
	VarKindVar   VarKind = "var"
	VarKindConst VarKind = "const"
)

Jump to

Keyboard shortcuts

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