├── index_test.go ├── .gitignore ├── convert.go ├── error_test.go ├── data-funcs_test.go ├── builtin-func_test.go ├── .travis.yml ├── slice_test.go ├── composite_test.go ├── builtin-type.go ├── error.go ├── index.go ├── ast-helper.go ├── slice.go ├── value_test.go ├── composite.go ├── data-funcs-helper.go ├── call.go ├── args.go ├── expr_test.go ├── doc_test.go ├── README.md ├── expr.go ├── value.go ├── doc.go ├── ast_test.go ├── data-funcs.go ├── data_test.go ├── LICENSE ├── errors.go ├── data.go ├── builtin-func.go ├── ast.go └── tests_test.go /index_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestIndexMap(t *testing.T) { 9 | if r, err := indexMap(reflect.ValueOf(1), MakeRegularInterface(1)); r != nil || err == nil { 10 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | .idea 10 | 11 | # Architecture specific extensions/prefixes 12 | *.[568vq] 13 | [568vq].out 14 | 15 | *.cgo1.go 16 | *.cgo2.c 17 | _cgo_defun.c 18 | _cgo_gotypes.go 19 | _cgo_export.* 20 | 21 | _testmain.go 22 | 23 | *.exe 24 | *.test 25 | *.prof 26 | -------------------------------------------------------------------------------- /convert.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "reflect" 5 | ) 6 | 7 | func convertCall(t reflect.Type, args []Data) (r Value, err *intError) { 8 | if len(args) != 1 { 9 | return nil, convertArgsCountMismError(t, 1, args) 10 | } 11 | rV, ok := args[0].Convert(t) 12 | if ok { 13 | r = MakeData(rV) 14 | } else { 15 | err = convertUnableError(t, args[0]) 16 | } 17 | return 18 | } 19 | -------------------------------------------------------------------------------- /error_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "go/token" 5 | "testing" 6 | ) 7 | 8 | func TestError_Error(t *testing.T) { 9 | err := identUndefinedError("myIdent").noPos().error(token.NewFileSet()).Error() 10 | if str := "-: undefined: myIdent"; str != err { 11 | t.Errorf("expect %v, got %v", str, err) 12 | } 13 | } 14 | 15 | func TestIntError_NoPos(t *testing.T) { 16 | if (*intError)(nil).noPos() != nil { 17 | t.Error("expect nil") 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /data-funcs_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/goh/constanth" 5 | "github.com/apaxa-go/helper/mathh" 6 | "github.com/apaxa-go/helper/reflecth" 7 | "go/token" 8 | "testing" 9 | ) 10 | 11 | func TestCompareOpWithUntypedBool(t *testing.T) { 12 | if r, err := compareOpWithUntypedBool(MakeNil(), token.EQL, true); r != nil || err == nil { 13 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 14 | } 15 | } 16 | 17 | func TestShiftOp(t *testing.T) { 18 | if mathh.IntBits == 32 { 19 | if r, err := shiftOp(MakeRegularInterface(1), token.SHL, MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeUint64(mathh.MaxUint32+1), reflecth.TypeUint64()))); r != nil || err == nil { 20 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /builtin-func_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestIsBuiltInFunc(t *testing.T) { 8 | // Keep this list up-to-date with list at isBuiltInFunc. 9 | bFs := []string{"len", "cap", "complex", "real", "imag", "new", "make", "append"} 10 | for _, f := range bFs { 11 | if !isBuiltInFunc(f) { 12 | t.Error("expect " + f + " to be an built-in function") 13 | } 14 | if _, intErr := callBuiltInFunc(f, nil, false); *intErr == *(undefIdentError(f)) { 15 | t.Error("expect for " + f + " not \"" + string(*intErr) + "\" error") 16 | } 17 | } 18 | } 19 | 20 | // Check for cases which can not be generated by parsing expression source. 21 | func TestCallBuiltInFunc(t *testing.T) { 22 | if r, err := callBuiltInFunc("nonbuiltin", nil, false); r != nil || err == nil { 23 | t.Error("expect error") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: false 3 | os: 4 | - linux 5 | - osx 6 | go: 7 | - 1.x 8 | - 1.7.x 9 | - master 10 | env: 11 | - GO_ARCH=amd64 12 | - GO_ARCH=386 13 | - GO_OS=windows GO_ARCH=amd64 14 | - GO_OS=windows GO_ARCH=386 15 | matrix: 16 | exclude: 17 | - os: osx 18 | env: GO_ARCH=386 19 | - os: osx 20 | env: GO_OS=windows GO_ARCH=amd64 21 | - os: osx 22 | env: GO_OS=windows GO_ARCH=386 23 | allow_failures: 24 | - go: master 25 | before_install: 26 | - export GOARCH=$GO_ARCH 27 | - export GOOS=$GO_OS 28 | - export PATH=${PATH}:${GOPATH}/bin/:${GOPATH}/bin/`go env GOOS`_`go env GOARCH`/ 29 | - go env 30 | - export 31 | - if [[ "$GOOS" != "windows" ]]; then go get github.com/mattn/goveralls; fi 32 | script: 33 | - if [[ "$GOOS" == "windows" ]]; then go build -v ./... ; fi 34 | - if [[ "$GOOS" != "windows" ]]; then goveralls -service travis-ci ; fi 35 | -------------------------------------------------------------------------------- /slice_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestSlice2(t *testing.T) { 9 | if r, err := slice2(reflect.ValueOf([]int{1, 2, 3, 4, 5}), -2, 2); r != nil || err == nil { 10 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 11 | } 12 | if r, err := slice2(reflect.ValueOf([...]int{1, 2, 3, 4, 5}), 2, 3); r != nil || err == nil { 13 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 14 | } 15 | } 16 | 17 | func TestSlice3(t *testing.T) { 18 | if r, err := slice3(reflect.ValueOf([]int{1, 2, 3, 4, 5}), 1, -1, 3); r != nil || err == nil { 19 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 20 | } 21 | if r, err := slice3(reflect.ValueOf([]int{1, 2, 3, 4, 5}), 1, 2, -1); r != nil || err == nil { 22 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 23 | } 24 | if r, err := slice3(reflect.ValueOf([]int{1, 2, 3, 4, 5}), -2, 2, 3); r != nil || err == nil { 25 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 26 | } 27 | if r, err := slice3(reflect.ValueOf([...]int{1, 2, 3, 4, 5}), 2, 3, 4); r != nil || err == nil { 28 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /composite_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/reflecth" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func TestCompositeLitStructKeys(t *testing.T) { 10 | if r, err := compositeLitStructKeys(reflecth.TypeBool(), nil, ""); r != nil || err == nil { 11 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 12 | } 13 | } 14 | 15 | func TestCompositeLitStructOrdered(t *testing.T) { 16 | if r, err := compositeLitStructOrdered(reflecth.TypeBool(), nil, ""); r != nil || err == nil { 17 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 18 | } 19 | } 20 | 21 | func TestCompositeLitArrayLike(t *testing.T) { 22 | // 23 | // 24 | // 25 | if r, err := compositeLitArrayLike(reflecth.TypeBool(), nil); r != nil || err == nil { 26 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 27 | } 28 | // 29 | // 30 | // 31 | if r, err := compositeLitArrayLike(reflect.TypeOf([]int{}), map[int]Data{-1: MakeRegularInterface(1)}); r != nil || err == nil { 32 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 33 | } 34 | } 35 | 36 | func TestCompositeLitMap(t *testing.T) { 37 | if r, err := compositeLitMap(reflecth.TypeBool(), nil); r != nil || err == nil { 38 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /builtin-type.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/reflecth" 5 | "reflect" 6 | ) 7 | 8 | func isBuiltInType(ident string) bool { 9 | _, ok := builtInTypes[ident] 10 | return ok 11 | } 12 | 13 | var builtInTypes = map[string]reflect.Type{ 14 | "bool": reflecth.TypeBool(), 15 | 16 | //////////////// Numeric //////////////// 17 | "uint": reflecth.TypeUint(), 18 | "uint8": reflecth.TypeUint8(), 19 | "uint16": reflecth.TypeUint16(), 20 | "uint32": reflecth.TypeUint32(), 21 | "uint64": reflecth.TypeUint64(), 22 | 23 | "int": reflecth.TypeInt(), 24 | "int8": reflecth.TypeInt8(), 25 | "int16": reflecth.TypeInt16(), 26 | "int32": reflecth.TypeInt32(), 27 | "int64": reflecth.TypeInt64(), 28 | 29 | "float32": reflecth.TypeFloat32(), 30 | "float64": reflecth.TypeFloat64(), 31 | 32 | "complex64": reflecth.TypeComplex64(), 33 | "complex128": reflecth.TypeComplex128(), 34 | 35 | "byte": reflecth.TypeByte(), 36 | "rune": reflecth.TypeRune(), 37 | 38 | "uintptr": reflecth.TypeUintptr(), 39 | ///////////////////////////////////////// 40 | 41 | "string": reflecth.TypeString(), 42 | } 43 | 44 | // In some places required specific types. This variables allow to avoid using types map. 45 | var ( 46 | bytesSliceT = reflect.SliceOf(reflect.TypeOf(byte(0))) 47 | ) 48 | -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "fmt" 5 | "github.com/apaxa-go/helper/goh/asth" 6 | "go/ast" 7 | "go/token" 8 | ) 9 | 10 | // Error is used for all errors related to passed expression. 11 | // It describes problem (as text) and (in most cases) position of problem. 12 | type Error struct { 13 | Msg string // description of problem 14 | Pos asth.Position // position of problem 15 | } 16 | 17 | // Error implements standard error interface. 18 | func (err Error) Error() string { 19 | return err.Pos.String() + ": " + err.Msg 20 | } 21 | 22 | type posError struct { 23 | msg string 24 | pos, end token.Pos 25 | } 26 | 27 | func (err *posError) error(fset *token.FileSet) error { 28 | if err == nil { 29 | return nil 30 | } 31 | return Error{Msg: err.msg, Pos: asth.MakePosition(err.pos, err.end, fset)} 32 | } 33 | 34 | type intError string 35 | 36 | func toIntError(err error) *intError { 37 | if err == nil { 38 | return nil 39 | } 40 | return newIntError(err.Error()) 41 | } 42 | func newIntError(msg string) *intError { 43 | return (*intError)(&msg) 44 | } 45 | func newIntErrorf(format string, a ...interface{}) *intError { 46 | return newIntError(fmt.Sprintf(format, a...)) 47 | } 48 | 49 | func (err *intError) pos(n ast.Node) *posError { 50 | if err == nil { 51 | return nil 52 | } 53 | return &posError{msg: string(*err), pos: n.Pos(), end: n.End()} 54 | } 55 | 56 | func (err *intError) noPos() *posError { 57 | if err == nil { 58 | return nil 59 | } 60 | return &posError{msg: string(*err)} 61 | } 62 | -------------------------------------------------------------------------------- /index.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "go/constant" 5 | "reflect" 6 | ) 7 | 8 | func indexMap(x reflect.Value, i Data) (r Value, err *intError) { 9 | if k := x.Kind(); k != reflect.Map { 10 | return nil, invIndexOpError(MakeRegular(x), i) 11 | } 12 | 13 | iReqT := x.Type().Key() 14 | 15 | iV, ok := i.Assign(iReqT) 16 | if !ok { 17 | return nil, convertUnableError(iReqT, i) 18 | } 19 | 20 | // 21 | rV := x.MapIndex(iV) 22 | if !rV.IsValid() { // Return zero value if no such key in map 23 | return MakeDataRegular(reflect.New(x.Type().Elem()).Elem()), nil 24 | } 25 | 26 | return MakeDataRegular(rV), nil 27 | } 28 | 29 | func indexOther(x reflect.Value, i Data) (r Value, err *intError) { 30 | if k := x.Kind(); k != reflect.String && k != reflect.Array && k != reflect.Slice { 31 | return nil, invIndexOpError(MakeRegular(x), i) 32 | } 33 | 34 | iInt, ok := i.AsInt() 35 | if !ok { 36 | return nil, convertUnableError(reflect.TypeOf(int(0)), i) 37 | } 38 | 39 | // check out-of-range 40 | if iInt < 0 || iInt >= x.Len() { 41 | return nil, indexOutOfRangeError(iInt) 42 | } 43 | 44 | return MakeDataRegular(x.Index(iInt)), nil 45 | } 46 | 47 | func indexConstant(x constant.Value, i Data) (r Value, err *intError) { 48 | if x.Kind() != constant.String { 49 | return nil, invIndexOpError(MakeUntypedConst(x), i) 50 | } 51 | 52 | iInt, ok := i.AsInt() 53 | if !ok { 54 | return nil, convertUnableError(reflect.TypeOf(int(0)), i) 55 | } 56 | 57 | xStr := constant.StringVal(x) 58 | // check out-of-range 59 | if iInt < 0 || iInt >= len(xStr) { 60 | return nil, indexOutOfRangeError(iInt) 61 | } 62 | 63 | if i.IsConst() { 64 | 65 | return MakeDataUntypedConst(constant.MakeInt64(int64(xStr[iInt]))), nil 66 | } 67 | return MakeDataRegularInterface(xStr[iInt]), nil 68 | } 69 | -------------------------------------------------------------------------------- /ast-helper.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/reflecth" 5 | "go/ast" 6 | "reflect" 7 | ) 8 | 9 | func (expr *Expression) funcTranslateArgs(fields *ast.FieldList, ellipsisAlowed bool, args Args) (r []reflect.Type, variadic bool, err *posError) { 10 | if fields == nil || len(fields.List) == 0 { 11 | return 12 | } 13 | r = make([]reflect.Type, len(fields.List)) 14 | for i := range fields.List { 15 | // check for variadic 16 | if _, ellipsis := fields.List[i].Type.(*ast.Ellipsis); ellipsis { 17 | if !ellipsisAlowed || i != len(fields.List)-1 { 18 | return nil, false, funcInvEllipsisPos().pos(fields.List[i]) 19 | } 20 | variadic = true 21 | } 22 | // calc type 23 | r[i], err = expr.astExprAsType(fields.List[i].Type, args) 24 | if err != nil { 25 | return nil, false, err 26 | } 27 | } 28 | return 29 | } 30 | 31 | // fieldByName is just a replacement for "x.FieldByName(field)" with write access to private fields. 32 | // x must be of kind reflect.Struct. 33 | func fieldByName(x reflect.Value, field string, pkgPath string) reflect.Value { 34 | r := x.FieldByName(field) 35 | //if pkgPath != "" && x.Type().PkgPath() == pkgPath && r.CanAddr() { 36 | if x.Type().PkgPath() == pkgPath && r.CanAddr() { 37 | r = reflecth.MakeSettable(r) 38 | } 39 | return r 40 | } 41 | 42 | // fieldByIndex is just a replacement for "x.Field(i)" with write access to private fields. 43 | // x must be of kind reflect.Struct. 44 | func fieldByIndex(x reflect.Value, i int, pkgPath string) reflect.Value { 45 | r := x.Field(i) 46 | //if pkgPath != "" && x.Type().PkgPath() == pkgPath && r.CanAddr() { 47 | if x.Type().PkgPath() == pkgPath && r.CanAddr() { 48 | r = reflecth.MakeSettable(r) 49 | } 50 | return r 51 | } 52 | 53 | // 54 | // 55 | // 56 | type upTypesT struct { 57 | d Data 58 | err *intError 59 | } 60 | 61 | func upT(d Data, err *intError) upTypesT { 62 | return upTypesT{d, err} 63 | } 64 | func (u upTypesT) pos(n ast.Node) (r Value, err *posError) { 65 | if u.err == nil { 66 | r = MakeData(u.d) 67 | } else { 68 | err = u.err.pos(n) 69 | } 70 | return 71 | } 72 | -------------------------------------------------------------------------------- /slice.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "reflect" 5 | ) 6 | 7 | const indexSkipped int = -1 8 | 9 | // Returns int index value for passed Value. 10 | // i may be nil (if index omitted). 11 | // Result also checked for not negative value (negative value cause error). 12 | func getSliceIndex(i Data) (r int, err *intError) { 13 | if i == nil { 14 | return indexSkipped, nil 15 | } 16 | r, ok := i.AsInt() 17 | if !ok { 18 | return 0, convertUnableError(reflect.TypeOf(int(0)), i) 19 | } 20 | if r < 0 { 21 | return 0, indexOutOfRangeError(r) 22 | } 23 | return 24 | } 25 | 26 | func slice2(x reflect.Value, low, high int) (r Value, err *intError) { 27 | // resolve pointer to array 28 | if x.Kind() == reflect.Ptr && x.Elem().Kind() == reflect.Array { 29 | x = x.Elem() 30 | } 31 | 32 | // check slicing possibility 33 | if k := x.Kind(); k != reflect.Array && k != reflect.Slice && k != reflect.String { 34 | return nil, invSliceOpError(MakeRegular(x)) 35 | } else if k == reflect.Array && !x.CanAddr() { 36 | return nil, invSliceOpError(MakeRegular(x)) 37 | } 38 | 39 | // resolve default value 40 | if low == indexSkipped { 41 | low = 0 42 | } 43 | if high == indexSkipped { 44 | high = x.Len() 45 | } 46 | 47 | // validate indexes 48 | switch { 49 | case low < 0: 50 | return nil, indexOutOfRangeError(low) 51 | case high > x.Len(): 52 | return nil, indexOutOfRangeError(high) 53 | case low > high: 54 | return nil, invSliceIndexError(low, high) 55 | } 56 | 57 | return MakeDataRegular(x.Slice(low, high)), nil 58 | } 59 | 60 | func slice3(x reflect.Value, low, high, max int) (r Value, err *intError) { 61 | // resolve pointer to array 62 | if x.Kind() == reflect.Ptr && x.Elem().Kind() == reflect.Array { 63 | x = x.Elem() 64 | } 65 | 66 | // check slicing possibility 67 | if k := x.Kind(); k != reflect.Array && k != reflect.Slice { 68 | return nil, invSliceOpError(MakeRegular(x)) 69 | } else if k == reflect.Array && !x.CanAddr() { 70 | return nil, invSliceOpError(MakeRegular(x)) 71 | } 72 | 73 | // resolve default value 74 | if low == indexSkipped { 75 | low = 0 76 | } 77 | 78 | // validate indexes 79 | if high == indexSkipped || max == indexSkipped { 80 | return nil, invSlice3IndexOmitted() 81 | } 82 | switch { 83 | case low < 0: 84 | return nil, indexOutOfRangeError(low) 85 | case max > x.Cap(): 86 | return nil, indexOutOfRangeError(high) 87 | case low > high: 88 | return nil, invSliceIndexError(low, high) 89 | case high > max: 90 | return nil, invSliceIndexError(high, max) 91 | } 92 | 93 | return MakeDataRegular(x.Slice3(low, high, max)), nil 94 | } 95 | -------------------------------------------------------------------------------- /value_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/reflecth" 5 | "testing" 6 | ) 7 | 8 | func TestValue_String(t *testing.T) { 9 | type testElement struct { 10 | v Value 11 | s string 12 | } 13 | 14 | tests := []testElement{ 15 | {MakeDataRegularInterface(1), "1 (type int)"}, 16 | {MakeType(nil), "type value nil"}, 17 | {MakeType(reflecth.TypeBool()), "type value bool"}, 18 | {MakeBuiltInFunc("len"), "built-in function value len"}, 19 | {MakePackage(ArgsFromInterfaces(ArgsI{"SomeVar": 1})), "package (exports: SomeVar)"}, 20 | } 21 | 22 | for _, test := range tests { 23 | if r := test.v.String(); r != test.s { 24 | t.Errorf(`expect "%v", got "%v"`, test.s, r) 25 | } 26 | } 27 | } 28 | 29 | func TestValue_Data(t *testing.T) { 30 | depanic := func(x Value) (panic bool) { 31 | defer func() { panic = recover() != nil }() 32 | _ = x.Data() 33 | return 34 | } 35 | values := []Value{ 36 | MakeType(reflecth.TypeBool()), 37 | MakeBuiltInFunc("len"), 38 | MakePackage(ArgsFromInterfaces(ArgsI{"SomeVar": 1})), 39 | } 40 | for _, v := range values { 41 | if !depanic(v) { 42 | t.Errorf("%v: expect panic", v) 43 | } 44 | } 45 | } 46 | 47 | func TestValue_Type(t *testing.T) { 48 | depanic := func(x Value) (panic bool) { 49 | defer func() { panic = recover() != nil }() 50 | _ = x.Type() 51 | return 52 | } 53 | values := []Value{ 54 | MakeDataRegularInterface(1), 55 | MakeBuiltInFunc("len"), 56 | MakePackage(ArgsFromInterfaces(ArgsI{"SomeVar": 1})), 57 | } 58 | for _, v := range values { 59 | if !depanic(v) { 60 | t.Errorf("%v: expect panic", v) 61 | } 62 | } 63 | } 64 | 65 | func TestValue_BuiltInFunc(t *testing.T) { 66 | depanic := func(x Value) (panic bool) { 67 | defer func() { panic = recover() != nil }() 68 | _ = x.BuiltInFunc() 69 | return 70 | } 71 | values := []Value{ 72 | MakeDataRegularInterface(1), 73 | MakeType(reflecth.TypeBool()), 74 | MakePackage(ArgsFromInterfaces(ArgsI{"SomeVar": 1})), 75 | } 76 | for _, v := range values { 77 | if !depanic(v) { 78 | t.Errorf("%v: expect panic", v) 79 | } 80 | } 81 | } 82 | 83 | func TestValue_Package(t *testing.T) { 84 | depanic := func(x Value) (panic bool) { 85 | defer func() { panic = recover() != nil }() 86 | _ = x.Package() 87 | return 88 | } 89 | values := []Value{ 90 | MakeDataRegularInterface(1), 91 | MakeType(reflecth.TypeBool()), 92 | MakeBuiltInFunc("len"), 93 | } 94 | for _, v := range values { 95 | if !depanic(v) { 96 | t.Errorf("%v: expect panic", v) 97 | } 98 | } 99 | } 100 | 101 | func TestValue_ImplementsValue(t *testing.T) { 102 | values := []Value{ 103 | MakeDataRegularInterface(1), 104 | MakeType(reflecth.TypeBool()), 105 | MakeBuiltInFunc("len"), 106 | MakePackage(ArgsFromInterfaces(ArgsI{"SomeVar": 1})), 107 | } 108 | for _, v := range values { 109 | v.implementsValue() 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /composite.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "reflect" 5 | ) 6 | 7 | func assign(dst reflect.Value, src Data) (err *intError) { 8 | if !dst.CanSet() { 9 | return assignDstUnsettableError(MakeRegular(dst)) 10 | } 11 | 12 | newValue, ok := src.Assign(dst.Type()) 13 | if !ok { 14 | return assignTypesMismError(dst.Type(), src) 15 | } 16 | 17 | dst.Set(newValue) 18 | return nil 19 | } 20 | 21 | func compositeLitStructKeys(t reflect.Type, elts map[string]Data, pkg string) (r Value, err *intError) { 22 | if t.Kind() != reflect.Struct { 23 | return nil, compLitInvTypeError(t) 24 | } 25 | rV := reflect.New(t).Elem() 26 | 27 | for field, value := range elts { 28 | fV := fieldByName(rV, field, pkg) 29 | if !fV.IsValid() { 30 | return nil, compLitUnknFieldError(rV, field) 31 | } 32 | err = assign(fV, value) 33 | if err != nil { 34 | return 35 | } 36 | } 37 | 38 | return MakeDataRegular(rV), nil 39 | } 40 | 41 | func compositeLitStructOrdered(t reflect.Type, elts []Data, pkg string) (r Value, err *intError) { 42 | if t.Kind() != reflect.Struct { 43 | return nil, compLitInvTypeError(t) 44 | } 45 | if t.NumField() != len(elts) { 46 | return nil, compLitArgsCountMismError(t.NumField(), len(elts)) 47 | } 48 | rV := reflect.New(t).Elem() 49 | 50 | for i := range elts { 51 | fV := fieldByIndex(rV, i, pkg) 52 | err = assign(fV, elts[i]) 53 | if err != nil { 54 | return 55 | } 56 | } 57 | 58 | return MakeDataRegular(rV), nil 59 | } 60 | 61 | func compositeLitArrayLike(t reflect.Type, elts map[int]Data) (r Value, err *intError) { 62 | // Calc max index (len of slice) 63 | var maxIndex = -1 64 | for i := range elts { 65 | if i < 0 { 66 | return nil, compLitNegIndexError() 67 | } 68 | if i > maxIndex { 69 | maxIndex = i 70 | } 71 | } 72 | 73 | // Init result 74 | var rV reflect.Value 75 | switch t.Kind() { 76 | case reflect.Array: 77 | rV = reflect.New(t).Elem() 78 | if maxIndex > rV.Len()-1 { 79 | return nil, compLitIndexOutOfBoundsError(rV.Len()-1, maxIndex) 80 | } 81 | case reflect.Slice: 82 | rV = reflect.MakeSlice(t, maxIndex+1, maxIndex+1) 83 | default: 84 | return nil, compLitInvTypeError(t) 85 | } 86 | 87 | // Fill result 88 | for i := range elts { 89 | iV := rV.Index(i) 90 | err = assign(iV, elts[i]) 91 | if err != nil { 92 | return 93 | } 94 | } 95 | 96 | return MakeDataRegular(rV), nil 97 | } 98 | 99 | func compositeLitMap(t reflect.Type, elts map[Data]Data) (r Value, err *intError) { 100 | if t.Kind() != reflect.Map { 101 | return nil, compLitInvTypeError(t) 102 | } 103 | 104 | rV := reflect.MakeMap(t) // reflect.New(t).Elem() 105 | kV := reflect.New(t.Key()).Elem() 106 | vV := reflect.New(t.Elem()).Elem() 107 | for k, v := range elts { 108 | err = assign(kV, k) 109 | if err != nil { 110 | return 111 | } 112 | err = assign(vV, v) 113 | if err != nil { 114 | return 115 | } 116 | rV.SetMapIndex(kV, vV) 117 | } 118 | 119 | return MakeDataRegular(rV), nil 120 | } 121 | -------------------------------------------------------------------------------- /data-funcs-helper.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/goh/constanth" 5 | "github.com/apaxa-go/helper/reflecth" 6 | "go/constant" 7 | "go/token" 8 | "reflect" 9 | ) 10 | 11 | func binaryOpRegular(x reflect.Value, op token.Token, y reflect.Value) (r Data, err *intError) { 12 | if rV, errE := reflecth.BinaryOp(x, op, y); errE == nil { 13 | r = regData(rV) 14 | } else { 15 | err = toIntError(errE) 16 | } 17 | return 18 | } 19 | func compareOpRegular(x reflect.Value, op token.Token, y reflect.Value) (r bool, err *intError) { 20 | var errE error 21 | r, errE = reflecth.CompareOp(x, op, y) 22 | err = toIntError(errE) 23 | return 24 | } 25 | func shiftOpRegular(x reflect.Value, op token.Token, s uint) (r Data, err *intError) { 26 | if rV, errE := reflecth.ShiftOp(x, op, s); errE == nil { 27 | r = regData(rV) 28 | } else { 29 | err = toIntError(errE) 30 | } 31 | return 32 | } 33 | func unaryOpRegular(op token.Token, y reflect.Value) (r Data, err *intError) { 34 | if rV, errE := reflecth.UnaryOp(op, y); errE == nil { 35 | r = regData(rV) 36 | } else { 37 | err = toIntError(errE) 38 | } 39 | return 40 | } 41 | func binaryOpTypedConst(x constanth.TypedValue, op token.Token, y constanth.TypedValue) (r Data, err *intError) { 42 | if rTC, errE := constanth.BinaryOpTyped(x, op, y); errE == nil { 43 | r = typedConstData(rTC) 44 | } else { 45 | err = toIntError(errE) 46 | } 47 | return 48 | } 49 | func compareOpTypedConst(x constanth.TypedValue, op token.Token, y constanth.TypedValue) (r bool, err *intError) { 50 | var errE error 51 | r, errE = constanth.CompareOpTyped(x, op, y) 52 | err = toIntError(errE) 53 | return 54 | } 55 | func shiftOpTypedConst(x constanth.TypedValue, op token.Token, s uint) (r constanth.TypedValue, err *intError) { 56 | var errE error 57 | r, errE = constanth.ShiftOpTyped(x, op, s) 58 | err = toIntError(errE) 59 | return 60 | } 61 | func unaryOpTypedConst(op token.Token, y constanth.TypedValue, prec uint) (r Data, err *intError) { 62 | if rTC, errE := constanth.UnaryOpTyped(op, y, prec); errE == nil { 63 | r = typedConstData(rTC) 64 | } else { 65 | err = toIntError(errE) 66 | } 67 | return 68 | } 69 | func binaryOpUntypedConst(x constant.Value, op token.Token, y constant.Value) (r Data, err *intError) { 70 | if rC, errE := constanth.BinaryOp(x, op, y); errE == nil { 71 | r = untypedConstData{rC} 72 | } else { 73 | err = toIntError(errE) 74 | } 75 | return 76 | } 77 | func compareOpUntypedConst(x constant.Value, op token.Token, y constant.Value) (r bool, err *intError) { 78 | var errE error 79 | r, errE = constanth.CompareOp(x, op, y) 80 | err = toIntError(errE) 81 | return 82 | } 83 | func shiftOpUntypedConst(x constant.Value, op token.Token, s uint) (r constant.Value, err *intError) { 84 | var errE error 85 | r, errE = constanth.ShiftOp(x, op, s) 86 | err = toIntError(errE) 87 | return 88 | } 89 | func unaryOpUntypedConst(op token.Token, y constant.Value, prec uint) (r Data, err *intError) { 90 | if rC, errE := constanth.UnaryOp(op, y, prec); errE == nil { 91 | r = untypedConstData{rC} 92 | } else { 93 | err = toIntError(errE) 94 | } 95 | return 96 | } 97 | -------------------------------------------------------------------------------- /call.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "reflect" 5 | ) 6 | 7 | // ellipsis true if last argument has ellipsis notation ("f(a,b,c...)"). 8 | func callRegular(f reflect.Value, args []Data, ellipsis bool) (r Value, err *intError) { 9 | if f.Kind() != reflect.Func { 10 | return nil, callNonFuncError(MakeDataRegular(f)) 11 | } 12 | fT := f.Type() 13 | if fT.NumOut() != 1 { 14 | return nil, callResultCountMismError(fT.NumOut()) 15 | } 16 | 17 | switch { 18 | case fT.IsVariadic() && ellipsis: 19 | return callRegularVariadicEllipsis(f, args) 20 | case fT.IsVariadic() && !ellipsis: 21 | return callRegularVariadic(f, args) 22 | case !fT.IsVariadic() && !ellipsis: 23 | return callRegularNonVariadic(f, args) 24 | } 25 | return nil, callRegularWithEllipsisError() 26 | } 27 | 28 | // f must be variadic func with single result (check must perform caller). 29 | func callRegularVariadicEllipsis(f reflect.Value, args []Data) (r Value, err *intError) { 30 | fT := f.Type() 31 | if len(args) != fT.NumIn() { 32 | return nil, callArgsCountMismError(fT.NumIn(), len(args)) 33 | } 34 | 35 | // Prepare arguments 36 | typedArgs := make([]reflect.Value, len(args)) 37 | for i := range args { 38 | var ok bool 39 | typedArgs[i], ok = args[i].Assign(fT.In(i)) 40 | if !ok { 41 | return nil, callInvArgAtError(i, args[i], fT.In(i)) 42 | } 43 | } 44 | 45 | defer func() { 46 | if rec := recover(); rec != nil { 47 | r = nil 48 | err = callPanicError(rec) 49 | } 50 | }() 51 | rs := f.CallSlice(typedArgs) 52 | return MakeDataRegular(rs[0]), nil 53 | } 54 | 55 | // f must be variadic func with single result (check must perform caller). 56 | func callRegularVariadic(f reflect.Value, args []Data) (r Value, err *intError) { 57 | fT := f.Type() 58 | if len(args) < fT.NumIn()-1 { 59 | return nil, callArgsCountMismError(fT.NumIn(), len(args)-1) 60 | } 61 | 62 | // Prepare arguments 63 | typedArgs := make([]reflect.Value, len(args)) 64 | // non-variadic arguments 65 | for i := 0; i < fT.NumIn()-1; i++ { 66 | var ok bool 67 | typedArgs[i], ok = args[i].Assign(fT.In(i)) 68 | if !ok { 69 | return nil, callInvArgAtError(i, args[i], fT.In(i)) 70 | } 71 | } 72 | // variadic arguments 73 | variadicT := fT.In(fT.NumIn() - 1).Elem() 74 | for i := fT.NumIn() - 1; i < len(args); i++ { 75 | var ok bool 76 | typedArgs[i], ok = args[i].Assign(variadicT) 77 | if !ok { 78 | return nil, callInvArgAtError(i, args[i], variadicT) 79 | } 80 | } 81 | 82 | defer func() { 83 | if rec := recover(); rec != nil { 84 | r = nil 85 | err = callPanicError(rec) 86 | } 87 | }() 88 | rs := f.Call(typedArgs) 89 | return MakeDataRegular(rs[0]), nil 90 | } 91 | 92 | // f must be non-variadic func with single result (check must perform caller). 93 | func callRegularNonVariadic(f reflect.Value, args []Data) (r Value, err *intError) { 94 | // Check in/out arguments count 95 | fT := f.Type() 96 | if len(args) != fT.NumIn() { 97 | return nil, callArgsCountMismError(fT.NumIn(), len(args)) 98 | } 99 | 100 | // Prepare arguments 101 | typedArgs := make([]reflect.Value, len(args)) 102 | for i := range args { 103 | var ok bool 104 | typedArgs[i], ok = args[i].Assign(fT.In(i)) 105 | if !ok { 106 | return nil, callInvArgAtError(i, args[i], fT.In(i)) 107 | } 108 | } 109 | 110 | defer func() { 111 | if rec := recover(); rec != nil { 112 | r = nil 113 | err = callPanicError(rec) 114 | } 115 | }() 116 | rs := f.Call(typedArgs) 117 | return MakeDataRegular(rs[0]), nil 118 | } 119 | -------------------------------------------------------------------------------- /args.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "errors" 5 | "github.com/apaxa-go/helper/goh/asth" 6 | "reflect" 7 | "strings" 8 | ) 9 | 10 | type ( 11 | // Args represents arguments passed into the expression for evaluation. 12 | // It can be nil if no arguments required for evaluation. 13 | // Map indexes is the identifiers (possible with short package specification like "strconv.FormatInt" or "mypackage.MySomething", not "github.com/me/mypackage.MySomething"). 14 | // Map elements is corresponding values. Usually elements is of kind Regular (for typed variables and function), TypedConst (for typed constant) or UntypedConst (for untyped constant). For using function in expression pass it as variable (kind Regular). 15 | Args map[string]Value 16 | // ArgsI is helper class for ArgsFromInterfaces. 17 | // It can be used in composite literal for this function. 18 | ArgsI map[string]interface{} 19 | // ArgsR is helper class for ArgsFromRegulars. 20 | // It can be used in composite literal for this function. 21 | ArgsR map[string]reflect.Value 22 | ) 23 | 24 | // ArgsFromRegulars converts map[string]reflect.Value to Args (map[string]Value). 25 | // ArgsR may be useful. 26 | func ArgsFromRegulars(x map[string]reflect.Value) Args { 27 | r := make(Args, len(x)) 28 | for i := range x { 29 | r[i] = MakeDataRegular(x[i]) 30 | } 31 | return r 32 | } 33 | 34 | // ArgsFromInterfaces converts map[string]interface{} to Args (map[string]Value). 35 | // ArgsI may be useful. 36 | func ArgsFromInterfaces(x map[string]interface{}) Args { 37 | r := make(Args, len(x)) 38 | for i := range x { 39 | r[i] = MakeDataRegularInterface(x[i]) 40 | } 41 | return r 42 | } 43 | 44 | // Compute package if any 45 | func (args Args) normalize() error { 46 | packages := make(map[string]Args) 47 | 48 | // Extract args with package specific 49 | for ident := range args { 50 | parts := strings.Split(ident, ".") 51 | switch len(parts) { 52 | case 1: 53 | continue 54 | case 2: 55 | if parts[0] == "_" || !asth.IsValidIdent(parts[0]) || !asth.IsValidExportedIdent(parts[1]) { 56 | return errors.New("invalid identifier " + ident) 57 | } 58 | 59 | if _, ok := packages[parts[0]]; !ok { 60 | packages[parts[0]] = make(Args) 61 | } 62 | packages[parts[0]][parts[1]] = args[ident] 63 | delete(args, ident) 64 | default: 65 | return errors.New("invalid identifier " + ident) 66 | } 67 | } 68 | 69 | // Add computed packages 70 | for pk, pv := range packages { 71 | // Check for unique package name 72 | if _, ok := args[pk]; ok { 73 | return errors.New("something with package name already exists " + pk) 74 | } 75 | args[pk] = MakePackage(pv) 76 | } 77 | 78 | return nil 79 | } 80 | 81 | // Make all args addressable 82 | func (args Args) makeAddressable() { 83 | for ident, arg := range args { 84 | if arg.Kind() != Datas { 85 | continue 86 | } 87 | if arg.Data().Kind() != Regular { 88 | continue 89 | } 90 | oldV := arg.Data().Regular() 91 | if oldV.CanAddr() { 92 | continue 93 | } 94 | 95 | newV := reflect.New(oldV.Type()).Elem() 96 | newV.Set(oldV) 97 | args[ident] = MakeDataRegular(newV) 98 | } 99 | } 100 | 101 | func (args Args) validate() error { 102 | for ident, arg := range args { 103 | switch arg.Kind() { 104 | case Type: 105 | if arg.Type() == nil { 106 | return errors.New(ident + ": invalid type nil") 107 | } 108 | case Datas: 109 | if arg.Kind() == Datas && arg.Data().Kind() == Regular && !arg.Data().Regular().IsValid() { 110 | return errors.New(ident + ": invalid regular data") 111 | } 112 | } 113 | } 114 | return nil 115 | } 116 | -------------------------------------------------------------------------------- /expr_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "bytes" 5 | "go/parser" 6 | "go/token" 7 | "testing" 8 | ) 9 | 10 | func TestExpression_EvalRaw(t *testing.T) { 11 | for section := range testsExpr { 12 | for _, test := range testsExpr[section] { 13 | expr, err := ParseString(test.expr, "") 14 | if err != nil { 15 | t.Errorf("%v: %v", test.expr, err) 16 | continue 17 | } 18 | 19 | r, err := expr.EvalRaw(test.vars) 20 | if !test.Validate(r, err) { 21 | t.Errorf(test.ErrorMsg(r, err)) 22 | } 23 | } 24 | } 25 | } 26 | 27 | func TestExpression_EvalToInterface(t *testing.T) { 28 | e, err := ParseBytes([]byte("1"), "") 29 | if err != nil { 30 | t.Fatal("no error expected") 31 | } 32 | r, err := e.EvalToInterface(nil) 33 | if r != 1 || err != nil { 34 | t.Errorf("expect %v %v, got %v %v", 1, false, r, err) 35 | } 36 | } 37 | 38 | func TestExpression_EvalToRegular(t *testing.T) { 39 | e, err := ParseBytes([]byte("int8(1)"), "") 40 | if err != nil { 41 | t.Fatal("no error expected") 42 | } 43 | r, err := e.EvalToRegular(nil) 44 | if r.Interface() != int8(1) || err != nil { 45 | t.Errorf("expect %v %v, got %v %v", int8(1), false, r, err) 46 | } 47 | 48 | // 49 | // 50 | // 51 | e, err = ParseBytes([]byte(veryLongNumber), "") 52 | if err != nil { 53 | t.Fatal("no error expected") 54 | } 55 | r, err = e.EvalToRegular(nil) 56 | if err == nil { 57 | t.Error("expect error") 58 | } 59 | 60 | // 61 | // 62 | // 63 | e, err = ParseString("1==1", "") 64 | if err != nil { 65 | t.Fatal("no error expected") 66 | } 67 | r, err = e.EvalToRegular(nil) 68 | if r.Interface() != true || err != nil { 69 | t.Errorf("expect %v %v, got %v %v", true, false, r, err) 70 | } 71 | 72 | // 73 | // 74 | // 75 | e, err = ParseString("nil", "") 76 | if err != nil { 77 | t.Fatal("no error expected") 78 | } 79 | r, err = e.EvalToRegular(nil) 80 | if err == nil { 81 | t.Error("expect error") 82 | } 83 | 84 | // 85 | // 86 | // 87 | e, err = ParseString("a", "") 88 | if err != nil { 89 | t.Fatal("no error expected") 90 | } 91 | r, err = e.EvalToRegular(ArgsFromInterfaces(ArgsI{"a": uint16(5)})) 92 | if r.Interface() != uint16(5) || err != nil { 93 | t.Errorf("expect %v %v, got %v %v", uint16(5), false, r, err) 94 | } 95 | 96 | // 97 | // 98 | // 99 | e, err = ParseString("a", "") 100 | if err != nil { 101 | t.Fatal("no error expected") 102 | } 103 | r, err = e.EvalToRegular(nil) 104 | if err == nil { 105 | t.Error("expect error") 106 | } 107 | } 108 | 109 | func TestExpression_EvalToData(t *testing.T) { 110 | e, err := ParseBytes([]byte("a"), "") 111 | if err != nil { 112 | t.Fatal("no error expected") 113 | } 114 | _, err = e.EvalToRegular(ArgsFromInterfaces(ArgsI{"a.A": 1})) 115 | if err == nil { 116 | t.Error("expect error") 117 | } 118 | } 119 | 120 | func TestParseReader(t *testing.T) { 121 | reader := bytes.NewBufferString("1+2") 122 | 123 | e, err := ParseReader(reader, "") 124 | if err != nil { 125 | t.Fatal("no error expected") 126 | } 127 | r, err := e.EvalToInterface(nil) 128 | if r != 3 || err != nil { 129 | t.Errorf("expect %v %v, got %v %v", 3, false, r, err) 130 | } 131 | 132 | // 133 | // 134 | // 135 | reader = bytes.NewBufferString("1+2as98jknasdf#$") 136 | 137 | _, err = ParseReader(reader, "") 138 | if err == nil { 139 | t.Fatal("expected error") 140 | } 141 | } 142 | 143 | func TestMakeExpression(t *testing.T) { 144 | fset := token.NewFileSet() 145 | e, err := parser.ParseExprFrom(fset, "", "1+2", 0) 146 | if err != nil { 147 | t.Fatal("expect no error") 148 | } 149 | 150 | E := MakeExpression(e, fset, "") 151 | r, err := E.EvalToInterface(nil) 152 | if r != 3 || err != nil { 153 | t.Errorf("expect %v %v, got %v %v", 3, false, r, err) 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /doc_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "fmt" 5 | "github.com/apaxa-go/helper/goh/constanth" 6 | "math" 7 | "testing" 8 | ) 9 | 10 | const exampleBenchSrc = `exampleString(fmt.Sprint(interface{}(math.MaxInt32/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(2)-cap(make([]string, 1, 100))))).String().String() + "."` 11 | const exampleBenchResult exampleString = "!!268435357!!." 12 | 13 | func TestDocSimpleExample(t *testing.T) { 14 | src := "int8(1*(1+2))" 15 | expr, err := ParseString(src, "") 16 | if err != nil { 17 | t.Error(err) 18 | } 19 | r, err := expr.EvalToInterface(nil) 20 | if err != nil { 21 | t.Fatal(err) 22 | } 23 | if testR := int8(1 * (1 + 2)); r != testR { 24 | t.Errorf("expect %v, got %v", testR, r) 25 | } 26 | } 27 | 28 | type exampleString string 29 | 30 | func (s exampleString) String() exampleString { return "!" + s + "!" } 31 | 32 | type exampleStruct struct { 33 | A, B int 34 | } 35 | 36 | func (s exampleStruct) Sum() int { return s.A + s.B } 37 | 38 | func TestDocComplicatedExample(t *testing.T) { 39 | c := make(chan int64, 10) 40 | c <- 2 41 | c <- 2 42 | 43 | testR := exampleString(fmt.Sprint(interface{}(math.MaxInt32/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(<-(<-chan int64)(c))-cap(make([]string, 1, 100))))).String().String() + "." 44 | src := `exampleString(fmt.Sprint(interface{}(math.MaxInt32/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(<-(<-chan int64)(c))-cap(make([]string, 1, 100))))).String().String() + "."` 45 | expr, err := ParseString(src, "") 46 | if err != nil { 47 | t.Error(err) 48 | } 49 | a := Args{ 50 | "exampleString": MakeTypeInterface(exampleString("")), 51 | "fmt.Sprint": MakeDataRegularInterface(fmt.Sprint), 52 | "math.MaxInt32": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt32)), 53 | "exampleStruct": MakeTypeInterface(exampleStruct{}), 54 | "c": MakeDataRegularInterface(c), 55 | } 56 | r, err := expr.EvalToInterface(a) 57 | if err != nil { 58 | t.Fatal(err) 59 | } 60 | if r != testR { 61 | t.Errorf("expect %v, got %v", testR, r) 62 | } 63 | fmt.Printf("%v %T\n", r, r) 64 | } 65 | 66 | func TestDocErrorExample(t *testing.T) { 67 | src := `exampleString(fmt.Sprint(interface{}(math.MaxInt32/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(<-(<-chan int64)(c))-cap(make([]string, 1, 100))))).String().String() + "."` 68 | expr, err := ParseString(src, "") 69 | if err != nil { 70 | t.Error(err) 71 | } 72 | a := Args{ 73 | "exampleString": MakeTypeInterface(exampleString("")), 74 | "fmt.Sprint": MakeDataRegularInterface(fmt.Sprint), 75 | "math.MaxInt32": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt32)), 76 | "exampleStruct": MakeTypeInterface(exampleStruct{}), 77 | // Remove "c" from passed arguments: 78 | // "c": MakeDataRegularInterface(c), 79 | } 80 | _, err = expr.EvalToInterface(a) 81 | if err == nil { 82 | t.Error("expect error") 83 | } 84 | fmt.Println(err) 85 | } 86 | 87 | func BenchmarkDocParse(b *testing.B) { 88 | for i := 0; i < b.N; i++ { 89 | _, err := ParseString(exampleBenchSrc, "") 90 | if err != nil { 91 | b.Error(err) 92 | } 93 | } 94 | } 95 | 96 | func BenchmarkDocEval(b *testing.B) { 97 | expr, err := ParseString(exampleBenchSrc, "") 98 | if err != nil { 99 | b.Fatal(err) 100 | } 101 | 102 | for i := 0; i < b.N; i++ { 103 | a := Args{ 104 | "exampleString": MakeTypeInterface(exampleString("")), 105 | "fmt.Sprint": MakeDataRegularInterface(fmt.Sprint), 106 | "math.MaxInt32": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt32)), 107 | "exampleStruct": MakeTypeInterface(exampleStruct{}), 108 | } 109 | r, err := expr.EvalToInterface(a) 110 | if err != nil { 111 | b.Fatal(err) 112 | } 113 | if r != exampleBenchResult { 114 | b.Fatalf("expect %v, got %v", exampleBenchResult, r) 115 | } 116 | } 117 | } 118 | 119 | func BenchmarkDocGoEval(b *testing.B) { 120 | for i := 0; i < b.N; i++ { 121 | r := exampleString(fmt.Sprint(interface{}(math.MaxInt32/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(2)-cap(make([]string, 1, 100))))).String().String() + "." 122 | if r != exampleBenchResult { 123 | b.Fatalf("expect %v, got %v", exampleBenchResult, r) 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # eval 2 | 3 | [![Build Status](https://travis-ci.org/apaxa-go/eval.svg?branch=master)](https://travis-ci.org/apaxa-go/eval) 4 | [![Coverage Status](https://coveralls.io/repos/github/apaxa-go/eval/badge.svg?branch=master)](https://coveralls.io/github/apaxa-go/eval?branch=master) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/apaxa-go/eval)](https://goreportcard.com/report/github.com/apaxa-go/eval) 6 | [![GoDoc](https://godoc.org/github.com/apaxa-go/eval?status.svg)](https://godoc.org/github.com/apaxa-go/eval) 7 | 8 | Package eval implements evaluation of GoLang expression at runtime. 9 | 10 | # **THIS LIB NO MORE MAINTAINED!** 11 | 12 | # For whose who wants to implement golang eval 13 | Suggestions: 14 | 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). 15 | 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). 16 | 3. Follow language specification (it is hard to implement some additional custom behaviour without breaking compatibility with language accepted expressions). 17 | 4. Language specification may omit some details (so also test with golang compiler). 18 | 19 | # Requirements for expression: 20 | 1. expression itself and all of subexpression must return exactly one value, 21 | 2. see documentation Bugs section for other requirements/restrictions. 22 | 23 | # What does supported: 24 | 25 | 1. types (by passing predefined/custom types and by defining unnamed types in expression itself), 26 | 2. named arguments (regular variables, typed & untyped constants, untyped boolean variable), 27 | 3. "package.SomeThing" notation, 28 | 4. evaluate expression as if it is evaluates in specified package (even write access to private fields), 29 | 5. evaluate expression like Go evaluates it (following most of specification rules), 30 | 6. position of error in source on evaluation. 31 | 32 | # Examples: 33 | Simple: 34 | ``` 35 | src:="int8(1*(1+2))" 36 | expr,err:=ParseString(src,"") 37 | if err!=nil{ 38 | return err 39 | } 40 | r,err:=expr.EvalToInterface(nil) 41 | if err!=nil{ 42 | return err 43 | } 44 | fmt.Printf("%v %T", r, r) // "3 int8" 45 | ``` 46 | 47 | Complicated: 48 | ``` 49 | type exampleString string 50 | 51 | func (s exampleString) String() exampleString { return "!" + s + "!" } 52 | 53 | type exampleStruct struct { 54 | A, B int 55 | } 56 | 57 | func (s exampleStruct) Sum() int { return s.A + s.B } 58 | 59 | func main(){ 60 | c := make(chan int64, 10) 61 | c <- 2 62 | 63 | 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() + "."` 64 | 65 | expr, err := ParseString(src, "") 66 | if err != nil { 67 | return 68 | } 69 | a := Args{ 70 | "exampleString": MakeTypeInterface(exampleString("")), 71 | "fmt.Sprint": MakeDataRegularInterface(fmt.Sprint), 72 | "math.MaxInt64": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt64)), 73 | "exampleStruct": MakeTypeInterface(exampleStruct{}), 74 | "c": MakeDataRegularInterface(c), 75 | } 76 | r, err := expr.EvalToInterface(a) 77 | if err != nil { 78 | return 79 | } 80 | if r != testR { 81 | return 82 | } 83 | fmt.Printf("%v %T\n", r, r) // "!!1152921504606846877!!. exampleString" 84 | return 85 | } 86 | ``` 87 | 88 | With error: 89 | ``` 90 | 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() + "."` 91 | expr, err := ParseString(src, "") 92 | if err != nil { 93 | t.Error(err) 94 | } 95 | a := Args{ 96 | "exampleString": MakeTypeInterface(exampleString("")), 97 | "fmt.Sprint": MakeDataRegularInterface(fmt.Sprint), 98 | "math.MaxInt64": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt64)), 99 | "exampleStruct": MakeTypeInterface(exampleStruct{}), 100 | // Remove "c" from passed arguments: 101 | // "c": MakeDataRegularInterface(c), 102 | } 103 | _, err = expr.EvalToInterface(a) 104 | fmt.Println(err) // "expression:1:119: undefined: c" 105 | ``` 106 | 107 | # Bugs 108 | Please report bug if you found it. -------------------------------------------------------------------------------- /expr.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "github.com/apaxa-go/helper/goh/constanth" 7 | "go/ast" 8 | "go/parser" 9 | "go/token" 10 | "io" 11 | "reflect" 12 | ) 13 | 14 | // DefaultFileName is used as filename if expression constructor does not allow to set custom filename. 15 | const DefaultFileName = "expression" 16 | 17 | // Expression store expression for evaluation. 18 | // It allows evaluate expression multiple times. 19 | // The zero value for Expression is invalid and causes undefined behaviour. 20 | type Expression struct { 21 | e ast.Expr 22 | fset *token.FileSet 23 | pkgPath string 24 | } 25 | 26 | // MakeExpression make expression with specified arguments. 27 | // It does not perform any validation of arguments. 28 | // e is AST of expression. 29 | // fset is used to describe position of error and must be non nil (use token.NewFileSet instead). 30 | // pkgPath is fully qualified package name, for more details see package level documentation. 31 | func MakeExpression(e ast.Expr, fset *token.FileSet, pkgPath string) *Expression { 32 | return &Expression{e, fset, pkgPath} 33 | } 34 | 35 | // Parse parses filename or src for expression using parser.ParseExprFrom. 36 | // For information about filename and src see parser.ParseExprFrom documentation. 37 | // pkgPath is fully qualified package name, for more details see package level documentation. 38 | func Parse(filename string, src interface{}, pkgPath string) (r *Expression, err error) { 39 | r = new(Expression) 40 | r.fset = token.NewFileSet() 41 | r.e, err = parser.ParseExprFrom(r.fset, filename, src, 0) 42 | if err != nil { 43 | return nil, err 44 | } 45 | r.pkgPath = pkgPath 46 | return 47 | } 48 | 49 | // ParseString parses expression from string src. 50 | // pkgPath is fully qualified package name, for more details see package level documentation. 51 | func ParseString(src string, pkgPath string) (r *Expression, err error) { 52 | return Parse(DefaultFileName, src, pkgPath) 53 | } 54 | 55 | // ParseBytes parses expression from []byte src. 56 | // pkgPath is fully qualified package name, for more details see package level documentation. 57 | func ParseBytes(src []byte, pkgPath string) (r *Expression, err error) { 58 | return Parse(DefaultFileName, src, pkgPath) 59 | } 60 | 61 | // ParseReader parses expression from io.Reader src. 62 | // pkgPath is fully qualified package name, for more details see package level documentation. 63 | func ParseReader(src io.Reader, pkgPath string) (r *Expression, err error) { 64 | return Parse(DefaultFileName, src, pkgPath) 65 | } 66 | 67 | // EvalRaw evaluates expression with given arguments args. 68 | // Result of evaluation is Value. 69 | func (e *Expression) EvalRaw(args Args) (r Value, err error) { 70 | defer func() { 71 | rec := recover() 72 | if rec != nil { 73 | err = errors.New(`BUG: unhandled panic "` + fmt.Sprint(rec) + `". Please report bug.`) 74 | } 75 | }() 76 | 77 | err = args.validate() 78 | if err != nil { 79 | return 80 | } 81 | 82 | args.makeAddressable() 83 | 84 | err = args.normalize() 85 | if err != nil { 86 | return 87 | } 88 | 89 | var posErr *posError 90 | r, posErr = e.astExpr(e.e, args) 91 | err = posErr.error(e.fset) 92 | return 93 | } 94 | 95 | // EvalToData evaluates expression with given arguments args. 96 | // It returns error if result of evaluation is not Data. 97 | func (e *Expression) EvalToData(args Args) (r Data, err error) { 98 | var tmp Value 99 | tmp, err = e.EvalRaw(args) 100 | if err != nil { 101 | return 102 | } 103 | 104 | if tmp.Kind() != Datas { 105 | err = notExprError(tmp).pos(e.e).error(e.fset) 106 | return 107 | } 108 | 109 | r = tmp.Data() 110 | return 111 | } 112 | 113 | // EvalToRegular evaluates expression with given arguments args. 114 | // It returns error if result of evaluation is not Data or if it is impossible to represent it as variable using GoLang assignation rules. 115 | func (e *Expression) EvalToRegular(args Args) (r reflect.Value, err error) { 116 | var tmp Data 117 | tmp, err = e.EvalToData(args) 118 | if err != nil { 119 | return 120 | } 121 | 122 | switch tmp.Kind() { 123 | case Regular: 124 | r = tmp.Regular() 125 | case TypedConst: 126 | r = tmp.TypedConst().Value() 127 | case UntypedConst: 128 | tmpC := tmp.UntypedConst() 129 | var ok bool 130 | r, ok = constanth.DefaultValue(tmpC) 131 | if !ok { 132 | err = constOverflowType(tmpC, constanth.DefaultType(tmpC)).pos(e.e).error(e.fset) 133 | } 134 | case UntypedBool: 135 | r = reflect.ValueOf(tmp.UntypedBool()) 136 | default: 137 | err = notExprError(MakeData(tmp)).pos(e.e).error(e.fset) 138 | } 139 | return 140 | } 141 | 142 | // EvalToInterface evaluates expression with given arguments args. 143 | // It returns error if result of evaluation is not Data or if it is impossible to represent it as variable using GoLang assignation rules. 144 | func (e *Expression) EvalToInterface(args Args) (r interface{}, err error) { 145 | var tmp reflect.Value 146 | tmp, err = e.EvalToRegular(args) 147 | if err == nil { 148 | r = tmp.Interface() 149 | } 150 | return 151 | } 152 | -------------------------------------------------------------------------------- /value.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "fmt" 5 | "github.com/apaxa-go/helper/goh/constanth" 6 | "go/constant" 7 | "reflect" 8 | ) 9 | 10 | // ValueKind specifies the kind of value represented by a Value. 11 | type ValueKind int 12 | 13 | // Possible values for value's kind: 14 | const ( 15 | Datas ValueKind = iota // value is Data 16 | Type // type 17 | BuiltInFunc // built-in function 18 | Package // package 19 | ) 20 | 21 | // Value used to store arguments passed to/returned from expression. 22 | // It can stores: data, type, built-in function and package. 23 | // GoLang valid expression can return only data, all other kind is primary used internally while evaluation. 24 | type Value interface { 25 | // Kind returns current kind of value represented by a Value. 26 | Kind() ValueKind 27 | 28 | // DeepType returns human readable kind of stored value. If value stores Data then result is kind of this Data (deep resolution). 29 | DeepType() string 30 | // String returns string human-readable representation of underlying value. 31 | String() string 32 | 33 | // Data returns data if value stores data, otherwise it panics. 34 | Data() Data 35 | // Type returns type if value stores type, otherwise it panics. 36 | Type() reflect.Type 37 | // BuiltInFunc returns name of built-in function if value stores built-in function, otherwise it panics. 38 | BuiltInFunc() string 39 | // Package returns package as map[] if value stores package, otherwise it panics. Name of package itself is unknown. 40 | Package() map[string]Value 41 | 42 | // prevent 3rd party classes from implementing Value. 43 | implementsValue() 44 | } 45 | 46 | type ( 47 | dataVal struct{ v Data } 48 | typeVal struct{ v reflect.Type } 49 | builtInFuncVal string 50 | packageVal map[string]Value 51 | ) 52 | 53 | func (dataVal) Kind() ValueKind { return Datas } 54 | func (typeVal) Kind() ValueKind { return Type } 55 | func (builtInFuncVal) Kind() ValueKind { return BuiltInFunc } 56 | func (packageVal) Kind() ValueKind { return Package } 57 | 58 | func (x dataVal) DeepType() string { return x.v.Kind().String() } 59 | func (x typeVal) DeepType() string { return "type" } 60 | func (builtInFuncVal) DeepType() string { return "built-in function" } 61 | func (packageVal) DeepType() string { return "package" } 62 | 63 | func (x dataVal) String() string { return x.Data().DeepString() } 64 | func (x typeVal) String() string { 65 | var v string 66 | if x.v == nil { 67 | v = "nil" 68 | } else { 69 | v = x.v.String() 70 | } 71 | return fmt.Sprint("type value " + v) 72 | } 73 | func (x builtInFuncVal) String() string { return fmt.Sprintf("built-in function value %v", string(x)) } 74 | func (x packageVal) String() string { 75 | var v = "package (exports:" 76 | for i := range map[string]Value(x) { 77 | v += " " + i 78 | } 79 | v += ")" 80 | return v 81 | } 82 | 83 | func (x dataVal) Data() Data { return x.v } 84 | func (typeVal) Data() Data { panic("") } 85 | func (builtInFuncVal) Data() Data { panic("") } 86 | func (packageVal) Data() Data { panic("") } 87 | 88 | func (dataVal) Type() reflect.Type { panic("") } 89 | func (x typeVal) Type() reflect.Type { return x.v } 90 | func (builtInFuncVal) Type() reflect.Type { panic("") } 91 | func (packageVal) Type() reflect.Type { panic("") } 92 | 93 | func (dataVal) BuiltInFunc() string { panic("") } 94 | func (typeVal) BuiltInFunc() string { panic("") } 95 | func (x builtInFuncVal) BuiltInFunc() string { return string(x) } 96 | func (packageVal) BuiltInFunc() string { panic("") } 97 | 98 | func (dataVal) Package() map[string]Value { panic("") } 99 | func (typeVal) Package() map[string]Value { panic("") } 100 | func (builtInFuncVal) Package() map[string]Value { panic("") } 101 | func (x packageVal) Package() map[string]Value { return map[string]Value(x) } 102 | 103 | func (dataVal) implementsValue() {} 104 | func (typeVal) implementsValue() {} 105 | func (builtInFuncVal) implementsValue() {} 106 | func (packageVal) implementsValue() {} 107 | 108 | // MakeType makes Value which stores type x. 109 | func MakeType(x reflect.Type) Value { return typeVal{x} } 110 | 111 | // MakeTypeInterface makes Value which stores type of x. 112 | func MakeTypeInterface(x interface{}) Value { return MakeType(reflect.TypeOf(x)) } 113 | 114 | // MakeBuiltInFunc makes Value which stores built-in function specified by its name x. 115 | // MakeBuiltInFunc does not perform any checks for validating name. 116 | func MakeBuiltInFunc(x string) Value { return builtInFuncVal(x) } 117 | 118 | // MakePackage makes Value which stores package x. 119 | // x must be a map[]. 120 | // No name of package itself specified. 121 | // Keys in args must not have dots in names. 122 | func MakePackage(x Args) Value { return packageVal(x) } 123 | 124 | // MakeData makes Value which stores data x. 125 | func MakeData(x Data) Value { return dataVal{x} } 126 | 127 | // MakeDataNil makes Value which stores data "nil". 128 | func MakeDataNil() Value { return MakeData(MakeNil()) } 129 | 130 | // MakeDataRegular makes Value which stores regular data x (x is a reflect.Value of required variable). 131 | func MakeDataRegular(x reflect.Value) Value { return MakeData(MakeRegular(x)) } 132 | 133 | // MakeDataRegularInterface makes Value which stores regular data x (x is a required variable). 134 | func MakeDataRegularInterface(x interface{}) Value { return MakeData(MakeRegularInterface(x)) } 135 | 136 | // MakeDataTypedConst makes Value which stores typed constant x. 137 | func MakeDataTypedConst(x constanth.TypedValue) Value { return MakeData(MakeTypedConst(x)) } 138 | 139 | // MakeDataUntypedConst makes Value which stores untyped constant x. 140 | func MakeDataUntypedConst(x constant.Value) Value { return MakeData(MakeUntypedConst(x)) } 141 | 142 | // MakeDataUntypedBool makes Value which stores untyped boolean variable with value x. 143 | func MakeDataUntypedBool(x bool) Value { return MakeData(MakeUntypedBool(x)) } 144 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package eval implements evaluation of GoLang expression at runtime. 2 | // 3 | // Requirements for expression: 4 | // 1. expression itself and all of subexpression must return exactly one value, 5 | // 2. see Bugs section for other requirements/restrictions. 6 | // 7 | // What does supported: 8 | // 9 | // 1. types (by passing predefined/custom types and by defining unnamed types in expression itself), 10 | // 2. named arguments (regular variables, typed & untyped constants, untyped boolean variable), 11 | // 3. "package.SomeThing" notation, 12 | // 4. evaluate expression as if it is evaluates in specified package (even write access to private fields), 13 | // 5. evaluate expression like Go evaluates it (following most of specification rules), 14 | // 6. position of error in source on evaluation. 15 | // 16 | // Supported expression: 17 | // 1. identifier ("MyVar") 18 | // 2. constant ("123.456") 19 | // 3. selector expression ("MyVar.MyField") 20 | // 4. call function and method ("a.F(1,a,nil)") 21 | // 5. unary expression ("-a") 22 | // 6. binary expression ("a+1") 23 | // 7. pointer indirection ("*p") 24 | // 8. pointer dereferencing ("&a") 25 | // 9. parenthesized expression ("2*(1+3)") 26 | // 10. channel type ("chan int") 27 | // 11. function type ("func(int)string"; only type declaration, not function implementation) 28 | // 12. array & slice type ("[...]int{1,2,3}") 29 | // 13. interface type ("interface{}"; only empty interface supported) 30 | // 14. index expression ("a[i]") 31 | // 15. short and full slice expression ("a[1:2:3]") 32 | // 16. composite literal ("MyStruct{nil,2,a}") 33 | // 17. type conversion ("MyInt(int(1))") 34 | // 18. type assertion ("a.(int)"; only single result form) 35 | // 19. receiving from channel ("<-c") 36 | // 37 | // Predefined types (no need to pass it via args): 38 | // 1. bool 39 | // 2. [u]int[8/16/32/64] 40 | // 3. float{32/64} 41 | // 4. complex{64/128} 42 | // 5. byte 43 | // 6. rune 44 | // 7. uintptr 45 | // 8. string 46 | // 47 | // Implemented built-in functions (no need to pass it via args): 48 | // 1. len 49 | // 2. cap 50 | // 3. complex 51 | // 4. real 52 | // 5. imag 53 | // 6. new 54 | // 7. make 55 | // 8. append 56 | // 57 | // Simple example: 58 | // src:="int8(1*(1+2))" 59 | // expr,err:=ParseString(src,"") 60 | // if err!=nil{ 61 | // return err 62 | // } 63 | // r,err:=expr.EvalToInterface(nil) 64 | // if err!=nil{ 65 | // return err 66 | // } 67 | // fmt.Printf("%v %T", r, r) // "3 int8" 68 | // 69 | // Complicated example: 70 | // type exampleString string 71 | // 72 | // func (s exampleString) String() exampleString { return "!" + s + "!" } 73 | // 74 | // type exampleStruct struct { 75 | // A, B int 76 | // } 77 | // 78 | // func (s exampleStruct) Sum() int { return s.A + s.B } 79 | // 80 | // func main(){ 81 | // c := make(chan int64, 10) 82 | // c <- 2 83 | // 84 | // src := `exampleString(fmt.Sprint(interface{}(math.MaxInt32/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(<-(<-chan int64)(c))-cap(make([]string, 1, 100))))).String().String() + "."` 85 | // 86 | // expr, err := ParseString(src, "") 87 | // if err != nil { 88 | // return 89 | // } 90 | // a := Args{ 91 | // "exampleString": MakeTypeInterface(exampleString("")), 92 | // "fmt.Sprint": MakeDataRegularInterface(fmt.Sprint), 93 | // "math.MaxInt32": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt32)), 94 | // "exampleStruct": MakeTypeInterface(exampleStruct{}), 95 | // "c": MakeDataRegularInterface(c), 96 | // } 97 | // r, err := expr.EvalToInterface(a) 98 | // if err != nil { 99 | // return 100 | // } 101 | // if r != testR { 102 | // return 103 | // } 104 | // fmt.Printf("%v %T\n", r, r) // "!!268435357!!. eval.exampleString" 105 | // return 106 | // } 107 | // 108 | // Example with error in expression: 109 | // src := `exampleString(fmt.Sprint(interface{}(math.MaxInt32/exampleStruct(struct{ A, B int }{3, 5}).Sum()+int(<-(<-chan int64)(c))-cap(make([]string, 1, 100))))).String().String() + "."` 110 | // expr, err := ParseString(src, "") 111 | // if err != nil { 112 | // t.Error(err) 113 | // } 114 | // a := Args{ 115 | // "exampleString": MakeTypeInterface(exampleString("")), 116 | // "fmt.Sprint": MakeDataRegularInterface(fmt.Sprint), 117 | // "math.MaxInt32": MakeDataUntypedConst(constanth.MakeUint(math.MaxInt32)), 118 | // "exampleStruct": MakeTypeInterface(exampleStruct{}), 119 | // // Remove "c" from passed arguments: 120 | // // "c": MakeDataRegularInterface(c), 121 | // } 122 | // _, err = expr.EvalToInterface(a) 123 | // fmt.Println(err) // "expression:1:119: undefined: c" 124 | // 125 | // Package eval built on top of reflection, go/ast, go/parser, go/token & go/constant. 126 | // To create Expression it possible to use MakeExpression or some of Parse* functions. 127 | // All of them use pkgPath to control access rights. 128 | // pkgPath used when: 129 | // 130 | // 1. Accessing struct private field. If type of struct belong to pkgPath then all access to struct fields can modify its value (for example, it is possible to set such fields in composite literal). 131 | // 132 | // 2. Creating type in composite literal. All created in expression structures belong to pkgPath. 133 | // 134 | // When Expression is ready it may be evaluated multiple times. Evaluation done via Eval* methods: 135 | // 1. EvalRaw - the most flexible, but the hardest to use, 136 | // 2. EvalToData, 137 | // 3. EvalToRegular, 138 | // 4. EvalToInterface - the least flexible, but the easiest to use. 139 | // In most cases EvalToInterface should be enough and it is easy to use. 140 | // 141 | // Evaluation performance: 142 | // // Parse expression from string 143 | // BenchmarkDocParse-8 200000 9118 ns/op 3800 B/op 106 allocs/op 144 | // // Eval already parsed expression 145 | // BenchmarkDocEval-8 100000 15559 ns/op 6131 B/op 151 allocs/op 146 | // // Eval the same expression by Go 147 | // BenchmarkDocGoEval-8 5000000 283 ns/op 72 B/op 3 allocs/op 148 | // 149 | // If you found a bug (result of this package evaluation differs from evaluation by Go itself) - please report bug at github.com/apaxa-go/eval. 150 | package eval 151 | -------------------------------------------------------------------------------- /ast_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "go/ast" 5 | "go/token" 6 | "reflect" 7 | "testing" 8 | ) 9 | 10 | // 11 | // Types, funcs & objects for testing 12 | // 13 | type SampleStruct struct { 14 | F uint16 15 | } 16 | 17 | func (s SampleStruct) M(x uint32) uint64 { return uint64(s.F) * uint64(x) } 18 | func (s SampleStruct) M2(x uint32) (uint64, int64) { 19 | return uint64(s.F) * uint64(x), int64(s.F) - int64(x) 20 | } 21 | 22 | type SampleInt int8 23 | 24 | func (s SampleInt) Mv(x int16) int32 { return -int32(s) * int32(x) } 25 | func (s *SampleInt) Mp(x int16) int32 { return -int32(*s)*int32(x) + 1 } 26 | 27 | // Check for method extracting. 28 | // It is not trivial to fully check returned value, so do it separately from other tests 29 | func TestSelector(t *testing.T) { 30 | type testSelectorElement struct { 31 | expr string 32 | vars Args 33 | arg interface{} 34 | r interface{} 35 | } 36 | 37 | tests := []testSelectorElement{ 38 | {"a.M", ArgsFromInterfaces(ArgsI{"a": SampleStruct{2}}), uint32(3), uint64(6)}, 39 | {"b.Mv", ArgsFromInterfaces(ArgsI{"b": SampleInt(4)}), int16(5), int32(-20)}, 40 | {"b.Mv", ArgsFromInterfaces(ArgsI{"b": new(SampleInt)}), int16(6), int32(0)}, 41 | {"b.Mp", ArgsFromInterfaces(ArgsI{"b": new(SampleInt)}), int16(7), int32(1)}, 42 | } 43 | 44 | for _, v := range tests { 45 | 46 | expr, err := ParseString(v.expr, "") 47 | if err != nil { 48 | t.Errorf("%v: %v", v.expr, err) 49 | continue 50 | } 51 | selectorAst, ok := expr.e.(*ast.SelectorExpr) 52 | if !ok { 53 | t.Errorf("%v: not a astSelectorExpr", v.expr) 54 | continue 55 | } 56 | 57 | r, posErr := expr.astSelectorExpr(selectorAst, v.vars) 58 | err = posErr.error(token.NewFileSet()) 59 | if err != nil { 60 | t.Errorf("expect not error, got %v", err.Error()) 61 | continue 62 | } 63 | 64 | if r.Kind() != Datas || r.Data().Kind() != Regular || r.Data().Regular().Kind() != reflect.Func { 65 | t.Errorf("expect function, got %v", r.String()) 66 | continue 67 | } 68 | rV := r.Data().Regular() 69 | 70 | rs := rV.Call([]reflect.Value{reflect.ValueOf(v.arg)}) 71 | if l := len(rs); l != 1 { 72 | t.Errorf("expect 1 result, got %v", l) 73 | continue 74 | } 75 | 76 | if rI := rs[0].Interface(); rI != v.r { 77 | t.Errorf("expect %v, got %v", v.r, rI) 78 | } 79 | } 80 | } 81 | 82 | // Check for getting address (&). 83 | // It is not trivial to fully check returned value, so do it separately from other tests 84 | func TestUnary(t *testing.T) { 85 | tmp := SampleStruct{5} 86 | tmp2 := []int8{6} 87 | tests := []testExprElement{ 88 | {"&a.F", ArgsFromInterfaces(ArgsI{"a": &tmp}), MakeDataRegularInterface(&tmp.F), false}, 89 | {"&a[0]", ArgsFromInterfaces(ArgsI{"a": tmp2}), MakeDataRegularInterface(&tmp2[0]), false}, 90 | } 91 | 92 | for _, v := range tests { 93 | expr, err := ParseString(v.expr, "") 94 | if err != nil { 95 | t.Errorf("%v: %v", v.expr, err) 96 | continue 97 | } 98 | unaryAst, ok := expr.e.(*ast.UnaryExpr) 99 | if !ok { 100 | t.Errorf("%v: not a astUnaryExpr", v.expr) 101 | continue 102 | } 103 | 104 | r, posErr := expr.astUnaryExpr(unaryAst, v.vars) 105 | err = posErr.error(token.NewFileSet()) 106 | if !v.Validate(r, err) { 107 | t.Errorf(v.ErrorMsg(r, err)) 108 | } 109 | } 110 | } 111 | 112 | // Check for cases which can not be generated by parsing expression source. 113 | func TestAstSelectorExpr(t *testing.T) { 114 | tmp := ast.BasicLit{Kind: token.INT, Value: "1234"} 115 | e := ast.SelectorExpr{X: &tmp, Sel: nil} 116 | if r, err := ((*Expression)(nil)).astSelectorExpr(&e, nil); r != nil || err == nil { 117 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 118 | } 119 | } 120 | 121 | // Check for cases which can not be generated by parsing expression source. 122 | func TestAstBasicLit(t *testing.T) { 123 | e := ast.BasicLit{Kind: token.INT, Value: "str"} 124 | if r, err := ((*Expression)(nil)).astBasicLit(&e, nil); r != nil || err == nil { 125 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 126 | } 127 | } 128 | 129 | // Check for cases which can not be generated by parsing expression source. 130 | func TestAstExpr(t *testing.T) { 131 | if r, err := ((*Expression)(nil)).astExpr(nil, nil); r != nil || err == nil { 132 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 133 | } 134 | if r, err := ((*Expression)(nil)).astExpr(&ast.BadExpr{}, nil); r != nil || err == nil { 135 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 136 | } 137 | } 138 | 139 | // Check for cases which can not be generated by parsing expression source. 140 | func TestAstStructType(t *testing.T) { 141 | // 142 | // 1 143 | // 144 | e := &ast.StructType{} 145 | if r, err := ((*Expression)(nil)).astStructType(e, nil); r != nil || err == nil { 146 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 147 | } 148 | 149 | // 150 | // 2 151 | // 152 | expr, err := ParseString("struct{X int `potobuf:1`}", "") 153 | if err != nil { 154 | t.Fatal("expect no error") 155 | } 156 | e = expr.e.(*ast.StructType) 157 | e.Fields.List[0].Tag.Value = "1234" 158 | e.Fields.List[0].Tag.Kind = token.INT 159 | if r, err := expr.astStructType(e, nil); r != nil || err == nil { 160 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 161 | } 162 | 163 | // 164 | // 3 165 | // 166 | expr, err = ParseString("struct{int `potobuf:1`}", "") 167 | if err != nil { 168 | t.Fatal("expect no error") 169 | } 170 | e = expr.e.(*ast.StructType) 171 | e.Fields.List[0].Tag.Value = "1234" 172 | e.Fields.List[0].Tag.Kind = token.INT 173 | if r, err := expr.astStructType(e, nil); r != nil || err == nil { 174 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 175 | } 176 | } 177 | 178 | // Check for cases which can not be generated by parsing expression source. 179 | func TestAstInterfaceType(t *testing.T) { 180 | e := &ast.InterfaceType{} 181 | if r, err := ((*Expression)(nil)).astInterfaceType(e, nil); r != nil || err == nil { 182 | t.Errorf("expect %v %v, got %v %v", nil, true, r, err) 183 | } 184 | } 185 | 186 | func TestAstSelectorExpr2(t *testing.T) { 187 | expr, err := ParseString(`myStruct1{i:1}`, "github.com/apaxa-go/eval") 188 | testR := MakeDataRegularInterface(myStruct1{i: 1}) 189 | if err != nil { 190 | t.Fatal("expect no error") 191 | } 192 | r, err := expr.EvalRaw(Args{"myStruct1": MakeType(reflect.TypeOf(myStruct1{}))}) 193 | if err != nil || !isValuesEqual(r, testR) { 194 | t.Fatalf("expect %v %v, got %v %v", testR, nil, r, err) 195 | } 196 | 197 | // 198 | // 199 | // 200 | expr, err = ParseString(`myStruct1{1,"str"}`, "github.com/apaxa-go/eval") 201 | testR = MakeDataRegularInterface(myStruct1{1, "str"}) 202 | if err != nil { 203 | t.Fatal("expect no error") 204 | } 205 | r, err = expr.EvalRaw(Args{"myStruct1": MakeType(reflect.TypeOf(myStruct1{}))}) 206 | if err != nil || !isValuesEqual(r, testR) { 207 | t.Fatalf("expect %v %v, got %v %v", testR, nil, r, err) 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /data-funcs.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/goh/constanth" 5 | "github.com/apaxa-go/helper/reflecth" 6 | "go/constant" 7 | "go/token" 8 | "reflect" 9 | ) 10 | 11 | func binaryOp(x Data, op token.Token, y Data) (r Data, err *intError) { 12 | switch xK, yK := x.Kind(), y.Kind(); { 13 | case xK == Nil || yK == Nil || xK == UntypedBool || yK == UntypedBool: // This case needed first to prevent other cases to perform. 14 | fallthrough 15 | default: 16 | err = invBinOpTypesInvalError(x, op, y) 17 | case xK == Regular && yK == Regular, xK == Regular, yK == Regular: // At least one args is regular value 18 | // Prepare args 19 | var xV, yV reflect.Value 20 | switch { 21 | case xK == Regular && yK == Regular: 22 | xV = x.Regular() 23 | yV = y.Regular() 24 | case xK == Regular: 25 | xV = x.Regular() 26 | var ok bool 27 | yV, ok = y.Assign(xV.Type()) 28 | if !ok { 29 | return nil, invBinOpTypesMismError(x, op, y) 30 | } 31 | case yK == Regular: 32 | yV = y.Regular() 33 | var ok bool 34 | xV, ok = x.Assign(yV.Type()) 35 | if !ok { 36 | return nil, invBinOpTypesMismError(x, op, y) 37 | } 38 | } 39 | 40 | // Calc 41 | r, err = binaryOpRegular(xV, op, yV) 42 | case xK == TypedConst && yK == TypedConst, xK == TypedConst && yK == UntypedConst, xK == UntypedConst && yK == TypedConst: // At least one args is typed constant 43 | // Prepare args 44 | var xTC, yTC constanth.TypedValue 45 | switch { 46 | case xK == TypedConst && yK == TypedConst: 47 | xTC = x.TypedConst() 48 | yTC = y.TypedConst() 49 | case xK == TypedConst: 50 | xTC = x.TypedConst() 51 | var ok bool 52 | yTC, ok = constanth.MakeTypedValue(y.UntypedConst(), xTC.Type()) 53 | if !ok { 54 | return nil, invBinOpTypesMismError(x, op, y) 55 | } 56 | case yK == TypedConst: 57 | yTC = y.TypedConst() 58 | var ok bool 59 | xTC, ok = constanth.MakeTypedValue(x.UntypedConst(), yTC.Type()) 60 | if !ok { 61 | return nil, invBinOpTypesMismError(x, op, y) 62 | } 63 | } 64 | 65 | // Calc 66 | r, err = binaryOpTypedConst(xTC, op, yTC) 67 | case xK == UntypedConst && yK == UntypedConst: 68 | r, err = binaryOpUntypedConst(x.UntypedConst(), op, y.UntypedConst()) 69 | } 70 | return 71 | } 72 | 73 | func compareOpWithNil(x Data, op token.Token) (r Data, err *intError) { 74 | var equality bool // true if op == "==" 75 | switch op { 76 | case token.EQL: 77 | equality = true 78 | case token.NEQ: 79 | equality = false 80 | default: 81 | return nil, invBinOpError(x.DeepString(), op.String(), "nil", "operator "+op.String()+" not defined on nil") 82 | } 83 | 84 | if x.Kind() == Regular { 85 | switch xV := x.Regular(); xV.Kind() { 86 | case reflect.Slice, reflect.Map, reflect.Func, reflect.Ptr, reflect.Chan, reflect.Interface: 87 | return untypedBoolData(xV.IsNil() == equality), nil // TODO IsNill not the same as ==nil 88 | } 89 | } 90 | return nil, cmpWithNilError(x, op) 91 | } 92 | 93 | func compareOpWithUntypedBool(x Data, op token.Token, y bool) (r Data, err *intError) { 94 | var equality bool // true if op == "==" 95 | switch op { 96 | case token.EQL: 97 | equality = true 98 | case token.NEQ: 99 | equality = false 100 | default: 101 | return nil, invBinOpUnknOpError(x, op, MakeUntypedBool(y)) 102 | } 103 | 104 | var xB bool 105 | switch x.Kind() { 106 | case Regular: 107 | xV := x.Regular() 108 | if xV.Kind() != reflect.Bool { 109 | return nil, invBinOpTypesMismError(x, op, MakeUntypedBool(y)) 110 | } 111 | xB = xV.Bool() 112 | case TypedConst: 113 | var ok bool 114 | xB, ok = constanth.BoolVal(x.TypedConst().Untyped()) 115 | if !ok { 116 | return nil, invBinOpTypesMismError(x, op, MakeUntypedBool(y)) 117 | } 118 | case UntypedConst: 119 | var ok bool 120 | xB, ok = constanth.BoolVal(x.UntypedConst()) 121 | if !ok { 122 | return nil, invBinOpTypesMismError(x, op, MakeUntypedBool(y)) 123 | } 124 | case UntypedBool: 125 | xB = x.UntypedBool() 126 | default: 127 | return nil, invBinOpTypesInvalError(x, op, MakeUntypedBool(y)) 128 | } 129 | 130 | return untypedBoolData((xB == y) == equality), nil 131 | } 132 | 133 | func compareOp(x Data, op token.Token, y Data) (r Data, err *intError) { 134 | var rB bool 135 | switch xK, yK := x.Kind(), y.Kind(); { 136 | case xK == Nil: 137 | return compareOpWithNil(y, op) 138 | case yK == Nil: 139 | return compareOpWithNil(x, op) 140 | case xK == UntypedBool: 141 | return compareOpWithUntypedBool(y, op, x.UntypedBool()) 142 | case yK == UntypedBool: 143 | return compareOpWithUntypedBool(x, op, y.UntypedBool()) 144 | case xK == Regular && yK == Regular, xK == Regular, yK == Regular: // At least one args is regular value 145 | // Prepare args 146 | var xV, yV reflect.Value 147 | switch { 148 | case xK == Regular && yK == Regular: 149 | xV = x.Regular() 150 | yV = y.Regular() 151 | case xK == Regular: 152 | xV = x.Regular() 153 | var ok bool 154 | yV, ok = y.Assign(xV.Type()) 155 | if !ok { 156 | return nil, invBinOpTypesMismError(x, op, y) 157 | } 158 | case yK == Regular: 159 | yV = y.Regular() 160 | var ok bool 161 | xV, ok = x.Assign(yV.Type()) 162 | if !ok { 163 | return nil, invBinOpTypesMismError(x, op, y) 164 | } 165 | } 166 | 167 | // Calc 168 | rB, err = compareOpRegular(xV, op, yV) 169 | case xK == TypedConst && yK == TypedConst, xK == TypedConst && yK == UntypedConst, xK == UntypedConst && yK == TypedConst: // At least one args is typed constant 170 | // Prepare args 171 | var xTC, yTC constanth.TypedValue 172 | switch { 173 | case xK == TypedConst && yK == TypedConst: 174 | xTC = x.TypedConst() 175 | yTC = y.TypedConst() 176 | case xK == TypedConst: 177 | xTC = x.TypedConst() 178 | var ok bool 179 | yTC, ok = constanth.MakeTypedValue(y.UntypedConst(), xTC.Type()) 180 | if !ok { 181 | return nil, invBinOpTypesMismError(x, op, y) 182 | } 183 | case yK == TypedConst: 184 | yTC = y.TypedConst() 185 | var ok bool 186 | xTC, ok = constanth.MakeTypedValue(x.UntypedConst(), yTC.Type()) 187 | if !ok { 188 | return nil, invBinOpTypesMismError(x, op, y) 189 | } 190 | } 191 | 192 | // Calc 193 | rB, err = compareOpTypedConst(xTC, op, yTC) 194 | case xK == UntypedConst && yK == UntypedConst: 195 | rB, err = compareOpUntypedConst(x.UntypedConst(), op, y.UntypedConst()) 196 | default: 197 | err = invBinOpTypesInvalError(x, op, y) // unreachable? 198 | } 199 | if err == nil { 200 | r = untypedBoolData(rB) 201 | } 202 | return 203 | } 204 | 205 | func shiftOp(x Data, op token.Token, y Data) (r Data, err *intError) { 206 | // Calc right operand 207 | var yUint uint 208 | switch y.Kind() { 209 | case Regular: 210 | yV := y.Regular() 211 | if !reflecth.IsUint(yV.Kind()) { 212 | return nil, invBinOpShiftCountError(x, op, y) 213 | } 214 | yUint = uint(yV.Uint()) 215 | case TypedConst: 216 | yTC := y.TypedConst() 217 | if !reflecth.IsUint(yTC.Type().Kind()) { 218 | return nil, invBinOpShiftCountError(x, op, y) 219 | } 220 | var ok bool 221 | yUint, ok = constanth.UintVal(yTC.Untyped()) 222 | if !ok { 223 | return nil, invBinOpShiftCountError(x, op, y) // can be reachable only on 32-bit arch 224 | } 225 | case UntypedConst: 226 | var ok bool 227 | yUint, ok = constanth.UintVal(y.UntypedConst()) 228 | if !ok { 229 | return nil, invBinOpShiftCountError(x, op, y) 230 | } 231 | default: 232 | return nil, invBinOpShiftCountError(x, op, y) 233 | } 234 | 235 | switch x.Kind() { 236 | case Regular: 237 | r, err = shiftOpRegular(x.Regular(), op, yUint) 238 | case TypedConst: 239 | var rTC constanth.TypedValue 240 | rTC, err = shiftOpTypedConst(x.TypedConst(), op, yUint) 241 | if err == nil { 242 | switch y.IsConst() { 243 | case true: 244 | r = typedConstData(rTC) 245 | case false: 246 | r = regData(rTC.Value()) 247 | } 248 | } 249 | case UntypedConst: 250 | var rC constant.Value 251 | rC, err = shiftOpUntypedConst(x.UntypedConst(), op, yUint) 252 | if err == nil { 253 | switch y.IsConst() { 254 | case true: 255 | r = MakeUntypedConst(rC) 256 | case false: 257 | rV, ok := constanth.DefaultValue(rC) 258 | if !ok { 259 | err = constOverflowType(rC, constanth.DefaultType(rC)) 260 | } else { 261 | r = MakeRegular(rV) 262 | } 263 | } 264 | } 265 | 266 | default: 267 | err = invBinOpShiftArgError(x, op, y) 268 | } 269 | return 270 | } 271 | 272 | func unaryOp(op token.Token, y Data) (r Data, err *intError) { 273 | switch y.Kind() { 274 | case Regular: 275 | r, err = unaryOpRegular(op, y.Regular()) 276 | case TypedConst: 277 | r, err = unaryOpTypedConst(op, y.TypedConst(), 0) // TODO prec should be set? 278 | case UntypedConst: 279 | r, err = unaryOpUntypedConst(op, y.UntypedConst(), 0) // TODO prec should be set? 280 | case UntypedBool: 281 | switch op { 282 | case token.NOT: 283 | r = untypedBoolData(!y.UntypedBool()) 284 | default: 285 | err = invUnaryOp(y, op) 286 | } 287 | default: 288 | err = invUnaryOp(y, op) 289 | } 290 | return 291 | } 292 | -------------------------------------------------------------------------------- /data_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/goh/constanth" 5 | "github.com/apaxa-go/helper/mathh" 6 | "github.com/apaxa-go/helper/reflecth" 7 | "reflect" 8 | "testing" 9 | ) 10 | 11 | func TestDataKind_String(t *testing.T) { 12 | if s := Nil.String(); s != "nil" { 13 | t.Errorf("got %v", s) 14 | } 15 | if s := Regular.String(); s != "regular variable" { 16 | t.Errorf("got %v", s) 17 | } 18 | if s := TypedConst.String(); s != "typed constant" { 19 | t.Errorf("got %v", s) 20 | } 21 | if s := UntypedConst.String(); s != "untyped constant" { 22 | t.Errorf("got %v", s) 23 | } 24 | if s := UntypedBool.String(); s != "untyped boolean" { 25 | t.Errorf("got %v", s) 26 | } 27 | if s := DataKind(100).String(); s != "unknown data" { 28 | t.Errorf("got %v", s) 29 | } 30 | } 31 | 32 | func TestNilData_Regular(t *testing.T) { 33 | defer func() { _ = recover() }() 34 | MakeNil().Regular() 35 | t.Error("expect panic") 36 | } 37 | 38 | func TestTypedConstData_Regular(t *testing.T) { 39 | defer func() { _ = recover() }() 40 | MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeBool(true), reflecth.TypeBool())).Regular() 41 | t.Error("expect panic") 42 | } 43 | 44 | func TestUntypedConstData_Regular(t *testing.T) { 45 | defer func() { _ = recover() }() 46 | MakeUntypedConst(constanth.MakeInt(1)).Regular() 47 | t.Error("expect panic") 48 | } 49 | 50 | func TestUntypedBoolData_Regular(t *testing.T) { 51 | defer func() { _ = recover() }() 52 | MakeUntypedBool(true).Regular() 53 | t.Error("expect panic") 54 | } 55 | 56 | func TestNilData_TypedConst(t *testing.T) { 57 | defer func() { _ = recover() }() 58 | MakeNil().TypedConst() 59 | t.Error("expect panic") 60 | } 61 | 62 | func TestRegData_TypedConst(t *testing.T) { 63 | defer func() { _ = recover() }() 64 | MakeRegularInterface("str").TypedConst() 65 | t.Error("expect panic") 66 | } 67 | 68 | func TestUntypedConstData_TypedConst(t *testing.T) { 69 | defer func() { _ = recover() }() 70 | MakeUntypedConst(constanth.MakeInt(1)).TypedConst() 71 | t.Error("expect panic") 72 | } 73 | 74 | func TestUntypedBoolData_TypedConst(t *testing.T) { 75 | defer func() { _ = recover() }() 76 | MakeUntypedBool(true).TypedConst() 77 | t.Error("expect panic") 78 | } 79 | 80 | func TestNilData_UntypedConst(t *testing.T) { 81 | defer func() { _ = recover() }() 82 | MakeNil().UntypedConst() 83 | t.Error("expect panic") 84 | } 85 | 86 | func TestRegData_UntypedConst(t *testing.T) { 87 | defer func() { _ = recover() }() 88 | MakeRegularInterface("str").UntypedConst() 89 | t.Error("expect panic") 90 | } 91 | 92 | func TestTypedConstData_UntypedConst(t *testing.T) { 93 | defer func() { _ = recover() }() 94 | MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeBool(true), reflecth.TypeBool())).UntypedConst() 95 | t.Error("expect panic") 96 | } 97 | 98 | func TestUntypedBoolData_UntypedConst(t *testing.T) { 99 | defer func() { _ = recover() }() 100 | MakeUntypedBool(true).UntypedConst() 101 | t.Error("expect panic") 102 | } 103 | 104 | func TestNilData_UntypedBool(t *testing.T) { 105 | defer func() { _ = recover() }() 106 | MakeNil().UntypedBool() 107 | t.Error("expect panic") 108 | } 109 | 110 | func TestRegData_UntypedBool(t *testing.T) { 111 | defer func() { _ = recover() }() 112 | MakeRegularInterface("str").UntypedBool() 113 | t.Error("expect panic") 114 | } 115 | 116 | func TestTypedConstData_UntypedBool(t *testing.T) { 117 | defer func() { _ = recover() }() 118 | MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeBool(true), reflecth.TypeBool())).UntypedBool() 119 | t.Error("expect panic") 120 | } 121 | 122 | func TestUntypedConstData_UntypedBool(t *testing.T) { 123 | defer func() { _ = recover() }() 124 | MakeUntypedConst(constanth.MakeInt(1)).UntypedBool() 125 | t.Error("expect panic") 126 | } 127 | 128 | func TestData_IsConst(t *testing.T) { 129 | if MakeNil().IsConst() { 130 | t.Error("expect false") 131 | } 132 | if MakeRegularInterface("str").IsConst() { 133 | t.Error("expect false") 134 | } 135 | if !MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeBool(true), reflecth.TypeBool())).IsConst() { 136 | t.Error("expect true") 137 | } 138 | if !MakeUntypedConst(constanth.MakeInt(1)).IsConst() { 139 | t.Error("expect true") 140 | } 141 | if MakeUntypedBool(true).IsConst() { 142 | t.Error("expect false") 143 | } 144 | } 145 | 146 | func TestData_IsTyped(t *testing.T) { 147 | if MakeNil().IsTyped() { 148 | t.Error("expect false") 149 | } 150 | if !MakeRegularInterface("str").IsTyped() { 151 | t.Error("expect true") 152 | } 153 | if !MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeBool(true), reflecth.TypeBool())).IsTyped() { 154 | t.Error("expect true") 155 | } 156 | if MakeUntypedConst(constanth.MakeInt(1)).IsTyped() { 157 | t.Error("expect false") 158 | } 159 | if MakeUntypedBool(true).IsTyped() { 160 | t.Error("expect false") 161 | } 162 | } 163 | 164 | func TestNilData_DeepValue(t *testing.T) { 165 | if v := MakeNil().DeepValue(); v != "nil" { 166 | t.Errorf("got %v", v) 167 | } 168 | } 169 | 170 | func TestData_Assign(t *testing.T) { 171 | type testElement struct { 172 | d Data 173 | t reflect.Type 174 | a bool // assignable 175 | aR reflect.Value 176 | c bool // convertible 177 | cR Data 178 | } 179 | 180 | tests := []testElement{ 181 | {MakeNil(), reflect.TypeOf([]int{}), true, reflect.ValueOf([]int(nil)), true, MakeRegularInterface([]int(nil))}, 182 | {MakeNil(), reflecth.TypeBool(), false, reflect.Value{}, false, nil}, 183 | {MakeRegularInterface(1), reflecth.TypeFloat64(), false, reflect.Value{}, true, MakeRegularInterface(float64(1))}, 184 | {MakeRegularInterface(1), reflecth.TypeInt(), true, reflect.ValueOf(1), true, MakeRegularInterface(1)}, 185 | {MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt32(256), reflecth.TypeInt32())), reflecth.TypeInt8(), false, reflect.Value{}, false, nil}, 186 | {MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt32(256), reflecth.TypeInt32())), reflecth.TypeInt32(), true, reflect.ValueOf(int32(256)), true, MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt32(256), reflecth.TypeInt32()))}, 187 | {MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt32(256), reflecth.TypeInt32())), reflecth.TypeInt64(), false, reflect.Value{}, true, MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt64(256), reflecth.TypeInt64()))}, 188 | {MakeUntypedConst(constanth.MakeString("str")), reflecth.TypeInt32(), false, reflect.Value{}, false, nil}, 189 | {MakeUntypedConst(constanth.MakeInt16(1000)), reflecth.TypeInt32(), true, reflect.ValueOf(int32(1000)), true, MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt32(1000), reflecth.TypeInt32()))}, 190 | {MakeUntypedBool(true), reflecth.TypeBool(), true, reflect.ValueOf(true), true, MakeRegularInterface(true)}, 191 | {MakeUntypedBool(true), reflecth.TypeString(), false, reflect.Value{}, false, nil}, 192 | } 193 | 194 | assign := func(d Data, t reflect.Type) (r reflect.Value, ok bool) { 195 | ok = true 196 | defer func() { 197 | if rec := recover(); rec != nil { 198 | ok = false 199 | } 200 | }() 201 | r = d.MustAssign(t) 202 | return 203 | } 204 | convert := func(d Data, t reflect.Type) (r Data, ok bool) { 205 | ok = true 206 | defer func() { 207 | if rec := recover(); rec != nil { 208 | ok = false 209 | } 210 | }() 211 | r = d.MustConvert(t) 212 | return 213 | } 214 | 215 | for _, test := range tests { 216 | a := test.d.AssignableTo(test.t) 217 | aR, a1 := assign(test.d, test.t) 218 | c := test.d.ConvertibleTo(test.t) 219 | cR, c1 := convert(test.d, test.t) 220 | if a != test.a || a1 != test.a || (test.a && (!isDatasEqual(MakeRegular(aR), MakeRegular(test.aR)))) || c != test.c || c1 != test.c || (test.c && (!isDatasEqual(cR, test.cR))) { 221 | t.Errorf("%v to %v: expect\n%v %v %v %v %v %v\ngot\n%v %v %v %v %v %v", test.d, test.t, test.a, test.a, test.aR, test.c, test.c, test.cR.DeepString(), a, a1, aR, c, c1, cR.DeepString()) 222 | } 223 | } 224 | } 225 | 226 | func TestData_AsInt(t *testing.T) { 227 | type testElement struct { 228 | d Data 229 | r int 230 | ok bool 231 | } 232 | 233 | tests := []testElement{ 234 | {MakeNil(), 0, false}, 235 | {MakeRegularInterface(100), 100, true}, 236 | {MakeRegularInterface(uint(100)), 100, true}, 237 | {MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt(100), reflecth.TypeInt())), 100, true}, 238 | {MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeString("100"), reflecth.TypeString())), 0, false}, 239 | {MakeUntypedConst(constanth.MakeUint64(mathh.MaxInt64 + 1)), 0, false}, 240 | {MakeUntypedConst(constanth.MakeUint64(mathh.MaxInt32)), mathh.MaxInt32, true}, 241 | {MakeUntypedBool(true), 0, false}, 242 | } 243 | 244 | for _, test := range tests { 245 | r, ok := test.d.AsInt() 246 | if r != test.r || ok != test.ok { 247 | t.Errorf("%v: expect %v %v, got %v %v", test.d.DeepValue(), test.r, test.ok, r, ok) 248 | } 249 | } 250 | } 251 | 252 | func TestData_ImplementsData(t *testing.T) { 253 | datas := []Data{ 254 | MakeNil(), 255 | MakeRegularInterface(1), 256 | MakeTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt(100), reflecth.TypeInt())), 257 | MakeUntypedConst(constanth.MakeUint64(mathh.MaxInt64 + 1)), 258 | MakeUntypedBool(true), 259 | } 260 | for _, d := range datas { 261 | d.implementsData() 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/strconvh" 5 | "go/ast" 6 | "go/constant" 7 | "go/token" 8 | "reflect" 9 | ) 10 | 11 | func identUndefinedError(ident string) *intError { 12 | return newIntError("undefined: " + ident) 13 | } 14 | func invAstError(msg string) *intError { 15 | return newIntError("invalid AST: " + msg) 16 | } 17 | func invAstNilError() *intError { 18 | return invAstError("evaluate nil expr") 19 | } 20 | func invAstUnsupportedError(e ast.Expr) *intError { 21 | return invAstError("expression evaluation does not support " + reflect.TypeOf(e).String()) 22 | } 23 | func invAstSelectorError() *intError { 24 | return invAstError("no field specified (Sel is nil)") 25 | } 26 | func invAstNilStructFieldsError() *intError { 27 | return invAstError("nil struct's fields") 28 | } 29 | func invAstNilInterfaceMethodsError() *intError { 30 | return invAstError("nil interface's methods") 31 | } 32 | func unsupportedInterfaceTypeError() *intError { 33 | return newIntError("non empty interface type (with methods) declaration currently does not supported") 34 | } 35 | func invAstNonStringTagError() *intError { 36 | return invAstError("tag is not of type string") 37 | } 38 | func invSelectorXError(x Value) *intError { 39 | return newIntError("unable to select from " + x.DeepType()) 40 | } 41 | func syntaxError(msg string) *intError { 42 | return newIntError("syntax error: " + msg) 43 | } 44 | func syntaxInvBasLitError(literal string) *intError { 45 | return syntaxError("invalid basic literal \"" + literal + "\"") 46 | } 47 | func indirectInvalError(x Value) *intError { 48 | return newIntError("invalid indirect of " + x.String() + " (type " + x.DeepType() + ")") 49 | } 50 | func notExprError(x Value) *intError { 51 | return newIntError(x.DeepType() + " is not an expression") 52 | } 53 | 54 | //func syntaxMisChanTypeError() *intError { 55 | // return syntaxError("syntax error: missing channel element type") 56 | //} 57 | //func syntaxMisArrayTypeError() *intError { 58 | // return syntaxError("syntax error: missing array element type") 59 | //} 60 | //func syntaxMisVariadicTypeError() *intError { 61 | // return syntaxError("final argument in variadic function missing type") 62 | //} 63 | func sliceInvTypeError(x Data) *intError { 64 | return newIntError("cannot slice " + x.DeepString()) 65 | } 66 | func notTypeError(x Value) *intError { 67 | return newIntError(x.String() + " is not a type") 68 | } 69 | func initMixError() *intError { 70 | return newIntError("mixture of field:value and value initializers") 71 | } 72 | func initStructInvFieldNameError() *intError { 73 | return newIntError("invalid field name in struct initializer") 74 | } 75 | func initArrayInvIndexError() *intError { 76 | return newIntError("index must be non-negative integer constant") 77 | } 78 | func initArrayDupIndexError(i int) *intError { 79 | return newIntError("duplicate index in array literal: " + strconvh.FormatInt(i)) 80 | } 81 | func initMapMisKeyError() *intError { 82 | return newIntError("missing key in map literal") 83 | } 84 | func initInvTypeError(t reflect.Type) *intError { 85 | return newIntError("invalid type for composite literal: " + t.String()) 86 | } 87 | func funcInvEllipsisPos() *intError { 88 | return newIntError("can only use ... with final input parameter") 89 | } 90 | func cannotUseAsError(dst reflect.Type, src Data, in string) *intError { 91 | return newIntError("cannot use " + src.DeepString() + " as type " + dst.String() + " in " + in) 92 | } 93 | func assignTypesMismError(dst reflect.Type, src Data) *intError { 94 | return cannotUseAsError(dst, src, "assigment") 95 | } 96 | func appendMismTypeError(dst reflect.Type, src Data) *intError { 97 | return cannotUseAsError(dst, src, "append") 98 | } 99 | func assignDstUnsettableError(dst Data) *intError { 100 | return newIntError("cannot change " + dst.DeepString() + " in assignment") 101 | } 102 | func compLitInvTypeError(t reflect.Type) *intError { 103 | return newIntError("invalid type for composite literal: " + t.String()) 104 | } 105 | func compLitUnknFieldError(s reflect.Value, f string) *intError { 106 | return newIntError("unknown " + s.Type().String() + " field '" + f + "' in struct literal") 107 | } 108 | func compLitArgsCountMismError(req, got int) *intError { 109 | if req > got { 110 | return newIntError("too few values in struct initializer") 111 | } 112 | return newIntError("too many values in struct initializer") 113 | } 114 | func compLitNegIndexError() *intError { 115 | return newIntError("index must be non-negative integer constant") 116 | } 117 | func compLitIndexOutOfBoundsError(max, i int) *intError { 118 | return newIntError("array index " + strconvh.FormatInt(i) + " out of bounds [0:" + strconvh.FormatInt(max) + "]") 119 | } 120 | func invBinOpError(x, op, y, reason string) *intError { 121 | return newIntError("invalid operation: " + x + " " + op + " " + y + " (" + reason + ")") 122 | } 123 | func invBinOpUnknOpError(x Data, op token.Token, y Data) *intError { 124 | return invBinOpError(x.DeepString(), op.String(), y.DeepString(), "operator "+op.String()+" not defined on nil") 125 | } 126 | func invBinOpTypesMismError(x Data, op token.Token, y Data) *intError { 127 | return invBinOpError(x.DeepString(), op.String(), y.DeepString(), "mismatched types "+x.DeepType()+" and "+y.DeepType()) 128 | } 129 | func invBinOpTypesInvalError(x Data, op token.Token, y Data) *intError { 130 | return invBinOpError(x.DeepString(), op.String(), y.DeepString(), "invalid types "+x.DeepType()+" and/or "+y.DeepType()) 131 | } 132 | 133 | //func invBinOpTypesIncompError(x Value, op token.Token, y Value) *intError { 134 | // return invBinOpError(x.String(), op.String(), y.String(), "incomparable types "+x.DeepType()+" and "+y.DeepType()) 135 | //} 136 | //func invBinOpTypesUnorderError(x Value, op token.Token, y Value) *intError { 137 | // return invBinOpError(x.String(), op.String(), y.String(), "unordered types "+x.DeepType()+" and "+y.DeepType()) 138 | //} 139 | //func invBinOpInvalError(x Value, op token.Token, y Value) *intError { 140 | // return invBinOpError(x.String(), op.String(), y.String(), "invalid operator") 141 | //} 142 | func invBinOpShiftCountError(x Data, op token.Token, y Data) *intError { 143 | return invBinOpError(x.DeepString(), op.String(), y.DeepString(), "shift count type "+y.DeepType()+", must be unsigned integer") 144 | } 145 | func invBinOpShiftArgError(x Data, op token.Token, y Data) *intError { 146 | return invBinOpError(x.DeepString(), op.String(), y.DeepString(), "shift of type "+y.DeepType()) 147 | } 148 | func callBuiltInArgsCountMismError(fn string, req, got int) *intError { 149 | if req > got { 150 | return newIntError("not enough arguments in call to " + fn) 151 | } 152 | return newIntError("too many arguments in call to " + fn) 153 | } 154 | func invBuiltInArgError(fn string, x Data) *intError { 155 | return newIntError("invalid argument " + x.DeepString() + " for " + fn) 156 | } 157 | func invBuiltInArgAtError(fn string, pos int, x Data) *intError { 158 | return newIntError("invalid argument #" + strconvh.FormatInt(pos) + " " + x.DeepString() + " for " + fn) 159 | } 160 | func invBuiltInArgsError(fn string, x []Data) *intError { 161 | var msg string 162 | for i := range x { 163 | if i != 0 { 164 | msg += ", " 165 | } 166 | msg += x[i].DeepString() 167 | } 168 | return newIntError("invalid arguments " + msg + " for " + fn) 169 | } 170 | func callArgsCountMismError(req, got int) *intError { 171 | if req > got { 172 | return newIntError("not enough arguments in call") 173 | } 174 | return newIntError("too many arguments in call") 175 | } 176 | func callNonFuncError(f Value) *intError { 177 | return newIntError("cannot call non-function (type " + f.DeepType() + ")") 178 | } 179 | func callResultCountMismError(got int) *intError { 180 | if got > 1 { 181 | return newIntError("multiple-value in single-value context") 182 | } 183 | return newIntError("function call with no result used as value") 184 | } 185 | func callInvArgAtError(pos int, x Data, reqT reflect.Type) *intError { 186 | return newIntError("cannot use " + x.DeepString() + " as type " + reqT.String() + " in argument #" + strconvh.FormatInt(pos)) 187 | } 188 | func callPanicError(p interface{}) *intError { 189 | return newIntErrorf("runtime panic in function call (%v)", p) 190 | } 191 | func convertArgsCountMismError(t reflect.Type, req int, x []Data) *intError { 192 | var msg string 193 | switch { 194 | case len(x) > req: 195 | msg = "too many arguments to conversion to " + t.String() + ": " 196 | for i := range x { 197 | if i != 0 { 198 | msg += ", " 199 | } 200 | msg += x[i].DeepValue() 201 | } 202 | default: 203 | msg = "no arguments to conversion to " + t.String() 204 | } 205 | return newIntError(msg) 206 | } 207 | func convertUnableError(t reflect.Type, x Data) *intError { 208 | return newIntError("cannot convert " + x.DeepString() + " to type " + t.String()) 209 | } 210 | 211 | //func convertNilUnableError(t reflect.Type) *intError { 212 | // return newIntError("cannot convertCall nil to type " + t.String()) 213 | //} 214 | func undefIdentError(ident string) *intError { 215 | return newIntError("undefined: " + ident) 216 | } 217 | func invSliceOpError(x Data) *intError { 218 | return newIntError("cannot slice " + x.DeepString()) 219 | } 220 | func invSliceIndexError(low, high int) *intError { 221 | return newIntError("invalid slice index: " + strconvh.FormatInt(low) + " > " + strconvh.FormatInt(high)) 222 | } 223 | func invSlice3IndexOmitted() *intError { 224 | return newIntError("only first index in 3-index slice can be omitted") 225 | } 226 | func invUnaryOp(x Data, op token.Token) *intError { 227 | return newIntError("invalid operation: " + op.String() + " " + x.DeepType()) 228 | } 229 | 230 | //func invUnaryOpReason(x Value, op token.Token, reason interface{}) *intError { 231 | // return newIntErrorf("invalid operation: %v %v: %v", op.String(), x.DeepType(), reason) 232 | //} 233 | //func invUnaryReceiveError(x Value, op token.Token) *intError { 234 | // return invUnaryOpReason(x, op, "receive from non-chan type "+x.Type().String()) 235 | //} 236 | func selectorUndefIdentError(t reflect.Type, name string) *intError { 237 | return undefIdentError(t.String() + "." + name) 238 | } 239 | func arrayBoundInvBoundError(l Data) *intError { 240 | return newIntError("invalid array bound " + l.DeepString()) 241 | } 242 | func arrayBoundNegError() *intError { 243 | return newIntError("array bound must be non-negative") 244 | } 245 | func convertWithEllipsisError(t reflect.Type) *intError { 246 | return newIntError("invalid use of ... in type conversion to " + t.String()) 247 | } 248 | func callBuiltInWithEllipsisError(f string) *intError { 249 | return newIntError("invalid use of ... with builtin " + f) 250 | } 251 | func callRegularWithEllipsisError() *intError { 252 | return newIntError("invalid use of ... in call") 253 | } 254 | func makeInvalidTypeError(t reflect.Type) *intError { 255 | return newIntError("cannot make type " + t.String()) 256 | } 257 | func makeNotIntArgError(t reflect.Type, argPos int, arg Value) *intError { 258 | return newIntError("non-integer argument #" + strconvh.FormatInt(argPos) + " in make(" + t.String() + ") - " + arg.DeepType()) 259 | } 260 | func makeNegArgError(t reflect.Type, argPos int) *intError { 261 | return newIntError("negative argument #" + strconvh.FormatInt(argPos) + " in make(" + t.String() + ")") 262 | } 263 | func makeSliceMismArgsError(t reflect.Type) *intError { 264 | return newIntError("len larger than cap in make(" + t.String() + ")") 265 | } 266 | func appendFirstNotSliceError(x Data) *intError { 267 | return newIntError("first argument to append must be slice; have " + x.DeepType()) 268 | } 269 | func typeAssertLeftInvalError(x Data) *intError { 270 | return newIntError("invalid type assertion: (non-interface type " + x.DeepType() + " on left)") 271 | } 272 | func typeAssertImposError(x reflect.Value, t reflect.Type) *intError { 273 | return newIntError("impossible type " + t.String() + ": string does not implement " + x.Type().String()) 274 | } 275 | func typeAssertFalseError(x reflect.Value, t reflect.Type) *intError { 276 | return newIntError("interface conversion: " + x.Type().String() + " is not " + t.String()) 277 | } 278 | func invOpError(op, reason string) *intError { 279 | return newIntError("invalid operation: " + op + " (" + reason + ")") 280 | } 281 | func invIndexOpError(x Data, i Data) *intError { 282 | return invOpError(x.DeepString()+"["+i.DeepString()+"]", "type "+x.DeepType()+" does not support indexing") 283 | } 284 | func indexOutOfRangeError(i int) *intError { 285 | return newIntError("index " + strconvh.FormatInt(i) + " out of range") 286 | } 287 | func cmpWithNilError(x Data, op token.Token) *intError { 288 | return invBinOpError(x.DeepString(), op.String(), "nil", "compare with nil is not defined on "+x.DeepType()) 289 | } 290 | 291 | //func invMem(x Value) *intError { 292 | // return newIntError("invalid memory address or nil pointer dereference (" + x.String() + " is nil)") 293 | //} 294 | func constOverflowType(x constant.Value, t reflect.Type) *intError { 295 | return newIntError("constant " + x.ExactString() + " overflow " + t.String()) 296 | } 297 | func interfaceMethodExpr() *intError { 298 | return newIntError("Method expressions for interface types currently does not supported") 299 | } 300 | -------------------------------------------------------------------------------- /data.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "fmt" 5 | "github.com/apaxa-go/helper/goh/constanth" 6 | "github.com/apaxa-go/helper/mathh" 7 | "github.com/apaxa-go/helper/reflecth" 8 | "github.com/apaxa-go/helper/strconvh" 9 | "go/constant" 10 | "reflect" 11 | ) 12 | 13 | // DataKind specifies the kind of value represented by a Value. 14 | type DataKind int 15 | 16 | // Possible values for value's kind: 17 | const ( 18 | Nil DataKind = iota // just nil (result of parsing keyword "nil") 19 | Regular // regular typed variable 20 | TypedConst // typed constant 21 | UntypedConst // untyped constant 22 | UntypedBool // untyped boolean variable 23 | ) 24 | 25 | // String returns human readable representation of data's kind. 26 | func (k DataKind) String() string { 27 | switch k { 28 | case Nil: 29 | return "nil" 30 | case Regular: 31 | return "regular variable" 32 | case TypedConst: 33 | return "typed constant" 34 | case UntypedConst: 35 | return "untyped constant" 36 | case UntypedBool: 37 | return "untyped boolean" 38 | default: 39 | return "unknown data" 40 | } 41 | } 42 | 43 | // Data used to store all kind of data passed to/returned from expression. 44 | // It can stores: nil (keyword "nil"), regular typed variable, typed constant, untyped constant and untyped boolean variable (result of comparison). 45 | // GoLang valid expression cannot return nil (it is just a keyword), but it is presented here for internal purposes. 46 | type Data interface { 47 | // Kind returns current kind of data represented by a Data. 48 | Kind() DataKind 49 | 50 | // Regular returns regular variable (reflect.Value of it) if data stores regular variable, otherwise it panics. 51 | Regular() reflect.Value 52 | // TypedConst returns typed constant if data stores typed constant, otherwise it panics. 53 | TypedConst() constanth.TypedValue 54 | // UntypedConst returns untyped constant if data stores untyped constant, otherwise it panics. 55 | UntypedConst() constant.Value 56 | // UntypedBool returns value of untyped boolean variable if data stores untyped boolean variable, otherwise it panics. 57 | UntypedBool() bool 58 | 59 | // IsConst returns true if data stores typed or untyped constant. 60 | IsConst() bool 61 | // IsTyped returns true if data stores regular typed variable or typed constant. 62 | IsTyped() bool 63 | 64 | // AssignableTo reports whether data is assignable to type t. 65 | AssignableTo(t reflect.Type) bool 66 | // MustAssign creates new variable of type t and sets it to data. 67 | // It panics if operation cannot be performed. 68 | MustAssign(t reflect.Type) reflect.Value 69 | // Assign creates new variable of type t and tries to set it to data. 70 | // ok reports whether operation was successful. 71 | Assign(t reflect.Type) (r reflect.Value, ok bool) 72 | // ConvertibleTo reports whether data is convertible to type t. 73 | ConvertibleTo(t reflect.Type) bool 74 | // MustConvert converts data to type t. 75 | // Original data remains unchanged. 76 | // It panics if operation cannot be performed. 77 | MustConvert(t reflect.Type) Data 78 | // Convert tries to convert data to type t. 79 | // Original data remains unchanged. 80 | // ok reports whether operation was successful. 81 | Convert(t reflect.Type) (r Data, ok bool) 82 | 83 | // AsInt returns int value for regular variable of [u]int* kinds (if feats in int) and for constants (if it can be represent exactly; type of const does not mean anything). 84 | // ok reports whether operation was successful. 85 | AsInt() (r int, ok bool) 86 | 87 | // DeepType returns human readable representation of stored data's type. 88 | // Example: "untyped constant". 89 | DeepType() string 90 | // DeepValue returns human readable representation of stored data's value (without its type). 91 | // Example: "1". 92 | DeepValue() string 93 | // DeepString returns human readable representation of stored data's type and value. 94 | // Result is in form of " (type )". 95 | DeepString() string 96 | 97 | // prevent 3rd party classes from implementing Data 98 | implementsData() 99 | } 100 | 101 | type ( 102 | nilData struct{} 103 | regData reflect.Value // typed non-const data 104 | typedConstData constanth.TypedValue // typed const data 105 | untypedConstData struct { // untyped const data 106 | c constant.Value 107 | } 108 | untypedBoolData bool 109 | ) 110 | 111 | // 112 | // 113 | // 114 | func (nilData) Kind() DataKind { return Nil } 115 | func (regData) Kind() DataKind { return Regular } 116 | func (typedConstData) Kind() DataKind { return TypedConst } 117 | func (untypedConstData) Kind() DataKind { return UntypedConst } 118 | func (untypedBoolData) Kind() DataKind { return UntypedBool } 119 | 120 | // 121 | // direct access to underlying type 122 | // 123 | func (nilData) Regular() reflect.Value { panic(`"nil" is not a regular value`) } 124 | func (x regData) Regular() reflect.Value { return reflect.Value(x) } 125 | func (typedConstData) Regular() reflect.Value { panic(`typed constant is not a regular value`) } 126 | func (untypedConstData) Regular() reflect.Value { panic(`untyped constant is not a regular value`) } 127 | func (untypedBoolData) Regular() reflect.Value { panic(`untyped boolean is not a regular value`) } 128 | 129 | func (nilData) TypedConst() constanth.TypedValue { panic(`"nil" is not a typed constant`) } 130 | func (regData) TypedConst() constanth.TypedValue { panic(`regular value is not a typed constant`) } 131 | func (x typedConstData) TypedConst() constanth.TypedValue { return constanth.TypedValue(x) } 132 | func (untypedConstData) TypedConst() constanth.TypedValue { 133 | panic(`untyped constant is not a typed constant`) 134 | } 135 | func (untypedBoolData) TypedConst() constanth.TypedValue { 136 | panic(`untyped boolean is not a typed constant`) 137 | } 138 | 139 | func (nilData) UntypedConst() constant.Value { panic(`"nil" is not an untyped constant`) } 140 | func (regData) UntypedConst() constant.Value { panic(`regular value is not an untyped constant`) } 141 | func (typedConstData) UntypedConst() constant.Value { 142 | panic(`typed constant is not an untyped constant`) 143 | } 144 | func (x untypedConstData) UntypedConst() constant.Value { return x.c } 145 | func (untypedBoolData) UntypedConst() constant.Value { 146 | panic(`untyped boolean is not an untyped constant`) 147 | } 148 | 149 | func (nilData) UntypedBool() bool { panic(`"nil" is not an untyped boolean`) } 150 | func (regData) UntypedBool() bool { panic(`regular value is not an untyped boolean`) } 151 | func (typedConstData) UntypedBool() bool { panic(`typed constant is not an untyped boolean`) } 152 | func (untypedConstData) UntypedBool() bool { panic(`untyped constant is not an untyped boolean`) } 153 | func (x untypedBoolData) UntypedBool() bool { return bool(x) } 154 | 155 | // 156 | // 157 | // 158 | func (nilData) IsConst() bool { return false } 159 | func (regData) IsConst() bool { return false } 160 | func (typedConstData) IsConst() bool { return true } 161 | func (untypedConstData) IsConst() bool { return true } 162 | func (untypedBoolData) IsConst() bool { return false } 163 | 164 | func (nilData) IsTyped() bool { return false } 165 | func (regData) IsTyped() bool { return true } 166 | func (typedConstData) IsTyped() bool { return true } 167 | func (untypedConstData) IsTyped() bool { return false } 168 | func (untypedBoolData) IsTyped() bool { return false } 169 | 170 | // 171 | // nilData assign & convert 172 | // 173 | func (nilData) AssignableTo(t reflect.Type) bool { 174 | switch t.Kind() { 175 | case reflect.Slice, reflect.Ptr, reflect.Func, reflect.Interface, reflect.Map, reflect.Chan: 176 | return true 177 | } 178 | return false 179 | } 180 | func (x nilData) MustAssign(t reflect.Type) reflect.Value { 181 | r, ok := x.Assign(t) 182 | if ok { 183 | return r 184 | } 185 | panic("unable to assign nil to " + t.String()) 186 | } 187 | func (x nilData) Assign(t reflect.Type) (r reflect.Value, ok bool) { 188 | if x.AssignableTo(t) { 189 | r = reflect.New(t).Elem() 190 | ok = true 191 | } 192 | return 193 | } 194 | func (x nilData) ConvertibleTo(t reflect.Type) bool { return x.AssignableTo(t) } 195 | func (x nilData) MustConvert(t reflect.Type) Data { return regData(x.MustAssign(t)) } 196 | func (x nilData) Convert(t reflect.Type) (r Data, ok bool) { 197 | tmp, ok := x.Assign(t) 198 | if ok { 199 | r = regData(tmp) 200 | } 201 | return 202 | } 203 | 204 | // 205 | // regData assign & convert 206 | // 207 | func (x regData) Assign(t reflect.Type) (r reflect.Value, ok bool) { 208 | if ok = x.Regular().Type().AssignableTo(t); ok { 209 | r = x.MustAssign(t) 210 | } 211 | return 212 | } 213 | func (x regData) AssignableTo(t reflect.Type) bool { return x.Regular().Type().AssignableTo(t) } 214 | func (x regData) Convert(t reflect.Type) (r Data, ok bool) { 215 | if ok = x.Regular().Type().ConvertibleTo(t); ok { 216 | r = x.MustConvert(t) 217 | } 218 | return 219 | } 220 | func (x regData) ConvertibleTo(t reflect.Type) bool { return x.Regular().Type().ConvertibleTo(t) } 221 | func (x regData) MustAssign(t reflect.Type) reflect.Value { 222 | r := reflect.New(t).Elem() 223 | r.Set(x.Regular()) 224 | return r 225 | } 226 | func (x regData) MustConvert(t reflect.Type) Data { return regData(x.Regular().Convert(t)) } 227 | 228 | // 229 | // typedConstData assign & convert 230 | // 231 | func (x typedConstData) Assign(t reflect.Type) (r reflect.Value, ok bool) { 232 | return x.TypedConst().Assign(t) 233 | } 234 | func (x typedConstData) AssignableTo(t reflect.Type) bool { return x.TypedConst().AssignableTo(t) } 235 | func (x typedConstData) Convert(t reflect.Type) (r Data, ok bool) { 236 | // Need split logic - more details in constanth.TypedValue.Convert. 237 | switch t.Kind() { 238 | case reflect.Interface: 239 | var tmp reflect.Value 240 | tmp, ok = x.Assign(t) 241 | if ok { 242 | r = MakeRegular(tmp) 243 | } 244 | return 245 | default: 246 | var tmp constanth.TypedValue 247 | tmp, ok = x.TypedConst().Convert(t) 248 | if ok { 249 | r = MakeTypedConst(tmp) 250 | } 251 | return 252 | } 253 | } 254 | func (x typedConstData) ConvertibleTo(t reflect.Type) bool { 255 | //return x.TypedConst().ConvertibleTo(t) // does not work for interfaces 256 | _, ok := x.Convert(t) 257 | return ok 258 | } 259 | func (x typedConstData) MustAssign(t reflect.Type) reflect.Value { return x.TypedConst().MustAssign(t) } 260 | func (x typedConstData) MustConvert(t reflect.Type) Data { 261 | // return typedConstData(x.TypedConst().MustConvert(t)) // does not work for interfaces 262 | r, ok := x.Convert(t) 263 | if !ok { 264 | panic("unable to convert " + x.TypedConst().String() + " to type " + t.String()) 265 | } 266 | return r 267 | } 268 | 269 | // 270 | // untypedConstData assign & convert 271 | // 272 | func (x untypedConstData) Assign(t reflect.Type) (r reflect.Value, ok bool) { 273 | return constanth.Assign(x.UntypedConst(), t) 274 | } 275 | func (x untypedConstData) AssignableTo(t reflect.Type) bool { 276 | return constanth.AssignableTo(x.UntypedConst(), t) 277 | } 278 | func (x untypedConstData) Convert(t reflect.Type) (r Data, ok bool) { 279 | // Need split logic - more details in constanth.Convert. 280 | switch t.Kind() { 281 | case reflect.Interface: 282 | var tmp reflect.Value 283 | tmp, ok = constanth.Assign(x.UntypedConst(), t) 284 | if ok { 285 | r = MakeRegular(tmp) // untyped constant data after convertation to interface will be regular data 286 | } 287 | return 288 | default: 289 | var tmp constanth.TypedValue 290 | tmp, ok = constanth.Convert(x.UntypedConst(), t) 291 | if ok { 292 | r = MakeTypedConst(tmp) // untyped constant data after convertation will be typed constant data 293 | } 294 | return 295 | } 296 | } 297 | func (x untypedConstData) ConvertibleTo(t reflect.Type) bool { 298 | //return constanth.ConvertibleTo(x.UntypedConst(), t) // does not work for interfaces 299 | _, ok := x.Convert(t) 300 | return ok 301 | } 302 | func (x untypedConstData) MustAssign(t reflect.Type) reflect.Value { 303 | return constanth.MustAssign(x.UntypedConst(), t) 304 | } 305 | func (x untypedConstData) MustConvert(t reflect.Type) Data { 306 | //return typedConstData(constanth.MustConvert(x.UntypedConst(), t)) // does not work for interfaces 307 | r, ok := x.Convert(t) 308 | if !ok { 309 | panic("unable to convert " + x.UntypedConst().String() + " to type " + t.String()) 310 | } 311 | return r 312 | } 313 | 314 | // 315 | // untypedBoolData assign & convert 316 | // 317 | func (x untypedBoolData) AssignableTo(t reflect.Type) bool { 318 | return t.Kind() == reflect.Bool || t == reflecth.TypeEmptyInterface() 319 | } 320 | func (x untypedBoolData) MustAssign(t reflect.Type) reflect.Value { 321 | r, ok := x.Assign(t) 322 | if !ok { 323 | panic("unable to assign " + x.DeepString() + " to type " + t.String()) 324 | } 325 | return r 326 | } 327 | func (x untypedBoolData) Assign(t reflect.Type) (r reflect.Value, ok bool) { 328 | ok = x.AssignableTo(t) 329 | if !ok { 330 | return 331 | } 332 | 333 | switch t.Kind() { 334 | case reflect.Interface: 335 | r = reflect.New(t).Elem() 336 | r.Set(x.MustAssign(reflecth.TypeBool())) 337 | return 338 | default: // Kind bool 339 | r = reflect.New(t).Elem() 340 | r.SetBool(x.UntypedBool()) 341 | return 342 | } 343 | } 344 | func (x untypedBoolData) ConvertibleTo(t reflect.Type) bool { return x.AssignableTo(t) } 345 | func (x untypedBoolData) MustConvert(t reflect.Type) Data { return regData(x.MustAssign(t)) } 346 | func (x untypedBoolData) Convert(t reflect.Type) (r Data, ok bool) { 347 | var rV reflect.Value 348 | rV, ok = x.Assign(t) 349 | if ok { 350 | r = regData(rV) 351 | } 352 | return 353 | } 354 | 355 | // 356 | // As int 357 | // 358 | func (nilData) AsInt() (r int, ok bool) { return } 359 | func (x regData) AsInt() (r int, ok bool) { 360 | xV := x.Regular() 361 | switch xK := xV.Kind(); { 362 | case reflecth.IsInt(xK): 363 | r64 := xV.Int() 364 | if r64 >= mathh.MinInt && r64 <= mathh.MaxInt { 365 | r = int(r64) 366 | ok = true 367 | } 368 | case reflecth.IsUint(xK): 369 | r64 := xV.Uint() 370 | if r64 <= mathh.MaxInt { 371 | r = int(r64) 372 | ok = true 373 | } 374 | } 375 | return 376 | } 377 | func (x typedConstData) AsInt() (r int, ok bool) { 378 | return constanth.IntVal(x.TypedConst().Untyped()) 379 | } 380 | func (x untypedConstData) AsInt() (r int, ok bool) { 381 | return constanth.IntVal(x.UntypedConst()) 382 | } 383 | func (untypedBoolData) AsInt() (r int, ok bool) { return } 384 | 385 | func (nilData) DeepType() string { return "untyped nil" } 386 | func (x regData) DeepType() string { return x.Regular().Type().String() } 387 | func (x typedConstData) DeepType() string { return x.TypedConst().Type().String() + " constant" } 388 | func (x untypedConstData) DeepType() string { return "untyped constant" } 389 | func (x untypedBoolData) DeepType() string { return "untyped bool" } 390 | 391 | func (nilData) DeepValue() string { return "nil" } 392 | func (x regData) DeepValue() string { return fmt.Sprint(x.Regular()) } 393 | func (x typedConstData) DeepValue() string { return x.TypedConst().Untyped().ExactString() } 394 | func (x untypedConstData) DeepValue() string { return x.UntypedConst().ExactString() } 395 | func (x untypedBoolData) DeepValue() string { return strconvh.FormatBool(x.UntypedBool()) } 396 | 397 | func (nilData) DeepString() string { return "untyped nil" } 398 | func (x regData) DeepString() string { return x.DeepValue() + " (type " + x.DeepType() + ")" } 399 | func (x typedConstData) DeepString() string { return x.DeepValue() + " (type " + x.DeepType() + ")" } 400 | func (x untypedConstData) DeepString() string { return x.DeepValue() + " (type " + x.DeepType() + ")" } 401 | func (x untypedBoolData) DeepString() string { return x.DeepValue() + " (type " + x.DeepType() + ")" } 402 | 403 | // 404 | // 405 | // 406 | func (nilData) implementsData() {} 407 | func (regData) implementsData() {} 408 | func (typedConstData) implementsData() {} 409 | func (untypedConstData) implementsData() {} 410 | func (untypedBoolData) implementsData() {} 411 | 412 | // 413 | // 414 | // 415 | 416 | // MakeNil makes Data which stores "nil". 417 | func MakeNil() Data { return nilData{} } 418 | 419 | // MakeRegular makes Data which stores regular typed variable x (x is a reflect.Value of required variable). 420 | func MakeRegular(x reflect.Value) Data { return regData(x) } 421 | 422 | // MakeRegularInterface makes Data which stores regular typed variable x (x is a required variable). 423 | func MakeRegularInterface(x interface{}) Data { return MakeRegular(reflect.ValueOf(x)) } 424 | 425 | // MakeTypedConst makes Data which stores typed constant x. 426 | func MakeTypedConst(x constanth.TypedValue) Data { return typedConstData(x) } 427 | 428 | // MakeUntypedConst makes Data which stores untyped constant x. 429 | func MakeUntypedConst(x constant.Value) Data { return untypedConstData{x} } 430 | 431 | // MakeUntypedBool makes Data which stores untyped boolean variable with value x. 432 | func MakeUntypedBool(x bool) Data { return untypedBoolData(x) } 433 | -------------------------------------------------------------------------------- /builtin-func.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "github.com/apaxa-go/helper/goh/constanth" 5 | "github.com/apaxa-go/helper/reflecth" 6 | "go/constant" 7 | "go/token" 8 | "reflect" 9 | ) 10 | 11 | func isBuiltInFunc(ident string) bool { 12 | switch ident { 13 | case "len", "cap", "complex", "real", "imag", "new", "make", "append": 14 | return true 15 | default: 16 | return false 17 | } 18 | } 19 | 20 | func callBuiltInFunc(f string, args []Value, ellipsis bool) (r Value, err *intError) { 21 | if f != "append" && ellipsis { 22 | return nil, callBuiltInWithEllipsisError(f) 23 | } 24 | 25 | // make & new require not only Data args 26 | switch f { 27 | case "new": 28 | if len(args) != 1 { 29 | err = callBuiltInArgsCountMismError(f, 1, len(args)) 30 | return 31 | } 32 | return builtInNew(args[0]) 33 | case "make": 34 | return builtInMake(args) 35 | } 36 | 37 | // other built-in functions requires only Data, so try to convert args here 38 | argsD := make([]Data, len(args)) 39 | for i := range args { 40 | if args[i].Kind() != Datas { 41 | return nil, notExprError(args[i]) 42 | } 43 | argsD[i] = args[i].Data() 44 | } 45 | 46 | // all built-in funcs which require Data only args 47 | switch f { 48 | case "len": 49 | if len(argsD) != 1 { 50 | err = callBuiltInArgsCountMismError(f, 1, len(argsD)) 51 | return 52 | } 53 | return builtInLen(argsD[0]) 54 | case "cap": 55 | if len(argsD) != 1 { 56 | err = callBuiltInArgsCountMismError(f, 1, len(argsD)) 57 | return 58 | } 59 | return builtInCap(argsD[0]) 60 | case "complex": 61 | if len(argsD) != 2 { 62 | err = callBuiltInArgsCountMismError(f, 2, len(argsD)) 63 | return 64 | } 65 | return builtInComplex(argsD[0], argsD[1]) 66 | case "real": 67 | if len(argsD) != 1 { 68 | err = callBuiltInArgsCountMismError(f, 1, len(argsD)) 69 | return 70 | } 71 | return builtInReal(argsD[0]) 72 | case "imag": 73 | if len(argsD) != 1 { 74 | err = callBuiltInArgsCountMismError(f, 1, len(argsD)) 75 | return 76 | } 77 | return builtInImag(argsD[0]) 78 | case "append": 79 | if len(argsD) < 1 { 80 | err = callBuiltInArgsCountMismError(f, 1, len(argsD)) 81 | return 82 | } 83 | return builtInAppend(argsD[0], argsD[1:], ellipsis) 84 | default: 85 | return nil, undefIdentError(f) 86 | } 87 | } 88 | 89 | func builtInNew(t Value) (r Value, err *intError) { 90 | const fn = "new" 91 | switch t.Kind() { 92 | case Type: 93 | return MakeDataRegular(reflect.New(t.Type())), nil 94 | default: 95 | return nil, notTypeError(t) 96 | } 97 | } 98 | 99 | func builtInMake(v []Value) (r Value, err *intError) { 100 | const fn = "make" 101 | if len(v) < 1 || len(v) > 3 { 102 | return nil, callBuiltInArgsCountMismError(fn, 1, len(v)) 103 | } 104 | 105 | // calc type 106 | if v[0].Kind() != Type { 107 | return nil, notTypeError(v[0]) 108 | } 109 | t := v[0].Type() 110 | 111 | // calc int args; -1 means no arg passed 112 | var n, m int = -1, -1 113 | switch len(v) { 114 | case 3: 115 | if v[2].Kind() != Datas { 116 | return nil, makeNotIntArgError(t, 2, v[2]) 117 | } 118 | var ok bool 119 | m, ok = v[2].Data().AsInt() 120 | if !ok { 121 | return nil, makeNotIntArgError(t, 2, v[2]) 122 | } 123 | if m < 0 { 124 | return nil, makeNegArgError(t, 2) 125 | } 126 | fallthrough 127 | case 2: 128 | if v[1].Kind() != Datas { 129 | return nil, makeNotIntArgError(t, 1, v[1]) 130 | } 131 | var ok bool 132 | n, ok = v[1].Data().AsInt() 133 | if !ok { 134 | return nil, makeNotIntArgError(t, 1, v[1]) 135 | } 136 | if n < 0 { 137 | return nil, makeNegArgError(t, 1) 138 | } 139 | } 140 | return builtInMakeParsed(t, n, m) 141 | } 142 | 143 | // BUG(a.bekker): make(,n) ignore n (but check it type). 144 | 145 | // n & m must be >=-1. -1 means that args is missing 146 | func builtInMakeParsed(t reflect.Type, n, m int) (r Value, err *intError) { 147 | const fn = "make" 148 | switch t.Kind() { 149 | case reflect.Slice: 150 | if n == -1 { 151 | return nil, callBuiltInArgsCountMismError(fn, 2, 1) 152 | } 153 | if m == -1 { 154 | m = n 155 | } 156 | if n > m { 157 | return nil, makeSliceMismArgsError(t) 158 | } 159 | return MakeDataRegular(reflect.MakeSlice(t, n, m)), nil 160 | case reflect.Map: 161 | if m != -1 { 162 | return nil, callBuiltInArgsCountMismError(fn, 2, 3) 163 | } 164 | return MakeDataRegular(reflect.MakeMap(t)), nil 165 | case reflect.Chan: 166 | if m != -1 { 167 | return nil, callBuiltInArgsCountMismError(fn, 2, 3) 168 | } 169 | if n == -1 { 170 | n = 0 171 | } 172 | return MakeDataRegular(reflect.MakeChan(t, n)), nil 173 | default: 174 | return nil, makeInvalidTypeError(t) 175 | } 176 | } 177 | 178 | func builtInLenConstant(v constant.Value) (r Value, err *intError) { 179 | const fn = "len" 180 | if v.Kind() != constant.String { 181 | return nil, invBuiltInArgError(fn, MakeUntypedConst(v)) 182 | } 183 | l := len(constant.StringVal(v)) 184 | return MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt(l), reflecth.TypeInt())), nil 185 | } 186 | 187 | func builtInLenRegular(v reflect.Value) (r Value, err *intError) { 188 | const fn = "len" 189 | // Resolve pointer to array 190 | if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Array { 191 | v = v.Elem() 192 | } 193 | 194 | switch v.Kind() { 195 | case reflect.Array: 196 | rTC, _ := constanth.MakeTypedValue(constanth.MakeInt(v.Len()), reflecth.TypeInt()) 197 | return MakeDataTypedConst(rTC), nil 198 | case reflect.Chan, reflect.Map, reflect.Slice, reflect.String: 199 | return MakeDataRegularInterface(v.Len()), nil 200 | default: 201 | return nil, invBuiltInArgError(fn, MakeRegular(v)) 202 | } 203 | } 204 | 205 | // BUG(a.bekker): Builtin function len does not fully following GoLang spec (it always returns typed int constant for arrays & pointers to array). 206 | 207 | func builtInLen(v Data) (r Value, err *intError) { 208 | const fn = "len" 209 | switch v.Kind() { 210 | case Regular: 211 | return builtInLenRegular(v.Regular()) 212 | case TypedConst: 213 | return builtInLenConstant(v.TypedConst().Untyped()) 214 | case UntypedConst: 215 | return builtInLenConstant(v.UntypedConst()) 216 | default: 217 | return nil, invBuiltInArgError(fn, v) 218 | } 219 | } 220 | 221 | func builtInCapRegular(v reflect.Value) (r Value, err *intError) { 222 | const fn = "cap" 223 | // Resolve pointer to array 224 | if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Array { 225 | v = v.Elem() 226 | } 227 | 228 | switch v.Kind() { 229 | case reflect.Array: 230 | rTC, _ := constanth.MakeTypedValue(constant.MakeInt64(int64(v.Cap())), reflecth.TypeInt()) // no need to check ok because language spec guarantees that v.Cap() fits into an int 231 | return MakeDataTypedConst(rTC), nil 232 | case reflect.Chan, reflect.Slice: 233 | return MakeDataRegularInterface(v.Cap()), nil 234 | default: 235 | return nil, invBuiltInArgError(fn, MakeRegular(v)) 236 | } 237 | } 238 | 239 | // BUG(a.bekker): Builtin function cap does not fully following GoLang spec (always returns int instead of untyped for array & pointer to array). 240 | 241 | func builtInCap(v Data) (r Value, err *intError) { 242 | const fn = "cap" 243 | switch v.Kind() { 244 | case Regular: 245 | return builtInCapRegular(v.Regular()) 246 | default: 247 | return nil, invBuiltInArgError(fn, v) 248 | } 249 | } 250 | 251 | func builtInComplexConstant(realPart, imaginaryPart constant.Value) (r constant.Value, err *intError) { 252 | const fn = "complex" 253 | switch realPart.Kind() { 254 | case constant.Int, constant.Float: 255 | // nothing to do 256 | default: 257 | return nil, invBuiltInArgAtError(fn, 0, MakeUntypedConst(realPart)) 258 | } 259 | 260 | switch imaginaryPart.Kind() { 261 | case constant.Int, constant.Float: 262 | // nothing to do 263 | default: 264 | return nil, invBuiltInArgAtError(fn, 1, MakeUntypedConst(imaginaryPart)) 265 | } 266 | 267 | rC := constant.BinaryOp(realPart, token.ADD, constant.MakeImag(imaginaryPart)) 268 | if rC.Kind() != constant.Complex { 269 | return nil, invBuiltInArgsError(fn, []Data{MakeUntypedConst(realPart), MakeUntypedConst(imaginaryPart)}) // unreachable? 270 | } 271 | return rC, nil 272 | } 273 | 274 | func builtInComplexArgParse(a Data) (r float64, can32, can64 bool) { 275 | switch a.Kind() { 276 | case Regular: 277 | aV := a.Regular() 278 | can32 = aV.Kind() == reflect.Float32 279 | can64 = aV.Kind() == reflect.Float64 280 | if can32 || can64 { 281 | r = aV.Float() 282 | } 283 | return 284 | case TypedConst: 285 | aTC := a.TypedConst() 286 | can32 = aTC.Type().Kind() == reflect.Float32 287 | can64 = aTC.Type().Kind() == reflect.Float64 288 | if !can32 && !can64 { 289 | return 290 | } 291 | 292 | var ok bool 293 | r, ok = constanth.Float64Val(aTC.Untyped()) 294 | if !ok { 295 | can32, can64 = false, false // looks like reachable only if typed constant is created by directly accessing private field 296 | } 297 | return 298 | case UntypedConst: 299 | aC := a.UntypedConst() 300 | r, can64 = constanth.Float64Val(aC) 301 | _, can32 = constanth.Float32Val(aC) 302 | return 303 | } 304 | return 0, false, false 305 | } 306 | 307 | func builtInComplex(realPart, imaginaryPart Data) (r Value, err *intError) { 308 | const fn = "complex" 309 | switch reK, imK := realPart.Kind(), imaginaryPart.Kind(); { 310 | case reK == UntypedConst && imK == UntypedConst: 311 | var rC constant.Value 312 | rC, err = builtInComplexConstant(realPart.UntypedConst(), imaginaryPart.UntypedConst()) 313 | if err == nil { 314 | r = MakeDataUntypedConst(rC) 315 | } 316 | return 317 | case reK == TypedConst && imK == TypedConst, reK == TypedConst && imK == UntypedConst, reK == UntypedConst && imK == TypedConst: // result is the typed constant 318 | // calc result type & convert arguments to untyped constants 319 | var rT reflect.Type 320 | var reC, imC constant.Value 321 | switch { 322 | case reK == TypedConst && imK == TypedConst: 323 | reC = realPart.TypedConst().Untyped() 324 | imC = imaginaryPart.TypedConst().Untyped() 325 | reTK := realPart.TypedConst().Type().Kind() 326 | imTK := imaginaryPart.TypedConst().Type().Kind() 327 | switch { 328 | case reTK == reflect.Float32 && imTK == reflect.Float32: 329 | rT = reflecth.TypeComplex64() 330 | case reTK == reflect.Float64 && imTK == reflect.Float64: 331 | rT = reflecth.TypeComplex128() 332 | } 333 | case reK == TypedConst: 334 | reC = realPart.TypedConst().Untyped() 335 | imC = imaginaryPart.UntypedConst() 336 | switch realPart.TypedConst().Type().Kind() { 337 | case reflect.Float32: 338 | rT = reflecth.TypeComplex64() 339 | case reflect.Float64: 340 | rT = reflecth.TypeComplex128() 341 | } 342 | case imK == TypedConst: 343 | reC = realPart.UntypedConst() 344 | imC = imaginaryPart.TypedConst().Untyped() 345 | switch imaginaryPart.TypedConst().Type().Kind() { 346 | case reflect.Float32: 347 | rT = reflecth.TypeComplex64() 348 | case reflect.Float64: 349 | rT = reflecth.TypeComplex128() 350 | } 351 | } 352 | 353 | // check what result type calculated successfully 354 | if rT == nil { 355 | return nil, invBuiltInArgsError(fn, []Data{realPart, imaginaryPart}) 356 | } 357 | 358 | // calc result value (same as for untyped) 359 | var rC constant.Value 360 | rC, err = builtInComplexConstant(reC, imC) 361 | if err != nil { 362 | return 363 | } 364 | rCT, ok := constanth.Convert(rC, rT) 365 | if ok { 366 | r = MakeDataTypedConst(rCT) 367 | } else { 368 | err = invBuiltInArgsError(fn, []Data{realPart, imaginaryPart}) 369 | } 370 | return 371 | default: // result will be typed variable 372 | // Prepare arguments 373 | rF, r32, r64 := builtInComplexArgParse(realPart) 374 | if !r32 && !r64 { 375 | return nil, invBuiltInArgAtError(fn, 0, realPart) 376 | } 377 | iF, i32, i64 := builtInComplexArgParse(imaginaryPart) 378 | if !i32 && !i64 { 379 | return nil, invBuiltInArgAtError(fn, 1, imaginaryPart) 380 | } 381 | 382 | // Calc 383 | if r32 && i32 { 384 | return MakeDataRegularInterface(complex(float32(rF), float32(iF))), nil 385 | } 386 | if r64 && i64 { 387 | return MakeDataRegularInterface(complex(rF, iF)), nil 388 | } 389 | return nil, invBuiltInArgsError(fn, []Data{realPart, imaginaryPart}) 390 | } 391 | } 392 | 393 | func builtInRealConstant(v constant.Value) (r constant.Value, err *intError) { 394 | const fn = "real" 395 | if !constanth.IsNumeric(v.Kind()) { 396 | return nil, invBuiltInArgError(fn, MakeUntypedConst(v)) 397 | } 398 | rC := constant.Real(v) 399 | if rC.Kind() == constant.Unknown { 400 | return nil, invBuiltInArgError(fn, MakeUntypedConst(v)) // unreachable? 401 | } 402 | return rC, nil 403 | } 404 | 405 | func builtInRealRegular(v reflect.Value) (r Value, err *intError) { 406 | const fn = "real" 407 | switch v.Kind() { 408 | case reflect.Complex64: 409 | return MakeDataRegularInterface(real(complex64(v.Complex()))), nil 410 | case reflect.Complex128: 411 | return MakeDataRegularInterface(real(v.Complex())), nil 412 | default: 413 | return nil, invBuiltInArgError(fn, MakeRegular(v)) 414 | } 415 | } 416 | 417 | func builtInReal(v Data) (r Value, err *intError) { 418 | const fn = "real" 419 | switch v.Kind() { 420 | case Regular: 421 | return builtInRealRegular(v.Regular()) 422 | case TypedConst: 423 | vTC := v.TypedConst() 424 | var rT reflect.Type 425 | switch vTC.Type().Kind() { 426 | case reflect.Complex64: 427 | rT = reflecth.TypeFloat32() 428 | case reflect.Complex128: 429 | rT = reflecth.TypeFloat64() 430 | default: 431 | return nil, invBuiltInArgError(fn, v) 432 | } 433 | 434 | var rC constant.Value 435 | rC, err = builtInRealConstant(vTC.Untyped()) 436 | if err != nil { 437 | return // unreachable 438 | } 439 | rTC, ok := constanth.MakeTypedValue(rC, rT) 440 | if ok { 441 | r = MakeDataTypedConst(rTC) 442 | } else { 443 | err = invBuiltInArgError(fn, v) // unreachable 444 | } 445 | return 446 | case UntypedConst: 447 | var rT constant.Value 448 | rT, err = builtInRealConstant(v.UntypedConst()) 449 | if err != nil { 450 | return 451 | } 452 | r = MakeDataUntypedConst(rT) 453 | return 454 | default: 455 | return nil, invBuiltInArgError(fn, v) 456 | } 457 | } 458 | 459 | func builtInImagConstant(v constant.Value) (r constant.Value, err *intError) { 460 | const fn = "imag" 461 | if !constanth.IsNumeric(v.Kind()) { 462 | return nil, invBuiltInArgError(fn, MakeUntypedConst(v)) 463 | } 464 | rC := constant.Imag(v) 465 | if rC.Kind() == constant.Unknown { 466 | return nil, invBuiltInArgError(fn, MakeUntypedConst(v)) // unreachable? 467 | } 468 | return rC, nil 469 | } 470 | 471 | func builtInImagRegular(v reflect.Value) (r Value, err *intError) { 472 | const fn = "imag" 473 | switch v.Kind() { 474 | case reflect.Complex64: 475 | return MakeDataRegularInterface(imag(complex64(v.Complex()))), nil 476 | case reflect.Complex128: 477 | return MakeDataRegularInterface(imag(v.Complex())), nil 478 | default: 479 | return nil, invBuiltInArgError(fn, MakeRegular(v)) 480 | } 481 | } 482 | 483 | func builtInImag(v Data) (r Value, err *intError) { 484 | const fn = "imag" 485 | switch v.Kind() { 486 | case Regular: 487 | return builtInImagRegular(v.Regular()) 488 | case TypedConst: 489 | vTC := v.TypedConst() 490 | var rT reflect.Type 491 | switch vTC.Type().Kind() { 492 | case reflect.Complex64: 493 | rT = reflecth.TypeFloat32() 494 | case reflect.Complex128: 495 | rT = reflecth.TypeFloat64() 496 | default: 497 | return nil, invBuiltInArgError(fn, v) 498 | } 499 | 500 | var rC constant.Value 501 | rC, err = builtInImagConstant(vTC.Untyped()) 502 | if err != nil { 503 | return // unreachable 504 | } 505 | rTC, ok := constanth.MakeTypedValue(rC, rT) 506 | if ok { 507 | r = MakeDataTypedConst(rTC) 508 | } else { 509 | err = invBuiltInArgError(fn, v) // unreachable 510 | } 511 | return 512 | case UntypedConst: 513 | var rT constant.Value 514 | rT, err = builtInImagConstant(v.UntypedConst()) 515 | if err != nil { 516 | return 517 | } 518 | r = MakeDataUntypedConst(rT) 519 | return 520 | default: 521 | return nil, invBuiltInArgError(fn, v) 522 | } 523 | } 524 | 525 | func builtInAppend(v Data, a []Data, ellipsis bool) (r Value, err *intError) { 526 | const fn = "append" 527 | 528 | // Check for special case ("append([]byte, string...)") 529 | if ellipsis && len(a) == 1 && 530 | v.Kind() == Regular && v.Regular().Type().AssignableTo(bytesSliceT) { 531 | aV, ok := a[0].Assign(reflecth.TypeString()) 532 | if ok { 533 | newA0 := MakeRegularInterface([]byte(aV.String())) 534 | return builtInAppend(v, []Data{newA0}, true) 535 | } 536 | } 537 | 538 | if v.Kind() != Regular { 539 | return nil, appendFirstNotSliceError(v) 540 | } 541 | vV := v.Regular() 542 | if vV.Kind() != reflect.Slice { 543 | return nil, appendFirstNotSliceError(v) 544 | } 545 | 546 | elemT := v.Regular().Type().Elem() 547 | switch ellipsis { 548 | case true: 549 | if len(a) != 1 { 550 | return nil, callBuiltInArgsCountMismError(fn, 2, 1+len(a)) 551 | } 552 | if a[0].Kind() != Regular { 553 | return nil, appendMismTypeError(reflect.SliceOf(elemT), a[0]) 554 | } 555 | aV := a[0].Regular() 556 | if aV.Kind() != reflect.Slice { 557 | return nil, appendMismTypeError(reflect.SliceOf(elemT), a[0]) 558 | } 559 | if !aV.Type().Elem().AssignableTo(elemT) { 560 | return nil, appendMismTypeError(reflect.SliceOf(elemT), a[0]) 561 | } 562 | return MakeDataRegular(reflect.AppendSlice(vV, aV)), nil 563 | default: // false 564 | aV := make([]reflect.Value, len(a)) 565 | for i := range a { 566 | var ok bool 567 | aV[i], ok = a[i].Assign(elemT) 568 | if !ok { 569 | return nil, appendMismTypeError(elemT, a[i]) 570 | } 571 | } 572 | return MakeDataRegular(reflect.Append(vV, aV...)), nil 573 | } 574 | } 575 | -------------------------------------------------------------------------------- /ast.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "fmt" 5 | "github.com/apaxa-go/helper/goh/constanth" 6 | "github.com/apaxa-go/helper/goh/tokenh" 7 | "github.com/apaxa-go/helper/reflecth" 8 | "go/ast" 9 | "go/constant" 10 | "go/token" 11 | "reflect" 12 | ) 13 | 14 | func (expr *Expression) astIdent(e *ast.Ident, args Args) (r Value, err *posError) { 15 | switch e.Name { 16 | case "true": 17 | return MakeDataUntypedConst(constant.MakeBool(true)), nil 18 | case "false": 19 | return MakeDataUntypedConst(constant.MakeBool(false)), nil 20 | case "nil": 21 | return MakeDataNil(), nil 22 | } 23 | 24 | switch { 25 | case isBuiltInFunc(e.Name): 26 | return MakeBuiltInFunc(e.Name), nil 27 | case isBuiltInType(e.Name): 28 | return MakeType(builtInTypes[e.Name]), nil 29 | default: 30 | var ok bool 31 | r, ok = args[e.Name] 32 | if !ok { 33 | err = identUndefinedError(e.Name).pos(e) 34 | } 35 | return 36 | } 37 | } 38 | 39 | // astSelectorExpr can: 40 | // * get field from struct or pointer to struct 41 | // * get method (defined with receiver V) from variable of type V or pointer variable to type V 42 | // * get method (defined with pointer receiver V) from pointer variable to type V 43 | func (expr *Expression) astSelectorExpr(e *ast.SelectorExpr, args Args) (r Value, err *posError) { 44 | // Calc object (left of '.') 45 | x, err := expr.astExpr(e.X, args) 46 | if err != nil { 47 | return 48 | } 49 | 50 | // Extract field/method name 51 | if e.Sel == nil { 52 | return nil, &posError{msg: string(*invAstSelectorError()), pos: e.Pos()} // Looks like unreachable if e generated by parsing source (not by hand). It is not possible to use intError.pos here because it cause panic. 53 | } 54 | name := e.Sel.Name 55 | 56 | switch x.Kind() { 57 | case Package: 58 | var ok bool 59 | r, ok = x.Package()[name] 60 | if !ok { 61 | return nil, identUndefinedError("." + name).pos(e) 62 | } 63 | 64 | return 65 | case Datas: 66 | xD := x.Data() 67 | if xD.Kind() != Regular { 68 | return nil, invSelectorXError(x).pos(e) 69 | } 70 | xV := xD.Regular() 71 | 72 | // If kind is pointer than try to get method. 73 | // If no method can be get than dereference pointer. 74 | if xV.Kind() == reflect.Ptr { 75 | if method := xV.MethodByName(name); method.IsValid() { 76 | return MakeDataRegular(method), nil 77 | } 78 | xV = xV.Elem() 79 | } 80 | 81 | // If kind is struct than try to get field 82 | if xV.Kind() == reflect.Struct { 83 | if field := fieldByName(xV, name, expr.pkgPath); field.IsValid() { 84 | return MakeDataRegular(field), nil 85 | } 86 | } 87 | 88 | // Last case - try to get method (on already dereferenced variable) 89 | if method := xV.MethodByName(name); method.IsValid() { 90 | return MakeDataRegular(method), nil 91 | } 92 | 93 | return nil, identUndefinedError("." + name).pos(e) 94 | case Type: 95 | xT := x.Type() 96 | if xT.Kind() == reflect.Interface { 97 | return nil, interfaceMethodExpr().pos(e) // BUG 98 | } 99 | 100 | f, ok := xT.MethodByName(name) 101 | if !ok || !f.Func.IsValid() { 102 | return nil, selectorUndefIdentError(xT, name).pos(e) 103 | } 104 | return MakeDataRegular(f.Func), nil 105 | default: 106 | return nil, invSelectorXError(x).pos(e) 107 | } 108 | } 109 | 110 | func (expr *Expression) astBinaryExpr(e *ast.BinaryExpr, args Args) (r Value, err *posError) { 111 | x, err := expr.astExprAsData(e.X, args) 112 | if err != nil { 113 | return 114 | } 115 | y, err := expr.astExprAsData(e.Y, args) 116 | if err != nil { 117 | return 118 | } 119 | 120 | // Perform calc depending on operation type 121 | switch { 122 | case tokenh.IsComparison(e.Op): 123 | return upT(compareOp(x, e.Op, y)).pos(e) 124 | case tokenh.IsShift(e.Op): 125 | return upT(shiftOp(x, e.Op, y)).pos(e) 126 | default: 127 | return upT(binaryOp(x, e.Op, y)).pos(e) 128 | } 129 | } 130 | 131 | func (expr *Expression) astBasicLit(e *ast.BasicLit, args Args) (r Value, err *posError) { 132 | rC := constant.MakeFromLiteral(e.Value, e.Kind, 0) 133 | if rC.Kind() == constant.Unknown { 134 | return nil, syntaxInvBasLitError(e.Value).pos(e) // looks like unreachable if e generated by parsing source (not by hand). 135 | } 136 | return MakeDataUntypedConst(rC), nil 137 | } 138 | 139 | func (expr *Expression) astParenExpr(e *ast.ParenExpr, args Args) (r Value, err *posError) { 140 | return expr.astExpr(e.X, args) 141 | } 142 | 143 | func (expr *Expression) astCallExpr(e *ast.CallExpr, args Args) (r Value, err *posError) { 144 | // Resolve func 145 | f, err := expr.astExpr(e.Fun, args) 146 | if err != nil { 147 | return 148 | } 149 | 150 | // Resolve args 151 | var eArgs []Data 152 | if f.Kind() != BuiltInFunc { // for built-in funcs required []Value, not []Data 153 | eArgs = make([]Data, len(e.Args)) 154 | for i := range e.Args { 155 | eArgs[i], err = expr.astExprAsData(e.Args[i], args) 156 | if err != nil { 157 | return 158 | } 159 | } 160 | } 161 | 162 | var intErr *intError 163 | switch f.Kind() { 164 | case Datas: 165 | fD := f.Data() 166 | switch fD.Kind() { 167 | case Regular: 168 | r, intErr = callRegular(fD.Regular(), eArgs, e.Ellipsis != token.NoPos) 169 | default: 170 | intErr = callNonFuncError(f) 171 | } 172 | case BuiltInFunc: 173 | eArgs := make([]Value, len(e.Args)) 174 | for i := range e.Args { 175 | eArgs[i], err = expr.astExpr(e.Args[i], args) 176 | if err != nil { 177 | return 178 | } 179 | } 180 | r, intErr = callBuiltInFunc(f.BuiltInFunc(), eArgs, e.Ellipsis != token.NoPos) 181 | case Type: 182 | if e.Ellipsis != token.NoPos { 183 | return nil, convertWithEllipsisError(f.Type()).pos(e) 184 | } 185 | r, intErr = convertCall(f.Type(), eArgs) 186 | default: 187 | intErr = callNonFuncError(f) 188 | } 189 | 190 | err = intErr.pos(e) 191 | return 192 | } 193 | 194 | func (expr *Expression) astStarExpr(e *ast.StarExpr, args Args) (r Value, err *posError) { 195 | v, err := expr.astExpr(e.X, args) 196 | if err != nil { 197 | return 198 | } 199 | 200 | switch { 201 | case v.Kind() == Type: 202 | return MakeType(reflect.PtrTo(v.Type())), nil 203 | case v.Kind() == Datas && v.Data().Kind() == Regular && v.Data().Regular().Kind() == reflect.Ptr: 204 | return MakeDataRegular(v.Data().Regular().Elem()), nil 205 | default: 206 | return nil, indirectInvalError(v).pos(e) 207 | } 208 | } 209 | 210 | func (expr *Expression) astUnaryExpr(e *ast.UnaryExpr, args Args) (r Value, err *posError) { 211 | x, err := expr.astExprAsData(e.X, args) 212 | if err != nil { 213 | return 214 | } 215 | return upT(unaryOp(e.Op, x)).pos(e) 216 | } 217 | 218 | func (expr *Expression) astChanType(e *ast.ChanType, args Args) (r Value, err *posError) { 219 | t, err := expr.astExprAsType(e.Value, args) 220 | if err != nil { 221 | return 222 | } 223 | return MakeType(reflect.ChanOf(reflecth.ChanDirFromAst(e.Dir), t)), nil 224 | } 225 | 226 | // Here implements only for list of arguments types ("func(a ...string)"). 227 | // For ellipsis array literal ("[...]int{1,2}") see astCompositeLit. 228 | // For ellipsis argument for call ("f(1,a...)") see astCallExpr. 229 | func (expr *Expression) astEllipsis(e *ast.Ellipsis, args Args) (r Value, err *posError) { 230 | t, err := expr.astExprAsType(e.Elt, args) 231 | if err != nil { 232 | return 233 | } 234 | return MakeType(reflect.SliceOf(t)), nil 235 | } 236 | 237 | func (expr *Expression) astFuncType(e *ast.FuncType, args Args) (r Value, err *posError) { 238 | in, variadic, err := expr.funcTranslateArgs(e.Params, true, args) 239 | if err != nil { 240 | return 241 | } 242 | out, _, err := expr.funcTranslateArgs(e.Results, false, args) 243 | if err != nil { 244 | return 245 | } 246 | return MakeType(reflect.FuncOf(in, out, variadic)), nil 247 | } 248 | 249 | func (expr *Expression) astArrayType(e *ast.ArrayType, args Args) (r Value, err *posError) { 250 | t, err := expr.astExprAsType(e.Elt, args) 251 | if err != nil { 252 | return 253 | } 254 | 255 | switch e.Len { 256 | case nil: // Slice 257 | rT := reflect.SliceOf(t) 258 | return MakeType(rT), nil 259 | default: // Array 260 | // eval length 261 | var l Data 262 | l, err = expr.astExprAsData(e.Len, args) // Case with ellipsis in length must be caught by caller (astCompositeLit) 263 | if err != nil { 264 | return 265 | } 266 | 267 | // convert length to int 268 | var lInt int 269 | switch l.Kind() { 270 | case TypedConst: 271 | var ok bool 272 | lInt, ok = constanth.IntVal(l.TypedConst().Untyped()) 273 | if !l.TypedConst().AssignableTo(reflecth.TypeInt()) || !ok { // AssignableTo should be enough 274 | return nil, arrayBoundInvBoundError(l).pos(e.Len) 275 | } 276 | case UntypedConst: 277 | var ok bool 278 | lInt, ok = constanth.IntVal(l.UntypedConst()) 279 | if !ok { 280 | return nil, arrayBoundInvBoundError(l).pos(e.Len) 281 | } 282 | default: 283 | return nil, arrayBoundInvBoundError(l).pos(e.Len) 284 | } 285 | 286 | // validate length 287 | if lInt < 0 { 288 | return nil, arrayBoundNegError().pos(e) 289 | } 290 | 291 | // make array 292 | rT := reflect.ArrayOf(lInt, t) 293 | return MakeType(rT), nil 294 | } 295 | } 296 | 297 | func (expr *Expression) astIndexExpr(e *ast.IndexExpr, args Args) (r Value, err *posError) { 298 | x, err := expr.astExprAsData(e.X, args) 299 | if err != nil { 300 | return 301 | } 302 | 303 | i, err := expr.astExprAsData(e.Index, args) 304 | if err != nil { 305 | return nil, err 306 | } 307 | 308 | var intErr *intError 309 | switch x.Kind() { 310 | case Regular: 311 | switch x.Regular().Kind() { 312 | case reflect.Map: 313 | r, intErr = indexMap(x.Regular(), i) 314 | default: 315 | r, intErr = indexOther(x.Regular(), i) 316 | } 317 | case TypedConst: 318 | r, intErr = indexConstant(x.TypedConst().Untyped(), i) 319 | case UntypedConst: 320 | r, intErr = indexConstant(x.UntypedConst(), i) 321 | default: 322 | intErr = invIndexOpError(x, i) 323 | } 324 | 325 | err = intErr.pos(e) 326 | return 327 | } 328 | 329 | func (expr *Expression) astSliceExpr(e *ast.SliceExpr, args Args) (r Value, err *posError) { 330 | x, err := expr.astExprAsData(e.X, args) 331 | if err != nil { 332 | return 333 | } 334 | 335 | indexResolve := func(e ast.Expr) (iInt int, err1 *posError) { 336 | var i Data 337 | if e != nil { 338 | i, err1 = expr.astExprAsData(e, args) 339 | if err1 != nil { 340 | return 341 | } 342 | } 343 | 344 | var intErr *intError 345 | iInt, intErr = getSliceIndex(i) 346 | err1 = intErr.pos(e) 347 | return 348 | } 349 | 350 | // Calc indexes 351 | low, err := indexResolve(e.Low) 352 | if err != nil { 353 | return 354 | } 355 | high, err := indexResolve(e.High) 356 | if err != nil { 357 | return 358 | } 359 | var max int 360 | if e.Slice3 { 361 | max, err = indexResolve(e.Max) 362 | if err != nil { 363 | return 364 | } 365 | } 366 | 367 | var v reflect.Value 368 | switch x.Kind() { 369 | case Regular: 370 | v = x.Regular() 371 | case TypedConst: 372 | // Typed constant in slice expression may be only of string kind 373 | if x.TypedConst().Type().Kind() != reflect.String { 374 | return nil, sliceInvTypeError(x).pos(e.X) 375 | } 376 | v = x.TypedConst().Value() 377 | 378 | //xStr, ok := constanth.StringVal(x.TypedConst().Untyped()) 379 | //if !ok { 380 | // return nil, sliceInvTypeError(x).pos(e.X) 381 | //} 382 | //v = reflect.ValueOf(xStr) 383 | case UntypedConst: 384 | // Untyped constant in slice expression may be only of string kind 385 | xStr, ok := constanth.StringVal(x.UntypedConst()) 386 | if !ok { 387 | return nil, sliceInvTypeError(x).pos(e.X) 388 | } 389 | v = reflect.ValueOf(xStr) 390 | default: 391 | return nil, sliceInvTypeError(x).pos(e.X) 392 | } 393 | 394 | var intErr *intError 395 | if e.Slice3 { 396 | r, intErr = slice3(v, low, high, max) 397 | } else { 398 | r, intErr = slice2(v, low, high) 399 | } 400 | 401 | err = intErr.pos(e) 402 | return 403 | } 404 | 405 | func (expr *Expression) astCompositeLit(e *ast.CompositeLit, args Args) (r Value, err *posError) { 406 | // type 407 | var vT reflect.Type 408 | // case where type is an ellipsis array 409 | if aType, ok := e.Type.(*ast.ArrayType); ok { 410 | if _, ok := aType.Len.(*ast.Ellipsis); ok { 411 | // Resolve array elements type 412 | vT, err = expr.astExprAsType(aType.Elt, args) 413 | if err != nil { 414 | return 415 | } 416 | vT = reflect.ArrayOf(len(e.Elts), vT) 417 | } 418 | } 419 | // other cases 420 | if vT == nil { 421 | vT, err = expr.astExprAsType(e.Type, args) 422 | if err != nil { 423 | return 424 | } 425 | } 426 | 427 | // Construct 428 | var intErr *intError 429 | switch vT.Kind() { 430 | case reflect.Struct: 431 | var withKeys bool 432 | if len(e.Elts) == 0 { 433 | withKeys = true // Treat empty initialization list as with keys 434 | } else { 435 | _, withKeys = e.Elts[0].(*ast.KeyValueExpr) 436 | } 437 | 438 | switch withKeys { 439 | case true: 440 | elts := make(map[string]Data) 441 | for i := range e.Elts { 442 | kve, ok := e.Elts[i].(*ast.KeyValueExpr) 443 | if !ok { 444 | return nil, initMixError().pos(e) 445 | } 446 | 447 | key, ok := kve.Key.(*ast.Ident) 448 | if !ok { 449 | return nil, initStructInvFieldNameError().pos(kve) 450 | } 451 | 452 | elts[key.Name], err = expr.astExprAsData(kve.Value, args) 453 | if err != nil { 454 | return 455 | } 456 | } 457 | r, intErr = compositeLitStructKeys(vT, elts, expr.pkgPath) 458 | case false: 459 | elts := make([]Data, len(e.Elts)) 460 | for i := range e.Elts { 461 | if _, ok := e.Elts[i].(*ast.KeyValueExpr); ok { 462 | return nil, initMixError().pos(e) 463 | } 464 | 465 | elts[i], err = expr.astExprAsData(e.Elts[i], args) 466 | if err != nil { 467 | return 468 | } 469 | } 470 | r, intErr = compositeLitStructOrdered(vT, elts, expr.pkgPath) 471 | } 472 | case reflect.Array, reflect.Slice: 473 | elts := make(map[int]Data) 474 | nextIndex := 0 475 | for i := range e.Elts { 476 | var valueExpr ast.Expr 477 | if kve, ok := e.Elts[i].(*ast.KeyValueExpr); ok { 478 | var v Data 479 | v, err = expr.astExprAsData(kve.Key, args) 480 | if err != nil { 481 | return 482 | } 483 | switch v.Kind() { 484 | case TypedConst: 485 | if v.TypedConst().Type() != reflecth.TypeInt() { 486 | return nil, initArrayInvIndexError().pos(kve) 487 | } 488 | var ok bool 489 | nextIndex, ok = constanth.IntVal(v.TypedConst().Untyped()) 490 | if !ok || nextIndex < 0 { 491 | return nil, initArrayInvIndexError().pos(kve) 492 | } 493 | case UntypedConst: 494 | var ok bool 495 | nextIndex, ok = constanth.IntVal(v.UntypedConst()) 496 | if !ok || nextIndex < 0 { 497 | return nil, initArrayInvIndexError().pos(kve) 498 | } 499 | default: 500 | return nil, initArrayInvIndexError().pos(kve) 501 | } 502 | 503 | valueExpr = kve.Value 504 | } else { 505 | valueExpr = e.Elts[i] 506 | } 507 | 508 | if _, ok := elts[nextIndex]; ok { 509 | return nil, initArrayDupIndexError(nextIndex).pos(e.Elts[i]) 510 | } 511 | 512 | elts[nextIndex], err = expr.astExprAsData(valueExpr, args) 513 | if err != nil { 514 | return 515 | } 516 | nextIndex++ 517 | } 518 | 519 | r, intErr = compositeLitArrayLike(vT, elts) 520 | case reflect.Map: 521 | elts := make(map[Data]Data) 522 | for i := range e.Elts { 523 | kve, ok := e.Elts[i].(*ast.KeyValueExpr) 524 | if !ok { 525 | return nil, initMapMisKeyError().pos(e.Elts[i]) 526 | } 527 | 528 | var key Data 529 | key, err = expr.astExprAsData(kve.Key, args) 530 | if err != nil { 531 | return 532 | } 533 | elts[key], err = expr.astExprAsData(kve.Value, args) // looks like it is impossible to overwrite value here because key!=prev_key (it is interface) 534 | if err != nil { 535 | return 536 | } 537 | } 538 | 539 | r, intErr = compositeLitMap(vT, elts) 540 | default: 541 | return nil, initInvTypeError(vT).pos(e.Type) 542 | } 543 | 544 | err = intErr.pos(e) 545 | return 546 | } 547 | 548 | func (expr *Expression) astTypeAssertExpr(e *ast.TypeAssertExpr, args Args) (r Value, err *posError) { 549 | x, err := expr.astExprAsData(e.X, args) 550 | if err != nil { 551 | return 552 | } 553 | if x.Kind() != Regular || x.Regular().Kind() != reflect.Interface { 554 | return nil, typeAssertLeftInvalError(x).pos(e) 555 | } 556 | t, err := expr.astExprAsType(e.Type, args) 557 | if err != nil { 558 | return 559 | } 560 | rV, ok, valid := reflecth.TypeAssert(x.Regular(), t) 561 | if !valid { 562 | return nil, typeAssertImposError(x.Regular(), t).pos(e) 563 | } 564 | if !ok { 565 | return nil, typeAssertFalseError(x.Regular(), t).pos(e) 566 | } 567 | return MakeDataRegular(rV), nil 568 | } 569 | 570 | func (expr *Expression) astMapType(e *ast.MapType, args Args) (r Value, err *posError) { 571 | k, err := expr.astExprAsType(e.Key, args) 572 | if err != nil { 573 | return 574 | } 575 | v, err := expr.astExprAsType(e.Value, args) 576 | if err != nil { 577 | return 578 | } 579 | 580 | defer func() { 581 | if rec := recover(); rec != nil { 582 | err = newIntError(fmt.Sprint(rec)).pos(e) 583 | } 584 | }() 585 | rT := reflect.MapOf(k, v) 586 | 587 | r = MakeType(rT) 588 | return 589 | } 590 | 591 | // BUG(a.bekker): Eval* currently does not generate wrapper methods for embedded fields in structures (see reflect.StructOf for more details). 592 | 593 | func (expr *Expression) astStructType(e *ast.StructType, args Args) (r Value, err *posError) { 594 | // Looks like e.Incomplete does not mean anything in our case. 595 | if e.Fields == nil { 596 | return nil, &posError{msg: string(*invAstNilStructFieldsError()), pos: e.Pos()} // Looks like unreachable if e generated by parsing source (not by hand). It is not possible to use intError.pos here because it cause panic. 597 | } 598 | 599 | extractTag := func(l *ast.BasicLit) (tag reflect.StructTag, err *posError) { 600 | if l == nil { 601 | return 602 | } 603 | tagC := constant.MakeFromLiteral(l.Value, l.Kind, 0) 604 | if tagC.Kind() != constant.String { 605 | err = invAstNonStringTagError().pos(l) 606 | return 607 | } 608 | tag = reflect.StructTag(constant.StringVal(tagC)) 609 | return 610 | } 611 | 612 | fields := make([]reflect.StructField, e.Fields.NumFields()) 613 | i := 0 614 | for _, fs := range e.Fields.List { 615 | // Determine common fields type 616 | var fsT reflect.Type 617 | fsT, err = expr.astExprAsType(fs.Type, args) 618 | if err != nil { 619 | return 620 | } 621 | 622 | switch fs.Names { 623 | case nil: // Anonymous field 624 | fields[i].Name = "" 625 | fields[i].PkgPath = expr.pkgPath 626 | fields[i].Type = fsT 627 | fields[i].Anonymous = true 628 | fields[i].Tag, err = extractTag(fs.Tag) 629 | if err != nil { 630 | return 631 | } 632 | i++ 633 | default: // Named fields 634 | for _, f := range fs.Names { 635 | fields[i].Name = f.Name 636 | fields[i].PkgPath = expr.pkgPath 637 | fields[i].Type = fsT 638 | fields[i].Anonymous = false 639 | fields[i].Tag, err = extractTag(fs.Tag) 640 | if err != nil { 641 | return 642 | } 643 | i++ 644 | } 645 | } 646 | } 647 | 648 | defer func() { 649 | if rec := recover(); rec != nil { 650 | err = newIntError(fmt.Sprint(rec)).pos(e) 651 | } 652 | }() 653 | r = MakeType(reflect.StructOf(fields)) 654 | return 655 | } 656 | 657 | // BUG(a.bekker): Only empty interface type can be declared in expression. 658 | 659 | func (expr *Expression) astInterfaceType(e *ast.InterfaceType, args Args) (r Value, err *posError) { 660 | if e.Methods == nil { 661 | return nil, &posError{msg: string(*invAstNilInterfaceMethodsError()), pos: e.Pos()} // Looks like unreachable if e generated by parsing source (not by hand). It is not possible to use intError.pos here because it cause panic. 662 | } 663 | if len(e.Methods.List) != 0 { 664 | return nil, unsupportedInterfaceTypeError().pos(e) 665 | } 666 | r = MakeType(reflecth.TypeEmptyInterface()) 667 | return 668 | } 669 | 670 | func (expr *Expression) astExprAsData(e ast.Expr, args Args) (r Data, err *posError) { 671 | var rValue Value 672 | rValue, err = expr.astExpr(e, args) 673 | if err != nil { 674 | return 675 | } 676 | 677 | switch rValue.Kind() { 678 | case Datas: 679 | r = rValue.Data() 680 | default: 681 | err = notExprError(rValue).pos(e) 682 | } 683 | return 684 | } 685 | 686 | func (expr *Expression) astExprAsType(e ast.Expr, args Args) (r reflect.Type, err *posError) { 687 | var rValue Value 688 | rValue, err = expr.astExpr(e, args) 689 | if err != nil { 690 | return 691 | } 692 | 693 | switch rValue.Kind() { 694 | case Type: 695 | r = rValue.Type() 696 | default: 697 | err = notTypeError(rValue).pos(e) 698 | } 699 | return 700 | } 701 | 702 | func (expr *Expression) astExpr(e ast.Expr, args Args) (r Value, err *posError) { 703 | if e == nil { 704 | return nil, invAstNilError().noPos() 705 | } 706 | 707 | switch v := e.(type) { 708 | case *ast.Ident: 709 | return expr.astIdent(v, args) 710 | case *ast.SelectorExpr: 711 | return expr.astSelectorExpr(v, args) 712 | case *ast.BinaryExpr: 713 | return expr.astBinaryExpr(v, args) 714 | case *ast.BasicLit: 715 | return expr.astBasicLit(v, args) 716 | case *ast.ParenExpr: 717 | return expr.astParenExpr(v, args) 718 | case *ast.CallExpr: 719 | return expr.astCallExpr(v, args) 720 | case *ast.StarExpr: 721 | return expr.astStarExpr(v, args) 722 | case *ast.UnaryExpr: 723 | return expr.astUnaryExpr(v, args) 724 | case *ast.Ellipsis: 725 | return expr.astEllipsis(v, args) 726 | case *ast.ChanType: 727 | return expr.astChanType(v, args) 728 | case *ast.FuncType: 729 | return expr.astFuncType(v, args) 730 | case *ast.ArrayType: 731 | return expr.astArrayType(v, args) 732 | case *ast.IndexExpr: 733 | return expr.astIndexExpr(v, args) 734 | case *ast.SliceExpr: 735 | return expr.astSliceExpr(v, args) 736 | case *ast.CompositeLit: 737 | return expr.astCompositeLit(v, args) 738 | case *ast.TypeAssertExpr: 739 | return expr.astTypeAssertExpr(v, args) 740 | case *ast.MapType: 741 | return expr.astMapType(v, args) 742 | case *ast.StructType: 743 | return expr.astStructType(v, args) 744 | case *ast.InterfaceType: 745 | return expr.astInterfaceType(v, args) 746 | default: 747 | // BadExpr - no need to implement 748 | // FuncLit - do not want to implement (too hard, this project only evaluate expression) 749 | // KeyValueExpr - implemented in-place, not here 750 | return nil, invAstUnsupportedError(e).pos(e) 751 | } 752 | } 753 | -------------------------------------------------------------------------------- /tests_test.go: -------------------------------------------------------------------------------- 1 | package eval 2 | 3 | import ( 4 | "fmt" 5 | "github.com/apaxa-go/helper/goh/constanth" 6 | "github.com/apaxa-go/helper/mathh" 7 | "github.com/apaxa-go/helper/reflecth" 8 | "github.com/apaxa-go/helper/strconvh" 9 | "go/constant" 10 | "go/token" 11 | "reflect" 12 | "unicode" 13 | ) 14 | 15 | // 16 | // Equals 17 | // 18 | 19 | func isDatasEqual(v1, v2 Data) (r bool) { 20 | if v1.Kind() != v2.Kind() { 21 | return false 22 | } 23 | switch v1.Kind() { 24 | case Nil: 25 | return true 26 | case Regular: 27 | v1V := v1.Regular() 28 | v2V := v2.Regular() 29 | 30 | if v1V.Kind() != v2V.Kind() { 31 | return false 32 | } 33 | 34 | // Compare functions 35 | if v1V.Kind() == reflect.Func { 36 | return v1V.Pointer() == v2V.Pointer() // may return wrong result: http://stackoverflow.com/questions/9643205/how-do-i-compare-two-functions-for-pointer-equality-in-the-latest-go-weekly 37 | } 38 | 39 | // Compare channels 40 | if v1V.Kind() == reflect.Chan { 41 | if v1V.Type() != v2V.Type() { 42 | return false 43 | } 44 | for { 45 | x1, ok1 := v1V.TryRecv() 46 | x2, ok2 := v2V.TryRecv() 47 | if ok1 != ok2 { 48 | return false 49 | } 50 | if !ok1 && ((x1 == reflect.Value{}) != (x2 == reflect.Value{})) { 51 | return false 52 | } 53 | if (x1 != reflect.Value{}) && !isDatasEqual(MakeRegular(x1), MakeRegular(x2)) { 54 | return false 55 | } 56 | if !ok1 { 57 | return true 58 | } 59 | } 60 | } 61 | 62 | // Compare maps 63 | if v1V.Kind() == reflect.Map { 64 | return reflect.DeepEqual(v1V.Interface(), v2V.Interface()) // not a good check 65 | } 66 | 67 | // Compare slices 68 | if v1V.Kind() == reflect.Slice { 69 | return reflect.DeepEqual(v1V.Interface(), v2V.Interface()) // not a good check 70 | } 71 | 72 | defer func() { 73 | if rec := recover(); rec != nil { 74 | r = false 75 | } 76 | }() 77 | r = v1V.Interface() == v2V.Interface() 78 | return 79 | case TypedConst: 80 | return v1.TypedConst().Type() == v2.TypedConst().Type() && constant.Compare(v1.TypedConst().Untyped(), token.EQL, v2.TypedConst().Untyped()) 81 | case UntypedConst: 82 | return constant.Compare(v1.UntypedConst(), token.EQL, v2.UntypedConst()) 83 | case UntypedBool: 84 | return v1.UntypedBool() == v2.UntypedBool() 85 | default: 86 | panic("unhandled Data Kind in equal check") 87 | } 88 | } 89 | 90 | func isValuesEqual(v1, v2 Value) (r bool) { 91 | if v1.Kind() != v2.Kind() { 92 | return false 93 | } 94 | switch v1.Kind() { 95 | case Datas: 96 | return isDatasEqual(v1.Data(), v2.Data()) 97 | case Type: 98 | return v1.Type() == v2.Type() 99 | case BuiltInFunc: 100 | return v1.BuiltInFunc() == v2.BuiltInFunc() 101 | case Package: 102 | return reflect.DeepEqual(v1.Package(), v2.Package()) 103 | default: 104 | panic("unhandled Values Kind in equal check") 105 | } 106 | } 107 | 108 | // 109 | // Types for storing tests 110 | // 111 | 112 | type testExprElement struct { 113 | expr string 114 | vars Args 115 | r Value 116 | err bool 117 | } 118 | 119 | func (t testExprElement) Validate(r Value, err error) bool { 120 | // validate error 121 | if err != nil != t.err { 122 | return false 123 | } 124 | 125 | if t.r == nil && r == nil { 126 | return true 127 | } 128 | if t.r == nil || r == nil { 129 | return false 130 | } 131 | return isValuesEqual(t.r, r) 132 | } 133 | 134 | func (t testExprElement) ErrorMsg(r Value, err error) string { 135 | return fmt.Sprintf("'%v' (%+v): expect %v %v, got %v %v", t.expr, t.vars, t.r, t.err, r, err) 136 | } 137 | 138 | // Catalog of tests grouped by testing functionality. 139 | // Technically it is grouped by function in ast.go which is used to evaluate expression. 140 | type testExprCatalog map[string][]testExprElement 141 | 142 | // 143 | // Tests collection 144 | // 145 | 146 | // Required variables for tests 147 | var ( 148 | veryLongNumber = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" 149 | tmp0 = &(SampleStruct{2}) 150 | tmp1 = interface{}(strconvh.FormatInt) // because unable get address in one line 151 | tmp2 = reflect.Type(nil) 152 | tmp3 = myInterface(nil) 153 | tmp4 = myInterface(myImplementation{5}) 154 | tmp5 = interface{}(int8(5)) 155 | tmp6 = interface{}(5) 156 | tmp7 = interface{}(true) 157 | ) 158 | 159 | // Required types for tests 160 | type ( 161 | myInt int 162 | myStr string 163 | myStruct struct { 164 | I int 165 | S string 166 | } 167 | myStruct1 struct { 168 | i int 169 | s string 170 | } 171 | myInterface interface { 172 | MyMethod() 173 | } 174 | myImplementation struct { 175 | X int8 176 | } 177 | ) 178 | 179 | // Methods for tests 180 | func (x myImplementation) MyMethod() { 181 | x.X++ 182 | } 183 | 184 | // Required functions for tests 185 | func myDiv(k int, x ...int) []int { 186 | for i := range x { 187 | x[i] /= k 188 | } 189 | return x 190 | } 191 | 192 | var testsExpr = testExprCatalog{ 193 | "identifier": []testExprElement{ 194 | {"true", nil, MakeDataUntypedConst(constant.MakeBool(true)), false}, 195 | {"false", nil, MakeDataUntypedConst(constant.MakeBool(false)), false}, 196 | {"nil", nil, MakeDataNil(), false}, 197 | {"v1", ArgsFromInterfaces(ArgsI{"v0": 2, "v1": 3, "v2": 4}), MakeDataRegularInterface(int(3)), false}, 198 | {"v10", ArgsFromInterfaces(ArgsI{"v0": 2, "v1": 3, "v2": 4}), nil, true}, 199 | {"pow", ArgsFromInterfaces(ArgsI{"v0": 2, "pow": mathh.PowInt16, "v2": 4}), MakeDataRegularInterface(mathh.PowInt16), false}, 200 | }, 201 | "selector": []testExprElement{ 202 | {"a.F", ArgsFromInterfaces(ArgsI{"a": SampleStruct{2}}), MakeDataRegularInterface(uint16(2)), false}, 203 | {"a.F", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{2}}), MakeDataRegularInterface(uint16(2)), false}, 204 | {"a.F", ArgsFromInterfaces(ArgsI{"a": &tmp0}), nil, true}, // unable to double dereference on-the-fly, only single is possible 205 | {"a.F", nil, nil, true}, 206 | {"unicode.ReplacementChar", Args{"unicode.ReplacementChar": MakeDataUntypedConst(constanth.MakeInt(unicode.ReplacementChar))}, MakeDataUntypedConst(constanth.MakeInt(unicode.ReplacementChar)), false}, 207 | {"unicode.ReplacementChar2", Args{"unicode.ReplacementChar": MakeData(MakeUntypedConst(constanth.MakeInt(unicode.ReplacementChar)))}, nil, true}, 208 | {"(1).Method()", nil, nil, true}, 209 | {"reflect.Type.Name(reflect.TypeOf(1))", Args{"reflect.Type": MakeTypeInterface(reflect.Type(nil)), "reflect.TypeOf": MakeDataRegularInterface(reflect.TypeOf)}, nil, true}, 210 | {"unicode.IsDigit('1')", Args{"unicode.IsDigit": MakeDataRegularInterface(unicode.IsDigit)}, MakeDataRegularInterface(true), false}, 211 | {"token.Token.String(token.ADD)", Args{"token.Token": MakeTypeInterface(token.Token(0)), "token.ADD": MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt(int(token.ADD)), reflect.TypeOf(token.Token(0))))}, MakeDataRegularInterface("+"), false}, 212 | {"token.Token.String2(nil)", Args{"token.Token": MakeTypeInterface(token.Token(0))}, nil, true}, 213 | {"reflect.Type.Name(reflect.TypeOf(1))", Args{"reflect.Type": MakeType(reflecth.TypeOfPtr(&tmp2)), "reflect.TypeOf": MakeDataRegularInterface(reflect.TypeOf)}, nil, true}, // Known BUG. Must return "int", but currently method expression does not supported. 214 | {"new.Method()", nil, nil, true}, 215 | }, 216 | "binary": []testExprElement{ 217 | // Other 218 | {"new + 1", nil, nil, true}, 219 | {"1 + new", nil, nil, true}, 220 | {"nil+1", nil, nil, true}, 221 | {"1+2", nil, MakeDataUntypedConst(constant.MakeInt64(3)), false}, 222 | {"int(1)+int(2)", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeInt64(3), reflecth.TypeInt())), false}, 223 | {"1+int(2)", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeInt64(3), reflecth.TypeInt())), false}, 224 | {"int(1)+2", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeInt64(3), reflecth.TypeInt())), false}, 225 | {"128+int8(2)", nil, nil, true}, 226 | {"int8(1)+128", nil, nil, true}, 227 | {`1+"2"`, nil, nil, true}, 228 | {"a+2", ArgsFromInterfaces(ArgsI{"a": 1}), MakeDataRegularInterface(3), false}, 229 | {`a+"2"`, ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 230 | {"2+a", ArgsFromInterfaces(ArgsI{"a": 1}), MakeDataRegularInterface(3), false}, 231 | {`"2"+a`, ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 232 | {"a+b", ArgsFromInterfaces(ArgsI{"a": 1, "b": 2}), MakeDataRegularInterface(3), false}, 233 | {"a+b", ArgsFromInterfaces(ArgsI{"a": 1, "b": "2"}), nil, true}, 234 | {"true&&a", ArgsFromInterfaces(ArgsI{"a": false}), MakeDataRegularInterface(false), false}, 235 | {"a+b", ArgsFromInterfaces(ArgsI{"a": "1", "b": "2"}), MakeDataRegularInterface("12"), false}, 236 | {"a+b", ArgsFromInterfaces(ArgsI{"a": 1, "b": int8(2)}), nil, true}, 237 | {"a+2", ArgsFromInterfaces(ArgsI{"a": int8(1)}), MakeDataRegularInterface(int8(3)), false}, 238 | {"a+2", ArgsFromInterfaces(ArgsI{"a": int16(1)}), MakeDataRegularInterface(int16(3)), false}, 239 | {"a+2", ArgsFromInterfaces(ArgsI{"a": int32(1)}), MakeDataRegularInterface(int32(3)), false}, 240 | {"a+2", ArgsFromInterfaces(ArgsI{"a": int64(1)}), MakeDataRegularInterface(int64(3)), false}, 241 | {"a+2", ArgsFromInterfaces(ArgsI{"a": uint(1)}), MakeDataRegularInterface(uint(3)), false}, 242 | {"a+2", ArgsFromInterfaces(ArgsI{"a": uint8(1)}), MakeDataRegularInterface(uint8(3)), false}, 243 | {"a+2", ArgsFromInterfaces(ArgsI{"a": uint16(1)}), MakeDataRegularInterface(uint16(3)), false}, 244 | {"a+2", ArgsFromInterfaces(ArgsI{"a": uint32(1)}), MakeDataRegularInterface(uint32(3)), false}, 245 | {"a+2", ArgsFromInterfaces(ArgsI{"a": uint64(1)}), MakeDataRegularInterface(uint64(3)), false}, 246 | {"a+2.0", ArgsFromInterfaces(ArgsI{"a": uint64(1)}), MakeDataRegularInterface(uint64(3)), false}, 247 | {"a+2", ArgsFromInterfaces(ArgsI{"a": float32(1)}), MakeDataRegularInterface(float32(3)), false}, 248 | {"a+2", ArgsFromInterfaces(ArgsI{"a": float64(1)}), MakeDataRegularInterface(float64(3)), false}, 249 | {"a+0-11i", ArgsFromInterfaces(ArgsI{"a": complex64(2 + 3i)}), MakeDataRegularInterface(complex64(2 - 8i)), false}, 250 | {"a+0-11i", ArgsFromInterfaces(ArgsI{"a": complex128(2 + 3i)}), MakeDataRegularInterface(complex128(2 - 8i)), false}, 251 | {`string("str")-string("str")`, nil, nil, true}, 252 | // Shift 253 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": 4, "b": 2}), nil, true}, 255 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": 4, "b": uint8(2)}), MakeDataRegularInterface(1), false}, 257 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": int8(4), "b": uint16(2)}), MakeDataRegularInterface(int8(1)), false}, 259 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": int16(4), "b": uint32(2)}), MakeDataRegularInterface(int16(1)), false}, 261 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": int32(4), "b": uint64(2)}), MakeDataRegularInterface(int32(1)), false}, 263 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": int64(4), "b": uint(2)}), MakeDataRegularInterface(int64(1)), false}, 265 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": uint(4), "b": uint8(2)}), MakeDataRegularInterface(uint(1)), false}, 267 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": uint8(4), "b": uint16(2)}), MakeDataRegularInterface(uint8(1)), false}, 269 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": uint16(4), "b": uint32(2)}), MakeDataRegularInterface(uint16(1)), false}, 271 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": uint32(4), "b": uint64(2)}), MakeDataRegularInterface(uint32(1)), false}, 273 | {"a<>b", ArgsFromInterfaces(ArgsI{"a": uint64(4), "b": uint(2)}), MakeDataRegularInterface(uint64(1)), false}, 275 | {"4<<2", nil, MakeDataUntypedConst(constant.MakeInt64(16)), false}, 276 | {"4>>2", nil, MakeDataUntypedConst(constant.MakeInt64(1)), false}, 277 | {"4<>2", ArgsFromInterfaces(ArgsI{"a": int(4)}), MakeDataRegularInterface(1), false}, 279 | {`"4"<>"2"`, ArgsFromInterfaces(ArgsI{"a": int(4)}), nil, true}, 281 | {`"4">>2`, nil, nil, true}, 282 | {`4>>"2"`, nil, nil, true}, 283 | {"1<<2", nil, MakeDataUntypedConst(constant.MakeInt64(4)), false}, 284 | {`"1"<<2`, nil, nil, true}, 285 | {`1<<"2"`, nil, nil, true}, 286 | {"4<>2", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeUint8(1), reflecth.TypeUint8())), false}, 292 | {"uint(4)<=b", ArgsFromInterfaces(ArgsI{"a": int8(1), "b": int8(2)}), MakeDataUntypedBool(false), false}, 299 | {"a<=b", ArgsFromInterfaces(ArgsI{"a": int16(1), "b": int16(2)}), MakeDataUntypedBool(true), false}, 300 | {"a!=b", ArgsFromInterfaces(ArgsI{"a": int32(1), "b": int32(2)}), MakeDataUntypedBool(true), false}, 301 | {"a>b", ArgsFromInterfaces(ArgsI{"a": int64(1), "b": int64(2)}), MakeDataUntypedBool(false), false}, 302 | {"a=b", ArgsFromInterfaces(ArgsI{"a": uint8(1), "b": uint8(2)}), MakeDataUntypedBool(false), false}, 305 | {"a<=b", ArgsFromInterfaces(ArgsI{"a": uint16(1), "b": uint16(2)}), MakeDataUntypedBool(true), false}, 306 | {"a!=b", ArgsFromInterfaces(ArgsI{"a": uint32(1), "b": uint32(2)}), MakeDataUntypedBool(true), false}, 307 | {"a>b", ArgsFromInterfaces(ArgsI{"a": uint64(1), "b": uint64(2)}), MakeDataUntypedBool(false), false}, 308 | {"a=b", ArgsFromInterfaces(ArgsI{"a": float64(1), "b": float64(2)}), MakeDataUntypedBool(false), false}, 311 | {"a<=b", ArgsFromInterfaces(ArgsI{"a": float32(1), "b": float32(2)}), MakeDataUntypedBool(true), false}, 312 | {"a!=b", ArgsFromInterfaces(ArgsI{"a": float64(1), "b": float64(2)}), MakeDataUntypedBool(true), false}, 313 | {"a>b", ArgsFromInterfaces(ArgsI{"a": float32(1), "b": float32(2)}), MakeDataUntypedBool(false), false}, 314 | {"a=b", ArgsFromInterfaces(ArgsI{"a": "1", "b": "2"}), MakeDataUntypedBool(false), false}, 317 | {"a<=b", ArgsFromInterfaces(ArgsI{"a": "1", "b": "2"}), MakeDataUntypedBool(true), false}, 318 | {"a!=b", ArgsFromInterfaces(ArgsI{"a": "1", "b": "2"}), MakeDataUntypedBool(true), false}, 319 | {"a>b", ArgsFromInterfaces(ArgsI{"a": "1", "b": "2"}), MakeDataUntypedBool(false), false}, 320 | {"anil", nil, nil, true}, 333 | {"int(1)==nil", nil, nil, true}, 334 | {"nil==nil", nil, nil, true}, 335 | {"[]int(nil)==nil", nil, MakeDataUntypedBool(true), false}, 336 | {"[]int(nil)!=nil", nil, MakeDataUntypedBool(false), false}, 337 | {"1==2==true", nil, MakeDataUntypedBool(false), false}, 338 | {"1==2!=true", nil, MakeDataUntypedBool(true), false}, 339 | {"1==2==1", nil, nil, true}, 340 | {"1==2>1", nil, nil, true}, 341 | {"1==2==bool(true)", nil, MakeDataUntypedBool(false), false}, 342 | {"bool(true)==(1==2)", nil, MakeDataUntypedBool(false), false}, 343 | {"1==2==int(1)", nil, nil, true}, 344 | {"1==2==a", ArgsFromInterfaces(ArgsI{"a": false}), MakeDataUntypedBool(true), false}, 345 | {"1==2==a", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 346 | {"1==2==(3==3)", nil, MakeDataUntypedBool(false), false}, 347 | {"1==2==nil", nil, nil, true}, 348 | {"int(1)>int(2)", nil, MakeDataUntypedBool(false), false}, 349 | {"uint(1)<=2", nil, MakeDataUntypedBool(true), false}, 350 | {"uint(1)<=0.1", nil, nil, true}, 351 | {"0.1<=uint(1)", nil, nil, true}, 352 | {`"str0">=string("str1")`, nil, MakeDataUntypedBool(false), false}, 353 | {"a==1", ArgsFromInterfaces(ArgsI{"a": "str"}), nil, true}, 354 | {"1==a", ArgsFromInterfaces(ArgsI{"a": "str"}), nil, true}, 355 | }, 356 | "basic-lit": []testExprElement{}, 357 | "call": []testExprElement{ 358 | {"f(3)", ArgsFromInterfaces(ArgsI{"f": func(x uint8) uint64 { return 2 * uint64(x) }}), MakeDataRegularInterface(uint64(6)), false}, 359 | {"f(2)", nil, nil, true}, 360 | {"a.M(3)", ArgsFromInterfaces(ArgsI{"a": SampleStruct{2}}), MakeDataRegularInterface(uint64(6)), false}, 361 | {"a.M(5)", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{4}}), MakeDataRegularInterface(uint64(20)), false}, 362 | {"a.M(b)", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{4}, "b": uint32(5)}), MakeDataRegularInterface(uint64(20)), false}, 363 | {"a.M9(7)", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{6}}), nil, true}, 364 | {"a.F(7)", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{6}}), nil, true}, 365 | {"a.M(7,8)", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{6}}), nil, true}, 366 | {"a.M2(7)", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{6}}), nil, true}, 367 | {"a.M(b)", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{6}}), nil, true}, 368 | {`a.M("7")`, ArgsFromInterfaces(ArgsI{"a": &SampleStruct{6}}), nil, true}, 369 | {"a.M(b)", ArgsFromInterfaces(ArgsI{"a": &SampleStruct{6}, "b": "bad"}), nil, true}, 370 | {"a(2)", Args{"a": MakeDataUntypedConst(constant.MakeBool(true))}, nil, true}, 371 | {"f(a...)", ArgsFromInterfaces(ArgsI{"a": 1, "f": func(x uint8) uint64 { return 2 * uint64(x) }}), nil, true}, 372 | {"myDiv(2,6,8,10)", ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), MakeDataRegularInterface([]int{3, 4, 5}), false}, 373 | {"myDiv(2, []int{6,8,10}...)", ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), MakeDataRegularInterface([]int{3, 4, 5}), false}, 374 | {"myDiv([]int{2,6,8,}...)", ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), nil, true}, 375 | {"myDiv([]int{6,8,10}...)", ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), nil, true}, 376 | {`myDiv("str",[]int{6,8,10}...)`, ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), nil, true}, 377 | {"myDiv(0, []int{6,8,10}...)", ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), nil, true}, 378 | {"myDiv(2)", ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), MakeDataRegularInterface([]int{}), false}, 379 | {"myDiv()", ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), nil, true}, 380 | {`myDiv("str")`, ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), nil, true}, 381 | {`myDiv(2,"str")`, ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), nil, true}, 382 | {"myDiv(0, 6,8,10)", ArgsFromInterfaces(ArgsI{"myDiv": myDiv}), nil, true}, 383 | {"f(1,0)", ArgsFromInterfaces(ArgsI{"f": func(x, y uint8) uint8 { return x / y }}), nil, true}, 384 | {"f()", ArgsFromInterfaces(ArgsI{"f": func() {}}), nil, true}, 385 | {"new([]int, 1+true)", nil, nil, true}, 386 | {"int(([]int8{1,2,3})...)", nil, nil, true}, 387 | {"reflect()", ArgsFromInterfaces(ArgsI{"reflect.TypeOf": reflect.TypeOf}), nil, true}, 388 | {"len([]int{1,2,3}...)", nil, nil, true}, 389 | {"cap(struct{})", nil, nil, true}, 390 | {"new(1)", nil, nil, true}, 391 | {"make([]int,10)", nil, MakeDataRegularInterface(make([]int, 10)), false}, 392 | {"make([]int,10,12)", nil, MakeDataRegularInterface(make([]int, 10, 12)), false}, 393 | {"make([]int,10,1)", nil, nil, true}, 394 | {"make(1,2,3)", nil, nil, true}, 395 | {"make([]int,10,string)", nil, nil, true}, 396 | {"make([]int,string)", nil, nil, true}, 397 | {"make([]int,10,11.5)", nil, nil, true}, 398 | {"make([]int,10,-1)", nil, nil, true}, 399 | {"make([]int,11.5)", nil, nil, true}, 400 | {"make([]int,-1)", nil, nil, true}, 401 | {"make([]int)", nil, nil, true}, 402 | {"make(map[string]int)", nil, MakeDataRegularInterface(make(map[string]int)), false}, 403 | {"make(map[string]int,10)", nil, MakeDataRegularInterface(make(map[string]int)), false}, 404 | {"make(map[string]int,10,11)", nil, nil, true}, 405 | {"make(chan int8)", nil, MakeDataRegularInterface(make(chan int8)), false}, 406 | {"make(chan uint8,10)", nil, MakeDataRegularInterface(make(chan uint8, 10)), false}, 407 | {"make(chan int64,10,11)", nil, nil, true}, 408 | {"make(struct{},10)", nil, nil, true}, 409 | {"len(1)", nil, nil, true}, 410 | {"len(struct{}{})", nil, nil, true}, 411 | {`len(string("str"))`, nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt(3), reflecth.TypeInt())), false}, 412 | {"len(a)", ArgsFromInterfaces(ArgsI{"a": []int8{1, 2, 3}}), MakeDataRegularInterface(3), false}, 413 | {"len(a)", ArgsFromInterfaces(ArgsI{"a": [4]int8{1, 2, 3, 4}}), MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeInt64(4), reflecth.TypeInt())), false}, 414 | {"len(a)", ArgsFromInterfaces(ArgsI{"a": &([5]int8{1, 2, 3, 4, 5})}), MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeInt64(5), reflecth.TypeInt())), false}, 415 | {"len(a)", ArgsFromInterfaces(ArgsI{"a": "abcde"}), MakeDataRegularInterface(5), false}, 416 | {`len("abcdef")`, nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt(6), reflecth.TypeInt())), false}, 417 | {"len(a)", ArgsFromInterfaces(ArgsI{"a": map[string]int8{"first": 1, "second": 2}}), MakeDataRegularInterface(2), false}, 418 | {"len(a)", ArgsFromInterfaces(ArgsI{"a": make(chan int16)}), MakeDataRegularInterface(0), false}, 419 | {"len(1==2)", nil, nil, true}, 420 | {"cap(a)", ArgsFromInterfaces(ArgsI{"a": make([]int8, 3, 5)}), MakeDataRegularInterface(5), false}, 421 | {"cap(a)", ArgsFromInterfaces(ArgsI{"a": [4]int8{1, 2, 3, 4}}), MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeInt64(4), reflecth.TypeInt())), false}, 422 | {"cap(a)", ArgsFromInterfaces(ArgsI{"a": &([3]int8{1, 2, 3})}), MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeInt64(3), reflecth.TypeInt())), false}, 423 | {"cap(a)", ArgsFromInterfaces(ArgsI{"a": make(chan int16, 2)}), MakeDataRegularInterface(2), false}, 424 | {"cap(struct{}{})", nil, nil, true}, 425 | {"cap(1)", nil, nil, true}, 426 | {"complex(1,0.5)", nil, MakeDataUntypedConst(constanth.MakeComplex128(complex(1, 0.5))), false}, 427 | {"complex(a,0.3)", ArgsFromInterfaces(ArgsI{"a": float32(2)}), MakeDataRegularInterface(complex(float32(2), 0.3)), false}, 428 | {"complex(3,a)", ArgsFromInterfaces(ArgsI{"a": float64(0.4)}), MakeDataRegularInterface(complex(3, float64(0.4))), false}, 429 | {"complex(a,b)", ArgsFromInterfaces(ArgsI{"a": float32(4), "b": float32(0.5)}), MakeDataRegularInterface(complex(float32(4), 0.5)), false}, 430 | {`complex("1",2)`, nil, nil, true}, 431 | {`complex(1,"2")`, nil, nil, true}, 432 | {"complex(float32(1),0.5)", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeComplex64(complex(1, 0.5)), reflecth.TypeComplex64())), false}, 433 | {"complex(float64(1),0.5)", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeComplex128(complex(1, 0.5)), reflecth.TypeComplex128())), false}, 434 | {"complex(1,float32(0.5))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeComplex64(complex(1, 0.5)), reflecth.TypeComplex64())), false}, 435 | {"complex(1,float64(0.5))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeComplex128(complex(1, 0.5)), reflecth.TypeComplex128())), false}, 436 | {"complex(float32(1),float32(0.5))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeComplex64(complex(1, 0.5)), reflecth.TypeComplex64())), false}, 437 | {"complex(float64(1),float64(0.5))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeComplex128(complex(1, 0.5)), reflecth.TypeComplex128())), false}, 438 | {"complex(float32(1),a)", ArgsFromInterfaces(ArgsI{"a": float32(0.5)}), MakeDataRegularInterface(complex(float32(1), 0.5)), false}, 439 | {"complex(float64(1),a)", ArgsFromInterfaces(ArgsI{"a": float32(0.5)}), nil, true}, 440 | {`complex(string("str"),a)`, ArgsFromInterfaces(ArgsI{"a": float32(0.5)}), nil, true}, 441 | {`complex(a,string("str"))`, ArgsFromInterfaces(ArgsI{"a": float32(0.5)}), nil, true}, 442 | {`complex(a,1==2)`, ArgsFromInterfaces(ArgsI{"a": float32(0.5)}), nil, true}, 443 | {`complex(float32(1),"0.5")`, nil, nil, true}, 444 | {`complex(float32(1),` + veryLongNumber + `)`, nil, nil, true}, 445 | {"complex(float32(1),float64(0.5))", nil, nil, true}, 446 | {"real(0.5-0.2i)", nil, MakeDataUntypedConst(constant.MakeFloat64(0.5)), false}, 447 | {"real(a)", ArgsFromInterfaces(ArgsI{"a": 0.5 - 0.2i}), MakeDataRegularInterface(0.5), false}, 448 | {"real(a)", ArgsFromInterfaces(ArgsI{"a": complex64(0.5 - 0.2i)}), MakeDataRegularInterface(float32(0.5)), false}, 449 | {"real(a)", ArgsFromInterfaces(ArgsI{"a": "str"}), nil, true}, 450 | {"real(complex64(1-2i))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeFloat32(1), reflecth.TypeFloat32())), false}, 451 | {"real(complex128(1-2i))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeFloat64(1), reflecth.TypeFloat64())), false}, 452 | {`real(string("str"))`, nil, nil, true}, 453 | {`real("str")`, nil, nil, true}, 454 | {`real(1==2)`, nil, nil, true}, 455 | {"imag(0.2-0.5i)", nil, MakeDataUntypedConst(constant.MakeFloat64(-0.5)), false}, 456 | {"imag(a)", ArgsFromInterfaces(ArgsI{"a": 0.2 - 0.5i}), MakeDataRegularInterface(-0.5), false}, 457 | {"imag(a)", ArgsFromInterfaces(ArgsI{"a": complex64(0.2 - 0.5i)}), MakeDataRegularInterface(float32(-0.5)), false}, 458 | {"imag(a)", ArgsFromInterfaces(ArgsI{"a": "str"}), nil, true}, 459 | {"imag(complex64(1-2i))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeFloat32(-2), reflecth.TypeFloat32())), false}, 460 | {"imag(complex128(1-2i))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeFloat64(-2), reflecth.TypeFloat64())), false}, 461 | {`imag(string("str"))`, nil, nil, true}, 462 | {`imag("str")`, nil, nil, true}, 463 | {`imag(1==2)`, nil, nil, true}, 464 | {"append(1,2)", nil, nil, true}, 465 | {"append(a,2)", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 466 | {"append(a,b...)", ArgsFromInterfaces(ArgsI{"a": []int{1, 2}, "b": []int{3, 4}}), MakeDataRegularInterface([]int{1, 2, 3, 4}), false}, 467 | {"append(a,(1)...)", ArgsFromInterfaces(ArgsI{"a": []int{1, 2}}), nil, true}, 468 | {"append(a,b,c...)", ArgsFromInterfaces(ArgsI{"a": []int{1, 2}, "b": []int{3, 4}, "c": 5}), nil, true}, 469 | {"append(a,b...)", ArgsFromInterfaces(ArgsI{"a": []int{1, 2}, "b": 1}), nil, true}, 470 | {"append(a,b...)", ArgsFromInterfaces(ArgsI{"a": []int{1, 2}, "b": []myInt{3, 4}}), nil, true}, 471 | {"append(a,b)", ArgsFromInterfaces(ArgsI{"a": []int{1, 2}, "b": 3}), MakeDataRegularInterface([]int{1, 2, 3}), false}, 472 | {"append(a,b)", ArgsFromInterfaces(ArgsI{"a": []int{1, 2}, "b": myInt(3)}), nil, true}, 473 | }, 474 | "type": []testExprElement{ 475 | {"int8(1)", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeInt64(1), reflecth.TypeInt8())), false}, 476 | {"string(65)", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeString("A"), reflecth.TypeString())), false}, 477 | {"string(12345678901234567890)", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constant.MakeString(string(unicode.ReplacementChar)), reflecth.TypeString())), false}, 478 | {"int8(int64(127))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt8(127), reflecth.TypeInt8())), false}, 479 | {"int8(int64(128))", nil, nil, true}, 480 | {`append([]byte{1,3,5}, "135"...)`, nil, MakeDataRegularInterface([]byte{1, 3, 5, '1', '3', '5'}), false}, 481 | {"[]int(nil)", nil, MakeDataRegularInterface([]int(nil)), false}, 482 | {"int()", nil, nil, true}, 483 | {"int(1,2)", nil, nil, true}, 484 | {"[]int(nil)", nil, MakeDataRegularInterface([]int(nil)), false}, 485 | {"int(nil)", nil, nil, true}, 486 | {"int8(int(-1))", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt8(-1), reflecth.TypeInt8())), false}, 487 | {"uint(int(-1))", nil, nil, true}, 488 | {"bool(1==2)", nil, MakeDataRegularInterface(false), false}, 489 | {"str(1==2)", nil, nil, true}, 490 | {"myInterface(myImplementation{5})", Args{"myInterface": MakeType(reflecth.TypeOfPtr(&tmp4)), "myImplementation": MakeType(reflect.TypeOf(myImplementation{}))}, MakeDataRegular(reflecth.ValueOfPtr(&tmp4)), false}, 491 | {"interface{}(int8(5))", nil, MakeDataRegular(reflecth.ValueOfPtr(&(tmp5))), false}, 492 | {"interface{}(5)", nil, MakeDataRegular(reflecth.ValueOfPtr(&(tmp6))), false}, 493 | {"(interface{})(3>2)", nil, MakeDataRegular(reflecth.ValueOfPtr(&(tmp7))), false}, 494 | }, 495 | "star": []testExprElement{ 496 | {"*v", ArgsFromInterfaces(ArgsI{"v": new(int8)}), MakeDataRegularInterface(int8(0)), false}, 497 | {"*v", ArgsFromInterfaces(ArgsI{"v": int8(3)}), nil, true}, 498 | {"*v", nil, nil, true}, 499 | {"[]*([]int){&[]int{1,2},&[]int{3,4}}", nil, MakeDataRegularInterface([]*([]int){&[]int{1, 2}, &[]int{3, 4}}), false}, 500 | {"*new(myStruct)", Args{"myStruct": MakeType(reflect.TypeOf(myStruct{}))}, MakeDataRegularInterface(myStruct{}), false}, 501 | }, 502 | "paren": []testExprElement{ 503 | {"(v)", ArgsFromInterfaces(ArgsI{"v": int8(3)}), MakeDataRegularInterface(int8(3)), false}, 504 | {"(v)", nil, nil, true}, 505 | }, 506 | "unary": []testExprElement{ 507 | {"-1", nil, MakeDataUntypedConst(constant.MakeInt64(-1)), false}, 508 | {"+2", nil, MakeDataUntypedConst(constant.MakeInt64(+2)), false}, 509 | {"-a", ArgsFromInterfaces(ArgsI{"a": int8(3)}), MakeDataRegularInterface(int8(-3)), false}, 510 | {"-a", ArgsFromInterfaces(ArgsI{"a": int8(-128)}), MakeDataRegularInterface(int8(-128)), false}, // check overflow behaviour 511 | {"+a", ArgsFromInterfaces(ArgsI{"a": int8(4)}), MakeDataRegularInterface(int8(4)), false}, 512 | {"^a", ArgsFromInterfaces(ArgsI{"a": int8(5)}), MakeDataRegularInterface(int8(-6)), false}, 513 | {"!a", ArgsFromInterfaces(ArgsI{"a": true}), MakeDataRegularInterface(false), false}, 514 | {"-(new)", nil, nil, true}, 515 | {"-int8(1)", nil, MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeInt8(-1), reflecth.TypeInt8())), false}, 516 | {"!(1==2)", nil, MakeDataUntypedBool(true), false}, 517 | {"-(1==2)", nil, nil, true}, 518 | {"!nil", nil, nil, true}, 519 | {"-a", ArgsFromInterfaces(ArgsI{"a": "str"}), nil, true}, 520 | {`-string("str")`, nil, nil, true}, 521 | {`-"str"`, nil, nil, true}, 522 | }, 523 | "chan": []testExprElement{ 524 | {"chan int", nil, MakeType(reflect.ChanOf(reflect.BothDir, reflecth.TypeInt())), false}, 525 | {"chan a", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 526 | }, 527 | "func-type": { 528 | {"func(int, ...string)", nil, MakeTypeInterface((func(int, ...string))(nil)), false}, 529 | {"func(int, ...a)", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 530 | {"func(...int, string)", nil, nil, true}, 531 | {"func(int, []string)", nil, MakeTypeInterface((func(int, []string))(nil)), false}, 532 | {"func(int)(string)", nil, MakeTypeInterface((func(int) string)(nil)), false}, 533 | {"func(int)(string,a)", nil, nil, true}, 534 | }, 535 | "array-type": { 536 | {"[]a", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 537 | {"[a]int", ArgsFromInterfaces(ArgsI{"a": true}), nil, true}, 538 | {"[a]int", Args{"a": MakeTypeInterface(1)}, nil, true}, 539 | {"[a]int", Args{"a": MakeDataUntypedConst(constanth.MakeBool(true))}, nil, true}, 540 | {"[a]int", Args{"a": MakeDataTypedConst(constanth.MustMakeTypedValue(constanth.MakeBool(true), reflecth.TypeBool()))}, nil, true}, 541 | {"[-1]int", nil, nil, true}, 542 | }, 543 | "slice": []testExprElement{ 544 | {"a[1:3]", ArgsFromInterfaces(ArgsI{"a": []int8{10, 11, 12, 13}}), MakeDataRegularInterface([]int8{11, 12}), false}, 545 | {"a[:3]", ArgsFromInterfaces(ArgsI{"a": []int8{10, 11, 12, 13}}), MakeDataRegularInterface([]int8{10, 11, 12}), false}, 546 | {"a[1:]", ArgsFromInterfaces(ArgsI{"a": []int8{10, 11, 12, 13}}), MakeDataRegularInterface([]int8{11, 12, 13}), false}, 547 | {"a[:]", ArgsFromInterfaces(ArgsI{"a": []int8{10, 11, 12, 13}}), MakeDataRegularInterface([]int8{10, 11, 12, 13}), false}, 548 | {"a[1:3]", ArgsFromInterfaces(ArgsI{"a": "abcd"}), MakeDataRegularInterface("bc"), false}, 549 | {"a[1:3]", ArgsFromInterfaces(ArgsI{"a": &([4]int8{10, 11, 12, 13})}), MakeDataRegularInterface([]int8{11, 12}), false}, 550 | {"a[1:2]", Args{"a": MakeTypeInterface(1)}, nil, true}, 551 | {`"abcd"[a:2]`, Args{"a": MakeTypeInterface(1)}, nil, true}, 552 | {`"abcd"[1:a]`, Args{"a": MakeTypeInterface(1)}, nil, true}, 553 | {`"abcd"[1:2:a]`, Args{"a": MakeTypeInterface(1)}, nil, true}, 554 | {`"abcd"[1:2]`, nil, MakeDataRegularInterface("b"), false}, 555 | {`myStr("abcd")[1:2]`, Args{"myStr": MakeTypeInterface(myStr(""))}, MakeDataRegularInterface(myStr("b")), false}, 556 | {"1234[1:2]", nil, nil, true}, 557 | {"int(1234)[1:2]", nil, nil, true}, 558 | {"(1==2)[1:2]", nil, nil, true}, 559 | {"([]int{1,2,3,4,5})[1:3:5]", nil, MakeDataRegularInterface(([]int{1, 2, 3, 4, 5})[1:3:5]), false}, 560 | {"a[2:3]", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 561 | {"a[2:3]", ArgsFromInterfaces(ArgsI{"a": [1]int{2}}), nil, true}, 562 | {"[]int{1,2,3,4,5}[-1:3]", nil, nil, true}, 563 | {"[]int{1,2,3,4,5}[1:6]", nil, nil, true}, 564 | {"[]int{1,2,3,4,5}[3:1]", nil, nil, true}, 565 | {`[]int{1,2,3,4,5}["str":1]`, nil, nil, true}, 566 | 567 | {"a[2:3:4]", ArgsFromInterfaces(ArgsI{"a": &[5]int{1, 2, 3, 4, 5}}), MakeDataRegularInterface((&[5]int{1, 2, 3, 4, 5})[2:3:4]), false}, 568 | {"a[:3:4]", ArgsFromInterfaces(ArgsI{"a": &[5]int{1, 2, 3, 4, 5}}), MakeDataRegularInterface((&[5]int{1, 2, 3, 4, 5})[:3:4]), false}, 569 | {"a[2:3:4]", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 570 | {"a[2:3:4]", ArgsFromInterfaces(ArgsI{"a": [1]int{2}}), nil, true}, 571 | {"[]int{1,2,3,4,5}[3:2:4]", nil, nil, true}, 572 | {"[]int{1,2,3,4,5}[2:4:3]", nil, nil, true}, 573 | {"[]int{1,2,3,4,5}[2:3:6]", nil, nil, true}, 574 | }, 575 | "index": []testExprElement{ 576 | {"a[b]", ArgsFromInterfaces(ArgsI{"a": map[string]int8{"x": 10, "y": 20}, "b": "y"}), MakeDataRegularInterface(int8(20)), false}, 577 | {`a["y"]`, ArgsFromInterfaces(ArgsI{"a": map[string]int8{"x": 10, "y": 20}}), MakeDataRegularInterface(int8(20)), false}, 578 | {`"abcd"[c]`, ArgsFromInterfaces(ArgsI{"c": 1}), MakeDataRegularInterface(byte('b')), false}, 579 | {`string("abcd")[c]`, ArgsFromInterfaces(ArgsI{"c": 1}), MakeDataRegularInterface(byte('b')), false}, 580 | {`"abcd"[1]`, nil, MakeDataUntypedConst(constant.MakeInt64('b')), false}, 581 | {"a[b]", ArgsFromInterfaces(ArgsI{"a": "abcd", "b": 1}), MakeDataRegularInterface(byte('b')), false}, 582 | {"a[1]", ArgsFromInterfaces(ArgsI{"a": "abcd"}), MakeDataRegularInterface(byte('b')), false}, 583 | {"a[1]", Args{"a": MakeTypeInterface(1)}, nil, true}, 584 | {`"abcd"[a]`, Args{"a": MakeTypeInterface(1)}, nil, true}, 585 | {"(1==2)[0]", nil, nil, true}, 586 | {`map[string]int{"str0":1, "str1":2}[0]`, nil, nil, true}, 587 | {`map[string]int{"str0":1, "str1":2}["str1"]`, nil, MakeDataRegularInterface(2), false}, 588 | {`map[string]int{"str0":1, "str1":2}["str2"]`, nil, MakeDataRegularInterface(0), false}, 589 | {`1["str2"]`, nil, nil, true}, 590 | {`a["str2"]`, ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 591 | {`[]int{1,2}["str2"]`, nil, nil, true}, 592 | {`[]int{1,2}[-1]`, nil, nil, true}, 593 | {`[]int{1,2}[2]`, nil, nil, true}, 594 | {`"str"["str"]`, nil, nil, true}, 595 | {`"str"[-1]`, nil, nil, true}, 596 | {`"str"[3]`, nil, nil, true}, 597 | }, 598 | "composite": []testExprElement{ 599 | {`myStruct{}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, MakeDataRegularInterface(myStruct{}), false}, 600 | {`myStruct{1,"str"}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, MakeDataRegularInterface(myStruct{1, "str"}), false}, 601 | {`myStruct{1,"str",2}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 602 | {`myStruct{I:1,S:"str"}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, MakeDataRegularInterface(myStruct{I: 1, S: "str"}), false}, 603 | {`myStruct{S:"str",I:1}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, MakeDataRegularInterface(myStruct{S: "str", I: 1}), false}, 604 | {`myStruct{S:"str",1}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 605 | {`myStruct{S:"str",I2:1}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 606 | {`myStruct{S:"str",(I):1}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 607 | {`myStruct{S:"str",I:myStruct}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 608 | {`myStruct{"str",I:1}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 609 | {`myStruct{"str",myStruct}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 610 | {`myStruct{I:"str",S:1}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 611 | {`myStruct{"str"}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 612 | {`myStruct{"str",1}`, Args{"myStruct": MakeTypeInterface(myStruct{})}, nil, true}, 613 | {`myStruct1{"str",1}`, Args{"myStruct1": MakeTypeInterface(myStruct1{})}, nil, true}, 614 | {"[]int{2}", nil, MakeDataRegularInterface([]int{2}), false}, 615 | {"[]int{2:2}", nil, MakeDataRegularInterface([]int{0, 0, 2}), false}, 616 | {"[]int{x:2}", nil, nil, true}, 617 | {`[]int{"abc":2}`, nil, nil, true}, 618 | {"[]int{int(2):2}", nil, MakeDataRegularInterface([]int{0, 0, 2}), false}, 619 | {"[]int{uint64(2):2}", nil, nil, true}, 620 | {"[]int{int(-2):2}", nil, nil, true}, 621 | {"[]int{(1==2):2}", nil, nil, true}, 622 | {"[]int{2:2,2:3}", nil, nil, true}, 623 | {"[]int{2:x}", nil, nil, true}, 624 | {"[1]int{2}", nil, MakeDataRegularInterface([1]int{2}), false}, 625 | {"[...]int{2}", nil, MakeDataRegularInterface([...]int{2}), false}, 626 | {"[...]a{2}", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 627 | {"[1]a{2}", ArgsFromInterfaces(ArgsI{"a": 1}), nil, true}, 628 | {"[]int{-1:1}", nil, nil, true}, 629 | {"[3]int{3:1}", nil, nil, true}, 630 | {`[3]int{2:"str"}`, nil, nil, true}, 631 | {"map[string]int{}", nil, MakeDataRegularInterface(map[string]int{}), false}, 632 | {`map[string]int{"str":1234}`, nil, MakeDataRegularInterface(map[string]int{"str": 1234}), false}, 633 | {`map[string]int{1234}`, nil, nil, true}, 634 | {`map[string]int{str:1234}`, nil, nil, true}, 635 | {`map[string]int{"str":x}`, nil, nil, true}, 636 | {`map[string]int{1:2}`, nil, nil, true}, 637 | {`map[string]int{"str1":"str2"}`, nil, nil, true}, 638 | {`myStr{str:1234}`, Args{"myStr": MakeTypeInterface(myStr(""))}, nil, true}, 639 | {`map[x]int{"str":1}`, nil, nil, true}, 640 | {`map[string]x{"str":1}`, nil, nil, true}, 641 | {`map[map[string]int]int{}`, nil, nil, true}, 642 | }, 643 | "type-assert": { 644 | {"myStr.(string)", Args{"myStr": MakeTypeInterface(myStr(""))}, nil, true}, 645 | {"(1234).(string)", nil, nil, true}, 646 | {"x.(y)", ArgsFromRegulars(ArgsR{"x": reflecth.ValueOfPtr(&tmp1), "y": reflect.ValueOf(1)}), nil, true}, 647 | {"x.(y)", Args{"x": MakeDataRegular(reflecth.ValueOfPtr(&tmp3)), "y": MakeType(reflect.TypeOf(myStr("")))}, nil, true}, 648 | {"x.(y)", Args{"x": MakeDataRegular(reflecth.ValueOfPtr(&tmp1)), "y": MakeType(reflecth.TypeOfPtr(&tmp3))}, nil, true}, 649 | }, 650 | "struct-type": { 651 | {"struct{}", nil, MakeType(reflect.TypeOf(struct{}{})), false}, 652 | {"struct{S string; I int}", nil, MakeType(reflect.TypeOf(struct { 653 | S string 654 | I int 655 | }{})), false}, 656 | {"struct{string; I int `protobuf:\"1\"`}", nil, MakeType(reflect.TypeOf(struct { 657 | string 658 | I int `protobuf:"1"` 659 | }{})), false}, 660 | {`struct{I myStruct}`, nil, nil, true}, 661 | {`struct{I0 int; I0 int}`, nil, nil, true}, 662 | }, 663 | "interface-type": { 664 | {"interface{}", nil, MakeType(reflecth.TypeEmptyInterface()), false}, 665 | {"interface{M1(int)string}", nil, nil, true}, 666 | }, 667 | "expr": []testExprElement{ 668 | {"(f.(func(int)(string)))(123)", ArgsFromRegulars(ArgsR{"f": reflecth.ValueOfPtr(&tmp1)}), MakeDataRegularInterface("123"), false}, 669 | {"((func(int)(string))(f))(123)", ArgsFromInterfaces(ArgsI{"f": strconvh.FormatInt}), MakeDataRegularInterface("123"), false}, 670 | { 671 | `((func(...string)(int))(f))("1","2","3")`, 672 | ArgsFromInterfaces(ArgsI{ 673 | "f": func(strs ...string) int { return len(strs) }, 674 | }), 675 | MakeDataRegularInterface(3), 676 | false, 677 | }, 678 | { 679 | `((func(...string)(int))(f))(([]string{"4","5","6","7"})...)`, 680 | ArgsFromInterfaces(ArgsI{ 681 | "f": func(strs ...string) int { return len(strs) }, 682 | }), 683 | MakeDataRegularInterface(4), 684 | false, 685 | }, 686 | {"a", Args{"a": MakeDataRegular(reflect.Value{})}, nil, true}, 687 | {"a.a", Args{"a.a": MakeDataRegularInterface(2)}, nil, true}, 688 | {"a.A", Args{"a": MakeDataRegularInterface(1), "a.A": MakeDataRegularInterface(2)}, nil, true}, 689 | {"a.a", Args{"a.a.a": MakeDataRegularInterface(2)}, nil, true}, 690 | }, 691 | } 692 | --------------------------------------------------------------------------------