diff --git a/codelab/README.md b/codelab/README.md index 00d7f729e..1d2fee9df 100644 --- a/codelab/README.md +++ b/codelab/README.md @@ -1673,3 +1673,104 @@ private static final CelValidator CEL_VALIDATOR = ``` Re-run the test to confirm that all tests pass. + +## Custom Types + +### Exercise 10: Custom Types + +Most users extend the type system by introducing new protobuf types to the CEL +environment. CEL has well-defined rules for mapping protobuf messages to struct +types so this is typically the simplest approach. + +If you have a use case where the data type is not represented as a proto, there +are two type kinds that can be introduced: + +- `struct`: an object with structured fields +- `opaque`: a type that is only meaningful as the input or output of an + extension function. + +In CEL-Java, custom non-proto types are represented as `OpaqueType` at compile +time and `OpaqueValue` at runtime. The recommended way to implement a custom +opaque type is **Direct Extension**, where an immutable domain class extends +`OpaqueValue`, returns `this` from `value()`, and returns its corresponding +`OpaqueType` from `celType()`. + +Open `Exercise10.java`, where two custom opaque types (`net.Address` and +`net.AddressMatcher`), their `CelTypeProvider` (`NETWORK_TYPE_PROVIDER`), and +their `OpaqueValue` implementations (`Address` and `AddressMatcher`) are +defined. + +Run the test: + +```sh +blaze test --test_output=errors //third_party/java/cel/codelab/src/test/codelab:Exercise10Test +``` + +You should see the tests failing with compilation errors because `ip`, the +custom types, and the network functions (`net.parseAddress`, +`net.parseAddressMatcher`, and `containsAddress`) have not yet been declared on +the compiler or bound on the runtime. + +First, update `compile` in `Exercise10.java` to register +`NETWORK_TYPE_PROVIDER`, declare `ip` and the type identifiers (`net.Address` +and `net.AddressMatcher`), and declare the extension functions: + +```java +CelAbstractSyntaxTree compile(String expression) throws CelValidationException { + CelCompiler celCompiler = + CelCompilerFactory.standardCelCompilerBuilder() + .setResultType(SimpleType.BOOL) + .setTypeProvider(NETWORK_TYPE_PROVIDER) + .addVar("ip", SimpleType.STRING) + .addVar("net.Address", TypeType.create(ADDRESS_TYPE)) + .addVar("net.AddressMatcher", TypeType.create(ADDRESS_MATCHER_TYPE)) + .addFunctionDeclarations( + newFunctionDeclaration( + "net.parseAddress", + newGlobalOverload( + "net_parseAddress_string", ADDRESS_TYPE, SimpleType.STRING)), + newFunctionDeclaration( + "net.parseAddressMatcher", + newGlobalOverload( + "net_parseAddressMatcher_string", + ADDRESS_MATCHER_TYPE, + SimpleType.STRING)), + newFunctionDeclaration( + "containsAddress", + newMemberOverload( + "net_AddressMatcher_containsAddress_net_Address", + SimpleType.BOOL, + ADDRESS_MATCHER_TYPE, + ADDRESS_TYPE))) + .build(); + + return celCompiler.compile(expression).getAst(); +} +``` + +Next, update `eval` in `Exercise10.java` to register `NETWORK_TYPE_PROVIDER` and +bind the function implementations: + +```java +Object eval(CelAbstractSyntaxTree ast, Map parameterValues) + throws CelEvaluationException { + CelRuntime celRuntime = + CelRuntimeFactory.plannerRuntimeBuilder() + .setTypeProvider(NETWORK_TYPE_PROVIDER) + .addFunctionBindings( + CelFunctionBinding.from( + "net_parseAddress_string", String.class, Address::parse), + CelFunctionBinding.from( + "net_parseAddressMatcher_string", String.class, AddressMatcher::parse), + CelFunctionBinding.from( + "net_AddressMatcher_containsAddress_net_Address", + AddressMatcher.class, + Address.class, + AddressMatcher::containsAddress)) + .build(); + + return celRuntime.createProgram(ast).eval(parameterValues); +} +``` + +Re-run the unit tests to confirm that all test cases pass. diff --git a/codelab/src/main/codelab/BUILD.bazel b/codelab/src/main/codelab/BUILD.bazel index af900769c..5476b8ff1 100644 --- a/codelab/src/main/codelab/BUILD.bazel +++ b/codelab/src/main/codelab/BUILD.bazel @@ -19,6 +19,8 @@ java_library( "//common/navigation", # unuseddeps: keep "//common/types", # unuseddeps: keep "//common/types:type_providers", # unuseddeps: keep + "//common/values", # unuseddeps: keep + "//common/values:cel_value", # unuseddeps: keep "//compiler", # unuseddeps: keep "//compiler:compiler_builder", # unuseddeps: keep "//optimizer", # unuseddeps: keep @@ -28,6 +30,7 @@ java_library( "//optimizer/optimizers:constant_folding", # unuseddeps: keep "//parser:macro", # unuseddeps: keep "//runtime", # unuseddeps: keep + "//runtime:function_binding", # unuseddeps: keep "//validator", # unuseddeps: keep "//validator:ast_validator", # unuseddeps: keep "//validator:validator_builder", # unuseddeps: keep @@ -36,6 +39,7 @@ java_library( "//validator/validators:regex", # unuseddeps: keep "//validator/validators:timestamp", # unuseddeps: keep "@com_google_googleapis//google/rpc/context:attribute_context_java_proto", # unuseddeps: keep + "@maven//:com_google_errorprone_error_prone_annotations", # unuseddeps: keep "@maven//:com_google_guava_guava", # unuseddeps: keep "@maven//:com_google_protobuf_protobuf_java", # unuseddeps: keep "@maven//:com_google_protobuf_protobuf_java_util", # unuseddeps: keep diff --git a/codelab/src/main/codelab/Exercise10.java b/codelab/src/main/codelab/Exercise10.java new file mode 100644 index 000000000..5a02bec5b --- /dev/null +++ b/codelab/src/main/codelab/Exercise10.java @@ -0,0 +1,216 @@ +// Copyright 2026 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 codelab; + +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableList; +import com.google.errorprone.annotations.Immutable; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.CelValidationException; +import dev.cel.common.types.CelType; +import dev.cel.common.types.CelTypeProvider; +import dev.cel.common.types.OpaqueType; +import dev.cel.common.types.SimpleType; +import dev.cel.common.values.OpaqueValue; +import dev.cel.compiler.CelCompiler; +import dev.cel.compiler.CelCompilerFactory; +import dev.cel.runtime.CelEvaluationException; +import dev.cel.runtime.CelRuntime; +import dev.cel.runtime.CelRuntimeFactory; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * Exercise10 demonstrates how to extend the CEL type system with custom opaque types. + * + *

