expr

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package expr is Kiln's tiny expression evaluator. It exists so the world IR can describe predicates, computed values, and conditions declaratively — without requiring an embedded Go interpreter.

The grammar is a deliberately small subset:

expr     = or
or       = and ("||" and)*
and      = comp ("&&" comp)*
comp     = add (("==" | "!=" | "<" | ">" | "<=" | ">=") add)?
add      = mul (("+" | "-") mul)*
mul      = unary (("*" | "/" | "%") unary)*
unary    = ("!" | "-") unary | postfix
postfix  = primary ("." ident | "[" expr "]" | "(" args? ")")*
primary  = number | string | bool | null | ident | "(" expr ")" | "[" args? "]"

Values are JSON-shaped: int64, float64, string, bool, nil, []any, map[string]any. Built-in functions live in Env (see DefaultEnv); the caller may register more.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrArity = errors.New("expr: wrong number of arguments")
	ErrType  = errors.New("expr: wrong argument type")
)

Sentinel errors built-in functions return for arity / type mistakes.

Functions

func EvalBool

func EvalBool(src string, scope Scope, env *Env) (bool, error)

EvalBool compiles and evaluates src, asserting the result is a bool.

Types

type Env

type Env struct {
	Functions map[string]Func
}

Env holds built-in and user-registered functions.

func DefaultEnv

func DefaultEnv() *Env

DefaultEnv returns the standard built-in function set.

func (*Env) Register

func (e *Env) Register(name string, fn Func)

Register adds or replaces a function in env.

type Expression

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

Expression is a compiled, ready-to-evaluate expression tree.

func Compile

func Compile(src string) (*Expression, error)

Compile parses src into an Expression. The expression can then be Eval'd repeatedly with different scopes.

func (*Expression) Eval

func (e *Expression) Eval(scope Scope, env *Env) (any, error)

Eval evaluates the compiled expression with the given scope and env. A nil env means DefaultEnv. A nil scope means an empty scope.

func (*Expression) Source

func (e *Expression) Source() string

Source returns the original source string the expression was compiled from.

type Func

type Func func(args []any) (any, error)

Func is a user-callable function.

type MapScope

type MapScope map[string]any

MapScope is a Scope backed by a map.

func (MapScope) Lookup

func (m MapScope) Lookup(name string) (any, bool)

Lookup implements Scope.

type Scope

type Scope interface {
	Lookup(name string) (any, bool)
}

Scope resolves named variables to runtime values.

Jump to

Keyboard shortcuts

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