Skip to content

checker: reject count() without predicate on non-bool arrays - #1032

Open
minilan677-netizen wants to merge 1 commit into
expr-lang:masterfrom
minilan677-netizen:fix/count-without-predicate-check-bool
Open

minilan677-netizen wants to merge 1 commit into
expr-lang:masterfrom
minilan677-netizen:fix/count-without-predicate-check-bool

Conversation

@minilan677-netizen

Copy link
Copy Markdown

Fixes #1031

Problem

Without a predicate, count(arr) counts the true elements. The VM does this by asserting each element to bool. The checker returned int for the one-argument form and never looked at the element type, so count(ints) with ints []int (or count(1..3), count(filter(ints, # > 1)), and so on) compiled fine and then failed at run time with interface conversion: interface {} is int, not bool. The predicate form already catches the same mistake at compile time (count(ArrayOfInt, {#}) gives predicate should return boolean (got int)).

Fix

In the one-argument branch of count, if the collection is an array whose element type is known and isn't bool, the checker now reports:

builtin count without predicate takes only array of bool (got array of int) (1:7)
 | count(ArrayOfInt)
 | ......^

Nothing changes for arrays of bool, arrays with an unknown element type ([]any, untyped env, mixed literals), or unknown collections.

Tests

  • checker/checker_test.go: two error cases (count(ArrayOfInt), count(1..3)) and three valid cases (count([true, false]), count(map(ArrayOfInt, # > 0)), count(ArrayOfAny)). The error cases fail without the fix.
  • testdata/generated.txt: I removed the 31 generated lines that call count() with no predicate on array/list ([]int / []Foo). They only passed because the call was never reached (ok ?? count(array), false && ...) or the array was empty (count(array[:0])). This is the same kind of cleanup fix(checker): validate sortBy order argument type #912 did for sortBy.
  • go test ./..., go test -race ., go test -tags=expr_debug -run=TestDebugger ./vm, go vet ./checker/, gofmt -l: all clean. I also ran FuzzExpr for 60s with no failures.

Fixes expr-lang#1031

Signed-off-by: minilan677-netizen <321019851+minilan677-netizen@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

count() without a predicate compiles for non-bool arrays and fails at run time

1 participant