Skip to content

Commit 1be5847

Browse files
l46kokcopybara-github
authored andcommitted
Fixes reading unsigned integers and setting oneof fields in the planner runtime
PiperOrigin-RevId: 1020240784
1 parent 31365e5 commit 1be5847

7 files changed

Lines changed: 86 additions & 21 deletions

File tree

‎common/src/main/java/dev/cel/common/internal/ProtoLiteAdapter.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,8 @@ private Message adaptValueToUint32(Object value) {
279279
if (value instanceof Integer) {
280280
return UInt32Value.of((Integer) value);
281281
}
282-
if (value instanceof Long) {
282+
// Per the spec, an int isn't a uint, unless unsigned longs are disabled.
283+
if (!celOptions.enableUnsignedLongs() && value instanceof Long) {
283284
try {
284285
return UInt32Value.of(unsignedIntCheckedCast((Long) value));
285286
} catch (IllegalArgumentException e) {
@@ -301,7 +302,7 @@ private Message adaptValueToUint64(Object value) {
301302
if (value instanceof Integer) {
302303
return UInt64Value.of(UnsignedInts.toLong((Integer) value));
303304
}
304-
if (value instanceof Long) {
305+
if (!celOptions.enableUnsignedLongs() && value instanceof Long) {
305306
return UInt64Value.of((Long) value);
306307
}
307308
if (value instanceof UnsignedLong) {

‎common/src/main/java/dev/cel/common/values/BaseProtoCelValueConverter.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,8 @@ protected Object fromWellKnownProto(MessageLiteOrBuilder message, WellKnownProto
9595
case STRING_VALUE:
9696
return normalizePrimitive(((StringValue) message).getValue());
9797
case UINT32_VALUE:
98-
return UnsignedLong.valueOf(((UInt32Value) message).getValue());
98+
return UnsignedLong.fromLongBits(
99+
Integer.toUnsignedLong(((UInt32Value) message).getValue()));
99100
case UINT64_VALUE:
100101
return UnsignedLong.fromLongBits(((UInt64Value) message).getValue());
101102
case EMPTY:

‎common/src/main/java/dev/cel/common/values/ProtoCelValueConverter.java‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package dev.cel.common.values;
1616

1717
import com.google.common.base.Preconditions;
18+
import com.google.common.collect.Lists;
1819
import com.google.common.primitives.UnsignedLong;
1920
import com.google.errorprone.annotations.Immutable;
2021
import com.google.protobuf.Any;
@@ -130,6 +131,10 @@ public Object fromProtoMessageFieldToCelValue(Message message, FieldDescriptor f
130131
}
131132

132133
if (fieldDescriptor.isMapField()) {
134+
FieldDescriptor keyFieldDescriptor =
135+
fieldDescriptor.getMessageType().findFieldByNumber(1);
136+
FieldDescriptor valueFieldDescriptor =
137+
fieldDescriptor.getMessageType().findFieldByNumber(2);
133138
Map<Object, Object> map = new HashMap<>();
134139
Object mapKey;
135140
Object mapValue;
@@ -140,34 +145,28 @@ public Object fromProtoMessageFieldToCelValue(Message message, FieldDescriptor f
140145
mapValue = mapEntry.getValue();
141146
} else if (entry instanceof DynamicMessage) {
142147
DynamicMessage dynamicMessage = (DynamicMessage) entry;
143-
FieldDescriptor keyFieldDescriptor =
144-
fieldDescriptor.getMessageType().findFieldByNumber(1);
145-
FieldDescriptor valueFieldDescriptor =
146-
fieldDescriptor.getMessageType().findFieldByNumber(2);
147148
mapKey = dynamicMessage.getField(keyFieldDescriptor);
148149
mapValue = dynamicMessage.getField(valueFieldDescriptor);
149150
} else {
150151
throw new IllegalStateException("Unexpected map field type: " + entry);
151152
}
152153

153-
map.put(mapKey, mapValue);
154+
map.put(
155+
toUnsigned(keyFieldDescriptor, mapKey), toUnsigned(valueFieldDescriptor, mapValue));
154156
}
155157
return toRuntimeValue(map);
156158
}
157159

158160
return toRuntimeValue(result);
159161
case UINT32:
160162
case FIXED32:
161-
if (!fieldDescriptor.isRepeated()) {
162-
return UnsignedLong.valueOf((int) result);
163-
}
164-
break;
165163
case UINT64:
166164
case FIXED64:
167-
if (!fieldDescriptor.isRepeated()) {
168-
return UnsignedLong.fromLongBits((long) result);
169-
}
170-
break;
165+
// Converts elements as they're read, so selecting one doesn't copy the whole list.
166+
return fieldDescriptor.isRepeated()
167+
? CelPreAdaptedList.wrap(
168+
Lists.transform((List<?>) result, element -> toUnsigned(fieldDescriptor, element)))
169+
: toUnsigned(fieldDescriptor, result);
171170
default:
172171
break;
173172
}
@@ -187,6 +186,20 @@ public Object fromProtoMessageFieldToCelValue(Message message, FieldDescriptor f
187186
return toRuntimeValue(result);
188187
}
189188

189+
// Protobuf returns uint32 and uint64 values as signed ints and longs.
190+
private static Object toUnsigned(FieldDescriptor fieldDescriptor, Object value) {
191+
switch (fieldDescriptor.getType()) {
192+
case UINT32:
193+
case FIXED32:
194+
return UnsignedLong.fromLongBits(Integer.toUnsignedLong((Integer) value));
195+
case UINT64:
196+
case FIXED64:
197+
return UnsignedLong.fromLongBits((Long) value);
198+
default:
199+
return value;
200+
}
201+
}
202+
190203
private ProtoCelValueConverter(
191204
CelDescriptorPool celDescriptorPool, DynamicProto dynamicProto, CelOptions celOptions) {
192205
Preconditions.checkNotNull(celDescriptorPool);

‎common/src/test/java/dev/cel/common/internal/ProtoAdapterTest.java‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
import com.google.protobuf.StringValue;
3737
import com.google.protobuf.Struct;
3838
import com.google.protobuf.Timestamp;
39+
import com.google.protobuf.UInt32Value;
3940
import com.google.protobuf.UInt64Value;
4041
import com.google.protobuf.Value;
4142
import com.google.type.Expr;
@@ -213,6 +214,31 @@ public void adaptValueToProto_asymmetricFloatDoubleConversion() {
213214
.isEqualTo(DoubleValue.of(1.5D));
214215
}
215216

217+
@Test
218+
public void adaptValueToProto_signedUintWrappers_throws() {
219+
ProtoAdapter protoAdapter = new ProtoAdapter(DYNAMIC_PROTO, CelOptions.DEFAULT);
220+
String uint32TypeName = UInt32Value.getDescriptor().getFullName();
221+
String uint64TypeName = UInt64Value.getDescriptor().getFullName();
222+
223+
assertThrows(
224+
IllegalArgumentException.class, () -> protoAdapter.adaptValueToProto(1L, uint32TypeName));
225+
assertThrows(
226+
IllegalArgumentException.class,
227+
() -> protoAdapter.adaptValueToProto(-1L, uint64TypeName));
228+
}
229+
230+
@Test
231+
@SuppressWarnings("deprecation") // Signed uints are only enabled through a deprecated option.
232+
public void adaptValueToProto_unsignedLongsDisabled_acceptsSignedUintWrappers() {
233+
ProtoAdapter protoAdapter =
234+
new ProtoAdapter(DYNAMIC_PROTO, CelOptions.current().enableUnsignedLongs(false).build());
235+
236+
assertThat(protoAdapter.adaptValueToProto(1L, UInt32Value.getDescriptor().getFullName()))
237+
.isEqualTo(UInt32Value.of(1));
238+
assertThat(protoAdapter.adaptValueToProto(1L, UInt64Value.getDescriptor().getFullName()))
239+
.isEqualTo(UInt64Value.of(1));
240+
}
241+
216242
@Test
217243
public void adaptValueToProto_asymmetricJsonConversion() {
218244
ProtoAdapter protoAdapter = new ProtoAdapter(DYNAMIC_PROTO, CelOptions.DEFAULT);

‎common/src/test/java/dev/cel/common/values/ProtoMessageValueTest.java‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ private enum SelectFieldTestCase {
191191
BOOL("single_bool", true),
192192
INT32("single_int32", 4L),
193193
INT64("single_int64", 5L),
194-
UINT32("single_uint32", UnsignedLong.valueOf(1L)),
194+
UINT32("single_uint32", UnsignedLong.valueOf(0xFFFFFFFFL)),
195195
UINT64("single_uint64", UnsignedLong.MAX_VALUE),
196196
FLOAT("single_float", 1.5d),
197197
DOUBLE("single_double", 2.5d),
@@ -203,14 +203,18 @@ private enum SelectFieldTestCase {
203203
TIMESTAMP("single_timestamp", Instant.ofEpochSecond(100)),
204204
INT32_WRAPPER("single_int32_wrapper", 5L),
205205
INT64_WRAPPER("single_int64_wrapper", 10L),
206-
UINT32_WRAPPER("single_uint32_wrapper", UnsignedLong.valueOf(1L)),
206+
UINT32_WRAPPER("single_uint32_wrapper", UnsignedLong.valueOf(0xFFFFFFFFL)),
207207
UINT64_WRAPPER("single_uint64_wrapper", UnsignedLong.MAX_VALUE),
208208
FLOAT_WRAPPER("single_float_wrapper", 7.5d),
209209
DOUBLE_WRAPPER("single_double_wrapper", 8.5d),
210210
STRING_WRAPPER("single_string_wrapper", "hello"),
211211
BYTES_WRAPPER("single_bytes_wrapper", CelByteString.of(new byte[] {0x02})),
212212
REPEATED_INT64("repeated_int64", ImmutableList.of(5L)),
213+
REPEATED_UINT64("repeated_uint64", ImmutableList.of(UnsignedLong.MAX_VALUE)),
213214
MAP_STRING_STRING("map_string_string", ImmutableMap.of("a", "b")),
215+
MAP_UINT32_UINT64(
216+
"map_uint32_uint64",
217+
ImmutableMap.of(UnsignedLong.valueOf(0xFFFFFFFFL), UnsignedLong.MAX_VALUE)),
214218
NESTED_MESSAGE(
215219
"standalone_message",
216220
ProtoMessageValue.create(
@@ -653,7 +657,7 @@ private static TestAllTypes createPopulatedTestAllTypes() {
653657
.setSingleBool(true)
654658
.setSingleInt32(4)
655659
.setSingleInt64(5L)
656-
.setSingleUint32(1)
660+
.setSingleUint32(0xFFFFFFFF)
657661
.setSingleUint64(UnsignedLong.MAX_VALUE.longValue())
658662
.setSingleFloat(1.5f)
659663
.setSingleDouble(2.5d)
@@ -664,14 +668,16 @@ private static TestAllTypes createPopulatedTestAllTypes() {
664668
.setSingleTimestamp(Timestamp.newBuilder().setSeconds(100))
665669
.setSingleInt32Wrapper(Int32Value.of(5))
666670
.setSingleInt64Wrapper(Int64Value.of(10L))
667-
.setSingleUint32Wrapper(UInt32Value.of(1))
671+
.setSingleUint32Wrapper(UInt32Value.of(0xFFFFFFFF))
668672
.setSingleUint64Wrapper(UInt64Value.of(UnsignedLong.MAX_VALUE.longValue()))
669673
.setSingleStringWrapper(StringValue.of("hello"))
670674
.setSingleFloatWrapper(FloatValue.of(7.5f))
671675
.setSingleDoubleWrapper(DoubleValue.of(8.5d))
672676
.setSingleBytesWrapper(BytesValue.of(ByteString.copyFrom(new byte[] {0x02})))
673677
.addRepeatedInt64(5L)
678+
.addRepeatedUint64(UnsignedLong.MAX_VALUE.longValue())
674679
.putMapStringString("a", "b")
680+
.putMapUint32Uint64(0xFFFFFFFF, UnsignedLong.MAX_VALUE.longValue())
675681
.setStandaloneMessage(NestedMessage.getDefaultInstance())
676682
.setStandaloneEnum(NestedEnum.BAR)
677683
.build();

‎runtime/src/main/java/dev/cel/runtime/planner/EvalCreateStruct.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ final class EvalCreateStruct extends PlannedInterpretable {
4646

4747
@Override
4848
Object evalInternal(GlobalResolver resolver, ExecutionFrame frame) {
49-
Map<String, Object> fieldValues = Maps.newHashMapWithExpectedSize(keys.length);
49+
// In source order, so that the last of several fields set in one oneof wins, as in protobuf.
50+
Map<String, Object> fieldValues = Maps.newLinkedHashMapWithExpectedSize(keys.length);
5051
AccumulatedUnknowns unknowns = null;
5152
for (int i = 0; i < keys.length; i++) {
5253
Object value = EvalHelpers.evalStrictly(values[i], resolver, frame);

‎runtime/src/test/java/dev/cel/runtime/planner/ProgramPlannerTest.java‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,23 @@ public void plan_createStruct_withContainer() throws Exception {
692692
assertThat(result).isEqualTo(TestAllTypes.getDefaultInstance());
693693
}
694694

695+
// With fewer fields, the oneof fields would share a HashMap bucket and keep their order.
696+
@Test
697+
@TestParameters({
698+
"{expression: 'TestAllTypes{oneof_bool: true, single_int32: 1, single_int64: 2,"
699+
+ " oneof_msg: TestAllTypes.NestedMessage{}}', expectedCase: ONEOF_MSG}",
700+
"{expression: 'TestAllTypes{oneof_msg: TestAllTypes.NestedMessage{}, single_int32: 1,"
701+
+ " single_int64: 2, oneof_bool: true}', expectedCase: ONEOF_BOOL}"
702+
})
703+
public void plan_createStruct_oneofSetTwice_lastFieldWins(
704+
String expression, TestAllTypes.KindCase expectedCase) throws Exception {
705+
CelAbstractSyntaxTree ast = compile(expression);
706+
707+
TestAllTypes result = (TestAllTypes) PLANNER.plan(ast).eval();
708+
709+
assertThat(result.getKindCase()).isEqualTo(expectedCase);
710+
}
711+
695712
@Test
696713
public void plan_call_zeroArgs() throws Exception {
697714
CelAbstractSyntaxTree ast = compile("zero()");

0 commit comments

Comments
 (0)