Skip to content

Commit 89b799e

Browse files
authored
Fix last optional element to be retained as an optional index while folding (#841)
* Fix last optional element to be marked as an optional index while folding
1 parent ea648d7 commit 89b799e

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

cel/folding.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -248,23 +248,26 @@ func pruneOptionalListElements(ctx *OptimizerContext, e ast.Expr) {
248248
}
249249
updatedElems := []ast.Expr{}
250250
updatedIndices := []int32{}
251-
for i, e := range elems {
252-
if !l.IsOptional(int32(i)) {
251+
newOptIndex := -1
252+
for _, e := range elems {
253+
newOptIndex++
254+
if !l.IsOptional(int32(newOptIndex)) {
253255
updatedElems = append(updatedElems, e)
254256
continue
255257
}
256258
if e.Kind() != ast.LiteralKind {
257259
updatedElems = append(updatedElems, e)
258-
updatedIndices = append(updatedIndices, int32(i))
260+
updatedIndices = append(updatedIndices, int32(newOptIndex))
259261
continue
260262
}
261263
optElemVal, ok := e.AsLiteral().(*types.Optional)
262264
if !ok {
263265
updatedElems = append(updatedElems, e)
264-
updatedIndices = append(updatedIndices, int32(i))
266+
updatedIndices = append(updatedIndices, int32(newOptIndex))
265267
continue
266268
}
267269
if !optElemVal.HasValue() {
270+
newOptIndex-- // Skipping causes the list to get smaller.
268271
continue
269272
}
270273
e.SetKindCase(ctx.NewLiteral(optElemVal.GetValue()))

cel/folding_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,26 @@ func TestConstantFoldingOptimizer(t *testing.T) {
129129
expr: `[google.expr.proto3.test.TestAllTypes{single_int32: 2 + 3}].map(i, i)[0]`,
130130
folded: `google.expr.proto3.test.TestAllTypes{single_int32: 5}`,
131131
},
132+
{
133+
expr: `[?optional.ofNonZeroValue(0)]`,
134+
folded: `[]`,
135+
},
132136
{
133137
expr: `[1, ?optional.ofNonZeroValue(0)]`,
134138
folded: `[1]`,
135139
},
140+
{
141+
expr: `[optional.none(), ?x]`,
142+
folded: `[optional.none(), ?x]`,
143+
},
144+
{
145+
expr: `[?optional.none(), ?x]`,
146+
folded: `[?x]`,
147+
},
148+
{
149+
expr: `[1, x, ?optional.ofNonZeroValue(0), ?x.?y]`,
150+
folded: `[1, x, ?x.?y]`,
151+
},
136152
{
137153
expr: `[1, x, ?optional.ofNonZeroValue(3), ?x.?y]`,
138154
folded: `[1, x, 3, ?x.?y]`,

0 commit comments

Comments
 (0)