GithubHelp home page GithubHelp logo

apaxa-go / eval Goto Github PK

View Code? Open in Web Editor NEW
58.0 7.0 7.0 86 KB

Package eval implements evaluation of GoLang expression at runtime.

License: Apache License 2.0

Go 100.00%
golang eval golang-expression library

eval's Introduction

eval

Build Status Coverage Status Go Report Card GoDoc

Package eval implements evaluation of GoLang expression at runtime.

THIS LIB NO MORE MAINTAINED!

For whose who wants to implement golang eval

Suggestions:

  1. Implement 2-steps algorithm: first step - analogue of golang compilation (resolve all types; compute all constants; convert all untyped constant and untyped variables to typed; also simplify AST tree here / convert to your own format), second step - analogue of golang runtime (here will be passed values of external variables and computed final result).
  2. You need to use golang eval package, but keep in mind that it can simplify break your lib on update (golang's backward compatibility does not save you).
  3. Follow language specification (it is hard to implement some additional custom behaviour without breaking compatibility with language accepted expressions).
  4. Language specification may omit some details (so also test with golang compiler).

Requirements for expression:

  1. expression itself and all of subexpression must return exactly one value,
  2. see documentation Bugs section for other requirements/restrictions.

What does supported:

  1. types (by passing predefined/custom types and by defining unnamed types in expression itself),
  2. named arguments (regular variables, typed & untyped constants, untyped boolean variable),
  3. "package.SomeThing" notation,
  4. evaluate expression as if it is evaluates in specified package (even write access to private fields),
  5. evaluate expression like Go evaluates it (following most of specification rules),
  6. position of error in source on evaluation.

Examples:

Simple:

src:="int8(1*(1+2))"
expr,err:=ParseString(src,"")
if err!=nil{
	return err
}
r,err:=expr.EvalToInterface(nil)
if err!=nil{
	return err
}
fmt.Printf("%v %T", r, r)	// "3 int8"

Complicated:

type exampleString string

func (s exampleString) String() exampleString { return "!" + s + "!" }

type exampleStruct struct {
	A, B int
}

func (s exampleStruct) Sum() int { return s.A + s.B }

func main(){
	c := make(chan int64, 10)
	c <- 2

	src := `exampleString(fmt.Sprint(interface{}(math.MaxInt64/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(<-(<-chan int64)(c))-cap(make([]string, 1, 100))))).String().String() + "."`

	expr, err := ParseString(src, "")
	if err != nil {
		return
	}
	a := Args{
		"exampleString": MakeTypeInterface(exampleString("")),
		"fmt.Sprint":    MakeDataRegularInterface(fmt.Sprint),
		"math.MaxInt64": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt64)),
		"exampleStruct": MakeTypeInterface(exampleStruct{}),
		"c":             MakeDataRegularInterface(c),
	}
	r, err := expr.EvalToInterface(a)
	if err != nil {
		return
	}
	if r != testR {
		return
	}
	fmt.Printf("%v %T\n", r, r)	// "!!1152921504606846877!!. exampleString"
	return
}

With error:

src := `exampleString(fmt.Sprint(interface{}(math.MaxInt64/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(<-(<-chan int64)(c))-cap(make([]string, 1, 100))))).String().String() + "."`
expr, err := ParseString(src, "")
if err != nil {
	t.Error(err)
}
a := Args{
	"exampleString": MakeTypeInterface(exampleString("")),
	"fmt.Sprint":    MakeDataRegularInterface(fmt.Sprint),
	"math.MaxInt64": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt64)),
	"exampleStruct": MakeTypeInterface(exampleStruct{}),
	// Remove "c" from passed arguments:
	// "c":             MakeDataRegularInterface(c),
}
_, err = expr.EvalToInterface(a)
fmt.Println(err)	// "expression:1:119: undefined: c"

Bugs

Please report bug if you found it.

eval's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

eval's Issues

Expression calculation error

Interface slices are used as input parameters when different types of parameters are used in the expression. Expression calculation error.

Test code:

package main

import (
"github.com/apaxa-go/eval"
"fmt"
)

func main() {
in := make([]interface{}, 0, 3)
in = append(in, true)
in = append(in, 1)
in = append(in, true)
expr1, err := eval.ParseString(" (in[1].(int) == 1) ", "")
if err != nil {
return
}
expr2, err := eval.ParseString(" in[0].(bool) && in[2].(bool) ", "")
if err != nil {
return
}
expr3, err := eval.ParseString(" (in[1].(int) == 1) || in[0].(bool) && in[2].(bool) ", "")
if err != nil {
return
}
a := eval.Args{
"in": eval.MakeDataRegularInterface(in),
}
r1, err := expr1.EvalToInterface(a)
if err != nil {
fmt.Println("11111111",err)
return
}
fmt.Printf("%v %T\n", r1, r1)
r2, err := expr2.EvalToInterface(a)
if err != nil {
fmt.Println("2222222",err)
return
}
fmt.Printf("%v %T\n", r2, r1)
r3, err := expr3.EvalToInterface(a)
if err != nil {
fmt.Println("33333333",err)
return
}
fmt.Printf("%v %T\n", r3, r1)

}

Result:

true bool
true bool
33333333 expression:1:2-1:52: invalid operation: true (type untyped bool) || true (type bool) (invalid types untyped bool and/or bool)

Boolean operators not supported?

If I try to evaluate true && true it works, but if I try to evaluate bk>=60 && aq>=60 (passing bk and aq as args), it fails:

expression:1:1-1:16: invalid operation: false (type untyped bool) && false (type untyped bool) (invalid types untyped bool and/or untyped bool)

I also tried with parenthesis.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.