Help us shape the future of Go! Take the 2026 Go Developer Survey

eval

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 10 Imported by: 0

README

eval

An arbitrary expression evaluator for Go. Parses a string expression once into an EvaluableExpression, then evaluates it repeatedly against a set of named parameters, returning a single interface{} result.

Supports arithmetic, comparison, logical, bitwise, ternary, and string operators; regular-expression matching; membership (in); parameter accessors that reach into struct fields and map keys (obj.Field); and user-defined functions.

expr, err := eval.NewEvaluableExpression("foo > 0 && bar in ('a', 'b')")
result, err := expr.Evaluate(map[string]interface{}{"foo": 1, "bar": "a"})
// result == true

For a stable set of custom functions, build with eval.NewEvaluableExpressionWithFunctions. To supply parameters lazily, pass any value implementing the Parameters interface to Eval.

Provenance

Taken from github.com/casbin/govaluate v1.3.0, itself a fork of github.com/Knetic/govaluate by George Lester. See NOTICE for the full lineage and LICENSE for the MIT terms.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DUMMY_PARAMETERS = MapParameters(map[string]interface{}{})

Functions

This section is empty.

Types

type EvaluableExpression

type EvaluableExpression struct {

	/*
		Represents the query format used to output dates. Typically only used when creating SQL or Mongo queries from an expression.
		Defaults to the complete ISO8601 format, including nanoseconds.
	*/
	QueryDateFormat string

	/*
		Whether or not to safely check types when evaluating.
		If true, this library will return error messages when invalid types are used.
		If false, the library will panic when operators encounter types they can't use.

		This is exclusively for users who need to squeeze every ounce of speed out of the library as they can,
		and you should only set this to false if you know exactly what you're doing.
	*/
	ChecksTypes bool
	// contains filtered or unexported fields
}

EvaluableExpression represents a set of ExpressionTokens which, taken together, are an expression that can be evaluated down into a single value.

func NewEvaluableExpression

func NewEvaluableExpression(expression string) (*EvaluableExpression, error)

Parses a new EvaluableExpression from the given [expression] string. Returns an error if the given expression has invalid syntax.

func NewEvaluableExpressionFromTokens

func NewEvaluableExpressionFromTokens(tokens []ExpressionToken) (*EvaluableExpression, error)

Similar to NewEvaluableExpression, except that instead of a string, an already-tokenized expression is given. This is useful in cases where you may be generating an expression automatically, or using some other parser (e.g., to parse from a query language)

func NewEvaluableExpressionWithFunctions

func NewEvaluableExpressionWithFunctions(expression string, functions map[string]ExpressionFunction) (*EvaluableExpression, error)

Similar to NewEvaluableExpression, except enables the use of user-defined functions. Functions passed into this will be available to the expression.

func (EvaluableExpression) Eval

func (this EvaluableExpression) Eval(parameters Parameters) (interface{}, error)

Runs the entire expression using the given [parameters]. e.g., If the expression contains a reference to the variable "foo", it will be taken from `parameters.Get("foo")`.

This function returns errors if the combination of expression and parameters cannot be run, such as if a variable in the expression is not present in [parameters].

In all non-error circumstances, this returns the single value result of the expression and parameters given. e.g., if the expression is "1 + 1", this will return 2.0. e.g., if the expression is "foo + 1" and parameters contains "foo" = 2, this will return 3.0

func (EvaluableExpression) Evaluate

func (this EvaluableExpression) Evaluate(parameters map[string]interface{}) (interface{}, error)

Same as `Eval`, but automatically wraps a map of parameters into a `eval.Parameters` structure.

func (EvaluableExpression) String

func (this EvaluableExpression) String() string

Returns the original expression used to create this EvaluableExpression.

func (EvaluableExpression) ToSQLQuery

func (this EvaluableExpression) ToSQLQuery() (string, error)

Returns a string representing this expression as if it were written in SQL. This function assumes that all parameters exist within the same table, and that the table essentially represents a serialized object of some sort (e.g., hibernate). If your data model is more normalized, you may need to consider iterating through each actual token given by `Tokens()` to create your query.

Boolean values are considered to be "1" for true, "0" for false.

Times are formatted according to this.QueryDateFormat.

func (EvaluableExpression) Tokens

func (this EvaluableExpression) Tokens() []ExpressionToken

Returns an array representing the ExpressionTokens that make up this expression.

func (EvaluableExpression) Vars

func (this EvaluableExpression) Vars() []string

Returns an array representing the variables contained in this EvaluableExpression.

type ExpressionFunction

type ExpressionFunction func(arguments ...interface{}) (interface{}, error)

Represents a function that can be called from within an expression. This method must return an error if, for any reason, it is unable to produce exactly one unambiguous result. An error returned will halt execution of the expression.

type ExpressionToken

type ExpressionToken struct {
	Kind  TokenKind
	Value interface{}
}

Represents a single parsed token.

type MapParameters

type MapParameters map[string]interface{}

func (MapParameters) Get

func (p MapParameters) Get(name string) (interface{}, error)

type OperatorSymbol

type OperatorSymbol int

Represents the valid symbols for operators.

const (
	VALUE OperatorSymbol = iota
	LITERAL
	NOOP
	EQ
	NEQ
	GT
	LT
	GTE
	LTE
	REQ
	NREQ
	IN

	AND
	OR

	PLUS
	MINUS
	BITWISE_AND
	BITWISE_OR
	BITWISE_XOR
	BITWISE_LSHIFT
	BITWISE_RSHIFT
	MULTIPLY
	DIVIDE
	MODULUS
	EXPONENT

	NEGATE
	INVERT
	BITWISE_NOT

	TERNARY_TRUE
	TERNARY_FALSE
	COALESCE

	FUNCTIONAL
	ACCESS
	SEPARATE
)

func (OperatorSymbol) IsModifierType

func (this OperatorSymbol) IsModifierType(candidate []OperatorSymbol) bool

Returns true if this operator is contained by the given array of candidate symbols. False otherwise.

func (OperatorSymbol) String

func (this OperatorSymbol) String() string

Generally used when formatting type check errors. We could store the stringified symbol somewhere else and not require a duplicated codeblock to translate OperatorSymbol to string, but that would require more memory, and another field somewhere. Adding operators is rare enough that we just stringify it here instead.

type Parameters

type Parameters interface {

	/*
		Get gets the parameter of the given name, or an error if the parameter is unavailable.
		Failure to find the given parameter should be indicated by returning an error.
	*/
	Get(name string) (interface{}, error)
}

Parameters is a collection of named parameters that can be used by an EvaluableExpression to retrieve parameters when an expression tries to use them.

type TokenKind

type TokenKind int

Represents all valid types of tokens that a token can be.

const (
	UNKNOWN TokenKind = iota

	PREFIX
	NUMERIC
	BOOLEAN
	STRING
	PATTERN
	TIME
	VARIABLE
	FUNCTION
	SEPARATOR
	ACCESSOR

	COMPARATOR
	LOGICALOP
	MODIFIER

	CLAUSE
	CLAUSE_CLOSE

	TERNARY
)

func (TokenKind) String

func (kind TokenKind) String() string

GetTokenKindString returns a string that describes the given TokenKind. e.g., when passed the NUMERIC TokenKind, this returns the string "NUMERIC".

Jump to

Keyboard shortcuts

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