Skip to content

Commit 44dfabc

Browse files
committed
Make AsAny the new default
1 parent cda16c2 commit 44dfabc

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

expr.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,34 +65,49 @@ func AsAny() Option {
6565
func AsKind(kind reflect.Kind) Option {
6666
return func(c *conf.Config) {
6767
c.Expect = kind
68+
c.ExpectAny = true
6869
}
6970
}
7071

7172
// AsBool tells the compiler to expect a boolean result.
7273
func AsBool() Option {
7374
return func(c *conf.Config) {
7475
c.Expect = reflect.Bool
76+
c.ExpectAny = true
7577
}
7678
}
7779

7880
// AsInt tells the compiler to expect an int result.
7981
func AsInt() Option {
8082
return func(c *conf.Config) {
8183
c.Expect = reflect.Int
84+
c.ExpectAny = true
8285
}
8386
}
8487

8588
// AsInt64 tells the compiler to expect an int64 result.
8689
func AsInt64() Option {
8790
return func(c *conf.Config) {
8891
c.Expect = reflect.Int64
92+
c.ExpectAny = true
8993
}
9094
}
9195

9296
// AsFloat64 tells the compiler to expect a float64 result.
9397
func AsFloat64() Option {
9498
return func(c *conf.Config) {
9599
c.Expect = reflect.Float64
100+
c.ExpectAny = true
101+
}
102+
}
103+
104+
// WarnOnAny tells the compiler to warn if expression return any type.
105+
func WarnOnAny() Option {
106+
return func(c *conf.Config) {
107+
if c.Expect == reflect.Invalid {
108+
panic("WarnOnAny() works only with combination with AsInt(), AsBool(), etc. options")
109+
}
110+
c.ExpectAny = false
96111
}
97112
}
98113

expr_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,17 @@ func ExampleAsFloat64_error() {
257257
// Output: expected float64, but got bool
258258
}
259259

260+
func ExampleWarnOnAny() {
261+
// Arrays always have []any type. The expression return type is any.
262+
// AsInt() instructs compiler to expect int or any, and cast to int,
263+
// if possible. WarnOnAny() instructs to return an error on any type.
264+
_, err := expr.Compile(`[42, true, "yes"][0]`, expr.AsInt(), expr.WarnOnAny())
265+
266+
fmt.Printf("%v", err)
267+
268+
// Output: expected int, but got interface {}
269+
}
270+
260271
func ExampleOperator() {
261272
code := `
262273
Now() > CreatedAt &&

0 commit comments

Comments
 (0)