Skip to content

Latest commit

 

History

History
453 lines (319 loc) · 9.43 KB

File metadata and controls

453 lines (319 loc) · 9.43 KB

API Reference

This reference covers every exported package symbol. Signatures are abbreviated only where the linked type is already defined in the same section.

Package

import expressionlanguage "github.com/lemric/expression-language-go"

The declared package name is expressionlanguage.

Language

type Language

Language owns the function registry and parsed-expression cache.

func New(options ...Option) *Language

Creates a language with constant, enum, min, max, and count built-ins and a concurrency-safe in-memory cache.

func (l *Language) Evaluate(expression Expression, variables Variables) (any, error)

Parses if necessary and evaluates an expression with identity-mapped variable names.

func (l *Language) Compile(expression Expression, names Names) (Program, error)

Parses if necessary and returns a reusable executable program.

func (l *Language) Parse(expression Expression, names Names, flags ParseFlags) (*ParsedExpression, error)

Returns a parsed expression, using the configured cache.

func (l *Language) Lint(expression Expression, names Names, flags ParseFlags) error

Validates an expression without retaining the AST.

func (l *Language) Register(name string, compiler FunctionCompiler, evaluator FunctionEvaluator) error
func (l *Language) AddFunction(function Function) error
func (l *Language) RegisterProvider(provider FunctionProvider) error

Mutate the function registry before first use. They return ErrFunctionsLocked after the registry is frozen.

Expressions and programs

type Expression

type Expression interface {
	// contains an unexported method
}

The accepted implementations are Source and *ParsedExpression. The unexported method intentionally prevents unrelated types from accidentally claiming to be expression inputs.

type Source

type Source string

Represents unparsed source.

func Expr(source string) Source

Creates a source expression with readable call-site intent.

type ParsedExpression

func NewParsedExpression(source string, node Node) *ParsedExpression
func (e *ParsedExpression) Source() string
func (e *ParsedExpression) Node() Node
func (e *ParsedExpression) MarshalBinary() ([]byte, error)

Contains original source and an AST root. MarshalBinary serializes both.

type Program

type Program func(Variables) (any, error)

A reusable compiled expression.

Variables, names, and values

type Variables

type Variables map[string]any

Contains runtime values keyed by host-side names.

type Names

type Names map[string]string

Maps host-side variable names to names visible in expressions. For example, Names{"receiver": "this"} exposes this and reads its runtime value from the receiver key.

type OrderedMap

type OrderedMap []OrderedMapEntry

type OrderedMapEntry struct {
	Key   any
	Value any
}

Represents insertion-ordered key/value data for indexing, property access, membership, dumps, evaluation, and serialization.

type Object

type Object interface {
	GetProperty(name string) (any, bool)
	CallMethod(name string, arguments []any) (any, error)
}

Provides explicit property and method access.

type Indexable

type Indexable interface {
	GetIndex(key any) (any, bool)
}

Provides custom bracket access.

type EnumCase

type EnumCase interface {
	EnumCase()
}

Marks values that the enum built-in may return.

Configuration

type Option

type Option func(*Language)

Options configure a language during New.

func WithCache(cache Cache) Option

Replaces the default parsed-expression cache. A nil cache is ignored.

func WithConstants(constants map[string]any) Option

Installs values used by constant and enum.

func WithProviders(providers ...FunctionProvider) Option

Registers providers in argument order.

func WithProviderSequence(providers iter.Seq[FunctionProvider]) Option

Registers providers yielded by a standard Go iterator.

Caching

type Cache

type Cache interface {
	Get(key string) (*ParsedExpression, bool, error)
	Set(key string, expression *ParsedExpression) error
}

Stores parsed expressions under opaque keys. Custom implementations must supply their own synchronization when shared.

Functions

type FunctionCompiler

type FunctionCompiler func(arguments []Program) (Program, error)

Builds a reusable function program from compiled argument programs.

type FunctionEvaluator

type FunctionEvaluator func(Variables, []any) (any, error)

Evaluates a function with runtime variables and evaluated arguments.

type Function

func NewFunction(name string, compiler FunctionCompiler, evaluator FunctionEvaluator) (Function, error)
func (f Function) Name() string
func (f Function) Compiler() FunctionCompiler
func (f Function) Evaluator() FunctionEvaluator

