expr

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: May 31, 2023 License: MIT Imports: 12 Imported by: 7

README

Expr

test Go Report Card GoDoc

expr logo

Expr package provides an engine that can compile and evaluate expressions. An expression is a one-liner that returns a value (mostly, but not limited to, booleans). It is designed for simplicity, speed and safety.

The purpose of the package is to allow users to use expressions inside configuration for more complex logic. It is a perfect candidate for the foundation of a business rule engine. The idea is to let configure things in a dynamic way without recompile of a program:

# Get the special price if
user.Group in ["good_customers", "collaborator"]

# Promote article to the homepage when
len(article.Comments) > 100 and article.Category not in ["misc"]

# Send an alert when
product.Stock < 15

Features

  • Seamless integration with Go (no need to redefine types)
  • Static typing (example).
    out, err := expr.Compile(`name + age`)
    // err: invalid operation + (mismatched types string and int)
    // | name + age
    // | .....^
    
  • User-friendly error messages.
  • Reasonable set of basic operators.
  • Builtins all, none, any, one, filter, map.
    all(Tweets, {.Size <= 280})
    
  • Fast (benchmarks): uses bytecode virtual machine and optimizing compiler.

Install

go get github.com/oarkflow/expr

Documentation

Expr Code Editor

Expr Code Editor

Also, I have an embeddable code editor written in JavaScript which allows editing expressions with syntax highlighting and autocomplete based on your types declaration.

Learn more →

Examples

Play Online

package main

import (
	"fmt"
	"github.com/oarkflow/expr"
)

func main() {
	env := map[string]interface{}{
		"greet":   "Hello, %v!",
		"names":   []string{"world", "you"},
		"sprintf": fmt.Sprintf,
	}

	code := `sprintf(greet, names[0])`

	program, err := expr.Compile(code, expr.Env(env))
	if err != nil {
		panic(err)
	}

	output, err := expr.Run(program, env)
	if err != nil {
		panic(err)
	}

	fmt.Println(output)
}

Play Online

package main

import (
	"fmt"
	"github.com/oarkflow/expr"
)

type Tweet struct {
	Len int
}

type Env struct {
	Tweets []Tweet
}

func main() {
	code := `all(Tweets, {.Len <= 240})`

	program, err := expr.Compile(code, expr.Env(Env{}))
	if err != nil {
		panic(err)
	}

	env := Env{
		Tweets: []Tweet{{42}, {98}, {69}},
	}
	output, err := expr.Run(program, env)
	if err != nil {
		panic(err)
	}

	fmt.Println(output)
}

Who uses Expr?

  • Aviasales uses Expr as a business rule engine for our flight search engine.
  • Wish.com uses Expr for decision-making rule engine in the Wish Assistant.
  • Argo uses Expr in Argo Rollouts and Argo Workflows for Kubernetes.
  • Crowdsec uses Expr in a security automation tool.
  • FACEIT uses Expr to allow customization of its eSports matchmaking algorithm.
  • qiniu uses Expr in trade systems.
  • Junglee Games uses Expr for an in house marketing retention tool Project Audience.
  • OpenTelemetry uses Expr in the OpenTelemetry Collector.
  • Philips Labs uses Expr in Tabia, a tool for collecting insights on the characteristics of our code bases.
  • CoreDNS uses Expr in CoreDNS, a DNS server.
  • Chaos Mesh uses Expr in Chaos Mesh, a cloud-native Chaos Engineering platform.
  • Milvus uses Expr in Milvus, an open-source vector database.
  • Visually.io uses Expr as a business rule engine for our personalization targeting algorithm.
  • Akvorado uses Expr to classify exporters and interfaces in network flows.

Add your company too

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFunction

func AddFunction(name string, handler func(params ...any) (any, error))

func Compile

func Compile(input string, ops ...Option) (*vm.Program, error)

Compile parses and compiles given input expression to bytecode program.

func Eval

func Eval(input string, env interface{}) (interface{}, error)

Eval parses, compiles and runs given input.

func Parse

func Parse(expr string) (*vm.Program, error)

func Run

func Run(program *vm.Program, env interface{}) (interface{}, error)

Run evaluates given bytecode program.

Types

type Option

type Option func(c *conf.Config)

Option for configuring config.

func AllowUndefinedVariables

func AllowUndefinedVariables() Option

AllowUndefinedVariables allows to use undefined variables inside expressions. This can be used with expr.Env option to partially define a few variables.

func AsBool

func AsBool() Option

AsBool tells the compiler to expect a boolean result.

func AsFloat64

func AsFloat64() Option

AsFloat64 tells the compiler to expect a float64 result.

func AsInt

func AsInt() Option

AsInt tells the compiler to expect an int result.

func AsInt64

func AsInt64() Option

AsInt64 tells the compiler to expect an int64 result.

func AsKind

func AsKind(kind reflect.Kind) Option

AsKind tells the compiler to expect kind of the result.

func ConstExpr

func ConstExpr(fn string) Option

ConstExpr defines func expression as constant. If all argument to this function is constants, then it can be replaced by result of this func call on compile step.

func Env

func Env(env interface{}) Option

Env specifies expected input of env for type checks. If struct is passed, all fields will be treated as variables, as well as all fields of embedded structs and struct itself. If map is passed, all items will be treated as variables. Methods defined on this type will be available as functions.

func Function

func Function(name string, fn func(params ...interface{}) (interface{}, error), types ...interface{}) Option

Function adds function to list of functions what will be available in expressions.

func Operator

func Operator(operator string, fn ...string) Option

Operator allows to replace a binary operator with a function.

func Optimize

func Optimize(b bool) Option

Optimize turns optimizations on or off.

func Patch

func Patch(visitor ast.Visitor) Option

Patch adds visitor to list of visitors what will be applied before compiling AST to bytecode.

Directories

Path Synopsis
vm

Jump to

Keyboard shortcuts

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