Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions builtin/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,9 @@ var Builtins = []*Function{
{
Name: "max",
Func: func(args ...any) (any, error) {
if len(args) == 0 {
return nil, fmt.Errorf("invalid number of arguments for max (expected at least 1, got 0)")
}
return minMax("max", runtime.Less, 0, args...)
},
Validate: func(args []reflect.Type) (reflect.Type, error) {
Expand All @@ -452,6 +455,9 @@ var Builtins = []*Function{
{
Name: "min",
Func: func(args ...any) (any, error) {
if len(args) == 0 {
return nil, fmt.Errorf("invalid number of arguments for min (expected at least 1, got 0)")
}
return minMax("min", runtime.More, 0, args...)
},
Validate: func(args []reflect.Type) (reflect.Type, error) {
Expand All @@ -461,6 +467,9 @@ var Builtins = []*Function{
{
Name: "mean",
Func: func(args ...any) (any, error) {
if len(args) == 0 {
return nil, fmt.Errorf("invalid number of arguments for mean (expected at least 1, got 0)")
}
count, sum, err := mean(0, args...)
if err != nil {
return nil, err
Expand All @@ -477,6 +486,9 @@ var Builtins = []*Function{
{
Name: "median",
Func: func(args ...any) (any, error) {
if len(args) == 0 {
return nil, fmt.Errorf("invalid number of arguments for median (expected at least 1, got 0)")
}
values, err := median(0, args...)
if err != nil {
return nil, err
Expand Down Expand Up @@ -574,9 +586,15 @@ var Builtins = []*Function{
{
Name: "date",
Func: func(args ...any) (any, error) {
if len(args) == 0 {
return nil, fmt.Errorf("invalid number of arguments for date (expected at least 1, got 0)")
}
tz, ok := args[0].(*time.Location)
if ok {
args = args[1:]
if len(args) == 0 {
return nil, fmt.Errorf("invalid number of arguments for date (expected at least 2, got 1)")
}
}

date := args[0].(string)
Expand Down Expand Up @@ -631,6 +649,9 @@ var Builtins = []*Function{
}
if args[0] != nil && args[0].AssignableTo(locationType) {
args = args[1:]
if len(args) == 0 {
return anyType, fmt.Errorf("invalid number of arguments (expected at least 2, got 1)")
}
}
if len(args) > 3 {
return anyType, fmt.Errorf("invalid number of arguments (expected at most 3, got %d)", len(args))
Expand Down Expand Up @@ -658,6 +679,9 @@ var Builtins = []*Function{
{
Name: "first",
Func: func(args ...any) (any, error) {
if len(args) == 0 {
return nil, fmt.Errorf("invalid number of arguments for first (expected 1, got 0)")
}
defer func() {
if r := recover(); r != nil {
return
Expand All @@ -681,6 +705,9 @@ var Builtins = []*Function{
{
Name: "last",
Func: func(args ...any) (any, error) {
if len(args) == 0 {
return nil, fmt.Errorf("invalid number of arguments for last (expected 1, got 0)")
}
defer func() {
if r := recover(); r != nil {
return
Expand Down
58 changes: 58 additions & 0 deletions builtin/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,64 @@ func TestBuiltin_errors(t *testing.T) {
}
}

// The checker does not check arguments of a call on an unknown value, so a
// builtin with a wrong number of arguments there must fail with a clean error.
func TestBuiltin_wrong_number_of_arguments_unchecked(t *testing.T) {
env := map[string]any{"fn": func() any { return nil }}
tests := []struct {
input string
err string
}{
{`fn().N(join())`, "invalid number of arguments for join (expected 1 or 2, got 0)"},
{`fn().N(indexOf("a"))`, "invalid number of arguments for indexOf (expected 2, got 1)"},
{`fn().N(repeat("a"))`, "invalid number of arguments for repeat (expected 2, got 1)"},
{`fn().N(toJSON())`, "invalid number of arguments for toJSON (expected 1, got 0)"},
{`fn().N(date())`, "invalid number of arguments for date (expected at least 1, got 0)"},
{`fn().N(upper())`, "invalid number of arguments for upper (expected 1, got 0)"},
{`fn().N(max())`, "invalid number of arguments for max (expected at least 1, got 0)"},
{`fn().N(min())`, "invalid number of arguments for min (expected at least 1, got 0)"},
{`fn().N(mean())`, "invalid number of arguments for mean (expected at least 1, got 0)"},
{`fn().N(median())`, "invalid number of arguments for median (expected at least 1, got 0)"},
{`fn().N(first())`, "invalid number of arguments for first (expected 1, got 0)"},
{`fn().N(last())`, "invalid number of arguments for last (expected 1, got 0)"},
}
for _, test := range tests {
t.Run(test.input, func(t *testing.T) {
program, err := expr.Compile(test.input, expr.Env(env))
require.NoError(t, err)

_, err = expr.Run(program, env)
require.Error(t, err)
assert.Equal(t, test.err, strings.Split(err.Error(), " (1:")[0])
})
}
}

// Extra arguments of a Fast builtin in an unchecked call must not stay on the
// stack and leak into the surrounding expression.
func TestBuiltin_fast_extra_arguments_unchecked(t *testing.T) {
env := map[string]any{
"x": "X",
"fn": func() any { return identity{} },
}
program, err := expr.Compile(`x + fn().N(upper("a", "b"))`, expr.Env(env))
require.NoError(t, err)

out, err := expr.Run(program, env)
require.NoError(t, err)
assert.Equal(t, "XB", out)
}

type identity struct{}

func (identity) N(v any) any { return v }

func TestBuiltin_date_location_only(t *testing.T) {
_, err := expr.Compile(`date(timezone("UTC"))`)
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid number of arguments (expected at least 2, got 1)")
}

func TestBuiltin_env_not_callable(t *testing.T) {
code := `$env(''matches'i'?t:get().UTC())`
env := map[string]any{"t": 1}
Expand Down
57 changes: 57 additions & 0 deletions compiler/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -1169,8 +1169,20 @@ func (c *compiler) BuiltinNode(node *ast.BuiltinNode) {

if id, ok := builtin.Index[node.Name]; ok {
f := builtin.Builtins[id]
if err := builtinArgsError(f, len(node.Arguments)); err != nil {
c.emit(OpPush, c.addConstant(err))
c.emit(OpThrow)
return
}
for i, arg := range node.Arguments {
c.compile(arg)
if f.Fast != nil && i < len(node.Arguments)-1 {
// A Fast builtin takes one argument. Extra arguments can only
// reach here unchecked (see builtinArgsError); they are evaluated
// and dropped so they do not stay on the stack.
c.emit(OpPop)
continue
}
argType := arg.Type()
if argType.Kind() == reflect.Ptr || arg.Nature().IsUnknown(c.ntCache) {
if f.Deref == nil {
Expand Down Expand Up @@ -1204,6 +1216,51 @@ func (c *compiler) BuiltinNode(node *ast.BuiltinNode) {
panic(fmt.Sprintf("unknown builtin %v", node.Name))
}

// builtinArgsError returns an error if builtin f gets fewer arguments than
// its Types allow (or none, for a Fast builtin). The checker reports a wrong
// number of arguments at compile time, but it does not check the arguments of a
// call on an unknown value, as in `x.Method(join())`. Such a call fails at run
// time with this error instead of indexing past the arguments or underflowing
// the stack. Builtins with only a Validate function check their own arguments.
// Extra arguments are evaluated and ignored, as before.
func builtinArgsError(f *builtin.Function, n int) error {
if f.Fast != nil {
if n == 0 {
return fmt.Errorf("invalid number of arguments for %s (expected 1, got 0)", f.Name)
}
return nil
}
least, most := -1, -1
for _, t := range f.Types {
in := t.NumIn()
if t.IsVariadic() {
in--
most = math.MaxInt
}
if least < 0 || in < least {
least = in
}
if in > most {
most = in
}
}
if n >= least {
return nil
}
var expected string
switch {
case most == math.MaxInt:
expected = fmt.Sprintf("at least %d", least)
case least == most:
expected = fmt.Sprintf("%d", least)
case most == least+1:
expected = fmt.Sprintf("%d or %d", least, most)
default:
expected = fmt.Sprintf("%d to %d", least, most)
}
return fmt.Errorf("invalid number of arguments for %s (expected %s, got %d)", f.Name, expected, n)
}

func (c *compiler) emitCond(body func()) {
noop := c.emit(OpJumpIfFalse, placeholder)
c.emit(OpPop)
Expand Down
Loading