diff --git a/expr.go b/expr.go index 8569de8f..f32df1d3 100644 --- a/expr.go +++ b/expr.go @@ -65,6 +65,7 @@ func AsAny() Option { func AsKind(kind reflect.Kind) Option { return func(c *conf.Config) { c.Expect = kind + c.ExpectAny = true } } @@ -72,6 +73,7 @@ func AsKind(kind reflect.Kind) Option { func AsBool() Option { return func(c *conf.Config) { c.Expect = reflect.Bool + c.ExpectAny = true } } @@ -79,6 +81,7 @@ func AsBool() Option { func AsInt() Option { return func(c *conf.Config) { c.Expect = reflect.Int + c.ExpectAny = true } } @@ -86,6 +89,7 @@ func AsInt() Option { func AsInt64() Option { return func(c *conf.Config) { c.Expect = reflect.Int64 + c.ExpectAny = true } } @@ -93,6 +97,17 @@ func AsInt64() Option { func AsFloat64() Option { return func(c *conf.Config) { c.Expect = reflect.Float64 + c.ExpectAny = true + } +} + +// WarnOnAny tells the compiler to warn if expression return any type. +func WarnOnAny() Option { + return func(c *conf.Config) { + if c.Expect == reflect.Invalid { + panic("WarnOnAny() works only with combination with AsInt(), AsBool(), etc. options") + } + c.ExpectAny = false } } diff --git a/expr_test.go b/expr_test.go index 66ef11ce..fb805c76 100644 --- a/expr_test.go +++ b/expr_test.go @@ -257,6 +257,17 @@ func ExampleAsFloat64_error() { // Output: expected float64, but got bool } +func ExampleWarnOnAny() { + // Arrays always have []any type. The expression return type is any. + // AsInt() instructs compiler to expect int or any, and cast to int, + // if possible. WarnOnAny() instructs to return an error on any type. + _, err := expr.Compile(`[42, true, "yes"][0]`, expr.AsInt(), expr.WarnOnAny()) + + fmt.Printf("%v", err) + + // Output: expected int, but got interface {} +} + func ExampleOperator() { code := ` Now() > CreatedAt &&