Skip to content
Open
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
6 changes: 5 additions & 1 deletion ast/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ func (n *ConstantNode) String() string {
}
b, err := json.Marshal(n.Value)
if err != nil {
panic(err)
// json.Marshal rejects values such as NaN and ±Inf, which can
// reach here after constant folding (e.g. an array literal like
// [0/0]). Fall back to a non-panicking representation instead of
// crashing the caller (the optimizer runs this during Compile).
return fmt.Sprintf("%v", n.Value)
}
return string(b)
}
Expand Down
3 changes: 3 additions & 0 deletions ast/print_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ast_test

import (
"math"
"testing"

"github.com/expr-lang/expr/internal/testify/assert"
Expand Down Expand Up @@ -120,6 +121,8 @@ func TestPrint_ConstantNode(t *testing.T) {
{"a", `"a"`},
{[]int{1, 2, 3}, `[1,2,3]`},
{map[string]int{"a": 1}, `{"a":1}`},
{[]any{math.NaN()}, `[NaN]`},
{math.Inf(1), `+Inf`},
}

for _, tt := range tests {
Expand Down
14 changes: 14 additions & 0 deletions optimizer/optimizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,17 @@ func TestOptimize_predicate_combination_nested(t *testing.T) {

assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node))
}

func TestOptimize_predicate_combination_with_non_json_float(t *testing.T) {
// Constant folding turns [0/0] into a ConstantNode holding []any{NaN}.
// predicateCombination compares the collection arguments via String(),
// which must not panic on values json.Marshal rejects (NaN, ±Inf).
for _, code := range []string{
`any([0/0], # > 0) || any([0/0], # > 0)`,
`all([1/0], # > 0) && all([1/0], # > 0)`,
`none([0/0], # > 0) && none([0/0], # > 0)`,
} {
_, err := expr.Compile(code)
require.NoError(t, err, code)
}
}
Loading