A validated immutable expression function definition.

type Functions

type Functions map[string]Function

A function registry keyed by expression-visible name. It is accepted by direct node evaluation and compilation and by NewParser.

type FunctionProvider

type FunctionProvider interface {
	Functions() []Function
}

Supplies a related group of function definitions.

Lexer and tokens

type Lexer

func NewLexer() *Lexer
func (l *Lexer) Tokenize(source string) (*TokenStream, error)

Tokenizes and validates lexical structure, bracket matching, strings, numbers, comments, names, operators, and punctuation.

type TokenType

type TokenType string

Token kinds:

const (
	TokenEOF         TokenType = "end of expression"
	TokenName        TokenType = "name"
	TokenNumber      TokenType = "number"
	TokenString      TokenType = "string"
	TokenOperator    TokenType = "operator"
	TokenPunctuation TokenType = "punctuation"
)

type Token

type Token struct {
	Type     TokenType
	Value    any
	Position int
}

func (t Token) Is(tokenType TokenType, value any) bool
func (t Token) String() string

Position identifies the one-based source location for normal lexer output. Is compares type and optionally value.

type TokenStream

func NewTokenStream(tokens []Token, expression string) *TokenStream
func (s *TokenStream) Tokens() []Token
func (s *TokenStream) Expression() string
func (s *TokenStream) Next() error
func (s *TokenStream) Expect(tokenType TokenType, value any, message string) error
func (s *TokenStream) EOF() bool

A mutable token cursor. Tokens returns a public copy of the token slice.

Parser

type Parser

func NewParser(functions Functions) *Parser
func (p *Parser) Parse(stream *TokenStream, names Names, flags ParseFlags) (Node, error)
func (p *Parser) Lint(stream *TokenStream, names Names, flags ParseFlags) error

NewParser clones the supplied function registry. Parsing consumes the token stream cursor.

type ParseFlags

type ParseFlags uint8

const (
	IgnoreUnknownVariables ParseFlags = 1 << iota
	IgnoreUnknownFunctions
)

Flags relax semantic symbol validation and can be combined with bitwise OR.

Nodes

type Node

type Node interface {
	Compile(Functions) (Program, error)
	Evaluate(Functions, Variables) (any, error)
	Dump() string
}

The public AST contract.

type ArrayElement

type ArrayElement struct {
	Key   Node
	Value Node
}

A nil Key denotes an implicit numeric array position.

Node constructors

func NewConstant(value any) Node
func NewIdentifierConstant(value string) Node
func NewName(name string) Node
func NewNullCoalescedName(name string) Node
func NewUnary(operator string, operand Node) Node
func NewBinary(operator string, left, right Node) Node
func NewArray(elements ...ArrayElement) Node
func NewArguments(arguments ...Node) Node
func NewArgumentsElements(elements ...ArrayElement) Node
func NewSequence(nodes ...Node) Node
func NewConditional(condition, whenTrue, whenFalse Node) Node
func NewFunctionCall(name string, arguments ...Node) Node
func NewGetAttr(receiver, attribute Node, arguments []Node, kind AccessKind, nullSafe bool) Node
func NewNullCoalesce(left, right Node) Node

NewIdentifierConstant creates an unquoted static attribute identifier for manually built property and method nodes. NewArguments and NewArgumentsElements create argument-list nodes used by direct AST tooling.

type AccessKind

type AccessKind uint8

const (
	AccessProperty AccessKind = iota + 1
	AccessMethod
	AccessIndex
)

Selects property, method, or bracket behavior for NewGetAttr.

Serialization

func MarshalNode(node Node) ([]byte, error)
func UnmarshalNode(data []byte) (Node, error)
func UnmarshalParsedExpression(data []byte) (*ParsedExpression, error)

MarshalNode and UnmarshalNode encode and decode one AST. A parsed expression is encoded with (*ParsedExpression).MarshalBinary and restored with UnmarshalParsedExpression.

Errors

type SyntaxError

type SyntaxError struct {
	Message    string
	Position   int
	Expression string
}

func (e *SyntaxError) Error() string

Reports lexical or syntactic failures and selected syntax-level evaluation errors such as malformed regular expressions.

ErrFunctionsLocked

var ErrFunctionsLocked error

Reports an attempt to mutate the function registry after the language has been used.