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
- Variables
- func Aggregate(name string, list []any) (result any, ok bool)
- func Compare(a, b any) (int, bool)
- func Equal(a, b any) bool
- func FromGo(v any) any
- func IsIrrelevant(text string) bool
- func IsNull(v any) bool
- func IsNumber(v any) bool
- func IsTemporal(v any) bool
- func KeyOf(v any) (string, bool)
- func NewFunctionValue(f Function) any
- func NumberOffset(v any, delta int64) any
- func ParseTemporal(s, want string) (any, error)
- func SortValues(vs []any)
- func SplitList(list string) []string
- func TemporalOffset(v any, d time.Duration) any
- func ToGo(v any) any
- func TypeName(v any) string
- type Budget
- type CompileError
- type Compiler
- type Dialect
- type EvalError
- type Evaluator
- func (e *Evaluator) Compile(text string) (*Expr, error)
- func (e *Evaluator) CompileUnaryTest(text string) (*UnaryTest, error)
- func (e *Evaluator) Compiler() *Compiler
- func (e *Evaluator) Dialect() Dialect
- func (e *Evaluator) Eval(x *Expr, vars map[string]any) (any, error)
- func (e *Evaluator) EvalBudget(x *Expr, vars map[string]any, budget *Budget) (any, error)
- func (e *Evaluator) EvalText(text string, vars map[string]any) (any, error)
- func (e *Evaluator) EvalUnaryTest(u *UnaryTest, input any, vars map[string]any) (bool, error)
- func (e *Evaluator) EvalUnaryTestBudget(u *UnaryTest, input any, vars map[string]any, budget *Budget) (bool, error)
- func (e *Evaluator) MaxIterations() int64
- func (e *Evaluator) NewBudget() *Budget
- type Expr
- type Function
- type FunctionLibrary
- type Literal
- type Option
- type UnaryTest
Constants ¶
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 ¶
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.
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.
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
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 ¶
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 ¶
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 ¶
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 ¶
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 IsTemporal ¶
IsTemporal reports whether v is a FEEL date, time or date-and-time.
func KeyOf ¶ added in v0.4.0
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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.
type CompileError ¶
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 ¶
NewCompiler returns a compiler for the given dialect.
func (*Compiler) Compile ¶
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 ¶
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.
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 )
type EvalError ¶
EvalError wraps a runtime failure with the expression that produced it.
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 ¶
NewEvaluator builds an evaluator for a dialect, layering the DMN 1.5 standard library supplement beneath any application function libraries.
func (*Evaluator) CompileUnaryTest ¶
CompileUnaryTest parses a decision-table input entry.
func (*Evaluator) Compiler ¶
Compiler exposes the evaluator's compile cache so callers can pre-compile and validate expressions at model-load time.
func (*Evaluator) Eval ¶
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
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 ¶
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 ¶
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
MaxIterations reports the iteration budget: of one evaluation under Eval, of every evaluation sharing a Budget from NewBudget.
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 ¶
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".
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 ¶
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 ¶
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
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 ¶
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 ¶
Literals returns the constants a unary test mentions across all of its alternatives.
func (*UnaryTest) MatchesAnything ¶
MatchesAnything reports whether the entry is the irrelevance marker.