Skip to content
Open
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
101 changes: 101 additions & 0 deletions codelab/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, ?> 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.
4 changes: 4 additions & 0 deletions codelab/src/main/codelab/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
216 changes: 216 additions & 0 deletions codelab/src/main/codelab/Exercise10.java
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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<CelType> types() {
return ImmutableList.of(ADDRESS_TYPE, ADDRESS_MATCHER_TYPE);
}

@Override
public Optional<CelType> 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<String, ?> 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<String> 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<String> 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);
}
}
}
3 changes: 3 additions & 0 deletions codelab/src/main/codelab/solutions/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down
Loading
Loading