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: 11 additions & 0 deletions common/src/main/java/dev/cel/common/CelOptions.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,6 +109,8 @@ public enum ProtoUnsetFieldOptions {

public abstract ProtoUnsetFieldOptions fromProtoUnsetFieldOption();

public abstract boolean adaptRuntimeTypeValueToNativeType();

public abstract boolean enableStringConversion();

public abstract boolean enableStringConcatenation();
Expand DownExpand Up@@ -209,6 +211,7 @@ public static Builder newBuilder() {
.comprehensionMaxIterations(-1)
.unwrapWellKnownTypesOnFunctionDispatch(true)
.fromProtoUnsetFieldOption(ProtoUnsetFieldOptions.BIND_DEFAULT)
.adaptRuntimeTypeValueToNativeType(false)
.enableStringConversion(true)
.enableStringConcatenation(true)
.enableListConcatenation(true)
Expand DownExpand Up@@ -516,6 +519,14 @@ public abstract static class Builder {
*/
public abstract Builder fromProtoUnsetFieldOption(ProtoUnsetFieldOptions value);

/**
* If enabled, result of the type function call `type(foo)` will be evaluated as a native-type
* equivalent {@code CelType} instead of the protobuf type equivalent from {value.proto}.
*
* <p>This is a temporary flag for migration purposes, and will be removed in the near future.
*/
public abstract Builder adaptRuntimeTypeValueToNativeType(boolean value);

/**
* Enables string() overloads for the runtime. This option exists to maintain parity with
* cel-cpp interpreter options.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompilerFactory;
import dev.cel.extensions.CelExtensions;
import dev.cel.extensions.CelOptionalLibrary;
Expand DownExpand Up@@ -88,6 +89,7 @@ private static TypeRegistry newDefaultTypeRegistry() {
CelOptions.current()
.enableTimestampEpoch(true)
.enableUnsignedLongs(true)
.adaptRuntimeTypeValueToNativeType(true)
.enableHeterogeneousNumericComparisons(true)
.enableProtoDifferencerEquality(true)
.enableOptionalSyntax(true)
Expand DownExpand Up@@ -332,6 +334,10 @@ private static Value toValue(Object object, CelType type) throws Exception {
if (object instanceof Message) {
return Value.newBuilder().setObjectValue(Any.pack((Message) object)).build();
}
if (object instanceof TypeType) {
return Value.newBuilder().setTypeValue(((TypeType) object).containingTypeName()).build();
}

throw new IllegalArgumentException(
String.format("Unexpected result type: %s", object.getClass()));
}
Expand Down
1 change: 0 additions & 1 deletion extensions/src/test/java/dev/cel/extensions/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,7 +25,6 @@ java_library(
"//parser:macro",
"//runtime",
"//runtime:interpreter_util",
"@cel_spec//proto/cel/expr:expr_java_proto",
"@cel_spec//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@cel_spec//proto/test/v1/proto2:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import dev.cel.expr.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
Expand All@@ -43,6 +42,7 @@
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.expr.conformance.proto3.TestAllTypes.NestedMessage;
import dev.cel.parser.CelStandardMacro;
Expand DownExpand Up@@ -92,7 +92,11 @@ private enum ConstantTestCases {
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.setOptions(
CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build())
CelOptions.current()
.enableUnsignedLongs(true)
.enableTimestampEpoch(true)
.adaptRuntimeTypeValueToNativeType(true)
.build())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setContainer("cel.expr.conformance.proto3")
.addMessageTypes(TestAllTypes.getDescriptor())
Expand DownExpand Up@@ -1439,11 +1443,12 @@ public void optionalFlatMapMacro_withNonIdent_throws() {
@Test
public void optionalType_typeResolution() throws Exception {
Cel cel = newCelBuilder().build();

CelAbstractSyntaxTree ast = cel.compile("optional_type").getAst();

assertThat(cel.createProgram(ast).eval())
.isEqualTo(Value.newBuilder().setTypeValue("optional_type").build());
TypeType optionalRuntimeType = (TypeType) cel.createProgram(ast).eval();

assertThat(optionalRuntimeType.name()).isEqualTo("type");
assertThat(optionalRuntimeType.containingTypeName()).isEqualTo("optional_type");
}

@Test
Expand Down
13 changes: 13 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,18 @@ INTERPRETER_SOURCES = [
"UnknownTrackingInterpretable.java",
]

java_library(
name = "cel_type_resolver",
srcs = ["CelTypeResolver.java"],
deps = [
"//common/types",
"//common/types:type_providers",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
],
)

java_library(
name = "base",
srcs = BASE_SOURCES,
Expand DownExpand Up@@ -80,6 +92,7 @@ java_library(
exports = [":base"],
deps = [
":base",
":cel_type_resolver",
":evaluation_listener",
":runtime_helper",
":unknown_attributes",
Expand Down
155 changes: 155 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/CelTypeResolver.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.NullValue;
import com.google.protobuf.Timestamp;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* {@code CelTypeResolver} resolves incoming {@link CelType} into {@link TypeType}., either as part
* of a type call (type('foo'), type(1), etc.) or as a type literal (type, int, string, etc.)
*/
@Immutable
final class CelTypeResolver {

// Sentinel runtime value representing the special "type" ident. This ensures following to be
// true: type == type(string) && type == type(type("foo"))
private static final TypeType RUNTIME_TYPE_TYPE = TypeType.create(SimpleType.DYN);

private static final ImmutableMap<Class<?>, TypeType> COMMON_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Boolean.class, TypeType.create(SimpleType.BOOL))
.put(Double.class, TypeType.create(SimpleType.DOUBLE))
.put(Long.class, TypeType.create(SimpleType.INT))
.put(UnsignedLong.class, TypeType.create(SimpleType.UINT))
.put(String.class, TypeType.create(SimpleType.STRING))
.put(NullValue.class, TypeType.create(SimpleType.NULL_TYPE))
.put(Duration.class, TypeType.create(SimpleType.DURATION))
.put(Timestamp.class, TypeType.create(SimpleType.TIMESTAMP))
.put(ArrayList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ImmutableList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(HashMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(ImmutableMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(Optional.class, TypeType.create(OptionalType.create(SimpleType.DYN)))
.buildOrThrow();

private static final ImmutableMap<Class<?>, TypeType> EXTENDABLE_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Collection.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ByteString.class, TypeType.create(SimpleType.BYTES))
.put(Map.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.buildOrThrow();

/** Adapt the type-checked {@link CelType} into a runtime type value {@link TypeType}. */
static TypeType adaptType(CelType typeCheckedType) {
checkNotNull(typeCheckedType);

switch (typeCheckedType.kind()) {
case TYPE:
CelType typeOfType = ((TypeType) typeCheckedType).type();
switch (typeOfType.kind()) {
case STRUCT:
return TypeType.create(adaptStructType((StructType) typeOfType));
default:
return (TypeType) typeCheckedType;
}
case UNSPECIFIED:
throw new IllegalArgumentException("Unsupported CelType kind: " + typeCheckedType.kind());
default:
return TypeType.create(typeCheckedType);
}
}

/** Resolve the CEL type of the {@code obj}. */
static TypeType resolveObjectType(Object obj, CelType typeCheckedType) {
checkNotNull(obj);
if (obj instanceof TypeType) {
return RUNTIME_TYPE_TYPE;
}

Class<?> currentClass = obj.getClass();
TypeType runtimeType = COMMON_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

if (obj instanceof MessageOrBuilder) {
MessageOrBuilder msg = (MessageOrBuilder) obj;
// TODO: Replace with CelLiteDescriptor
return TypeType.create(StructTypeReference.create(msg.getDescriptorForType().getFullName()));
}

// Handle types that the client may have extended.
while (currentClass != null) {
runtimeType = EXTENDABLE_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

// Check interfaces
for (Class<?> interfaceClass : currentClass.getInterfaces()) {
runtimeType = EXTENDABLE_TYPES.get(interfaceClass);
if (runtimeType != null) {
return runtimeType;
}
}
currentClass = currentClass.getSuperclass();
}

// This is an opaque type, or something CEL doesn't know about.
return (TypeType) typeCheckedType;
}

private static CelType adaptStructType(StructType typeOfType) {
String structName = typeOfType.name();
CelType newTypeOfType;
if (structName.equals(SimpleType.DURATION.name())) {
newTypeOfType = SimpleType.DURATION;
} else if (structName.equals(SimpleType.TIMESTAMP.name())) {
newTypeOfType = SimpleType.TIMESTAMP;
} else {
// Coerces ProtoMessageTypeProvider to be a struct type reference for accurate
// equality tests.
// In the future, we can plumb ProtoMessageTypeProvider through the runtime to retain
// ProtoMessageType here.
newTypeOfType = StructTypeReference.create(typeOfType.name());
}
return newTypeOfType;
}

private CelTypeResolver() {}
}
49 changes: 20 additions & 29 deletions runtime/src/main/java/dev/cel/runtime/DefaultInterpreter.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,8 @@

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import dev.cel.expr.Value;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
Expand DownExpand Up@@ -53,26 +55,6 @@
/**
* Default implementation of the CEL interpreter.
*
* <p>Use as in:
*
* <pre>
* MessageFactory messageFactory = new LinkedMessageFactory();
* RuntimeTypeProvider typeProvider = new DescriptorMessageProvider(messageFactory);
* Dispatcher dispatcher = DefaultDispatcher.create();
* Interpreter interpreter = new DefaultInterpreter(typeProvider, dispatcher);
* Interpretable interpretable = interpreter.createInterpretable(checkedExpr);
* Object result = interpretable.eval(Activation.of("name", value));
* </pre>
*
* <p>Extensions functions can be added in addition to standard functions to the dispatcher as
* needed.
*
* <p>Note: {MessageFactory} instances may be combined using the {@link
* MessageFactory.CombinedMessageFactory}.
*
* <p>Note: On Android, the {@code DescriptorMessageProvider} is not supported as proto lite does
* not support descriptors. Instead, implement the {@code MessageProvider} interface directly.
*
* <p>CEL Library Internals. Do Not Use.
*/
@ThreadSafe
Expand DownExpand Up@@ -117,8 +99,8 @@ static IntermediateResult create(Object value) {
*/
public DefaultInterpreter(
RuntimeTypeProvider typeProvider, Dispatcher dispatcher, CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher);
this.celOptions = celOptions;
}

Expand All@@ -141,11 +123,11 @@ private static final class DefaultInterpretable
Dispatcher dispatcher,
CelAbstractSyntaxTree ast,
CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher).immutableCopy();
this.ast = Preconditions.checkNotNull(ast);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher).immutableCopy();
this.ast = checkNotNull(ast);
this.metadata = new DefaultMetadata(ast);
this.celOptions = Preconditions.checkNotNull(celOptions);
this.celOptions = checkNotNull(celOptions);
}

@Override
Expand DownExpand Up@@ -278,7 +260,10 @@ private IntermediateResult resolveIdent(ExecutionFrame frame, CelExpr expr, Stri
// Check whether the type exists in the type check map as a 'type'.
Optional<CelType> checkedType = ast.getType(expr.id());
if (checkedType.isPresent() && checkedType.get().kind() == CelKind.TYPE) {
Object typeValue = typeProvider.adaptType(checkedType.get());
Object typeValue =
celOptions.adaptRuntimeTypeValueToNativeType()
? CelTypeResolver.adaptType(checkedType.get())
: typeProvider.adaptType(checkedType.get());
return IntermediateResult.create(typeValue);
}

Expand DownExpand Up@@ -658,8 +643,14 @@ private IntermediateResult evalType(ExecutionFrame frame, CelCall callExpr)
.setLocation(metadata, typeExprArg.id())
.build());

Value checkedTypeValue = typeProvider.adaptType(checkedType);
Object typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
Object typeValue;
if (celOptions.adaptRuntimeTypeValueToNativeType()) {
CelType checkedTypeValue = CelTypeResolver.adaptType(checkedType);
typeValue = CelTypeResolver.resolveObjectType(argResult.value(), checkedTypeValue);
} else {
Value checkedTypeValue = typeProvider.adaptType(checkedType);
typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
}
return IntermediateResult.create(typeValue);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,9 +42,12 @@
* by the CEL standard environment.
*
* <p>CEL Library Internals. Do Not Use.
*
* @deprecated Use {@code CelTypeResolver} instead.
*/
@Immutable
@Internal
@Deprecated
public final class StandardTypeResolver implements TypeResolver {

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
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: 11 additions & 0 deletions common/src/main/java/dev/cel/common/CelOptions.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,6 +109,8 @@ public enum ProtoUnsetFieldOptions {

public abstract ProtoUnsetFieldOptions fromProtoUnsetFieldOption();

public abstract boolean adaptRuntimeTypeValueToNativeType();

public abstract boolean enableStringConversion();

public abstract boolean enableStringConcatenation();
Expand DownExpand Up@@ -209,6 +211,7 @@ public static Builder newBuilder() {
.comprehensionMaxIterations(-1)
.unwrapWellKnownTypesOnFunctionDispatch(true)
.fromProtoUnsetFieldOption(ProtoUnsetFieldOptions.BIND_DEFAULT)
.adaptRuntimeTypeValueToNativeType(false)
.enableStringConversion(true)
.enableStringConcatenation(true)
.enableListConcatenation(true)
Expand DownExpand Up@@ -516,6 +519,14 @@ public abstract static class Builder {
*/
public abstract Builder fromProtoUnsetFieldOption(ProtoUnsetFieldOptions value);

/**
* If enabled, result of the type function call `type(foo)` will be evaluated as a native-type
* equivalent {@code CelType} instead of the protobuf type equivalent from {value.proto}.
*
* <p>This is a temporary flag for migration purposes, and will be removed in the near future.
*/
public abstract Builder adaptRuntimeTypeValueToNativeType(boolean value);

/**
* Enables string() overloads for the runtime. This option exists to maintain parity with
* cel-cpp interpreter options.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompilerFactory;
import dev.cel.extensions.CelExtensions;
import dev.cel.extensions.CelOptionalLibrary;
Expand DownExpand Up@@ -88,6 +89,7 @@ private static TypeRegistry newDefaultTypeRegistry() {
CelOptions.current()
.enableTimestampEpoch(true)
.enableUnsignedLongs(true)
.adaptRuntimeTypeValueToNativeType(true)
.enableHeterogeneousNumericComparisons(true)
.enableProtoDifferencerEquality(true)
.enableOptionalSyntax(true)
Expand DownExpand Up@@ -332,6 +334,10 @@ private static Value toValue(Object object, CelType type) throws Exception {
if (object instanceof Message) {
return Value.newBuilder().setObjectValue(Any.pack((Message) object)).build();
}
if (object instanceof TypeType) {
return Value.newBuilder().setTypeValue(((TypeType) object).containingTypeName()).build();
}

throw new IllegalArgumentException(
String.format("Unexpected result type: %s", object.getClass()));
}
Expand Down
1 change: 0 additions & 1 deletion extensions/src/test/java/dev/cel/extensions/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,7 +25,6 @@ java_library(
"//parser:macro",
"//runtime",
"//runtime:interpreter_util",
"@cel_spec//proto/cel/expr:expr_java_proto",
"@cel_spec//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@cel_spec//proto/test/v1/proto2:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import dev.cel.expr.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
Expand All@@ -43,6 +42,7 @@
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.expr.conformance.proto3.TestAllTypes.NestedMessage;
import dev.cel.parser.CelStandardMacro;
Expand DownExpand Up@@ -92,7 +92,11 @@ private enum ConstantTestCases {
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.setOptions(
CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build())
CelOptions.current()
.enableUnsignedLongs(true)
.enableTimestampEpoch(true)
.adaptRuntimeTypeValueToNativeType(true)
.build())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setContainer("cel.expr.conformance.proto3")
.addMessageTypes(TestAllTypes.getDescriptor())
Expand DownExpand Up@@ -1439,11 +1443,12 @@ public void optionalFlatMapMacro_withNonIdent_throws() {
@Test
public void optionalType_typeResolution() throws Exception {
Cel cel = newCelBuilder().build();

CelAbstractSyntaxTree ast = cel.compile("optional_type").getAst();

assertThat(cel.createProgram(ast).eval())
.isEqualTo(Value.newBuilder().setTypeValue("optional_type").build());
TypeType optionalRuntimeType = (TypeType) cel.createProgram(ast).eval();

assertThat(optionalRuntimeType.name()).isEqualTo("type");
assertThat(optionalRuntimeType.containingTypeName()).isEqualTo("optional_type");
}

@Test
Expand Down
13 changes: 13 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,18 @@ INTERPRETER_SOURCES = [
"UnknownTrackingInterpretable.java",
]

java_library(
name = "cel_type_resolver",
srcs = ["CelTypeResolver.java"],
deps = [
"//common/types",
"//common/types:type_providers",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
],
)

java_library(
name = "base",
srcs = BASE_SOURCES,
Expand DownExpand Up@@ -80,6 +92,7 @@ java_library(
exports = [":base"],
deps = [
":base",
":cel_type_resolver",
":evaluation_listener",
":runtime_helper",
":unknown_attributes",
Expand Down
155 changes: 155 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/CelTypeResolver.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.NullValue;
import com.google.protobuf.Timestamp;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* {@code CelTypeResolver} resolves incoming {@link CelType} into {@link TypeType}., either as part
* of a type call (type('foo'), type(1), etc.) or as a type literal (type, int, string, etc.)
*/
@Immutable
final class CelTypeResolver {

// Sentinel runtime value representing the special "type" ident. This ensures following to be
// true: type == type(string) && type == type(type("foo"))
private static final TypeType RUNTIME_TYPE_TYPE = TypeType.create(SimpleType.DYN);

private static final ImmutableMap<Class<?>, TypeType> COMMON_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Boolean.class, TypeType.create(SimpleType.BOOL))
.put(Double.class, TypeType.create(SimpleType.DOUBLE))
.put(Long.class, TypeType.create(SimpleType.INT))
.put(UnsignedLong.class, TypeType.create(SimpleType.UINT))
.put(String.class, TypeType.create(SimpleType.STRING))
.put(NullValue.class, TypeType.create(SimpleType.NULL_TYPE))
.put(Duration.class, TypeType.create(SimpleType.DURATION))
.put(Timestamp.class, TypeType.create(SimpleType.TIMESTAMP))
.put(ArrayList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ImmutableList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(HashMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(ImmutableMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(Optional.class, TypeType.create(OptionalType.create(SimpleType.DYN)))
.buildOrThrow();

private static final ImmutableMap<Class<?>, TypeType> EXTENDABLE_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Collection.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ByteString.class, TypeType.create(SimpleType.BYTES))
.put(Map.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.buildOrThrow();

/** Adapt the type-checked {@link CelType} into a runtime type value {@link TypeType}. */
static TypeType adaptType(CelType typeCheckedType) {
checkNotNull(typeCheckedType);

switch (typeCheckedType.kind()) {
case TYPE:
CelType typeOfType = ((TypeType) typeCheckedType).type();
switch (typeOfType.kind()) {
case STRUCT:
return TypeType.create(adaptStructType((StructType) typeOfType));
default:
return (TypeType) typeCheckedType;
}
case UNSPECIFIED:
throw new IllegalArgumentException("Unsupported CelType kind: " + typeCheckedType.kind());
default:
return TypeType.create(typeCheckedType);
}
}

/** Resolve the CEL type of the {@code obj}. */
static TypeType resolveObjectType(Object obj, CelType typeCheckedType) {
checkNotNull(obj);
if (obj instanceof TypeType) {
return RUNTIME_TYPE_TYPE;
}

Class<?> currentClass = obj.getClass();
TypeType runtimeType = COMMON_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

if (obj instanceof MessageOrBuilder) {
MessageOrBuilder msg = (MessageOrBuilder) obj;
// TODO: Replace with CelLiteDescriptor
return TypeType.create(StructTypeReference.create(msg.getDescriptorForType().getFullName()));
}

// Handle types that the client may have extended.
while (currentClass != null) {
runtimeType = EXTENDABLE_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

// Check interfaces
for (Class<?> interfaceClass : currentClass.getInterfaces()) {
runtimeType = EXTENDABLE_TYPES.get(interfaceClass);
if (runtimeType != null) {
return runtimeType;
}
}
currentClass = currentClass.getSuperclass();
}

// This is an opaque type, or something CEL doesn't know about.
return (TypeType) typeCheckedType;
}

private static CelType adaptStructType(StructType typeOfType) {
String structName = typeOfType.name();
CelType newTypeOfType;
if (structName.equals(SimpleType.DURATION.name())) {
newTypeOfType = SimpleType.DURATION;
} else if (structName.equals(SimpleType.TIMESTAMP.name())) {
newTypeOfType = SimpleType.TIMESTAMP;
} else {
// Coerces ProtoMessageTypeProvider to be a struct type reference for accurate
// equality tests.
// In the future, we can plumb ProtoMessageTypeProvider through the runtime to retain
// ProtoMessageType here.
newTypeOfType = StructTypeReference.create(typeOfType.name());
}
return newTypeOfType;
}

private CelTypeResolver() {}
}
49 changes: 20 additions & 29 deletions runtime/src/main/java/dev/cel/runtime/DefaultInterpreter.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,8 @@

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import dev.cel.expr.Value;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
Expand DownExpand Up@@ -53,26 +55,6 @@
/**
* Default implementation of the CEL interpreter.
*
* <p>Use as in:
*
* <pre>
* MessageFactory messageFactory = new LinkedMessageFactory();
* RuntimeTypeProvider typeProvider = new DescriptorMessageProvider(messageFactory);
* Dispatcher dispatcher = DefaultDispatcher.create();
* Interpreter interpreter = new DefaultInterpreter(typeProvider, dispatcher);
* Interpretable interpretable = interpreter.createInterpretable(checkedExpr);
* Object result = interpretable.eval(Activation.of("name", value));
* </pre>
*
* <p>Extensions functions can be added in addition to standard functions to the dispatcher as
* needed.
*
* <p>Note: {MessageFactory} instances may be combined using the {@link
* MessageFactory.CombinedMessageFactory}.
*
* <p>Note: On Android, the {@code DescriptorMessageProvider} is not supported as proto lite does
* not support descriptors. Instead, implement the {@code MessageProvider} interface directly.
*
* <p>CEL Library Internals. Do Not Use.
*/
@ThreadSafe
Expand DownExpand Up@@ -117,8 +99,8 @@ static IntermediateResult create(Object value) {
*/
public DefaultInterpreter(
RuntimeTypeProvider typeProvider, Dispatcher dispatcher, CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher);
this.celOptions = celOptions;
}

Expand All@@ -141,11 +123,11 @@ private static final class DefaultInterpretable
Dispatcher dispatcher,
CelAbstractSyntaxTree ast,
CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher).immutableCopy();
this.ast = Preconditions.checkNotNull(ast);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher).immutableCopy();
this.ast = checkNotNull(ast);
this.metadata = new DefaultMetadata(ast);
this.celOptions = Preconditions.checkNotNull(celOptions);
this.celOptions = checkNotNull(celOptions);
}

@Override
Expand DownExpand Up@@ -278,7 +260,10 @@ private IntermediateResult resolveIdent(ExecutionFrame frame, CelExpr expr, Stri
// Check whether the type exists in the type check map as a 'type'.
Optional<CelType> checkedType = ast.getType(expr.id());
if (checkedType.isPresent() && checkedType.get().kind() == CelKind.TYPE) {
Object typeValue = typeProvider.adaptType(checkedType.get());
Object typeValue =
celOptions.adaptRuntimeTypeValueToNativeType()
? CelTypeResolver.adaptType(checkedType.get())
: typeProvider.adaptType(checkedType.get());
return IntermediateResult.create(typeValue);
}

Expand DownExpand Up@@ -658,8 +643,14 @@ private IntermediateResult evalType(ExecutionFrame frame, CelCall callExpr)
.setLocation(metadata, typeExprArg.id())
.build());

Value checkedTypeValue = typeProvider.adaptType(checkedType);
Object typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
Object typeValue;
if (celOptions.adaptRuntimeTypeValueToNativeType()) {
CelType checkedTypeValue = CelTypeResolver.adaptType(checkedType);
typeValue = CelTypeResolver.resolveObjectType(argResult.value(), checkedTypeValue);
} else {
Value checkedTypeValue = typeProvider.adaptType(checkedType);
typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
}
return IntermediateResult.create(typeValue);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,9 +42,12 @@
* by the CEL standard environment.
*
* <p>CEL Library Internals. Do Not Use.
*
* @deprecated Use {@code CelTypeResolver} instead.
*/
@Immutable
@Internal
@Deprecated
public final class StandardTypeResolver implements TypeResolver {

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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: 11 additions & 0 deletions common/src/main/java/dev/cel/common/CelOptions.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,6 +109,8 @@ public enum ProtoUnsetFieldOptions {

public abstract ProtoUnsetFieldOptions fromProtoUnsetFieldOption();

public abstract boolean adaptRuntimeTypeValueToNativeType();

public abstract boolean enableStringConversion();

public abstract boolean enableStringConcatenation();
Expand DownExpand Up@@ -209,6 +211,7 @@ public static Builder newBuilder() {
.comprehensionMaxIterations(-1)
.unwrapWellKnownTypesOnFunctionDispatch(true)
.fromProtoUnsetFieldOption(ProtoUnsetFieldOptions.BIND_DEFAULT)
.adaptRuntimeTypeValueToNativeType(false)
.enableStringConversion(true)
.enableStringConcatenation(true)
.enableListConcatenation(true)
Expand DownExpand Up@@ -516,6 +519,14 @@ public abstract static class Builder {
*/
public abstract Builder fromProtoUnsetFieldOption(ProtoUnsetFieldOptions value);

/**
* If enabled, result of the type function call `type(foo)` will be evaluated as a native-type
* equivalent {@code CelType} instead of the protobuf type equivalent from {value.proto}.
*
* <p>This is a temporary flag for migration purposes, and will be removed in the near future.
*/
public abstract Builder adaptRuntimeTypeValueToNativeType(boolean value);

/**
* Enables string() overloads for the runtime. This option exists to maintain parity with
* cel-cpp interpreter options.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompilerFactory;
import dev.cel.extensions.CelExtensions;
import dev.cel.extensions.CelOptionalLibrary;
Expand DownExpand Up@@ -88,6 +89,7 @@ private static TypeRegistry newDefaultTypeRegistry() {
CelOptions.current()
.enableTimestampEpoch(true)
.enableUnsignedLongs(true)
.adaptRuntimeTypeValueToNativeType(true)
.enableHeterogeneousNumericComparisons(true)
.enableProtoDifferencerEquality(true)
.enableOptionalSyntax(true)
Expand DownExpand Up@@ -332,6 +334,10 @@ private static Value toValue(Object object, CelType type) throws Exception {
if (object instanceof Message) {
return Value.newBuilder().setObjectValue(Any.pack((Message) object)).build();
}
if (object instanceof TypeType) {
return Value.newBuilder().setTypeValue(((TypeType) object).containingTypeName()).build();
}

throw new IllegalArgumentException(
String.format("Unexpected result type: %s", object.getClass()));
}
Expand Down
1 change: 0 additions & 1 deletion extensions/src/test/java/dev/cel/extensions/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,7 +25,6 @@ java_library(
"//parser:macro",
"//runtime",
"//runtime:interpreter_util",
"@cel_spec//proto/cel/expr:expr_java_proto",
"@cel_spec//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@cel_spec//proto/test/v1/proto2:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import dev.cel.expr.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
Expand All@@ -43,6 +42,7 @@
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.expr.conformance.proto3.TestAllTypes.NestedMessage;
import dev.cel.parser.CelStandardMacro;
Expand DownExpand Up@@ -92,7 +92,11 @@ private enum ConstantTestCases {
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.setOptions(
CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build())
CelOptions.current()
.enableUnsignedLongs(true)
.enableTimestampEpoch(true)
.adaptRuntimeTypeValueToNativeType(true)
.build())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setContainer("cel.expr.conformance.proto3")
.addMessageTypes(TestAllTypes.getDescriptor())
Expand DownExpand Up@@ -1439,11 +1443,12 @@ public void optionalFlatMapMacro_withNonIdent_throws() {
@Test
public void optionalType_typeResolution() throws Exception {
Cel cel = newCelBuilder().build();

CelAbstractSyntaxTree ast = cel.compile("optional_type").getAst();

assertThat(cel.createProgram(ast).eval())
.isEqualTo(Value.newBuilder().setTypeValue("optional_type").build());
TypeType optionalRuntimeType = (TypeType) cel.createProgram(ast).eval();

assertThat(optionalRuntimeType.name()).isEqualTo("type");
assertThat(optionalRuntimeType.containingTypeName()).isEqualTo("optional_type");
}

@Test
Expand Down
13 changes: 13 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,18 @@ INTERPRETER_SOURCES = [
"UnknownTrackingInterpretable.java",
]

java_library(
name = "cel_type_resolver",
srcs = ["CelTypeResolver.java"],
deps = [
"//common/types",
"//common/types:type_providers",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
],
)

java_library(
name = "base",
srcs = BASE_SOURCES,
Expand DownExpand Up@@ -80,6 +92,7 @@ java_library(
exports = [":base"],
deps = [
":base",
":cel_type_resolver",
":evaluation_listener",
":runtime_helper",
":unknown_attributes",
Expand Down
155 changes: 155 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/CelTypeResolver.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.NullValue;
import com.google.protobuf.Timestamp;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* {@code CelTypeResolver} resolves incoming {@link CelType} into {@link TypeType}., either as part
* of a type call (type('foo'), type(1), etc.) or as a type literal (type, int, string, etc.)
*/
@Immutable
final class CelTypeResolver {

// Sentinel runtime value representing the special "type" ident. This ensures following to be
// true: type == type(string) && type == type(type("foo"))
private static final TypeType RUNTIME_TYPE_TYPE = TypeType.create(SimpleType.DYN);

private static final ImmutableMap<Class<?>, TypeType> COMMON_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Boolean.class, TypeType.create(SimpleType.BOOL))
.put(Double.class, TypeType.create(SimpleType.DOUBLE))
.put(Long.class, TypeType.create(SimpleType.INT))
.put(UnsignedLong.class, TypeType.create(SimpleType.UINT))
.put(String.class, TypeType.create(SimpleType.STRING))
.put(NullValue.class, TypeType.create(SimpleType.NULL_TYPE))
.put(Duration.class, TypeType.create(SimpleType.DURATION))
.put(Timestamp.class, TypeType.create(SimpleType.TIMESTAMP))
.put(ArrayList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ImmutableList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(HashMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(ImmutableMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(Optional.class, TypeType.create(OptionalType.create(SimpleType.DYN)))
.buildOrThrow();

private static final ImmutableMap<Class<?>, TypeType> EXTENDABLE_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Collection.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ByteString.class, TypeType.create(SimpleType.BYTES))
.put(Map.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.buildOrThrow();

/** Adapt the type-checked {@link CelType} into a runtime type value {@link TypeType}. */
static TypeType adaptType(CelType typeCheckedType) {
checkNotNull(typeCheckedType);

switch (typeCheckedType.kind()) {
case TYPE:
CelType typeOfType = ((TypeType) typeCheckedType).type();
switch (typeOfType.kind()) {
case STRUCT:
return TypeType.create(adaptStructType((StructType) typeOfType));
default:
return (TypeType) typeCheckedType;
}
case UNSPECIFIED:
throw new IllegalArgumentException("Unsupported CelType kind: " + typeCheckedType.kind());
default:
return TypeType.create(typeCheckedType);
}
}

/** Resolve the CEL type of the {@code obj}. */
static TypeType resolveObjectType(Object obj, CelType typeCheckedType) {
checkNotNull(obj);
if (obj instanceof TypeType) {
return RUNTIME_TYPE_TYPE;
}

Class<?> currentClass = obj.getClass();
TypeType runtimeType = COMMON_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

if (obj instanceof MessageOrBuilder) {
MessageOrBuilder msg = (MessageOrBuilder) obj;
// TODO: Replace with CelLiteDescriptor
return TypeType.create(StructTypeReference.create(msg.getDescriptorForType().getFullName()));
}

// Handle types that the client may have extended.
while (currentClass != null) {
runtimeType = EXTENDABLE_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

// Check interfaces
for (Class<?> interfaceClass : currentClass.getInterfaces()) {
runtimeType = EXTENDABLE_TYPES.get(interfaceClass);
if (runtimeType != null) {
return runtimeType;
}
}
currentClass = currentClass.getSuperclass();
}

// This is an opaque type, or something CEL doesn't know about.
return (TypeType) typeCheckedType;
}

private static CelType adaptStructType(StructType typeOfType) {
String structName = typeOfType.name();
CelType newTypeOfType;
if (structName.equals(SimpleType.DURATION.name())) {
newTypeOfType = SimpleType.DURATION;
} else if (structName.equals(SimpleType.TIMESTAMP.name())) {
newTypeOfType = SimpleType.TIMESTAMP;
} else {
// Coerces ProtoMessageTypeProvider to be a struct type reference for accurate
// equality tests.
// In the future, we can plumb ProtoMessageTypeProvider through the runtime to retain
// ProtoMessageType here.
newTypeOfType = StructTypeReference.create(typeOfType.name());
}
return newTypeOfType;
}

private CelTypeResolver() {}
}
49 changes: 20 additions & 29 deletions runtime/src/main/java/dev/cel/runtime/DefaultInterpreter.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,8 @@

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import dev.cel.expr.Value;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
Expand DownExpand Up@@ -53,26 +55,6 @@
/**
* Default implementation of the CEL interpreter.
*
* <p>Use as in:
*
* <pre>
* MessageFactory messageFactory = new LinkedMessageFactory();
* RuntimeTypeProvider typeProvider = new DescriptorMessageProvider(messageFactory);
* Dispatcher dispatcher = DefaultDispatcher.create();
* Interpreter interpreter = new DefaultInterpreter(typeProvider, dispatcher);
* Interpretable interpretable = interpreter.createInterpretable(checkedExpr);
* Object result = interpretable.eval(Activation.of("name", value));
* </pre>
*
* <p>Extensions functions can be added in addition to standard functions to the dispatcher as
* needed.
*
* <p>Note: {MessageFactory} instances may be combined using the {@link
* MessageFactory.CombinedMessageFactory}.
*
* <p>Note: On Android, the {@code DescriptorMessageProvider} is not supported as proto lite does
* not support descriptors. Instead, implement the {@code MessageProvider} interface directly.
*
* <p>CEL Library Internals. Do Not Use.
*/
@ThreadSafe
Expand DownExpand Up@@ -117,8 +99,8 @@ static IntermediateResult create(Object value) {
*/
public DefaultInterpreter(
RuntimeTypeProvider typeProvider, Dispatcher dispatcher, CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher);
this.celOptions = celOptions;
}

Expand All@@ -141,11 +123,11 @@ private static final class DefaultInterpretable
Dispatcher dispatcher,
CelAbstractSyntaxTree ast,
CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher).immutableCopy();
this.ast = Preconditions.checkNotNull(ast);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher).immutableCopy();
this.ast = checkNotNull(ast);
this.metadata = new DefaultMetadata(ast);
this.celOptions = Preconditions.checkNotNull(celOptions);
this.celOptions = checkNotNull(celOptions);
}

@Override
Expand DownExpand Up@@ -278,7 +260,10 @@ private IntermediateResult resolveIdent(ExecutionFrame frame, CelExpr expr, Stri
// Check whether the type exists in the type check map as a 'type'.
Optional<CelType> checkedType = ast.getType(expr.id());
if (checkedType.isPresent() && checkedType.get().kind() == CelKind.TYPE) {
Object typeValue = typeProvider.adaptType(checkedType.get());
Object typeValue =
celOptions.adaptRuntimeTypeValueToNativeType()
? CelTypeResolver.adaptType(checkedType.get())
: typeProvider.adaptType(checkedType.get());
return IntermediateResult.create(typeValue);
}

Expand DownExpand Up@@ -658,8 +643,14 @@ private IntermediateResult evalType(ExecutionFrame frame, CelCall callExpr)
.setLocation(metadata, typeExprArg.id())
.build());

Value checkedTypeValue = typeProvider.adaptType(checkedType);
Object typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
Object typeValue;
if (celOptions.adaptRuntimeTypeValueToNativeType()) {
CelType checkedTypeValue = CelTypeResolver.adaptType(checkedType);
typeValue = CelTypeResolver.resolveObjectType(argResult.value(), checkedTypeValue);
} else {
Value checkedTypeValue = typeProvider.adaptType(checkedType);
typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
}
return IntermediateResult.create(typeValue);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,9 +42,12 @@
* by the CEL standard environment.
*
* <p>CEL Library Internals. Do Not Use.
*
* @deprecated Use {@code CelTypeResolver} instead.
*/
@Immutable
@Internal
@Deprecated
public final class StandardTypeResolver implements TypeResolver {

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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: 11 additions & 0 deletions common/src/main/java/dev/cel/common/CelOptions.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,6 +109,8 @@ public enum ProtoUnsetFieldOptions {

public abstract ProtoUnsetFieldOptions fromProtoUnsetFieldOption();

public abstract boolean adaptRuntimeTypeValueToNativeType();

public abstract boolean enableStringConversion();

public abstract boolean enableStringConcatenation();
Expand DownExpand Up@@ -209,6 +211,7 @@ public static Builder newBuilder() {
.comprehensionMaxIterations(-1)
.unwrapWellKnownTypesOnFunctionDispatch(true)
.fromProtoUnsetFieldOption(ProtoUnsetFieldOptions.BIND_DEFAULT)
.adaptRuntimeTypeValueToNativeType(false)
.enableStringConversion(true)
.enableStringConcatenation(true)
.enableListConcatenation(true)
Expand DownExpand Up@@ -516,6 +519,14 @@ public abstract static class Builder {
*/
public abstract Builder fromProtoUnsetFieldOption(ProtoUnsetFieldOptions value);

/**
* If enabled, result of the type function call `type(foo)` will be evaluated as a native-type
* equivalent {@code CelType} instead of the protobuf type equivalent from {value.proto}.
*
* <p>This is a temporary flag for migration purposes, and will be removed in the near future.
*/
public abstract Builder adaptRuntimeTypeValueToNativeType(boolean value);

/**
* Enables string() overloads for the runtime. This option exists to maintain parity with
* cel-cpp interpreter options.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompilerFactory;
import dev.cel.extensions.CelExtensions;
import dev.cel.extensions.CelOptionalLibrary;
Expand DownExpand Up@@ -88,6 +89,7 @@ private static TypeRegistry newDefaultTypeRegistry() {
CelOptions.current()
.enableTimestampEpoch(true)
.enableUnsignedLongs(true)
.adaptRuntimeTypeValueToNativeType(true)
.enableHeterogeneousNumericComparisons(true)
.enableProtoDifferencerEquality(true)
.enableOptionalSyntax(true)
Expand DownExpand Up@@ -332,6 +334,10 @@ private static Value toValue(Object object, CelType type) throws Exception {
if (object instanceof Message) {
return Value.newBuilder().setObjectValue(Any.pack((Message) object)).build();
}
if (object instanceof TypeType) {
return Value.newBuilder().setTypeValue(((TypeType) object).containingTypeName()).build();
}

throw new IllegalArgumentException(
String.format("Unexpected result type: %s", object.getClass()));
}
Expand Down
1 change: 0 additions & 1 deletion extensions/src/test/java/dev/cel/extensions/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,7 +25,6 @@ java_library(
"//parser:macro",
"//runtime",
"//runtime:interpreter_util",
"@cel_spec//proto/cel/expr:expr_java_proto",
"@cel_spec//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@cel_spec//proto/test/v1/proto2:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import dev.cel.expr.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
Expand All@@ -43,6 +42,7 @@
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.expr.conformance.proto3.TestAllTypes.NestedMessage;
import dev.cel.parser.CelStandardMacro;
Expand DownExpand Up@@ -92,7 +92,11 @@ private enum ConstantTestCases {
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.setOptions(
CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build())
CelOptions.current()
.enableUnsignedLongs(true)
.enableTimestampEpoch(true)
.adaptRuntimeTypeValueToNativeType(true)
.build())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setContainer("cel.expr.conformance.proto3")
.addMessageTypes(TestAllTypes.getDescriptor())
Expand DownExpand Up@@ -1439,11 +1443,12 @@ public void optionalFlatMapMacro_withNonIdent_throws() {
@Test
public void optionalType_typeResolution() throws Exception {
Cel cel = newCelBuilder().build();

CelAbstractSyntaxTree ast = cel.compile("optional_type").getAst();

assertThat(cel.createProgram(ast).eval())
.isEqualTo(Value.newBuilder().setTypeValue("optional_type").build());
TypeType optionalRuntimeType = (TypeType) cel.createProgram(ast).eval();

assertThat(optionalRuntimeType.name()).isEqualTo("type");
assertThat(optionalRuntimeType.containingTypeName()).isEqualTo("optional_type");
}

@Test
Expand Down
13 changes: 13 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,18 @@ INTERPRETER_SOURCES = [
"UnknownTrackingInterpretable.java",
]

java_library(
name = "cel_type_resolver",
srcs = ["CelTypeResolver.java"],
deps = [
"//common/types",
"//common/types:type_providers",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
],
)

java_library(
name = "base",
srcs = BASE_SOURCES,
Expand DownExpand Up@@ -80,6 +92,7 @@ java_library(
exports = [":base"],
deps = [
":base",
":cel_type_resolver",
":evaluation_listener",
":runtime_helper",
":unknown_attributes",
Expand Down
155 changes: 155 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/CelTypeResolver.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.NullValue;
import com.google.protobuf.Timestamp;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* {@code CelTypeResolver} resolves incoming {@link CelType} into {@link TypeType}., either as part
* of a type call (type('foo'), type(1), etc.) or as a type literal (type, int, string, etc.)
*/
@Immutable
final class CelTypeResolver {

// Sentinel runtime value representing the special "type" ident. This ensures following to be
// true: type == type(string) && type == type(type("foo"))
private static final TypeType RUNTIME_TYPE_TYPE = TypeType.create(SimpleType.DYN);

private static final ImmutableMap<Class<?>, TypeType> COMMON_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Boolean.class, TypeType.create(SimpleType.BOOL))
.put(Double.class, TypeType.create(SimpleType.DOUBLE))
.put(Long.class, TypeType.create(SimpleType.INT))
.put(UnsignedLong.class, TypeType.create(SimpleType.UINT))
.put(String.class, TypeType.create(SimpleType.STRING))
.put(NullValue.class, TypeType.create(SimpleType.NULL_TYPE))
.put(Duration.class, TypeType.create(SimpleType.DURATION))
.put(Timestamp.class, TypeType.create(SimpleType.TIMESTAMP))
.put(ArrayList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ImmutableList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(HashMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(ImmutableMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(Optional.class, TypeType.create(OptionalType.create(SimpleType.DYN)))
.buildOrThrow();

private static final ImmutableMap<Class<?>, TypeType> EXTENDABLE_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Collection.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ByteString.class, TypeType.create(SimpleType.BYTES))
.put(Map.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.buildOrThrow();

/** Adapt the type-checked {@link CelType} into a runtime type value {@link TypeType}. */
static TypeType adaptType(CelType typeCheckedType) {
checkNotNull(typeCheckedType);

switch (typeCheckedType.kind()) {
case TYPE:
CelType typeOfType = ((TypeType) typeCheckedType).type();
switch (typeOfType.kind()) {
case STRUCT:
return TypeType.create(adaptStructType((StructType) typeOfType));
default:
return (TypeType) typeCheckedType;
}
case UNSPECIFIED:
throw new IllegalArgumentException("Unsupported CelType kind: " + typeCheckedType.kind());
default:
return TypeType.create(typeCheckedType);
}
}

/** Resolve the CEL type of the {@code obj}. */
static TypeType resolveObjectType(Object obj, CelType typeCheckedType) {
checkNotNull(obj);
if (obj instanceof TypeType) {
return RUNTIME_TYPE_TYPE;
}

Class<?> currentClass = obj.getClass();
TypeType runtimeType = COMMON_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

if (obj instanceof MessageOrBuilder) {
MessageOrBuilder msg = (MessageOrBuilder) obj;
// TODO: Replace with CelLiteDescriptor
return TypeType.create(StructTypeReference.create(msg.getDescriptorForType().getFullName()));
}

// Handle types that the client may have extended.
while (currentClass != null) {
runtimeType = EXTENDABLE_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

// Check interfaces
for (Class<?> interfaceClass : currentClass.getInterfaces()) {
runtimeType = EXTENDABLE_TYPES.get(interfaceClass);
if (runtimeType != null) {
return runtimeType;
}
}
currentClass = currentClass.getSuperclass();
}

// This is an opaque type, or something CEL doesn't know about.
return (TypeType) typeCheckedType;
}

private static CelType adaptStructType(StructType typeOfType) {
String structName = typeOfType.name();
CelType newTypeOfType;
if (structName.equals(SimpleType.DURATION.name())) {
newTypeOfType = SimpleType.DURATION;
} else if (structName.equals(SimpleType.TIMESTAMP.name())) {
newTypeOfType = SimpleType.TIMESTAMP;
} else {
// Coerces ProtoMessageTypeProvider to be a struct type reference for accurate
// equality tests.
// In the future, we can plumb ProtoMessageTypeProvider through the runtime to retain
// ProtoMessageType here.
newTypeOfType = StructTypeReference.create(typeOfType.name());
}
return newTypeOfType;
}

private CelTypeResolver() {}
}
49 changes: 20 additions & 29 deletions runtime/src/main/java/dev/cel/runtime/DefaultInterpreter.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,8 @@

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import dev.cel.expr.Value;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
Expand DownExpand Up@@ -53,26 +55,6 @@
/**
* Default implementation of the CEL interpreter.
*
* <p>Use as in:
*
* <pre>
* MessageFactory messageFactory = new LinkedMessageFactory();
* RuntimeTypeProvider typeProvider = new DescriptorMessageProvider(messageFactory);
* Dispatcher dispatcher = DefaultDispatcher.create();
* Interpreter interpreter = new DefaultInterpreter(typeProvider, dispatcher);
* Interpretable interpretable = interpreter.createInterpretable(checkedExpr);
* Object result = interpretable.eval(Activation.of("name", value));
* </pre>
*
* <p>Extensions functions can be added in addition to standard functions to the dispatcher as
* needed.
*
* <p>Note: {MessageFactory} instances may be combined using the {@link
* MessageFactory.CombinedMessageFactory}.
*
* <p>Note: On Android, the {@code DescriptorMessageProvider} is not supported as proto lite does
* not support descriptors. Instead, implement the {@code MessageProvider} interface directly.
*
* <p>CEL Library Internals. Do Not Use.
*/
@ThreadSafe
Expand DownExpand Up@@ -117,8 +99,8 @@ static IntermediateResult create(Object value) {
*/
public DefaultInterpreter(
RuntimeTypeProvider typeProvider, Dispatcher dispatcher, CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher);
this.celOptions = celOptions;
}

Expand All@@ -141,11 +123,11 @@ private static final class DefaultInterpretable
Dispatcher dispatcher,
CelAbstractSyntaxTree ast,
CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher).immutableCopy();
this.ast = Preconditions.checkNotNull(ast);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher).immutableCopy();
this.ast = checkNotNull(ast);
this.metadata = new DefaultMetadata(ast);
this.celOptions = Preconditions.checkNotNull(celOptions);
this.celOptions = checkNotNull(celOptions);
}

@Override
Expand DownExpand Up@@ -278,7 +260,10 @@ private IntermediateResult resolveIdent(ExecutionFrame frame, CelExpr expr, Stri
// Check whether the type exists in the type check map as a 'type'.
Optional<CelType> checkedType = ast.getType(expr.id());
if (checkedType.isPresent() && checkedType.get().kind() == CelKind.TYPE) {
Object typeValue = typeProvider.adaptType(checkedType.get());
Object typeValue =
celOptions.adaptRuntimeTypeValueToNativeType()
? CelTypeResolver.adaptType(checkedType.get())
: typeProvider.adaptType(checkedType.get());
return IntermediateResult.create(typeValue);
}

Expand DownExpand Up@@ -658,8 +643,14 @@ private IntermediateResult evalType(ExecutionFrame frame, CelCall callExpr)
.setLocation(metadata, typeExprArg.id())
.build());

Value checkedTypeValue = typeProvider.adaptType(checkedType);
Object typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
Object typeValue;
if (celOptions.adaptRuntimeTypeValueToNativeType()) {
CelType checkedTypeValue = CelTypeResolver.adaptType(checkedType);
typeValue = CelTypeResolver.resolveObjectType(argResult.value(), checkedTypeValue);
} else {
Value checkedTypeValue = typeProvider.adaptType(checkedType);
typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
}
return IntermediateResult.create(typeValue);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,9 +42,12 @@
* by the CEL standard environment.
*
* <p>CEL Library Internals. Do Not Use.
*
* @deprecated Use {@code CelTypeResolver} instead.
*/
@Immutable
@Internal
@Deprecated
public final class StandardTypeResolver implements TypeResolver {

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
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: 11 additions & 0 deletions common/src/main/java/dev/cel/common/CelOptions.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,6 +109,8 @@ public enum ProtoUnsetFieldOptions {

public abstract ProtoUnsetFieldOptions fromProtoUnsetFieldOption();

public abstract boolean adaptRuntimeTypeValueToNativeType();

public abstract boolean enableStringConversion();

public abstract boolean enableStringConcatenation();
Expand DownExpand Up@@ -209,6 +211,7 @@ public static Builder newBuilder() {
.comprehensionMaxIterations(-1)
.unwrapWellKnownTypesOnFunctionDispatch(true)
.fromProtoUnsetFieldOption(ProtoUnsetFieldOptions.BIND_DEFAULT)
.adaptRuntimeTypeValueToNativeType(false)
.enableStringConversion(true)
.enableStringConcatenation(true)
.enableListConcatenation(true)
Expand DownExpand Up@@ -516,6 +519,14 @@ public abstract static class Builder {
*/
public abstract Builder fromProtoUnsetFieldOption(ProtoUnsetFieldOptions value);

/**
* If enabled, result of the type function call `type(foo)` will be evaluated as a native-type
* equivalent {@code CelType} instead of the protobuf type equivalent from {value.proto}.
*
* <p>This is a temporary flag for migration purposes, and will be removed in the near future.
*/
public abstract Builder adaptRuntimeTypeValueToNativeType(boolean value);

/**
* Enables string() overloads for the runtime. This option exists to maintain parity with
* cel-cpp interpreter options.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompilerFactory;
import dev.cel.extensions.CelExtensions;
import dev.cel.extensions.CelOptionalLibrary;
Expand DownExpand Up@@ -88,6 +89,7 @@ private static TypeRegistry newDefaultTypeRegistry() {
CelOptions.current()
.enableTimestampEpoch(true)
.enableUnsignedLongs(true)
.adaptRuntimeTypeValueToNativeType(true)
.enableHeterogeneousNumericComparisons(true)
.enableProtoDifferencerEquality(true)
.enableOptionalSyntax(true)
Expand DownExpand Up@@ -332,6 +334,10 @@ private static Value toValue(Object object, CelType type) throws Exception {
if (object instanceof Message) {
return Value.newBuilder().setObjectValue(Any.pack((Message) object)).build();
}
if (object instanceof TypeType) {
return Value.newBuilder().setTypeValue(((TypeType) object).containingTypeName()).build();
}

throw new IllegalArgumentException(
String.format("Unexpected result type: %s", object.getClass()));
}
Expand Down
1 change: 0 additions & 1 deletion extensions/src/test/java/dev/cel/extensions/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,7 +25,6 @@ java_library(
"//parser:macro",
"//runtime",
"//runtime:interpreter_util",
"@cel_spec//proto/cel/expr:expr_java_proto",
"@cel_spec//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@cel_spec//proto/test/v1/proto2:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import dev.cel.expr.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
Expand All@@ -43,6 +42,7 @@
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.expr.conformance.proto3.TestAllTypes.NestedMessage;
import dev.cel.parser.CelStandardMacro;
Expand DownExpand Up@@ -92,7 +92,11 @@ private enum ConstantTestCases {
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.setOptions(
CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build())
CelOptions.current()
.enableUnsignedLongs(true)
.enableTimestampEpoch(true)
.adaptRuntimeTypeValueToNativeType(true)
.build())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setContainer("cel.expr.conformance.proto3")
.addMessageTypes(TestAllTypes.getDescriptor())
Expand DownExpand Up@@ -1439,11 +1443,12 @@ public void optionalFlatMapMacro_withNonIdent_throws() {
@Test
public void optionalType_typeResolution() throws Exception {
Cel cel = newCelBuilder().build();

CelAbstractSyntaxTree ast = cel.compile("optional_type").getAst();

assertThat(cel.createProgram(ast).eval())
.isEqualTo(Value.newBuilder().setTypeValue("optional_type").build());
TypeType optionalRuntimeType = (TypeType) cel.createProgram(ast).eval();

assertThat(optionalRuntimeType.name()).isEqualTo("type");
assertThat(optionalRuntimeType.containingTypeName()).isEqualTo("optional_type");
}

@Test
Expand Down
13 changes: 13 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,18 @@ INTERPRETER_SOURCES = [
"UnknownTrackingInterpretable.java",
]

java_library(
name = "cel_type_resolver",
srcs = ["CelTypeResolver.java"],
deps = [
"//common/types",
"//common/types:type_providers",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
],
)

java_library(
name = "base",
srcs = BASE_SOURCES,
Expand DownExpand Up@@ -80,6 +92,7 @@ java_library(
exports = [":base"],
deps = [
":base",
":cel_type_resolver",
":evaluation_listener",
":runtime_helper",
":unknown_attributes",
Expand Down
155 changes: 155 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/CelTypeResolver.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.NullValue;
import com.google.protobuf.Timestamp;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* {@code CelTypeResolver} resolves incoming {@link CelType} into {@link TypeType}., either as part
* of a type call (type('foo'), type(1), etc.) or as a type literal (type, int, string, etc.)
*/
@Immutable
final class CelTypeResolver {

// Sentinel runtime value representing the special "type" ident. This ensures following to be
// true: type == type(string) && type == type(type("foo"))
private static final TypeType RUNTIME_TYPE_TYPE = TypeType.create(SimpleType.DYN);

private static final ImmutableMap<Class<?>, TypeType> COMMON_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Boolean.class, TypeType.create(SimpleType.BOOL))
.put(Double.class, TypeType.create(SimpleType.DOUBLE))
.put(Long.class, TypeType.create(SimpleType.INT))
.put(UnsignedLong.class, TypeType.create(SimpleType.UINT))
.put(String.class, TypeType.create(SimpleType.STRING))
.put(NullValue.class, TypeType.create(SimpleType.NULL_TYPE))
.put(Duration.class, TypeType.create(SimpleType.DURATION))
.put(Timestamp.class, TypeType.create(SimpleType.TIMESTAMP))
.put(ArrayList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ImmutableList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(HashMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(ImmutableMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(Optional.class, TypeType.create(OptionalType.create(SimpleType.DYN)))
.buildOrThrow();

private static final ImmutableMap<Class<?>, TypeType> EXTENDABLE_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Collection.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ByteString.class, TypeType.create(SimpleType.BYTES))
.put(Map.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.buildOrThrow();

/** Adapt the type-checked {@link CelType} into a runtime type value {@link TypeType}. */
static TypeType adaptType(CelType typeCheckedType) {
checkNotNull(typeCheckedType);

switch (typeCheckedType.kind()) {
case TYPE:
CelType typeOfType = ((TypeType) typeCheckedType).type();
switch (typeOfType.kind()) {
case STRUCT:
return TypeType.create(adaptStructType((StructType) typeOfType));
default:
return (TypeType) typeCheckedType;
}
case UNSPECIFIED:
throw new IllegalArgumentException("Unsupported CelType kind: " + typeCheckedType.kind());
default:
return TypeType.create(typeCheckedType);
}
}

/** Resolve the CEL type of the {@code obj}. */
static TypeType resolveObjectType(Object obj, CelType typeCheckedType) {
checkNotNull(obj);
if (obj instanceof TypeType) {
return RUNTIME_TYPE_TYPE;
}

Class<?> currentClass = obj.getClass();
TypeType runtimeType = COMMON_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

if (obj instanceof MessageOrBuilder) {
MessageOrBuilder msg = (MessageOrBuilder) obj;
// TODO: Replace with CelLiteDescriptor
return TypeType.create(StructTypeReference.create(msg.getDescriptorForType().getFullName()));
}

// Handle types that the client may have extended.
while (currentClass != null) {
runtimeType = EXTENDABLE_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

// Check interfaces
for (Class<?> interfaceClass : currentClass.getInterfaces()) {
runtimeType = EXTENDABLE_TYPES.get(interfaceClass);
if (runtimeType != null) {
return runtimeType;
}
}
currentClass = currentClass.getSuperclass();
}

// This is an opaque type, or something CEL doesn't know about.
return (TypeType) typeCheckedType;
}

private static CelType adaptStructType(StructType typeOfType) {
String structName = typeOfType.name();
CelType newTypeOfType;
if (structName.equals(SimpleType.DURATION.name())) {
newTypeOfType = SimpleType.DURATION;
} else if (structName.equals(SimpleType.TIMESTAMP.name())) {
newTypeOfType = SimpleType.TIMESTAMP;
} else {
// Coerces ProtoMessageTypeProvider to be a struct type reference for accurate
// equality tests.
// In the future, we can plumb ProtoMessageTypeProvider through the runtime to retain
// ProtoMessageType here.
newTypeOfType = StructTypeReference.create(typeOfType.name());
}
return newTypeOfType;
}

private CelTypeResolver() {}
}
49 changes: 20 additions & 29 deletions runtime/src/main/java/dev/cel/runtime/DefaultInterpreter.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,8 @@

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import dev.cel.expr.Value;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
Expand DownExpand Up@@ -53,26 +55,6 @@
/**
* Default implementation of the CEL interpreter.
*
* <p>Use as in:
*
* <pre>
* MessageFactory messageFactory = new LinkedMessageFactory();
* RuntimeTypeProvider typeProvider = new DescriptorMessageProvider(messageFactory);
* Dispatcher dispatcher = DefaultDispatcher.create();
* Interpreter interpreter = new DefaultInterpreter(typeProvider, dispatcher);
* Interpretable interpretable = interpreter.createInterpretable(checkedExpr);
* Object result = interpretable.eval(Activation.of("name", value));
* </pre>
*
* <p>Extensions functions can be added in addition to standard functions to the dispatcher as
* needed.
*
* <p>Note: {MessageFactory} instances may be combined using the {@link
* MessageFactory.CombinedMessageFactory}.
*
* <p>Note: On Android, the {@code DescriptorMessageProvider} is not supported as proto lite does
* not support descriptors. Instead, implement the {@code MessageProvider} interface directly.
*
* <p>CEL Library Internals. Do Not Use.
*/
@ThreadSafe
Expand DownExpand Up@@ -117,8 +99,8 @@ static IntermediateResult create(Object value) {
*/
public DefaultInterpreter(
RuntimeTypeProvider typeProvider, Dispatcher dispatcher, CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher);
this.celOptions = celOptions;
}

Expand All@@ -141,11 +123,11 @@ private static final class DefaultInterpretable
Dispatcher dispatcher,
CelAbstractSyntaxTree ast,
CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher).immutableCopy();
this.ast = Preconditions.checkNotNull(ast);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher).immutableCopy();
this.ast = checkNotNull(ast);
this.metadata = new DefaultMetadata(ast);
this.celOptions = Preconditions.checkNotNull(celOptions);
this.celOptions = checkNotNull(celOptions);
}

@Override
Expand DownExpand Up@@ -278,7 +260,10 @@ private IntermediateResult resolveIdent(ExecutionFrame frame, CelExpr expr, Stri
// Check whether the type exists in the type check map as a 'type'.
Optional<CelType> checkedType = ast.getType(expr.id());
if (checkedType.isPresent() && checkedType.get().kind() == CelKind.TYPE) {
Object typeValue = typeProvider.adaptType(checkedType.get());
Object typeValue =
celOptions.adaptRuntimeTypeValueToNativeType()
? CelTypeResolver.adaptType(checkedType.get())
: typeProvider.adaptType(checkedType.get());
return IntermediateResult.create(typeValue);
}

Expand DownExpand Up@@ -658,8 +643,14 @@ private IntermediateResult evalType(ExecutionFrame frame, CelCall callExpr)
.setLocation(metadata, typeExprArg.id())
.build());

Value checkedTypeValue = typeProvider.adaptType(checkedType);
Object typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
Object typeValue;
if (celOptions.adaptRuntimeTypeValueToNativeType()) {
CelType checkedTypeValue = CelTypeResolver.adaptType(checkedType);
typeValue = CelTypeResolver.resolveObjectType(argResult.value(), checkedTypeValue);
} else {
Value checkedTypeValue = typeProvider.adaptType(checkedType);
typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
}
return IntermediateResult.create(typeValue);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,9 +42,12 @@
* by the CEL standard environment.
*
* <p>CEL Library Internals. Do Not Use.
*
* @deprecated Use {@code CelTypeResolver} instead.
*/
@Immutable
@Internal
@Deprecated
public final class StandardTypeResolver implements TypeResolver {

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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: 11 additions & 0 deletions common/src/main/java/dev/cel/common/CelOptions.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,6 +109,8 @@ public enum ProtoUnsetFieldOptions {

public abstract ProtoUnsetFieldOptions fromProtoUnsetFieldOption();

public abstract boolean adaptRuntimeTypeValueToNativeType();

public abstract boolean enableStringConversion();

public abstract boolean enableStringConcatenation();
Expand DownExpand Up@@ -209,6 +211,7 @@ public static Builder newBuilder() {
.comprehensionMaxIterations(-1)
.unwrapWellKnownTypesOnFunctionDispatch(true)
.fromProtoUnsetFieldOption(ProtoUnsetFieldOptions.BIND_DEFAULT)
.adaptRuntimeTypeValueToNativeType(false)
.enableStringConversion(true)
.enableStringConcatenation(true)
.enableListConcatenation(true)
Expand DownExpand Up@@ -516,6 +519,14 @@ public abstract static class Builder {
*/
public abstract Builder fromProtoUnsetFieldOption(ProtoUnsetFieldOptions value);

/**
* If enabled, result of the type function call `type(foo)` will be evaluated as a native-type
* equivalent {@code CelType} instead of the protobuf type equivalent from {value.proto}.
*
* <p>This is a temporary flag for migration purposes, and will be removed in the near future.
*/
public abstract Builder adaptRuntimeTypeValueToNativeType(boolean value);

/**
* Enables string() overloads for the runtime. This option exists to maintain parity with
* cel-cpp interpreter options.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompilerFactory;
import dev.cel.extensions.CelExtensions;
import dev.cel.extensions.CelOptionalLibrary;
Expand DownExpand Up@@ -88,6 +89,7 @@ private static TypeRegistry newDefaultTypeRegistry() {
CelOptions.current()
.enableTimestampEpoch(true)
.enableUnsignedLongs(true)
.adaptRuntimeTypeValueToNativeType(true)
.enableHeterogeneousNumericComparisons(true)
.enableProtoDifferencerEquality(true)
.enableOptionalSyntax(true)
Expand DownExpand Up@@ -332,6 +334,10 @@ private static Value toValue(Object object, CelType type) throws Exception {
if (object instanceof Message) {
return Value.newBuilder().setObjectValue(Any.pack((Message) object)).build();
}
if (object instanceof TypeType) {
return Value.newBuilder().setTypeValue(((TypeType) object).containingTypeName()).build();
}

throw new IllegalArgumentException(
String.format("Unexpected result type: %s", object.getClass()));
}
Expand Down
1 change: 0 additions & 1 deletion extensions/src/test/java/dev/cel/extensions/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,7 +25,6 @@ java_library(
"//parser:macro",
"//runtime",
"//runtime:interpreter_util",
"@cel_spec//proto/cel/expr:expr_java_proto",
"@cel_spec//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@cel_spec//proto/test/v1/proto2:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import dev.cel.expr.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
Expand All@@ -43,6 +42,7 @@
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.expr.conformance.proto3.TestAllTypes.NestedMessage;
import dev.cel.parser.CelStandardMacro;
Expand DownExpand Up@@ -92,7 +92,11 @@ private enum ConstantTestCases {
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.setOptions(
CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build())
CelOptions.current()
.enableUnsignedLongs(true)
.enableTimestampEpoch(true)
.adaptRuntimeTypeValueToNativeType(true)
.build())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setContainer("cel.expr.conformance.proto3")
.addMessageTypes(TestAllTypes.getDescriptor())
Expand DownExpand Up@@ -1439,11 +1443,12 @@ public void optionalFlatMapMacro_withNonIdent_throws() {
@Test
public void optionalType_typeResolution() throws Exception {
Cel cel = newCelBuilder().build();

CelAbstractSyntaxTree ast = cel.compile("optional_type").getAst();

assertThat(cel.createProgram(ast).eval())
.isEqualTo(Value.newBuilder().setTypeValue("optional_type").build());
TypeType optionalRuntimeType = (TypeType) cel.createProgram(ast).eval();

assertThat(optionalRuntimeType.name()).isEqualTo("type");
assertThat(optionalRuntimeType.containingTypeName()).isEqualTo("optional_type");
}

@Test
Expand Down
13 changes: 13 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,18 @@ INTERPRETER_SOURCES = [
"UnknownTrackingInterpretable.java",
]

java_library(
name = "cel_type_resolver",
srcs = ["CelTypeResolver.java"],
deps = [
"//common/types",
"//common/types:type_providers",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
],
)

java_library(
name = "base",
srcs = BASE_SOURCES,
Expand DownExpand Up@@ -80,6 +92,7 @@ java_library(
exports = [":base"],
deps = [
":base",
":cel_type_resolver",
":evaluation_listener",
":runtime_helper",
":unknown_attributes",
Expand Down
155 changes: 155 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/CelTypeResolver.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.NullValue;
import com.google.protobuf.Timestamp;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* {@code CelTypeResolver} resolves incoming {@link CelType} into {@link TypeType}., either as part
* of a type call (type('foo'), type(1), etc.) or as a type literal (type, int, string, etc.)
*/
@Immutable
final class CelTypeResolver {

// Sentinel runtime value representing the special "type" ident. This ensures following to be
// true: type == type(string) && type == type(type("foo"))
private static final TypeType RUNTIME_TYPE_TYPE = TypeType.create(SimpleType.DYN);

private static final ImmutableMap<Class<?>, TypeType> COMMON_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Boolean.class, TypeType.create(SimpleType.BOOL))
.put(Double.class, TypeType.create(SimpleType.DOUBLE))
.put(Long.class, TypeType.create(SimpleType.INT))
.put(UnsignedLong.class, TypeType.create(SimpleType.UINT))
.put(String.class, TypeType.create(SimpleType.STRING))
.put(NullValue.class, TypeType.create(SimpleType.NULL_TYPE))
.put(Duration.class, TypeType.create(SimpleType.DURATION))
.put(Timestamp.class, TypeType.create(SimpleType.TIMESTAMP))
.put(ArrayList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ImmutableList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(HashMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(ImmutableMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(Optional.class, TypeType.create(OptionalType.create(SimpleType.DYN)))
.buildOrThrow();

private static final ImmutableMap<Class<?>, TypeType> EXTENDABLE_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Collection.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ByteString.class, TypeType.create(SimpleType.BYTES))
.put(Map.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.buildOrThrow();

/** Adapt the type-checked {@link CelType} into a runtime type value {@link TypeType}. */
static TypeType adaptType(CelType typeCheckedType) {
checkNotNull(typeCheckedType);

switch (typeCheckedType.kind()) {
case TYPE:
CelType typeOfType = ((TypeType) typeCheckedType).type();
switch (typeOfType.kind()) {
case STRUCT:
return TypeType.create(adaptStructType((StructType) typeOfType));
default:
return (TypeType) typeCheckedType;
}
case UNSPECIFIED:
throw new IllegalArgumentException("Unsupported CelType kind: " + typeCheckedType.kind());
default:
return TypeType.create(typeCheckedType);
}
}

/** Resolve the CEL type of the {@code obj}. */
static TypeType resolveObjectType(Object obj, CelType typeCheckedType) {
checkNotNull(obj);
if (obj instanceof TypeType) {
return RUNTIME_TYPE_TYPE;
}

Class<?> currentClass = obj.getClass();
TypeType runtimeType = COMMON_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

if (obj instanceof MessageOrBuilder) {
MessageOrBuilder msg = (MessageOrBuilder) obj;
// TODO: Replace with CelLiteDescriptor
return TypeType.create(StructTypeReference.create(msg.getDescriptorForType().getFullName()));
}

// Handle types that the client may have extended.
while (currentClass != null) {
runtimeType = EXTENDABLE_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

// Check interfaces
for (Class<?> interfaceClass : currentClass.getInterfaces()) {
runtimeType = EXTENDABLE_TYPES.get(interfaceClass);
if (runtimeType != null) {
return runtimeType;
}
}
currentClass = currentClass.getSuperclass();
}

// This is an opaque type, or something CEL doesn't know about.
return (TypeType) typeCheckedType;
}

private static CelType adaptStructType(StructType typeOfType) {
String structName = typeOfType.name();
CelType newTypeOfType;
if (structName.equals(SimpleType.DURATION.name())) {
newTypeOfType = SimpleType.DURATION;
} else if (structName.equals(SimpleType.TIMESTAMP.name())) {
newTypeOfType = SimpleType.TIMESTAMP;
} else {
// Coerces ProtoMessageTypeProvider to be a struct type reference for accurate
// equality tests.
// In the future, we can plumb ProtoMessageTypeProvider through the runtime to retain
// ProtoMessageType here.
newTypeOfType = StructTypeReference.create(typeOfType.name());
}
return newTypeOfType;
}

private CelTypeResolver() {}
}
49 changes: 20 additions & 29 deletions runtime/src/main/java/dev/cel/runtime/DefaultInterpreter.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,8 @@

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import dev.cel.expr.Value;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
Expand DownExpand Up@@ -53,26 +55,6 @@
/**
* Default implementation of the CEL interpreter.
*
* <p>Use as in:
*
* <pre>
* MessageFactory messageFactory = new LinkedMessageFactory();
* RuntimeTypeProvider typeProvider = new DescriptorMessageProvider(messageFactory);
* Dispatcher dispatcher = DefaultDispatcher.create();
* Interpreter interpreter = new DefaultInterpreter(typeProvider, dispatcher);
* Interpretable interpretable = interpreter.createInterpretable(checkedExpr);
* Object result = interpretable.eval(Activation.of("name", value));
* </pre>
*
* <p>Extensions functions can be added in addition to standard functions to the dispatcher as
* needed.
*
* <p>Note: {MessageFactory} instances may be combined using the {@link
* MessageFactory.CombinedMessageFactory}.
*
* <p>Note: On Android, the {@code DescriptorMessageProvider} is not supported as proto lite does
* not support descriptors. Instead, implement the {@code MessageProvider} interface directly.
*
* <p>CEL Library Internals. Do Not Use.
*/
@ThreadSafe
Expand DownExpand Up@@ -117,8 +99,8 @@ static IntermediateResult create(Object value) {
*/
public DefaultInterpreter(
RuntimeTypeProvider typeProvider, Dispatcher dispatcher, CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher);
this.celOptions = celOptions;
}

Expand All@@ -141,11 +123,11 @@ private static final class DefaultInterpretable
Dispatcher dispatcher,
CelAbstractSyntaxTree ast,
CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher).immutableCopy();
this.ast = Preconditions.checkNotNull(ast);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher).immutableCopy();
this.ast = checkNotNull(ast);
this.metadata = new DefaultMetadata(ast);
this.celOptions = Preconditions.checkNotNull(celOptions);
this.celOptions = checkNotNull(celOptions);
}

@Override
Expand DownExpand Up@@ -278,7 +260,10 @@ private IntermediateResult resolveIdent(ExecutionFrame frame, CelExpr expr, Stri
// Check whether the type exists in the type check map as a 'type'.
Optional<CelType> checkedType = ast.getType(expr.id());
if (checkedType.isPresent() && checkedType.get().kind() == CelKind.TYPE) {
Object typeValue = typeProvider.adaptType(checkedType.get());
Object typeValue =
celOptions.adaptRuntimeTypeValueToNativeType()
? CelTypeResolver.adaptType(checkedType.get())
: typeProvider.adaptType(checkedType.get());
return IntermediateResult.create(typeValue);
}

Expand DownExpand Up@@ -658,8 +643,14 @@ private IntermediateResult evalType(ExecutionFrame frame, CelCall callExpr)
.setLocation(metadata, typeExprArg.id())
.build());

Value checkedTypeValue = typeProvider.adaptType(checkedType);
Object typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
Object typeValue;
if (celOptions.adaptRuntimeTypeValueToNativeType()) {
CelType checkedTypeValue = CelTypeResolver.adaptType(checkedType);
typeValue = CelTypeResolver.resolveObjectType(argResult.value(), checkedTypeValue);
} else {
Value checkedTypeValue = typeProvider.adaptType(checkedType);
typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
}
return IntermediateResult.create(typeValue);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,9 +42,12 @@
* by the CEL standard environment.
*
* <p>CEL Library Internals. Do Not Use.
*
* @deprecated Use {@code CelTypeResolver} instead.
*/
@Immutable
@Internal
@Deprecated
public final class StandardTypeResolver implements TypeResolver {

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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: 11 additions & 0 deletions common/src/main/java/dev/cel/common/CelOptions.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,6 +109,8 @@ public enum ProtoUnsetFieldOptions {

public abstract ProtoUnsetFieldOptions fromProtoUnsetFieldOption();

public abstract boolean adaptRuntimeTypeValueToNativeType();

public abstract boolean enableStringConversion();

public abstract boolean enableStringConcatenation();
Expand DownExpand Up@@ -209,6 +211,7 @@ public static Builder newBuilder() {
.comprehensionMaxIterations(-1)
.unwrapWellKnownTypesOnFunctionDispatch(true)
.fromProtoUnsetFieldOption(ProtoUnsetFieldOptions.BIND_DEFAULT)
.adaptRuntimeTypeValueToNativeType(false)
.enableStringConversion(true)
.enableStringConcatenation(true)
.enableListConcatenation(true)
Expand DownExpand Up@@ -516,6 +519,14 @@ public abstract static class Builder {
*/
public abstract Builder fromProtoUnsetFieldOption(ProtoUnsetFieldOptions value);

/**
* If enabled, result of the type function call `type(foo)` will be evaluated as a native-type
* equivalent {@code CelType} instead of the protobuf type equivalent from {value.proto}.
*
* <p>This is a temporary flag for migration purposes, and will be removed in the near future.
*/
public abstract Builder adaptRuntimeTypeValueToNativeType(boolean value);

/**
* Enables string() overloads for the runtime. This option exists to maintain parity with
* cel-cpp interpreter options.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompilerFactory;
import dev.cel.extensions.CelExtensions;
import dev.cel.extensions.CelOptionalLibrary;
Expand DownExpand Up@@ -88,6 +89,7 @@ private static TypeRegistry newDefaultTypeRegistry() {
CelOptions.current()
.enableTimestampEpoch(true)
.enableUnsignedLongs(true)
.adaptRuntimeTypeValueToNativeType(true)
.enableHeterogeneousNumericComparisons(true)
.enableProtoDifferencerEquality(true)
.enableOptionalSyntax(true)
Expand DownExpand Up@@ -332,6 +334,10 @@ private static Value toValue(Object object, CelType type) throws Exception {
if (object instanceof Message) {
return Value.newBuilder().setObjectValue(Any.pack((Message) object)).build();
}
if (object instanceof TypeType) {
return Value.newBuilder().setTypeValue(((TypeType) object).containingTypeName()).build();
}

throw new IllegalArgumentException(
String.format("Unexpected result type: %s", object.getClass()));
}
Expand Down
1 change: 0 additions & 1 deletion extensions/src/test/java/dev/cel/extensions/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,7 +25,6 @@ java_library(
"//parser:macro",
"//runtime",
"//runtime:interpreter_util",
"@cel_spec//proto/cel/expr:expr_java_proto",
"@cel_spec//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@cel_spec//proto/test/v1/proto2:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import dev.cel.expr.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
Expand All@@ -43,6 +42,7 @@
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.expr.conformance.proto3.TestAllTypes.NestedMessage;
import dev.cel.parser.CelStandardMacro;
Expand DownExpand Up@@ -92,7 +92,11 @@ private enum ConstantTestCases {
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.setOptions(
CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build())
CelOptions.current()
.enableUnsignedLongs(true)
.enableTimestampEpoch(true)
.adaptRuntimeTypeValueToNativeType(true)
.build())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setContainer("cel.expr.conformance.proto3")
.addMessageTypes(TestAllTypes.getDescriptor())
Expand DownExpand Up@@ -1439,11 +1443,12 @@ public void optionalFlatMapMacro_withNonIdent_throws() {
@Test
public void optionalType_typeResolution() throws Exception {
Cel cel = newCelBuilder().build();

CelAbstractSyntaxTree ast = cel.compile("optional_type").getAst();

assertThat(cel.createProgram(ast).eval())
.isEqualTo(Value.newBuilder().setTypeValue("optional_type").build());
TypeType optionalRuntimeType = (TypeType) cel.createProgram(ast).eval();

assertThat(optionalRuntimeType.name()).isEqualTo("type");
assertThat(optionalRuntimeType.containingTypeName()).isEqualTo("optional_type");
}

@Test
Expand Down
13 changes: 13 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,18 @@ INTERPRETER_SOURCES = [
"UnknownTrackingInterpretable.java",
]

java_library(
name = "cel_type_resolver",
srcs = ["CelTypeResolver.java"],
deps = [
"//common/types",
"//common/types:type_providers",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
],
)

java_library(
name = "base",
srcs = BASE_SOURCES,
Expand DownExpand Up@@ -80,6 +92,7 @@ java_library(
exports = [":base"],
deps = [
":base",
":cel_type_resolver",
":evaluation_listener",
":runtime_helper",
":unknown_attributes",
Expand Down
155 changes: 155 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/CelTypeResolver.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.NullValue;
import com.google.protobuf.Timestamp;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* {@code CelTypeResolver} resolves incoming {@link CelType} into {@link TypeType}., either as part
* of a type call (type('foo'), type(1), etc.) or as a type literal (type, int, string, etc.)
*/
@Immutable
final class CelTypeResolver {

// Sentinel runtime value representing the special "type" ident. This ensures following to be
// true: type == type(string) && type == type(type("foo"))
private static final TypeType RUNTIME_TYPE_TYPE = TypeType.create(SimpleType.DYN);

private static final ImmutableMap<Class<?>, TypeType> COMMON_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Boolean.class, TypeType.create(SimpleType.BOOL))
.put(Double.class, TypeType.create(SimpleType.DOUBLE))
.put(Long.class, TypeType.create(SimpleType.INT))
.put(UnsignedLong.class, TypeType.create(SimpleType.UINT))
.put(String.class, TypeType.create(SimpleType.STRING))
.put(NullValue.class, TypeType.create(SimpleType.NULL_TYPE))
.put(Duration.class, TypeType.create(SimpleType.DURATION))
.put(Timestamp.class, TypeType.create(SimpleType.TIMESTAMP))
.put(ArrayList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ImmutableList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(HashMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(ImmutableMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(Optional.class, TypeType.create(OptionalType.create(SimpleType.DYN)))
.buildOrThrow();

private static final ImmutableMap<Class<?>, TypeType> EXTENDABLE_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Collection.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ByteString.class, TypeType.create(SimpleType.BYTES))
.put(Map.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.buildOrThrow();

/** Adapt the type-checked {@link CelType} into a runtime type value {@link TypeType}. */
static TypeType adaptType(CelType typeCheckedType) {
checkNotNull(typeCheckedType);

switch (typeCheckedType.kind()) {
case TYPE:
CelType typeOfType = ((TypeType) typeCheckedType).type();
switch (typeOfType.kind()) {
case STRUCT:
return TypeType.create(adaptStructType((StructType) typeOfType));
default:
return (TypeType) typeCheckedType;
}
case UNSPECIFIED:
throw new IllegalArgumentException("Unsupported CelType kind: " + typeCheckedType.kind());
default:
return TypeType.create(typeCheckedType);
}
}

/** Resolve the CEL type of the {@code obj}. */
static TypeType resolveObjectType(Object obj, CelType typeCheckedType) {
checkNotNull(obj);
if (obj instanceof TypeType) {
return RUNTIME_TYPE_TYPE;
}

Class<?> currentClass = obj.getClass();
TypeType runtimeType = COMMON_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

if (obj instanceof MessageOrBuilder) {
MessageOrBuilder msg = (MessageOrBuilder) obj;
// TODO: Replace with CelLiteDescriptor
return TypeType.create(StructTypeReference.create(msg.getDescriptorForType().getFullName()));
}

// Handle types that the client may have extended.
while (currentClass != null) {
runtimeType = EXTENDABLE_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

// Check interfaces
for (Class<?> interfaceClass : currentClass.getInterfaces()) {
runtimeType = EXTENDABLE_TYPES.get(interfaceClass);
if (runtimeType != null) {
return runtimeType;
}
}
currentClass = currentClass.getSuperclass();
}

// This is an opaque type, or something CEL doesn't know about.
return (TypeType) typeCheckedType;
}

private static CelType adaptStructType(StructType typeOfType) {
String structName = typeOfType.name();
CelType newTypeOfType;
if (structName.equals(SimpleType.DURATION.name())) {
newTypeOfType = SimpleType.DURATION;
} else if (structName.equals(SimpleType.TIMESTAMP.name())) {
newTypeOfType = SimpleType.TIMESTAMP;
} else {
// Coerces ProtoMessageTypeProvider to be a struct type reference for accurate
// equality tests.
// In the future, we can plumb ProtoMessageTypeProvider through the runtime to retain
// ProtoMessageType here.
newTypeOfType = StructTypeReference.create(typeOfType.name());
}
return newTypeOfType;
}

private CelTypeResolver() {}
}
49 changes: 20 additions & 29 deletions runtime/src/main/java/dev/cel/runtime/DefaultInterpreter.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,8 @@

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import dev.cel.expr.Value;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
Expand DownExpand Up@@ -53,26 +55,6 @@
/**
* Default implementation of the CEL interpreter.
*
* <p>Use as in:
*
* <pre>
* MessageFactory messageFactory = new LinkedMessageFactory();
* RuntimeTypeProvider typeProvider = new DescriptorMessageProvider(messageFactory);
* Dispatcher dispatcher = DefaultDispatcher.create();
* Interpreter interpreter = new DefaultInterpreter(typeProvider, dispatcher);
* Interpretable interpretable = interpreter.createInterpretable(checkedExpr);
* Object result = interpretable.eval(Activation.of("name", value));
* </pre>
*
* <p>Extensions functions can be added in addition to standard functions to the dispatcher as
* needed.
*
* <p>Note: {MessageFactory} instances may be combined using the {@link
* MessageFactory.CombinedMessageFactory}.
*
* <p>Note: On Android, the {@code DescriptorMessageProvider} is not supported as proto lite does
* not support descriptors. Instead, implement the {@code MessageProvider} interface directly.
*
* <p>CEL Library Internals. Do Not Use.
*/
@ThreadSafe
Expand DownExpand Up@@ -117,8 +99,8 @@ static IntermediateResult create(Object value) {
*/
public DefaultInterpreter(
RuntimeTypeProvider typeProvider, Dispatcher dispatcher, CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher);
this.celOptions = celOptions;
}

Expand All@@ -141,11 +123,11 @@ private static final class DefaultInterpretable
Dispatcher dispatcher,
CelAbstractSyntaxTree ast,
CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher).immutableCopy();
this.ast = Preconditions.checkNotNull(ast);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher).immutableCopy();
this.ast = checkNotNull(ast);
this.metadata = new DefaultMetadata(ast);
this.celOptions = Preconditions.checkNotNull(celOptions);
this.celOptions = checkNotNull(celOptions);
}

@Override
Expand DownExpand Up@@ -278,7 +260,10 @@ private IntermediateResult resolveIdent(ExecutionFrame frame, CelExpr expr, Stri
// Check whether the type exists in the type check map as a 'type'.
Optional<CelType> checkedType = ast.getType(expr.id());
if (checkedType.isPresent() && checkedType.get().kind() == CelKind.TYPE) {
Object typeValue = typeProvider.adaptType(checkedType.get());
Object typeValue =
celOptions.adaptRuntimeTypeValueToNativeType()
? CelTypeResolver.adaptType(checkedType.get())
: typeProvider.adaptType(checkedType.get());
return IntermediateResult.create(typeValue);
}

Expand DownExpand Up@@ -658,8 +643,14 @@ private IntermediateResult evalType(ExecutionFrame frame, CelCall callExpr)
.setLocation(metadata, typeExprArg.id())
.build());

Value checkedTypeValue = typeProvider.adaptType(checkedType);
Object typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
Object typeValue;
if (celOptions.adaptRuntimeTypeValueToNativeType()) {
CelType checkedTypeValue = CelTypeResolver.adaptType(checkedType);
typeValue = CelTypeResolver.resolveObjectType(argResult.value(), checkedTypeValue);
} else {
Value checkedTypeValue = typeProvider.adaptType(checkedType);
typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
}
return IntermediateResult.create(typeValue);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,9 +42,12 @@
* by the CEL standard environment.
*
* <p>CEL Library Internals. Do Not Use.
*
* @deprecated Use {@code CelTypeResolver} instead.
*/
@Immutable
@Internal
@Deprecated
public final class StandardTypeResolver implements TypeResolver {

/**
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
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: 11 additions & 0 deletions common/src/main/java/dev/cel/common/CelOptions.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,6 +109,8 @@ public enum ProtoUnsetFieldOptions {

public abstract ProtoUnsetFieldOptions fromProtoUnsetFieldOption();

public abstract boolean adaptRuntimeTypeValueToNativeType();

public abstract boolean enableStringConversion();

public abstract boolean enableStringConcatenation();
Expand DownExpand Up@@ -209,6 +211,7 @@ public static Builder newBuilder() {
.comprehensionMaxIterations(-1)
.unwrapWellKnownTypesOnFunctionDispatch(true)
.fromProtoUnsetFieldOption(ProtoUnsetFieldOptions.BIND_DEFAULT)
.adaptRuntimeTypeValueToNativeType(false)
.enableStringConversion(true)
.enableStringConcatenation(true)
.enableListConcatenation(true)
Expand DownExpand Up@@ -516,6 +519,14 @@ public abstract static class Builder {
*/
public abstract Builder fromProtoUnsetFieldOption(ProtoUnsetFieldOptions value);

/**
* If enabled, result of the type function call `type(foo)` will be evaluated as a native-type
* equivalent {@code CelType} instead of the protobuf type equivalent from {value.proto}.
*
* <p>This is a temporary flag for migration purposes, and will be removed in the near future.
*/
public abstract Builder adaptRuntimeTypeValueToNativeType(boolean value);

/**
* Enables string() overloads for the runtime. This option exists to maintain parity with
* cel-cpp interpreter options.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,6 +44,7 @@
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.TypeType;
import dev.cel.compiler.CelCompilerFactory;
import dev.cel.extensions.CelExtensions;
import dev.cel.extensions.CelOptionalLibrary;
Expand DownExpand Up@@ -88,6 +89,7 @@ private static TypeRegistry newDefaultTypeRegistry() {
CelOptions.current()
.enableTimestampEpoch(true)
.enableUnsignedLongs(true)
.adaptRuntimeTypeValueToNativeType(true)
.enableHeterogeneousNumericComparisons(true)
.enableProtoDifferencerEquality(true)
.enableOptionalSyntax(true)
Expand DownExpand Up@@ -332,6 +334,10 @@ private static Value toValue(Object object, CelType type) throws Exception {
if (object instanceof Message) {
return Value.newBuilder().setObjectValue(Any.pack((Message) object)).build();
}
if (object instanceof TypeType) {
return Value.newBuilder().setTypeValue(((TypeType) object).containingTypeName()).build();
}

throw new IllegalArgumentException(
String.format("Unexpected result type: %s", object.getClass()));
}
Expand Down
1 change: 0 additions & 1 deletion extensions/src/test/java/dev/cel/extensions/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,7 +25,6 @@ java_library(
"//parser:macro",
"//runtime",
"//runtime:interpreter_util",
"@cel_spec//proto/cel/expr:expr_java_proto",
"@cel_spec//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@cel_spec//proto/test/v1/proto2:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import dev.cel.expr.Value;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
Expand All@@ -43,6 +42,7 @@
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import dev.cel.expr.conformance.proto3.TestAllTypes;
import dev.cel.expr.conformance.proto3.TestAllTypes.NestedMessage;
import dev.cel.parser.CelStandardMacro;
Expand DownExpand Up@@ -92,7 +92,11 @@ private enum ConstantTestCases {
private static CelBuilder newCelBuilder() {
return CelFactory.standardCelBuilder()
.setOptions(
CelOptions.current().enableUnsignedLongs(true).enableTimestampEpoch(true).build())
CelOptions.current()
.enableUnsignedLongs(true)
.enableTimestampEpoch(true)
.adaptRuntimeTypeValueToNativeType(true)
.build())
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.setContainer("cel.expr.conformance.proto3")
.addMessageTypes(TestAllTypes.getDescriptor())
Expand DownExpand Up@@ -1439,11 +1443,12 @@ public void optionalFlatMapMacro_withNonIdent_throws() {
@Test
public void optionalType_typeResolution() throws Exception {
Cel cel = newCelBuilder().build();

CelAbstractSyntaxTree ast = cel.compile("optional_type").getAst();

assertThat(cel.createProgram(ast).eval())
.isEqualTo(Value.newBuilder().setTypeValue("optional_type").build());
TypeType optionalRuntimeType = (TypeType) cel.createProgram(ast).eval();

assertThat(optionalRuntimeType.name()).isEqualTo("type");
assertThat(optionalRuntimeType.containingTypeName()).isEqualTo("optional_type");
}

@Test
Expand Down
13 changes: 13 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/BUILD.bazel
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,18 @@ INTERPRETER_SOURCES = [
"UnknownTrackingInterpretable.java",
]

java_library(
name = "cel_type_resolver",
srcs = ["CelTypeResolver.java"],
deps = [
"//common/types",
"//common/types:type_providers",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
],
)

java_library(
name = "base",
srcs = BASE_SOURCES,
Expand DownExpand Up@@ -80,6 +92,7 @@ java_library(
exports = [":base"],
deps = [
":base",
":cel_type_resolver",
":evaluation_listener",
":runtime_helper",
":unknown_attributes",
Expand Down
155 changes: 155 additions & 0 deletions runtime/src/main/java/dev/cel/runtime/CelTypeResolver.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedLong;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.NullValue;
import com.google.protobuf.Timestamp;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.StructType;
import dev.cel.common.types.StructTypeReference;
import dev.cel.common.types.TypeType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* {@code CelTypeResolver} resolves incoming {@link CelType} into {@link TypeType}., either as part
* of a type call (type('foo'), type(1), etc.) or as a type literal (type, int, string, etc.)
*/
@Immutable
final class CelTypeResolver {

// Sentinel runtime value representing the special "type" ident. This ensures following to be
// true: type == type(string) && type == type(type("foo"))
private static final TypeType RUNTIME_TYPE_TYPE = TypeType.create(SimpleType.DYN);

private static final ImmutableMap<Class<?>, TypeType> COMMON_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Boolean.class, TypeType.create(SimpleType.BOOL))
.put(Double.class, TypeType.create(SimpleType.DOUBLE))
.put(Long.class, TypeType.create(SimpleType.INT))
.put(UnsignedLong.class, TypeType.create(SimpleType.UINT))
.put(String.class, TypeType.create(SimpleType.STRING))
.put(NullValue.class, TypeType.create(SimpleType.NULL_TYPE))
.put(Duration.class, TypeType.create(SimpleType.DURATION))
.put(Timestamp.class, TypeType.create(SimpleType.TIMESTAMP))
.put(ArrayList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ImmutableList.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(HashMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(ImmutableMap.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.put(Optional.class, TypeType.create(OptionalType.create(SimpleType.DYN)))
.buildOrThrow();

private static final ImmutableMap<Class<?>, TypeType> EXTENDABLE_TYPES =
ImmutableMap.<Class<?>, TypeType>builder()
.put(Collection.class, TypeType.create(ListType.create(SimpleType.DYN)))
.put(ByteString.class, TypeType.create(SimpleType.BYTES))
.put(Map.class, TypeType.create(MapType.create(SimpleType.DYN, SimpleType.DYN)))
.buildOrThrow();

/** Adapt the type-checked {@link CelType} into a runtime type value {@link TypeType}. */
static TypeType adaptType(CelType typeCheckedType) {
checkNotNull(typeCheckedType);

switch (typeCheckedType.kind()) {
case TYPE:
CelType typeOfType = ((TypeType) typeCheckedType).type();
switch (typeOfType.kind()) {
case STRUCT:
return TypeType.create(adaptStructType((StructType) typeOfType));
default:
return (TypeType) typeCheckedType;
}
case UNSPECIFIED:
throw new IllegalArgumentException("Unsupported CelType kind: " + typeCheckedType.kind());
default:
return TypeType.create(typeCheckedType);
}
}

/** Resolve the CEL type of the {@code obj}. */
static TypeType resolveObjectType(Object obj, CelType typeCheckedType) {
checkNotNull(obj);
if (obj instanceof TypeType) {
return RUNTIME_TYPE_TYPE;
}

Class<?> currentClass = obj.getClass();
TypeType runtimeType = COMMON_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

if (obj instanceof MessageOrBuilder) {
MessageOrBuilder msg = (MessageOrBuilder) obj;
// TODO: Replace with CelLiteDescriptor
return TypeType.create(StructTypeReference.create(msg.getDescriptorForType().getFullName()));
}

// Handle types that the client may have extended.
while (currentClass != null) {
runtimeType = EXTENDABLE_TYPES.get(currentClass);
if (runtimeType != null) {
return runtimeType;
}

// Check interfaces
for (Class<?> interfaceClass : currentClass.getInterfaces()) {
runtimeType = EXTENDABLE_TYPES.get(interfaceClass);
if (runtimeType != null) {
return runtimeType;
}
}
currentClass = currentClass.getSuperclass();
}

// This is an opaque type, or something CEL doesn't know about.
return (TypeType) typeCheckedType;
}

private static CelType adaptStructType(StructType typeOfType) {
String structName = typeOfType.name();
CelType newTypeOfType;
if (structName.equals(SimpleType.DURATION.name())) {
newTypeOfType = SimpleType.DURATION;
} else if (structName.equals(SimpleType.TIMESTAMP.name())) {
newTypeOfType = SimpleType.TIMESTAMP;
} else {
// Coerces ProtoMessageTypeProvider to be a struct type reference for accurate
// equality tests.
// In the future, we can plumb ProtoMessageTypeProvider through the runtime to retain
// ProtoMessageType here.
newTypeOfType = StructTypeReference.create(typeOfType.name());
}
return newTypeOfType;
}

private CelTypeResolver() {}
}
49 changes: 20 additions & 29 deletions runtime/src/main/java/dev/cel/runtime/DefaultInterpreter.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,6 +14,8 @@

package dev.cel.runtime;

import static com.google.common.base.Preconditions.checkNotNull;

import dev.cel.expr.Value;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
Expand DownExpand Up@@ -53,26 +55,6 @@
/**
* Default implementation of the CEL interpreter.
*
* <p>Use as in:
*
* <pre>
* MessageFactory messageFactory = new LinkedMessageFactory();
* RuntimeTypeProvider typeProvider = new DescriptorMessageProvider(messageFactory);
* Dispatcher dispatcher = DefaultDispatcher.create();
* Interpreter interpreter = new DefaultInterpreter(typeProvider, dispatcher);
* Interpretable interpretable = interpreter.createInterpretable(checkedExpr);
* Object result = interpretable.eval(Activation.of("name", value));
* </pre>
*
* <p>Extensions functions can be added in addition to standard functions to the dispatcher as
* needed.
*
* <p>Note: {MessageFactory} instances may be combined using the {@link
* MessageFactory.CombinedMessageFactory}.
*
* <p>Note: On Android, the {@code DescriptorMessageProvider} is not supported as proto lite does
* not support descriptors. Instead, implement the {@code MessageProvider} interface directly.
*
* <p>CEL Library Internals. Do Not Use.
*/
@ThreadSafe
Expand DownExpand Up@@ -117,8 +99,8 @@ static IntermediateResult create(Object value) {
*/
public DefaultInterpreter(
RuntimeTypeProvider typeProvider, Dispatcher dispatcher, CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher);
this.celOptions = celOptions;
}

Expand All@@ -141,11 +123,11 @@ private static final class DefaultInterpretable
Dispatcher dispatcher,
CelAbstractSyntaxTree ast,
CelOptions celOptions) {
this.typeProvider = Preconditions.checkNotNull(typeProvider);
this.dispatcher = Preconditions.checkNotNull(dispatcher).immutableCopy();
this.ast = Preconditions.checkNotNull(ast);
this.typeProvider = checkNotNull(typeProvider);
this.dispatcher = checkNotNull(dispatcher).immutableCopy();
this.ast = checkNotNull(ast);
this.metadata = new DefaultMetadata(ast);
this.celOptions = Preconditions.checkNotNull(celOptions);
this.celOptions = checkNotNull(celOptions);
}

@Override
Expand DownExpand Up@@ -278,7 +260,10 @@ private IntermediateResult resolveIdent(ExecutionFrame frame, CelExpr expr, Stri
// Check whether the type exists in the type check map as a 'type'.
Optional<CelType> checkedType = ast.getType(expr.id());
if (checkedType.isPresent() && checkedType.get().kind() == CelKind.TYPE) {
Object typeValue = typeProvider.adaptType(checkedType.get());
Object typeValue =
celOptions.adaptRuntimeTypeValueToNativeType()
? CelTypeResolver.adaptType(checkedType.get())
: typeProvider.adaptType(checkedType.get());
return IntermediateResult.create(typeValue);
}

Expand DownExpand Up@@ -658,8 +643,14 @@ private IntermediateResult evalType(ExecutionFrame frame, CelCall callExpr)
.setLocation(metadata, typeExprArg.id())
.build());

Value checkedTypeValue = typeProvider.adaptType(checkedType);
Object typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
Object typeValue;
if (celOptions.adaptRuntimeTypeValueToNativeType()) {
CelType checkedTypeValue = CelTypeResolver.adaptType(checkedType);
typeValue = CelTypeResolver.resolveObjectType(argResult.value(), checkedTypeValue);
} else {
Value checkedTypeValue = typeProvider.adaptType(checkedType);
typeValue = typeProvider.resolveObjectType(argResult.value(), checkedTypeValue);
}
return IntermediateResult.create(typeValue);
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -42,9 +42,12 @@
* by the CEL standard environment.
*
* <p>CEL Library Internals. Do Not Use.
*
* @deprecated Use {@code CelTypeResolver} instead.
*/
@Immutable
@Internal
@Deprecated
public final class StandardTypeResolver implements TypeResolver {

/**
Expand Down
Loading