Given a user-supplied IPv4 address string {@code ip}, compile and evaluate CEL expressions + * using two custom opaque types: {@code net.Address} and {@code net.AddressMatcher}. + */ +final class Exercise10 { + private static final OpaqueType ADDRESS_TYPE = OpaqueType.create("net.Address"); + private static final OpaqueType ADDRESS_MATCHER_TYPE = OpaqueType.create("net.AddressMatcher"); + + private static final CelTypeProvider NETWORK_TYPE_PROVIDER = + new CelTypeProvider() { + @Override + public ImmutableList types() { + return ImmutableList.of(ADDRESS_TYPE, ADDRESS_MATCHER_TYPE); + } + + @Override + public Optional findType(String typeName) { + if (typeName.equals(ADDRESS_TYPE.name())) { + return Optional.of(ADDRESS_TYPE); + } + if (typeName.equals(ADDRESS_MATCHER_TYPE.name())) { + return Optional.of(ADDRESS_MATCHER_TYPE); + } + return Optional.empty(); + } + }; + + /** + * Compiles the input expression using the custom network types and functions. + * + * @throws CelValidationException If the expression contains parsing or type-checking errors. + */ + CelAbstractSyntaxTree compile(String expression) throws CelValidationException { + CelCompiler celCompiler = + CelCompilerFactory.standardCelCompilerBuilder() + .setResultType(SimpleType.BOOL) + // Declare the input `ip` variable, custom types, and network functions here. + .build(); + + return celCompiler.compile(expression).getAst(); + } + + /** + * Evaluates the compiled AST with the provided parameter values. + * + * @throws CelEvaluationException If evaluation fails (for example, on an invalid IPv4 address). + */ + Object eval(CelAbstractSyntaxTree ast, Map parameterValues) + throws CelEvaluationException { + CelRuntime celRuntime = + CelRuntimeFactory.plannerRuntimeBuilder() + // Register the custom network types and function bindings here. + .build(); + + return celRuntime.createProgram(ast).eval(parameterValues); + } + + /** Custom opaque value representing an IPv4 address (`net.Address`). */ + @Immutable + static final class Address extends OpaqueValue { + private static final Splitter OCTET_SPLITTER = Splitter.on('.'); + private final int ipv4; + + private Address(int ipv4) { + this.ipv4 = ipv4; + } + + static Address parse(String str) { + List parts = OCTET_SPLITTER.splitToList(str); + if (parts.size() != 4) { + throw new IllegalArgumentException("invalid address: " + str); + } + int ipv4 = 0; + for (String part : parts) { + int octet; + try { + octet = Integer.parseInt(part); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("invalid address: " + str, e); + } + if (octet < 0 || octet > 255) { + throw new IllegalArgumentException("invalid address: " + str); + } + ipv4 = (ipv4 << 8) | octet; + } + return new Address(ipv4); + } + + int ipv4() { + return ipv4; + } + + @Override + public Object value() { + return this; + } + + @Override + public OpaqueType celType() { + return ADDRESS_TYPE; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Address)) { + return false; + } + Address that = (Address) o; + return this.ipv4 == that.ipv4; + } + + @Override + public int hashCode() { + return Integer.hashCode(ipv4); + } + } + + /** Custom opaque value representing an IPv4 address range (`net.AddressMatcher`). */ + @Immutable + static final class AddressMatcher extends OpaqueValue { + private static final Splitter RANGE_SPLITTER = Splitter.on('-'); + private final int minIncl; + private final int maxIncl; + + private AddressMatcher(int minIncl, int maxIncl) { + this.minIncl = minIncl; + this.maxIncl = maxIncl; + } + + static AddressMatcher parse(String str) { + List parts = RANGE_SPLITTER.splitToList(str); + if (parts.size() != 2) { + throw new IllegalArgumentException("invalid address matcher: " + str); + } + Address min = Address.parse(parts.get(0)); + Address max = Address.parse(parts.get(1)); + if (Integer.compareUnsigned(min.ipv4(), max.ipv4()) > 0) { + throw new IllegalArgumentException("invalid address matcher: " + str); + } + return new AddressMatcher(min.ipv4(), max.ipv4()); + } + + boolean containsAddress(Address address) { + return Integer.compareUnsigned(address.ipv4(), minIncl) >= 0 + && Integer.compareUnsigned(address.ipv4(), maxIncl) <= 0; + } + + @Override + public Object value() { + return this; + } + + @Override + public OpaqueType celType() { + return ADDRESS_MATCHER_TYPE; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof AddressMatcher)) { + return false; + } + AddressMatcher that = (AddressMatcher) o; + return this.minIncl == that.minIncl && this.maxIncl == that.maxIncl; + } + + @Override + public int hashCode() { + return Objects.hash(minIncl, maxIncl); + } + } +} diff --git a/codelab/src/main/codelab/solutions/BUILD.bazel b/codelab/src/main/codelab/solutions/BUILD.bazel index eae465fa7..3087d6746 100644 --- a/codelab/src/main/codelab/solutions/BUILD.bazel +++ b/codelab/src/main/codelab/solutions/BUILD.bazel @@ -20,6 +20,8 @@ java_library( "//common/navigation", "//common/types", "//common/types:type_providers", + "//common/values", + "//common/values:cel_value", "//compiler", "//compiler:compiler_builder", "//optimizer", @@ -38,6 +40,7 @@ java_library( "//validator/validators:regex", "//validator/validators:timestamp", "@com_google_googleapis//google/rpc/context:attribute_context_java_proto", + "@maven//:com_google_errorprone_error_prone_annotations", "@maven//:com_google_guava_guava", "@maven//:com_google_protobuf_protobuf_java", "@maven//:com_google_protobuf_protobuf_java_util", diff --git a/codelab/src/main/codelab/solutions/Exercise10.java b/codelab/src/main/codelab/solutions/Exercise10.java new file mode 100644 index 000000000..a669617c7 --- /dev/null +++ b/codelab/src/main/codelab/solutions/Exercise10.java @@ -0,0 +1,249 @@ +// Copyright 2026 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 codelab.solutions; + +import static dev.cel.common.CelFunctionDecl.newFunctionDeclaration; +import static dev.cel.common.CelOverloadDecl.newGlobalOverload; +import static dev.cel.common.CelOverloadDecl.newMemberOverload; + +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableList; +import com.google.errorprone.annotations.Immutable; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.common.CelValidationException; +import dev.cel.common.types.CelType; +import dev.cel.common.types.CelTypeProvider; +import dev.cel.common.types.OpaqueType; +import dev.cel.common.types.SimpleType; +import dev.cel.common.types.TypeType; +import dev.cel.common.values.OpaqueValue; +import dev.cel.compiler.CelCompiler; +import dev.cel.compiler.CelCompilerFactory; +import dev.cel.runtime.CelEvaluationException; +import dev.cel.runtime.CelFunctionBinding; +import dev.cel.runtime.CelRuntime; +import dev.cel.runtime.CelRuntimeFactory; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * Exercise10 demonstrates how to extend the CEL type system with custom opaque types. + * + *

Given a user-supplied IPv4 address string {@code ip}, compile and evaluate CEL expressions + * using two custom opaque types: {@code net.Address} and {@code net.AddressMatcher}. + */ +final class Exercise10 { + private static final OpaqueType ADDRESS_TYPE = OpaqueType.create("net.Address"); + private static final OpaqueType ADDRESS_MATCHER_TYPE = OpaqueType.create("net.AddressMatcher"); + + private static final CelTypeProvider NETWORK_TYPE_PROVIDER = + new CelTypeProvider() { + @Override + public ImmutableList types() { + return ImmutableList.of(ADDRESS_TYPE, ADDRESS_MATCHER_TYPE); + } + + @Override + public Optional findType(String typeName) { + if (typeName.equals(ADDRESS_TYPE.name())) { + return Optional.of(ADDRESS_TYPE); + } + if (typeName.equals(ADDRESS_MATCHER_TYPE.name())) { + return Optional.of(ADDRESS_MATCHER_TYPE); + } + return Optional.empty(); + } + }; + + /** + * Compiles the input expression using the custom network types and functions. + * + * @throws CelValidationException If the expression contains parsing or type-checking errors. + */ + CelAbstractSyntaxTree compile(String expression) throws CelValidationException { + CelCompiler celCompiler = + CelCompilerFactory.standardCelCompilerBuilder() + .setResultType(SimpleType.BOOL) + .setTypeProvider(NETWORK_TYPE_PROVIDER) + .addVar("ip", SimpleType.STRING) + .addVar("net.Address", TypeType.create(ADDRESS_TYPE)) + .addVar("net.AddressMatcher", TypeType.create(ADDRESS_MATCHER_TYPE)) + .addFunctionDeclarations( + newFunctionDeclaration( + "net.parseAddress", + newGlobalOverload("net_parseAddress_string", ADDRESS_TYPE, SimpleType.STRING)), + newFunctionDeclaration( + "net.parseAddressMatcher", + newGlobalOverload( + "net_parseAddressMatcher_string", ADDRESS_MATCHER_TYPE, SimpleType.STRING)), + newFunctionDeclaration( + "containsAddress", + newMemberOverload( + "net_AddressMatcher_containsAddress_net_Address", + SimpleType.BOOL, + ADDRESS_MATCHER_TYPE, + ADDRESS_TYPE))) + .build(); + + return celCompiler.compile(expression).getAst(); + } + + /** + * Evaluates the compiled AST with the provided parameter values. + * + * @throws CelEvaluationException If evaluation fails (for example, on an invalid IPv4 address). + */ + Object eval(CelAbstractSyntaxTree ast, Map parameterValues) + throws CelEvaluationException { + CelRuntime celRuntime = + CelRuntimeFactory.plannerRuntimeBuilder() + .setTypeProvider(NETWORK_TYPE_PROVIDER) + .addFunctionBindings( + CelFunctionBinding.from("net_parseAddress_string", String.class, Address::parse), + CelFunctionBinding.from( + "net_parseAddressMatcher_string", String.class, AddressMatcher::parse), + CelFunctionBinding.from( + "net_AddressMatcher_containsAddress_net_Address", + AddressMatcher.class, + Address.class, + AddressMatcher::containsAddress)) + .build(); + + return celRuntime.createProgram(ast).eval(parameterValues); + } + + /** Custom opaque value representing an IPv4 address (`net.Address`). */ + @Immutable + static final class Address extends OpaqueValue { + private static final Splitter OCTET_SPLITTER = Splitter.on('.'); + private final int ipv4; + + private Address(int ipv4) { + this.ipv4 = ipv4; + } + + static Address parse(String str) { + List parts = OCTET_SPLITTER.splitToList(str); + if (parts.size() != 4) { + throw new IllegalArgumentException("invalid address: " + str); + } + int ipv4 = 0; + for (String part : parts) { + int octet; + try { + octet = Integer.parseInt(part); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("invalid address: " + str, e); + } + if (octet < 0 || octet > 255) { + throw new IllegalArgumentException("invalid address: " + str); + } + ipv4 = (ipv4 << 8) | octet; + } + return new Address(ipv4); + } + + int ipv4() { + return ipv4; + } + + @Override + public Object value() { + return this; + } + + @Override + public OpaqueType celType() { + return ADDRESS_TYPE; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Address)) { + return false; + } + Address that = (Address) o; + return this.ipv4 == that.ipv4; + } + + @Override + public int hashCode() { + return Integer.hashCode(ipv4); + } + } + + /** Custom opaque value representing an IPv4 address range (`net.AddressMatcher`). */ + @Immutable + static final class AddressMatcher extends OpaqueValue { + private static final Splitter RANGE_SPLITTER = Splitter.on('-'); + private final int minIncl; + private final int maxIncl; + + private AddressMatcher(int minIncl, int maxIncl) { + this.minIncl = minIncl; + this.maxIncl = maxIncl; + } + + static AddressMatcher parse(String str) { + List parts = RANGE_SPLITTER.splitToList(str); + if (parts.size() != 2) { + throw new IllegalArgumentException("invalid address matcher: " + str); + } + Address min = Address.parse(parts.get(0)); + Address max = Address.parse(parts.get(1)); + if (Integer.compareUnsigned(min.ipv4(), max.ipv4()) > 0) { + throw new IllegalArgumentException("invalid address matcher: " + str); + } + return new AddressMatcher(min.ipv4(), max.ipv4()); + } + + boolean containsAddress(Address address) { + return Integer.compareUnsigned(address.ipv4(), minIncl) >= 0 + && Integer.compareUnsigned(address.ipv4(), maxIncl) <= 0; + } + + @Override + public Object value() { + return this; + } + + @Override + public OpaqueType celType() { + return ADDRESS_MATCHER_TYPE; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof AddressMatcher)) { + return false; + } + AddressMatcher that = (AddressMatcher) o; + return this.minIncl == that.minIncl && this.maxIncl == that.maxIncl; + } + + @Override + public int hashCode() { + return Objects.hash(minIncl, maxIncl); + } + } +} diff --git a/codelab/src/main/kotlin/codelab/BUILD.bazel b/codelab/src/main/kotlin/codelab/BUILD.bazel new file mode 100644 index 000000000..59e20c057 --- /dev/null +++ b/codelab/src/main/kotlin/codelab/BUILD.bazel @@ -0,0 +1,37 @@ +# Copyright 2026 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. + +load("//tools/build_defs/kotlin:rules.bzl", "kt_jvm_library") + +package( + default_applicable_licenses = [ + "//:license", + ], + default_visibility = ["//codelab:__subpackages__"], +) + +kt_jvm_library( + name = "codelab", + srcs = glob(["*.kt"]), + deps = [ + "//common:cel_ast", + "//common:compiler_common", # unuseddeps: keep + "//common/types", # unuseddeps: keep + "//common/types:type_providers", + "//compiler", # unuseddeps: keep + "//compiler:compiler_builder", # unuseddeps: keep + "//runtime", # unuseddeps: keep + "@com_google_googleapis//google/rpc/context:attribute_context_java_proto", # unuseddeps: keep + ], +) diff --git a/codelab/src/main/kotlin/codelab/Exercise1.kt b/codelab/src/main/kotlin/codelab/Exercise1.kt new file mode 100644 index 000000000..d9cd3f5b5 --- /dev/null +++ b/codelab/src/main/kotlin/codelab/Exercise1.kt @@ -0,0 +1,44 @@ +// Copyright 2026 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 codelab + +import dev.cel.common.CelAbstractSyntaxTree + +/** + * Exercise1 evaluates a simple literal expression: "Hello, World!" + * + * Compile, eval, profit! + */ +internal class Exercise1 { + /** + * Compile the input [expression] and produce an AST. This method parses and type-checks the given + * expression to validate the syntax and type-agreement of the expression. + * + * @throws IllegalArgumentException If the expression is malformed due to syntactic or semantic + * errors. + */ + fun compile(expression: String): CelAbstractSyntaxTree { + throw UnsupportedOperationException("To be implemented") + } + + /** + * Evaluates the compiled AST. + * + * @throws IllegalArgumentException If the compiled expression in AST fails to evaluate. + */ + fun eval(ast: CelAbstractSyntaxTree): Any? { + throw UnsupportedOperationException("To be implemented") + } +} diff --git a/codelab/src/main/kotlin/codelab/Exercise2.kt b/codelab/src/main/kotlin/codelab/Exercise2.kt new file mode 100644 index 000000000..2a3db0ec8 --- /dev/null +++ b/codelab/src/main/kotlin/codelab/Exercise2.kt @@ -0,0 +1,50 @@ +// Copyright 2026 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 codelab + +import dev.cel.common.CelAbstractSyntaxTree +import dev.cel.common.types.CelType + +/** + * Exercise2 shows how to declare and use variables in expressions through two examples: + * - Given a user supplied integer value, test whether the value is negative + * - Given a request of type [com.google.rpc.context.AttributeContext.Request] determine whether a + * specific auth claim is set. + */ +internal class Exercise2 { + + /** + * Compiles the input expression with provided variable information. + * + * @throws IllegalArgumentException If the expression is malformed due to syntactic or semantic + * errors. + */ + fun compile( + expression: String, + variableName: String, + variableType: CelType, + ): CelAbstractSyntaxTree { + throw UnsupportedOperationException("To be implemented") + } + + /** + * Evaluates the compiled AST with the user provided parameter values. + * + * @throws IllegalArgumentException If the compiled expression in AST fails to evaluate. + */ + fun eval(ast: CelAbstractSyntaxTree, parameterValues: Map): Any? { + throw UnsupportedOperationException("To be implemented") + } +} diff --git a/codelab/src/main/kotlin/codelab/solutions/BUILD.bazel b/codelab/src/main/kotlin/codelab/solutions/BUILD.bazel new file mode 100644 index 000000000..9ccb22635 --- /dev/null +++ b/codelab/src/main/kotlin/codelab/solutions/BUILD.bazel @@ -0,0 +1,37 @@ +# Copyright 2026 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. + +load("//tools/build_defs/kotlin:rules.bzl", "kt_jvm_library") + +package( + default_applicable_licenses = [ + "//:license", + ], + default_visibility = ["//codelab:__subpackages__"], +) + +kt_jvm_library( + name = "solutions", + srcs = glob(["*.kt"]), + deps = [ + "//common:cel_ast", + "//common:compiler_common", + "//common/types", + "//common/types:type_providers", + "//compiler", + "//compiler:compiler_builder", + "//runtime", + "@com_google_googleapis//google/rpc/context:attribute_context_java_proto", + ], +) diff --git a/codelab/src/main/kotlin/codelab/solutions/Exercise1.kt b/codelab/src/main/kotlin/codelab/solutions/Exercise1.kt new file mode 100644 index 000000000..8b89ac061 --- /dev/null +++ b/codelab/src/main/kotlin/codelab/solutions/Exercise1.kt @@ -0,0 +1,85 @@ +// Copyright 2026 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 codelab.solutions + +import dev.cel.common.CelAbstractSyntaxTree +import dev.cel.common.CelValidationException +import dev.cel.common.types.SimpleType +import dev.cel.compiler.CelCompilerFactory +import dev.cel.runtime.CelEvaluationException +import dev.cel.runtime.CelRuntimeFactory + +/** + * Exercise1 evaluates a simple literal expression: "Hello, World!" + * + * Compile, eval, profit! + */ +internal class Exercise1 { + /** + * Compile the input [expression] and produce an AST. This method parses and type-checks the given + * expression to validate the syntax and type-agreement of the expression. + * + * @throws IllegalArgumentException If the expression is malformed due to syntactic or semantic + * errors. + */ + fun compile(expression: String): CelAbstractSyntaxTree { + // Construct a CelCompiler instance. + // "String" is the expected output type for the type-checked expression. + // CelCompiler is immutable and when statically configured can be moved to a companion object + // or top-level property. + val celCompiler = + CelCompilerFactory.standardCelCompilerBuilder().setResultType(SimpleType.STRING).build() + + val parsedAst = + try { + // Parse the expression. + celCompiler.parse(expression).ast + } catch (e: CelValidationException) { + // Report syntactic errors, if present. + throw IllegalArgumentException("Failed to parse expression. Reason: ${e.message}", e) + } + + return try { + // Type-check the expression for correctness. + celCompiler.check(parsedAst).ast + } catch (e: CelValidationException) { + // Report semantic errors, if present. + throw IllegalArgumentException("Failed to type-check expression. Reason: ${e.message}", e) + } + } + + /** + * Evaluates the compiled AST. + * + * @throws IllegalArgumentException If the compiled expression in AST fails to evaluate. + */ + fun eval(ast: CelAbstractSyntaxTree): Any? { + // Construct a CelRuntime instance. + // CelRuntime is immutable just like the compiler and can be moved to a companion object or + // top-level property. + val celRuntime = CelRuntimeFactory.plannerRuntimeBuilder().build() + + return try { + // Plan the program. + val program = celRuntime.createProgram(ast) + + // Evaluate the program without any additional arguments. + program.eval() + } catch (e: CelEvaluationException) { + // Report any evaluation errors, if present. + throw IllegalArgumentException("Evaluation error has occurred. Reason: ${e.message}", e) + } + } +} diff --git a/codelab/src/main/kotlin/codelab/solutions/Exercise2.kt b/codelab/src/main/kotlin/codelab/solutions/Exercise2.kt new file mode 100644 index 000000000..bbe5836b7 --- /dev/null +++ b/codelab/src/main/kotlin/codelab/solutions/Exercise2.kt @@ -0,0 +1,79 @@ +// Copyright 2026 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 codelab.solutions + +import com.google.rpc.context.AttributeContext +import dev.cel.common.CelAbstractSyntaxTree +import dev.cel.common.CelValidationException +import dev.cel.common.types.CelType +import dev.cel.common.types.SimpleType +import dev.cel.compiler.CelCompilerFactory +import dev.cel.runtime.CelEvaluationException +import dev.cel.runtime.CelRuntimeFactory + +/** + * Exercise2 shows how to declare and use variables in expressions through two examples: + * - Given a user supplied integer value, test whether the value is negative + * - Given a request of type [com.google.rpc.context.AttributeContext.Request] determine whether a + * specific auth claim is set. + */ +internal class Exercise2 { + + /** + * Compiles the input expression with provided variable information. + * + * @throws IllegalArgumentException If the expression is malformed due to syntactic or semantic + * errors. + */ + fun compile( + expression: String, + variableName: String, + variableType: CelType, + ): CelAbstractSyntaxTree { + // Compile (parse + type-check) the expression. + // CelCompiler is immutable and when statically configured can be moved to a companion object + // or top-level property. + val celCompiler = + CelCompilerFactory.standardCelCompilerBuilder() + .addVar(variableName, variableType) + .addMessageTypes(AttributeContext.Request.getDescriptor()) + .setResultType(SimpleType.BOOL) + .build() + return try { + celCompiler.compile(expression).ast + } catch (e: CelValidationException) { + throw IllegalArgumentException("Failed to compile expression. Reason: ${e.message}", e) + } + } + + /** + * Evaluates the compiled AST with the user provided parameter values. + * + * @throws IllegalArgumentException If the compiled expression in AST fails to evaluate. + */ + fun eval(ast: CelAbstractSyntaxTree, parameterValues: Map): Any? { + val celRuntime = CelRuntimeFactory.plannerRuntimeBuilder().build() + return try { + val program = celRuntime.createProgram(ast) + + // Evaluate using the provided map as input variables (key: variableName, value: + // variableValue). + program.eval(parameterValues) + } catch (e: CelEvaluationException) { + // Report any evaluation errors, if present. + throw IllegalArgumentException("Evaluation error has occurred. Reason: ${e.message}", e) + } + } +} diff --git a/codelab/src/test/codelab/BUILD.bazel b/codelab/src/test/codelab/BUILD.bazel index fb3f1e235..d89766069 100644 --- a/codelab/src/test/codelab/BUILD.bazel +++ b/codelab/src/test/codelab/BUILD.bazel @@ -152,6 +152,22 @@ java_test( ], ) +java_test( + name = "Exercise10Test", + srcs = ["Exercise10Test.java"], + tags = ["notap"], + test_class = "codelab.Exercise10Test", + deps = [ + "//:java_truth", + "//codelab", + "//common:cel_ast", + "//runtime", + "@maven//:com_google_guava_guava", + "@maven//:com_google_testparameterinjector_test_parameter_injector", + "@maven//:junit_junit", + ], +) + test_suite( name = "exercise_test_suite", tags = ["notap"], diff --git a/codelab/src/test/codelab/Exercise10Test.java b/codelab/src/test/codelab/Exercise10Test.java new file mode 100644 index 000000000..f7448f273 --- /dev/null +++ b/codelab/src/test/codelab/Exercise10Test.java @@ -0,0 +1,77 @@ +// Copyright 2026 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 codelab; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + +import com.google.common.collect.ImmutableMap; +import com.google.testing.junit.testparameterinjector.TestParameterInjector; +import com.google.testing.junit.testparameterinjector.TestParameters; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.runtime.CelEvaluationException; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(TestParameterInjector.class) +public final class Exercise10Test { + private final Exercise10 exercise10 = new Exercise10(); + + @Test + @TestParameters("{ip: '8.8.4.4', expectedResult: true}") + @TestParameters("{ip: '8.8.8.8', expectedResult: false}") + public void evaluate_ipInRange(String ip, boolean expectedResult) throws Exception { + CelAbstractSyntaxTree ast = + exercise10.compile( + "net.parseAddressMatcher('8.8.4.0-8.8.4.255').containsAddress(net.parseAddress(ip))"); + + Object result = exercise10.eval(ast, ImmutableMap.of("ip", ip)); + + assertThat(result).isEqualTo(expectedResult); + } + + @Test + @TestParameters("{ip: '8.8.4.4', expectedResult: true}") + @TestParameters("{ip: '8.8.8.8', expectedResult: false}") + public void evaluate_ipEquality(String ip, boolean expectedResult) throws Exception { + CelAbstractSyntaxTree ast = + exercise10.compile("net.parseAddress('8.8.4.4') == net.parseAddress(ip)"); + + Object result = exercise10.eval(ast, ImmutableMap.of("ip", ip)); + + assertThat(result).isEqualTo(expectedResult); + } + + @Test + public void evaluate_opaqueTypeIdentity() throws Exception { + CelAbstractSyntaxTree ast = exercise10.compile("type(net.parseAddress(ip)) == net.Address"); + + Object result = exercise10.eval(ast, ImmutableMap.of("ip", "8.8.4.4")); + + assertThat(result).isEqualTo(true); + } + + @Test + public void evaluate_invalidIp_throwsEvaluationException() throws Exception { + CelAbstractSyntaxTree ast = + exercise10.compile("net.parseAddress('8.8.4.4') == net.parseAddress(ip)"); + + CelEvaluationException exception = + assertThrows( + CelEvaluationException.class, () -> exercise10.eval(ast, ImmutableMap.of("ip", "8.8"))); + + assertThat(exception).hasCauseThat().hasMessageThat().contains("invalid address"); + } +} diff --git a/codelab/src/test/codelab/solutions/BUILD.bazel b/codelab/src/test/codelab/solutions/BUILD.bazel index 9eebbc3f4..9444f9670 100644 --- a/codelab/src/test/codelab/solutions/BUILD.bazel +++ b/codelab/src/test/codelab/solutions/BUILD.bazel @@ -142,3 +142,18 @@ java_test( "@maven//:junit_junit", ], ) + +java_test( + name = "Exercise10Test", + srcs = ["Exercise10Test.java"], + test_class = "codelab.solutions.Exercise10Test", + deps = [ + "//:java_truth", + "//codelab:solutions", + "//common:cel_ast", + "//runtime", + "@maven//:com_google_guava_guava", + "@maven//:com_google_testparameterinjector_test_parameter_injector", + "@maven//:junit_junit", + ], +) diff --git a/codelab/src/test/codelab/solutions/Exercise10Test.java b/codelab/src/test/codelab/solutions/Exercise10Test.java new file mode 100644 index 000000000..cdbb45b84 --- /dev/null +++ b/codelab/src/test/codelab/solutions/Exercise10Test.java @@ -0,0 +1,77 @@ +// Copyright 2026 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 codelab.solutions; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; + +import com.google.common.collect.ImmutableMap; +import com.google.testing.junit.testparameterinjector.TestParameterInjector; +import com.google.testing.junit.testparameterinjector.TestParameters; +import dev.cel.common.CelAbstractSyntaxTree; +import dev.cel.runtime.CelEvaluationException; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(TestParameterInjector.class) +public final class Exercise10Test { + private final Exercise10 exercise10 = new Exercise10(); + + @Test + @TestParameters("{ip: '8.8.4.4', expectedResult: true}") + @TestParameters("{ip: '8.8.8.8', expectedResult: false}") + public void evaluate_ipInRange(String ip, boolean expectedResult) throws Exception { + CelAbstractSyntaxTree ast = + exercise10.compile( + "net.parseAddressMatcher('8.8.4.0-8.8.4.255').containsAddress(net.parseAddress(ip))"); + + Object result = exercise10.eval(ast, ImmutableMap.of("ip", ip)); + + assertThat(result).isEqualTo(expectedResult); + } + + @Test + @TestParameters("{ip: '8.8.4.4', expectedResult: true}") + @TestParameters("{ip: '8.8.8.8', expectedResult: false}") + public void evaluate_ipEquality(String ip, boolean expectedResult) throws Exception { + CelAbstractSyntaxTree ast = + exercise10.compile("net.parseAddress('8.8.4.4') == net.parseAddress(ip)"); + + Object result = exercise10.eval(ast, ImmutableMap.of("ip", ip)); + + assertThat(result).isEqualTo(expectedResult); + } + + @Test + public void evaluate_opaqueTypeIdentity() throws Exception { + CelAbstractSyntaxTree ast = exercise10.compile("type(net.parseAddress(ip)) == net.Address"); + + Object result = exercise10.eval(ast, ImmutableMap.of("ip", "8.8.4.4")); + + assertThat(result).isEqualTo(true); + } + + @Test + public void evaluate_invalidIp_throwsEvaluationException() throws Exception { + CelAbstractSyntaxTree ast = + exercise10.compile("net.parseAddress('8.8.4.4') == net.parseAddress(ip)"); + + CelEvaluationException exception = + assertThrows( + CelEvaluationException.class, () -> exercise10.eval(ast, ImmutableMap.of("ip", "8.8"))); + + assertThat(exception).hasCauseThat().hasMessageThat().contains("invalid address"); + } +} diff --git a/codelab/src/test/kotlin/codelab/BUILD.bazel b/codelab/src/test/kotlin/codelab/BUILD.bazel new file mode 100644 index 000000000..159892da6 --- /dev/null +++ b/codelab/src/test/kotlin/codelab/BUILD.bazel @@ -0,0 +1,55 @@ +# Copyright 2026 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. + +load("//tools/build_defs/kotlin:rules.bzl", "kt_jvm_test") + +package(default_applicable_licenses = [ + "//:license", +]) + +kt_jvm_test( + name = "Exercise1Test", + srcs = ["Exercise1Test.kt"], + tags = ["notap"], + test_class = "codelab.Exercise1Test", + deps = [ + "//:java_truth", + "//codelab/src/main/kotlin/codelab", + "//compiler", + "//compiler:compiler_builder", + "//third_party/kotlin/kotlin:kotlin_test", + "@maven//:junit_junit", + ], +) + +kt_jvm_test( + name = "Exercise2Test", + srcs = ["Exercise2Test.kt"], + tags = ["notap"], + test_class = "codelab.Exercise2Test", + deps = [ + "//:java_truth", + "//codelab/src/main/kotlin/codelab", + "//common/types", + "@com_google_googleapis//google/rpc/context:attribute_context_java_proto", + "@maven//:com_google_protobuf_protobuf_java", + "@maven//:com_google_testparameterinjector_test_parameter_injector", + "@maven//:junit_junit", + ], +) + +test_suite( + name = "exercise_test_suite", + tags = ["notap"], +) diff --git a/codelab/src/test/kotlin/codelab/Exercise1Test.kt b/codelab/src/test/kotlin/codelab/Exercise1Test.kt new file mode 100644 index 000000000..1d0e25ac3 --- /dev/null +++ b/codelab/src/test/kotlin/codelab/Exercise1Test.kt @@ -0,0 +1,70 @@ +// Copyright 2026 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 codelab + +import com.google.common.truth.Truth.assertThat +import dev.cel.compiler.CelCompilerFactory +import kotlin.test.assertFailsWith +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class Exercise1Test { + private val exercise1 = Exercise1() + + @Test + fun compile_stringExpression_parseSuccess() { + val ast = exercise1.compile(TEST_EXPRESSION) + assertThat(ast).isNotNull() + } + + @Test + fun compile_stringExpression_typecheckSuccess() { + val ast = exercise1.compile(TEST_EXPRESSION) + assertThat(ast.isChecked).isTrue() + } + + @Test + fun compile_booleanExpression_throwsValidationException() { + val exception = assertFailsWith { exercise1.compile("true == true") } + + assertThat(exception).hasMessageThat().contains("Failed to type-check expression.") + assertThat(exception).hasMessageThat().contains("expected type 'string' but found 'bool'") + } + + @Test + fun evaluate_stringExpression_success() { + val ast = exercise1.compile(TEST_EXPRESSION) + + val evaluatedResult = exercise1.eval(ast) + + assertThat(evaluatedResult).isEqualTo("Hello, World!") + } + + @Test + fun evaluate_divideByZeroExpression_throwsEvaluationException() { + val compiler = CelCompilerFactory.standardCelCompilerBuilder().build() + val ast = compiler.compile("1/0").ast + + val exception = assertFailsWith { exercise1.eval(ast) } + + assertThat(exception).hasMessageThat().contains("evaluation error at :1: / by zero") + } + + private companion object { + const val TEST_EXPRESSION = "'Hello, World!'" + } +} diff --git a/codelab/src/test/kotlin/codelab/Exercise2Test.kt b/codelab/src/test/kotlin/codelab/Exercise2Test.kt new file mode 100644 index 000000000..38a76230b --- /dev/null +++ b/codelab/src/test/kotlin/codelab/Exercise2Test.kt @@ -0,0 +1,65 @@ +// Copyright 2026 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 codelab + +import com.google.common.truth.Truth.assertThat +import com.google.protobuf.Struct +import com.google.protobuf.Value +import com.google.rpc.context.AttributeContext +import com.google.testing.junit.testparameterinjector.TestParameterInjector +import com.google.testing.junit.testparameterinjector.TestParameters +import dev.cel.common.types.SimpleType +import dev.cel.common.types.StructTypeReference +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(TestParameterInjector::class) +class Exercise2Test { + private val exercise2 = Exercise2() + + @Test + @TestParameters("{value: 5, expectedResult: false}") + @TestParameters("{value: -5, expectedResult: true}") + fun evaluate_negativeExpression(value: Long, expectedResult: Boolean) { + val ast = exercise2.compile("value < 0", "value", SimpleType.INT) + + val evaluatedResult = exercise2.eval(ast, mapOf("value" to value)) + assertThat(evaluatedResult).isEqualTo(expectedResult) + } + + @Test + @TestParameters("{group: 'admin', expectedResult: true}") + @TestParameters("{group: 'users', expectedResult: false}") + fun evaluate_requestAuthorization(group: String, expectedResult: Boolean) { + val ast = + exercise2.compile( + "request.auth.claims.group == 'admin'", + "request", + StructTypeReference.create("google.rpc.context.AttributeContext.Request"), + ) + + val auth = + AttributeContext.Auth.newBuilder() + .setPrincipal("user:me@acme.co") + .setClaims( + Struct.newBuilder().putFields("group", Value.newBuilder().setStringValue(group).build()) + ) + .build() + val request = AttributeContext.Request.newBuilder().setAuth(auth).build() + + val evaluatedResult = exercise2.eval(ast, mapOf("request" to request)) + assertThat(evaluatedResult).isEqualTo(expectedResult) + } +} diff --git a/codelab/src/test/kotlin/codelab/solutions/BUILD.bazel b/codelab/src/test/kotlin/codelab/solutions/BUILD.bazel new file mode 100644 index 000000000..2596c17ca --- /dev/null +++ b/codelab/src/test/kotlin/codelab/solutions/BUILD.bazel @@ -0,0 +1,48 @@ +# Copyright 2026 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. + +load("//tools/build_defs/kotlin:rules.bzl", "kt_jvm_test") + +package(default_applicable_licenses = [ + "//:license", +]) + +kt_jvm_test( + name = "Exercise1Test", + srcs = ["Exercise1Test.kt"], + test_class = "codelab.solutions.Exercise1Test", + deps = [ + "//:java_truth", + "//codelab/src/main/kotlin/codelab/solutions", + "//compiler", + "//compiler:compiler_builder", + "//third_party/kotlin/kotlin:kotlin_test", + "@maven//:junit_junit", + ], +) + +kt_jvm_test( + name = "Exercise2Test", + srcs = ["Exercise2Test.kt"], + test_class = "codelab.solutions.Exercise2Test", + deps = [ + "//:java_truth", + "//codelab/src/main/kotlin/codelab/solutions", + "//common/types", + "@com_google_googleapis//google/rpc/context:attribute_context_java_proto", + "@maven//:com_google_protobuf_protobuf_java", + "@maven//:com_google_testparameterinjector_test_parameter_injector", + "@maven//:junit_junit", + ], +) diff --git a/codelab/src/test/kotlin/codelab/solutions/Exercise1Test.kt b/codelab/src/test/kotlin/codelab/solutions/Exercise1Test.kt new file mode 100644 index 000000000..effc1043b --- /dev/null +++ b/codelab/src/test/kotlin/codelab/solutions/Exercise1Test.kt @@ -0,0 +1,70 @@ +// Copyright 2026 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 codelab.solutions + +import com.google.common.truth.Truth.assertThat +import dev.cel.compiler.CelCompilerFactory +import kotlin.test.assertFailsWith +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class Exercise1Test { + private val exercise1 = Exercise1() + + @Test + fun compile_stringExpression_parseSuccess() { + val ast = exercise1.compile(TEST_EXPRESSION) + assertThat(ast).isNotNull() + } + + @Test + fun compile_stringExpression_typecheckSuccess() { + val ast = exercise1.compile(TEST_EXPRESSION) + assertThat(ast.isChecked).isTrue() + } + + @Test + fun compile_booleanExpression_throwsValidationException() { + val exception = assertFailsWith { exercise1.compile("true == true") } + + assertThat(exception).hasMessageThat().contains("Failed to type-check expression.") + assertThat(exception).hasMessageThat().contains("expected type 'string' but found 'bool'") + } + + @Test + fun evaluate_stringExpression_success() { + val ast = exercise1.compile(TEST_EXPRESSION) + + val evaluatedResult = exercise1.eval(ast) + + assertThat(evaluatedResult).isEqualTo("Hello, World!") + } + + @Test + fun evaluate_divideByZeroExpression_throwsEvaluationException() { + val compiler = CelCompilerFactory.standardCelCompilerBuilder().build() + val ast = compiler.compile("1/0").ast + + val exception = assertFailsWith { exercise1.eval(ast) } + + assertThat(exception).hasMessageThat().contains("evaluation error at :1: / by zero") + } + + private companion object { + const val TEST_EXPRESSION = "'Hello, World!'" + } +} diff --git a/codelab/src/test/kotlin/codelab/solutions/Exercise2Test.kt b/codelab/src/test/kotlin/codelab/solutions/Exercise2Test.kt new file mode 100644 index 000000000..421eb11df --- /dev/null +++ b/codelab/src/test/kotlin/codelab/solutions/Exercise2Test.kt @@ -0,0 +1,65 @@ +// Copyright 2026 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 codelab.solutions + +import com.google.common.truth.Truth.assertThat +import com.google.protobuf.Struct +import com.google.protobuf.Value +import com.google.rpc.context.AttributeContext +import com.google.testing.junit.testparameterinjector.TestParameterInjector +import com.google.testing.junit.testparameterinjector.TestParameters +import dev.cel.common.types.SimpleType +import dev.cel.common.types.StructTypeReference +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(TestParameterInjector::class) +class Exercise2Test { + private val exercise2 = Exercise2() + + @Test + @TestParameters("{value: 5, expectedResult: false}") + @TestParameters("{value: -5, expectedResult: true}") + fun evaluate_negativeExpression(value: Long, expectedResult: Boolean) { + val ast = exercise2.compile("value < 0", "value", SimpleType.INT) + + val evaluatedResult = exercise2.eval(ast, mapOf("value" to value)) + assertThat(evaluatedResult).isEqualTo(expectedResult) + } + + @Test + @TestParameters("{group: 'admin', expectedResult: true}") + @TestParameters("{group: 'users', expectedResult: false}") + fun evaluate_requestAuthorization(group: String, expectedResult: Boolean) { + val ast = + exercise2.compile( + "request.auth.claims.group == 'admin'", + "request", + StructTypeReference.create("google.rpc.context.AttributeContext.Request"), + ) + + val auth = + AttributeContext.Auth.newBuilder() + .setPrincipal("user:me@acme.co") + .setClaims( + Struct.newBuilder().putFields("group", Value.newBuilder().setStringValue(group).build()) + ) + .build() + val request = AttributeContext.Request.newBuilder().setAuth(auth).build() + + val evaluatedResult = exercise2.eval(ast, mapOf("request" to request)) + assertThat(evaluatedResult).isEqualTo(expectedResult) + } +}