Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix last optional element to be retained as an optional index while folding #841

Merged
merged 2 commits into from
Sep 19, 2023
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
11 changes: 7 additions & 4 deletions cel/folding.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,23 +248,26 @@ func pruneOptionalListElements(ctx *OptimizerContext, e ast.Expr) {
}
updatedElems := []ast.Expr{}
updatedIndices := []int32{}
for i, e := range elems {
if !l.IsOptional(int32(i)) {
newOptIndex := -1
for _, e := range elems {
newOptIndex++
if !l.IsOptional(int32(newOptIndex)) {
updatedElems = append(updatedElems, e)
continue
}
if e.Kind() != ast.LiteralKind {
updatedElems = append(updatedElems, e)
updatedIndices = append(updatedIndices, int32(i))
updatedIndices = append(updatedIndices, int32(newOptIndex))
continue
}
optElemVal, ok := e.AsLiteral().(*types.Optional)
if !ok {
updatedElems = append(updatedElems, e)
updatedIndices = append(updatedIndices, int32(i))
updatedIndices = append(updatedIndices, int32(newOptIndex))
continue
}
if !optElemVal.HasValue() {
newOptIndex-- // Skipping causes the list to get smaller.
continue
}
e.SetKindCase(ctx.NewLiteral(optElemVal.GetValue()))
Expand Down
16 changes: 16 additions & 0 deletions cel/folding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,26 @@ func TestConstantFoldingOptimizer(t *testing.T) {
expr: `[google.expr.proto3.test.TestAllTypes{single_int32: 2 + 3}].map(i, i)[0]`,
folded: `google.expr.proto3.test.TestAllTypes{single_int32: 5}`,
},
{
expr: `[?optional.ofNonZeroValue(0)]`,
folded: `[]`,
},
{
expr: `[1, ?optional.ofNonZeroValue(0)]`,
folded: `[1]`,
},
{
expr: `[optional.none(), ?x]`,
folded: `[optional.none(), ?x]`,
},
{
expr: `[?optional.none(), ?x]`,
folded: `[?x]`,
},
{
expr: `[1, x, ?optional.ofNonZeroValue(0), ?x.?y]`,
folded: `[1, x, ?x.?y]`,
},
{
expr: `[1, x, ?optional.ofNonZeroValue(3), ?x.?y]`,
folded: `[1, x, 3, ?x.?y]`,
Expand Down