Skip to content

Commit

Permalink
Make AsAny the new default
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Jan 21, 2024
1 parent cda16c2 commit 44dfabc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
15 changes: 15 additions & 0 deletions expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,34 +65,49 @@ func AsAny() Option {
func AsKind(kind reflect.Kind) Option {
return func(c *conf.Config) {
c.Expect = kind
c.ExpectAny = true
}
}

// AsBool tells the compiler to expect a boolean result.
func AsBool() Option {
return func(c *conf.Config) {
c.Expect = reflect.Bool
c.ExpectAny = true
}
}

// AsInt tells the compiler to expect an int result.
func AsInt() Option {
return func(c *conf.Config) {
c.Expect = reflect.Int
c.ExpectAny = true
}
}

// AsInt64 tells the compiler to expect an int64 result.
func AsInt64() Option {
return func(c *conf.Config) {
c.Expect = reflect.Int64
c.ExpectAny = true
}
}

// AsFloat64 tells the compiler to expect a float64 result.
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
}
}

Expand Down
11 changes: 11 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 &&
Expand Down

0 comments on commit 44dfabc

Please sign in to comment.