emuhedo / expr

Evaluate expression in Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Expr

Build Status Go Report Card Code Coverage GoDoc

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.
  • Static typing (example).
    out, err := expr.Eval("'hello' + 10")
    // err: invalid operation + (mismatched types string and int64)
    // | 'hello' + 10
    // | ........^
  • User-friendly error messages.
  • Reasonable set of basic operators.
  • Builtins all, none, any, one, filter, map.
    all(Tweets, {.Size < 140})
  • Fast (benchmarks).

Install

go get github.com/antonmedv/expr

Documentation

Examples

Executing arbitrary expressions.

env := map[string]interface{}{
    "foo": 1,
    "bar": struct{Value int}{1},
}

out, err := expr.Eval("foo + bar.Value", env)

Static type checker with struct as environment.

type Env struct {
	Foo int
	Bar *Bar
}

type Bar struct {
	Value int
}

program, err := expr.Compile("Foo + Bar.Value", expr.Env(&Env{}))

out, err := expr.Run(program, &Env{1, &Bar{2}})

Using env's methods as functions inside expressions.

type Env struct {
	Name string
}

func (e *Env) Title() string {
	return strings.Title(e.Name)
}

program, err := expr.Compile(`"Hello " + Title()`, expr.Env(&Env{}))

out, err := expr.Run(program, &Env{"world"})

Contributing

Expr consist of a few packages for parsing source code to AST, type checking AST, compiling to bytecode and VM for running bytecode program.

Also expr provides powerful tool exp for debugging. It has interactive terminal debugger for our bytecode virtual machine.

debugger

Who is using Expr?

  • Aviasales are actively using Expr for different parts of the search engine.

License

MIT

About

Evaluate expression in Go

License:MIT License


Languages

Language:Go 95.4%Language:ANTLR 4.6%