feel

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package feel adapts the FEEL implementation Verdict embeds (github.com/pbinitiative/feel) to the shape the DMN evaluator needs: a compile cache, unary-test evaluation with `?` bound, dialect gating between S-FEEL and full FEEL, a namespaced extension point for application function libraries, and lossless conversion between FEEL values and plain Go values.

Everything the rest of Verdict does with expressions goes through this package, so swapping the underlying evaluator is a single-package change.

Index

Constants

View Source
const DefaultMaxIterations = 1_000_000

DefaultMaxIterations is the iteration budget when no other is configured — of one expression evaluation under Eval, of every evaluation sharing a Budget (the engine's one per request): the total number of elements every iteration context of every `for`, `some` and `every` may produce — integer ranges (`a..b`) and list domains alike, with nested and multi-context products (`for i in 1..n, j in 1..n`) counted in full.

A million is far beyond what a decision model iterates on purpose — a day-by-day loop over a century is under 40,000 — while bounding the work and the lists a single expression can build to roughly a hundred megabytes. Without a budget one request to a model loaded through `verdict serve` could ask for a billion elements and exhaust the server's memory.

Variables

View Source
var ErrIterationBudgetExceeded = errors.New("feel: iteration exceeds the configured budget")

ErrIterationBudgetExceeded is matched by errors.Is when an evaluation's iteration contexts would together produce more elements than the configured budget (WithMaxIterations) — or than remain in the shared Budget it draws on.

View Source
var ErrNamespaceRequired = errors.New("feel: a function library must declare a namespace that is not a built-in name")

ErrNamespaceRequired is returned when a function library omits its namespace or claims one that would collide with a standard built-in.

View Source
var Null = &pfeel.NullValue{}

Null is the FEEL null value. It is distinct from a missing binding: a name bound to Null exists and evaluates to null, whereas an unbound name raises an evaluation error.

Functions

func Aggregate added in v0.4.0

func Aggregate(name string, list []any) (result any, ok bool)

Aggregate applies the DMN 1.5 §10.3.4.4 list aggregate name (count, min, max, sum, product, mean, median, stddev or mode) to a list of FEEL values, exactly as the FEEL built-in of that name does: a list outside the function's domain gives Null, never an error. ok is false only for an unknown name. It is the door a decision table's COLLECT aggregation, which §10.3.2.10 defines through these built-ins, uses into them.

func Compare

func Compare(a, b any) (int, bool)

Compare orders two FEEL values as FEEL's `<` does, reporting ok=false when FEEL defines no order between them. Numbers, strings, durations of one kind, times, and dates with date and times are ordered (DMN 1.5 Table 54); booleans, lists, contexts, ranges and functions are not, nor is any pair of different kinds or a null operand (§10.3.2.15). This is the ordering FEEL's min and max use, so COLLECT MIN/MAX agree with them, and the analyser picks its witnesses by it too.

func Equal

func Equal(a, b any) bool

Equal reports whether a = b is true in FEEL (DMN 1.5 §10.3.2.15, Tables 52 and 53). It is the fork's `=` with a null verdict folded to false, so it cannot disagree with an `=` in an expression: 1 and 1.00 are equal, as are two temporals denoting the same instant and PT60M and PT1H, while values of different kinds are not. Two nulls are equal. The ANY hit policy, PRIORITY and OUTPUT ORDER ranking, `duplicate values` and the analyser use it.

func FromGo

func FromGo(v any) any

FromGo converts a plain Go value into the representation the embedded evaluator expects. Numbers become arbitrary-precision FEEL numbers, times become FEEL date-and-times, durations become FEEL day/time durations, and maps and slices are converted element-wise. Values that are already FEEL values pass through untouched.

Structs and named map/slice types are converted through their reflected shape rather than through JSON, so a time.Time nested inside a struct keeps its type instead of degrading to a string.

func IsIrrelevant

func IsIrrelevant(text string) bool

IsIrrelevant reports whether a decision-table input entry means "any value". DMN spells this "-"; several exporters emit an empty cell instead, and dmn-js writes the Unicode dashes when a modeller types them.

func IsNull

func IsNull(v any) bool

IsNull reports whether v is the FEEL null in either its FEEL or Go spelling.

func IsNumber

func IsNumber(v any) bool

IsNumber reports whether v is a FEEL number.

func IsTemporal

func IsTemporal(v any) bool

IsTemporal reports whether v is a FEEL date, time or date-and-time.

func KeyOf added in v0.4.0

func KeyOf(v any) (string, bool)

KeyOf renders v as a string that identifies it as a FEEL value: two values get the same key only if they are the same kind and print the same lexical form. Every scalar is tagged with its kind, so a string never meets a number or a temporal that prints alike, a date never meets the midnight date and time of that day, and a zoneless date and time never meets the same wall clock at UTC (its lexical form has no `Z`). Numbers use their exact decimal form. Values with no deterministic rendering (functions, unknown Go types) report ok=false, so a caller using the key as a cache key can decline to cache rather than risk a wrong hit.

Two equal FEEL values can still get different keys (`1` and `1.0`, the same instant at two offsets); that costs a cache miss, never a wrong answer.

func NewFunctionValue

func NewFunctionValue(f Function) any

NewFunctionValue turns a Function into a value that can be bound into a scope and then called from FEEL. The evaluator uses it to expose business knowledge models as ordinary FEEL functions, which is what lets a literal expression call a BKM by name exactly as DMN specifies.

func NumberOffset

func NumberOffset(v any, delta int64) any

NumberOffset steps a number by a whole unit, returning v unchanged when it is not a number. Static analysis uses it to probe just either side of a threshold, which is what distinguishes `>= 10` from `> 10`.

func ParseTemporal

func ParseTemporal(s, want string) (any, error)

ParseTemporal parses a temporal literal into the requested FEEL type. It backs agent-response coercion, where a model answers a date-typed decision with a string.

func SortValues

func SortValues(vs []any)

SortValues sorts a list of FEEL values in ascending order, leaving values it cannot compare in their original relative position.

func SplitList

func SplitList(list string) []string

SplitList splits a comma-separated FEEL list — a decision table's inputValues or outputValues attribute — into its elements, ignoring commas inside string literals and nested brackets.

func TemporalOffset

func TemporalOffset(v any, d time.Duration) any

TemporalOffset shifts a date or date-and-time by d, returning v unchanged when it is neither. A date and time keeps its offset, or its lack of one, so a probe beside a zoneless boundary is zoneless too.

func ToGo

func ToGo(v any) any

ToGo converts a FEEL value into the plain Go value Verdict hands to the outside world: Result.Outputs, every trace node, an agent's Request.Inputs, and so every JSON surface built on them (MCP, Twirp, the CLI, Nexus). It is the one boundary conversion, so every one of those surfaces shows a value the same way.

Numbers become float64. Every temporal and both duration kinds become their FEEL lexical string, so the value says what kind it is and keeps its zone-ness: a date is "2024-03-05", a time "10:00:00" (or "10:00:00Z", "10:00:00+02:00"), a date and time "2024-03-05T10:00:00" when zoneless and "...Z", "...+02:00" or "...@Europe/Paris" when zoned, and a duration "P1DT2H" or "P1Y2M". Each string parses back to the same FEEL value through date(), time(), date and time() or duration(). Null becomes nil, and contexts and lists are converted element-wise.

FEEL numbers carry more precision than a float64 can hold. ToGo is the interop boundary, not the arithmetic one — every calculation happens in full precision inside the evaluator and only the final value is narrowed here.

func TypeName

func TypeName(v any) string

TypeName reports the FEEL type name of a value, for type-violation messages.

Types

type Budget added in v0.3.0

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

Budget is an iteration budget shared by several evaluations. Pass one to EvalBudget / EvalUnaryTestBudget and every element any of those evaluations' `for`, `some` and `every` contexts produce is drawn from it — including evaluations nested inside a function call (a business knowledge model invoked from FEEL) and evaluations on other goroutines. The engine creates one per request, which is what stops `for i in 1..1000 return bkm(i)` from multiplying the budget by the number of calls. It is safe for concurrent use and takes no lock.

func (*Budget) Limit added in v0.3.0

func (b *Budget) Limit() int64

Limit reports the elements the budget admits in total.

func (*Budget) Used added in v0.3.0

func (b *Budget) Used() int64

Used reports the elements charged against the budget so far.

type CompileError

type CompileError struct {
	Text    string
	Dialect Dialect
	Reason  string
	Err     error
}

CompileError reports an expression that failed to parse or that used a construct the active dialect forbids.

func (*CompileError) Error

func (e *CompileError) Error() string

func (*CompileError) Unwrap

func (e *CompileError) Unwrap() error

type Compiler

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

Compiler parses and caches FEEL expressions for one dialect. A Compiler is safe for concurrent use and is normally shared for the lifetime of an Engine.

func NewCompiler

func NewCompiler(d Dialect) *Compiler

NewCompiler returns a compiler for the given dialect.

func (*Compiler) Compile

func (c *Compiler) Compile(text string) (*Expr, error)

Compile parses text, memoising both successes and failures so a decision table with a hot cell pays the parse cost once per process.

func (*Compiler) CompileUnaryTest

func (c *Compiler) CompileUnaryTest(text string) (*UnaryTest, error)

CompileUnaryTest parses a decision-table input entry.

An empty entry, or the irrelevance marker "-", compiles to nil, which the evaluator treats as an unconditional match.

func (*Compiler) Dialect

func (c *Compiler) Dialect() Dialect

Dialect reports the compiler's dialect.

type Dialect

type Dialect int

Dialect selects the accepted expression grammar.

const (
	// FEEL is the full DMN Conformance Level 3 dialect.
	FEEL Dialect = iota
	// SFEEL is the Conformance Level 2 subset: literals, arithmetic,
	// comparisons, ranges, lists, conjunctions and qualified names. Iteration,
	// conditionals and inline function definitions are rejected at compile time.
	SFEEL
)

func (Dialect) String

func (d Dialect) String() string

type EvalError

type EvalError struct {
	Text string
	Err  error
}

EvalError wraps a runtime failure with the expression that produced it.

func (*EvalError) Error

func (e *EvalError) Error() string

func (*EvalError) Is added in v0.2.0

func (e *EvalError) Is(target error) bool

Is lets errors.Is match ErrIterationBudgetExceeded without exposing the vendored evaluator's own error type.

func (*EvalError) Unwrap

func (e *EvalError) Unwrap() error

type Evaluator

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

Evaluator compiles and evaluates FEEL against a scope stack. It is safe for concurrent use: each evaluation gets its own interpreter and the shared state (compile cache, global scope) is read-only after construction.

func NewEvaluator

func NewEvaluator(d Dialect, opts ...Option) (*Evaluator, error)

NewEvaluator builds an evaluator for a dialect, layering the DMN 1.5 standard library supplement beneath any application function libraries.

func (*Evaluator) Compile

func (e *Evaluator) Compile(text string) (*Expr, error)

Compile parses text under the evaluator's dialect.

func (*Evaluator) CompileUnaryTest

func (e *Evaluator) CompileUnaryTest(text string) (*UnaryTest, error)

CompileUnaryTest parses a decision-table input entry.

func (*Evaluator) Compiler

func (e *Evaluator) Compiler() *Compiler

Compiler exposes the evaluator's compile cache so callers can pre-compile and validate expressions at model-load time.

func (*Evaluator) Dialect

func (e *Evaluator) Dialect() Dialect

Dialect reports the evaluator's dialect.

func (*Evaluator) Eval

func (e *Evaluator) Eval(x *Expr, vars map[string]any) (any, error)

Eval evaluates a compiled expression against vars. A nil expression yields null, which is what an omitted decision-table output entry means.

func (*Evaluator) EvalBudget added in v0.3.0

func (e *Evaluator) EvalBudget(x *Expr, vars map[string]any, budget *Budget) (any, error)

EvalBudget is Eval drawing on a shared iteration budget. A nil budget gives the evaluation a whole budget of its own, as Eval does.

func (*Evaluator) EvalText

func (e *Evaluator) EvalText(text string, vars map[string]any) (any, error)

EvalText compiles and evaluates in one step. Prefer Eval with a pre-compiled expression on hot paths; this exists for one-shot callers such as the CLI.

func (*Evaluator) EvalUnaryTest

func (e *Evaluator) EvalUnaryTest(u *UnaryTest, input any, vars map[string]any) (bool, error)

EvalUnaryTest evaluates an input entry with the tested value bound to `?`.

A nil test is the irrelevance marker and matches unconditionally.

func (*Evaluator) EvalUnaryTestBudget added in v0.3.0

func (e *Evaluator) EvalUnaryTestBudget(u *UnaryTest, input any, vars map[string]any, budget *Budget) (bool, error)

EvalUnaryTestBudget is EvalUnaryTest drawing on a shared iteration budget: every alternative charges the same one. A nil budget gives each alternative a whole budget of its own, as EvalUnaryTest does.

func (*Evaluator) MaxIterations added in v0.2.0

func (e *Evaluator) MaxIterations() int64

MaxIterations reports the iteration budget: of one evaluation under Eval, of every evaluation sharing a Budget from NewBudget.

func (*Evaluator) NewBudget added in v0.3.0

func (e *Evaluator) NewBudget() *Budget

NewBudget returns a fresh shared budget of the evaluator's MaxIterations.

type Expr

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

Expr is a compiled FEEL expression. Expr values are immutable and safe for concurrent evaluation.

func (*Expr) Literals

func (e *Expr) Literals() []Literal

Literals returns the constants an expression mentions, in source order. Sub-expressions the extractor does not understand contribute nothing, so a caller must treat an empty result as "not statically decidable" rather than as "mentions no constants".

func (*Expr) Node

func (e *Expr) Node() pfeel.Node

Node exposes the underlying AST for analysis passes.

func (*Expr) Text

func (e *Expr) Text() string

Text returns the source the expression was compiled from.

type Function

type Function struct {
	// Params are the required positional parameter names, in order.
	Params []string
	// Optional are parameters that may be omitted; they follow Params.
	Optional []string
	// Variadic, when non-empty, collects any remaining arguments into a list
	// bound to this name.
	Variadic string
	// Help is a one-line description surfaced by `verdict explain`.
	Help string
	// Fn is the implementation.
	Fn func(args map[string]any) (any, error)
}

Function is an application-supplied FEEL function. Arguments arrive as FEEL values keyed by parameter name; the return value is converted with FromGo, so a handler may return plain Go values.

type FunctionLibrary

type FunctionLibrary struct {
	Namespace string
	Functions map[string]Function
}

FunctionLibrary is a namespaced bundle of application functions. The namespace is mandatory: functions are reachable only as `namespace.name(...)`, which is what makes it impossible for an extension to shadow a DMN standard built-in.

type Literal

type Literal struct {
	// Text is the literal as written, for the analysis report.
	Text string
	// Value is the FEEL value.
	Value any
}

Literal is a constant an expression mentions, paired with the source text that produced it.

Static analysis needs the boundaries a decision table's rules test against, and the AST that carries them is an implementation detail of the embedded evaluator. Exposing literals rather than nodes keeps the analyser independent of which FEEL implementation is underneath.

type Option

type Option func(*evaluatorOptions)

Option configures an Evaluator.

func WithClock

func WithClock(clock func() time.Time) Option

WithClock overrides the time source the temporal built-ins read.

`now()`, `today()` and anything derived from them are the one place a decision model can produce a different answer for identical inputs. Injecting a clock is what makes a model that reads the date testable — and what lets a replay reproduce an evaluation that happened yesterday.

func WithLibraries

func WithLibraries(libs ...FunctionLibrary) Option

WithLibraries registers namespaced application function libraries.

func WithMaxIterations added in v0.2.0

func WithMaxIterations(n int64) Option

WithMaxIterations sets the iteration budget: the total number of elements the `for`, `some` and `every` iteration contexts may produce together (see DefaultMaxIterations). An evaluation that would exceed it fails; an integer range that would is refused before any of its elements is built. Eval and EvalUnaryTest give each evaluation the whole budget; EvalBudget and EvalUnaryTestBudget draw on a shared Budget (NewBudget), which is how the engine bounds a whole request. Zero or a negative value means DefaultMaxIterations: there is deliberately no "unlimited" setting, since unbounded iteration is a memory-exhaustion vector; pass a larger budget instead.

type UnaryTest

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

UnaryTest is a compiled decision-table input entry.

A unary test is a distinct DMN production from an expression (DMN 1.5 §7.3.1, grammar rule 15): the tested value is implicit. `< 10` is a comparison against it, `[1..10]` is a containment check, `"low", "medium"` is a disjunction of equality tests, and `not(...)` negates the whole entry.

The embedded evaluator parses these forms but evaluates them as ordinary expressions — a bare range yields a range value, a bare literal yields the literal — so Verdict owns the unary-test semantics here: split the entry into its top-level alternatives, evaluate each as an expression with the tested value bound to `?`, and then interpret the resulting value as a test.

func (*UnaryTest) Alternatives

func (u *UnaryTest) Alternatives() []*Expr

Alternatives exposes the compiled alternatives for static analysis: the gap and overlap detector reads them to build each rule's input domain.

func (*UnaryTest) Literals

func (u *UnaryTest) Literals() []Literal

Literals returns the constants a unary test mentions across all of its alternatives.

func (*UnaryTest) MatchesAnything

func (u *UnaryTest) MatchesAnything() bool

MatchesAnything reports whether the entry is the irrelevance marker.

func (*UnaryTest) Negated

func (u *UnaryTest) Negated() bool

Negated reports whether the entry is wrapped in `not(...)`.

func (*UnaryTest) Text

func (u *UnaryTest) Text() string

Text returns the source entry.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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