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
7 changes: 5 additions & 2 deletions bundle/src/main/java/dev/cel/bundle/CelEnvironment.java
Original file line number Diff line number Diff line change
Expand Up @@ -722,9 +722,12 @@ public static TypeDecl create(String name) {

/**
* Parses a type specifier shorthand string (e.g. {@code "list<int>"}, {@code "map<string,
* dyn>"}, {@code "list<~T>"}) into a {@link TypeDecl}.
* dyn>"}, {@code "list<~T>"}) into a {@link TypeDecl}. Type names are resolved later, by {@link
* #toCelType(CelTypeProvider)}.
*
* @throws IllegalArgumentException if {@code typeSpecifier} is malformed
*/
static TypeDecl parse(String typeSpecifier) {
public static TypeDecl parse(String typeSpecifier) {
return TypeSpecifierParser.parse(typeSpecifier);
}

Expand Down
3 changes: 2 additions & 1 deletion verifier/src/main/java/dev/cel/verifier/tools/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,14 @@ java_library(
deps = [
"//:java_jline",
"//bundle:cel",
"//bundle:environment",
"//common:cel_ast",
"//common:compiler_common",
"//common:options",
"//common/internal:cel_descriptor_pools",
"//common/internal:well_known_proto",
"//common/types",
"//common/types:cel_types",
"//common/types:message_type_provider",
"//common/types:type_providers",
"//compiler",
"//compiler:compiler_builder",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,12 +280,11 @@ private static void handleVarCommand(
return;
}
String name = parts[0].trim();
String typeStr = parts[1].trim();
try {
CelType type = VerificationOptions.parseCelType(typeStr);
CelType type = VerificationOptions.parseCelType(parts[1]);
sessionVars.put(name, type);
out.println("Variable declared: " + name + " : " + CelTypes.format(type));
} catch (IllegalArgumentException e) {
} catch (IllegalArgumentException | IllegalStateException e) {
err.println(e.getMessage());
}
}
Expand Down Expand Up @@ -320,7 +319,9 @@ private static void printHelp(String topic, PrintStream out) {
+ " (google.protobuf.*)");
out.println(" - List types: list<T> (e.g., list<int>, list<string>)");
out.println(" - Map types: map<K,V> (e.g., map<string,int>, map<string,string>)");
out.println(" - Optional types: optional<T> (e.g., optional<string>, optional<int>)");
out.println(
" - Optional types: optional_type<T> (e.g., optional_type<string>,"
+ " optional_type<int>)");
out.println(" - Protobuf types: coming soon");
out.println();
out.println("Examples:");
Expand All @@ -330,7 +331,7 @@ private static void printHelp(String topic, PrintStream out) {
out.println(" cel-verifier> :var tags list<string>");
out.println(" cel-verifier> :var created_at timestamp");
out.println(" cel-verifier> :var timeout duration");
out.println(" cel-verifier> :var opt_flag optional<bool>");
out.println(" cel-verifier> :var opt_flag optional_type<bool>");
out.println(" cel-verifier> :var count google.protobuf.Int64Value");
break;
case "unknown":
Expand Down
143 changes: 18 additions & 125 deletions verifier/src/main/java/dev/cel/verifier/tools/VerificationOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,17 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import dev.cel.bundle.CelEnvironment.TypeDecl;
import dev.cel.common.types.CelKind;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.MapType;
import dev.cel.common.types.NullableType;
import dev.cel.common.types.OptionalType;
import dev.cel.common.types.SimpleType;
import dev.cel.common.types.CelTypeProvider;
import dev.cel.common.types.ProtoMessageTypeProvider;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/** Configuration options for CEL verification CLI operations. */
Expand All @@ -43,6 +42,10 @@ enum OutputFormat {
static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10);
static final int DEFAULT_COMPREHENSION_UNROLL_LIMIT = 5;
static final OutputFormat DEFAULT_OUTPUT_FORMAT = OutputFormat.TEXT;
private static final CelTypeProvider EMPTY_TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder().build();
private static final ImmutableSet<CelKind> UNDECLARABLE_KINDS =
Sets.immutableEnumSet(CelKind.NULL_TYPE, CelKind.TYPE, CelKind.TYPE_PARAM);

private final Duration timeout;
private final int comprehensionUnrollLimit;
Expand Down Expand Up @@ -141,130 +144,20 @@ static ImmutableMap<String, CelType> parseVariables(List<String> varSpecs) {
throw new IllegalArgumentException(
"Invalid variable specification: '" + varSpec + "'. Variable name cannot be empty.");
}
String typeStr = parts[1].trim().toLowerCase(Locale.US);
CelType type = parseCelType(typeStr);
vars.put(name, type);
vars.put(name, parseCelType(parts[1]));
}
return ImmutableMap.copyOf(vars);
}

static CelType parseCelType(String typeStr) {
// TODO: Replace with shorthand type parser once it is available.
Preconditions.checkNotNull(typeStr, "Type string cannot be null.");
String str = typeStr.trim().toLowerCase(Locale.US);

if (str.startsWith("list<") && str.endsWith(">")) {
// Strip "list<" prefix and trailing ">" to extract the element type "T".
String inner = str.substring("list<".length(), str.length() - 1).trim();
CelType elemType = parseCelType(inner);
return ListType.create(elemType);
}

if (str.startsWith("map<") && str.endsWith(">")) {
// Strip "map<" prefix and trailing ">" to extract the key and value types "K, V".
String inner = str.substring("map<".length(), str.length() - 1).trim();
List<String> parts = splitGenericArgs(inner);
if (parts.size() != 2) {
throw new IllegalArgumentException(
"Invalid map type format: '"
+ typeStr
+ "'. Expected format 'map<key_type, value_type>' (e.g., 'map<string, int>').");
}
CelType keyType = parseCelType(parts.get(0));
CelType valueType = parseCelType(parts.get(1));
return MapType.create(keyType, valueType);
}

if (str.startsWith("optional<") && str.endsWith(">")) {
// Strip "optional<" prefix and trailing ">" to extract the wrapped type "T".
String inner = str.substring("optional<".length(), str.length() - 1).trim();
CelType elemType = parseCelType(inner);
return OptionalType.create(elemType);
}

if (str.startsWith("optional_type<") && str.endsWith(">")) {
// Strip "optional_type<" prefix and trailing ">" to extract the wrapped type "T".
String inner = str.substring("optional_type<".length(), str.length() - 1).trim();
CelType elemType = parseCelType(inner);
return OptionalType.create(elemType);
}

switch (str) {
case "int":
return SimpleType.INT;
case "uint":
return SimpleType.UINT;
case "string":
return SimpleType.STRING;
case "bool":
case "boolean":
return SimpleType.BOOL;
case "double":
case "float":
return SimpleType.DOUBLE;
case "bytes":
return SimpleType.BYTES;
case "dyn":
return SimpleType.DYN;
case "timestamp":
case "google.protobuf.timestamp":
return SimpleType.TIMESTAMP;
case "duration":
case "google.protobuf.duration":
return SimpleType.DURATION;
case "google.protobuf.value":
return SimpleType.DYN;
case "google.protobuf.struct":
return MapType.create(SimpleType.STRING, SimpleType.DYN);
case "google.protobuf.listvalue":
return ListType.create(SimpleType.DYN);
case "google.protobuf.boolvalue":
return NullableType.create(SimpleType.BOOL);
case "google.protobuf.bytesvalue":
return NullableType.create(SimpleType.BYTES);
case "google.protobuf.doublevalue":
case "google.protobuf.floatvalue":
return NullableType.create(SimpleType.DOUBLE);
case "google.protobuf.int32value":
case "google.protobuf.int64value":
return NullableType.create(SimpleType.INT);
case "google.protobuf.uint32value":
case "google.protobuf.uint64value":
return NullableType.create(SimpleType.UINT);
case "google.protobuf.stringvalue":
return NullableType.create(SimpleType.STRING);
default:
// TODO: Support protobuf message types (coming soon).
throw new IllegalArgumentException(
"Unsupported type for CLI variable declaration: '"
+ typeStr
+ "'. Supported types: int, uint, string, bool, double, bytes, dyn, timestamp,"
+ " duration, list<T>, map<K, V>, optional<T>.");
}
CelType type = TypeDecl.parse(typeStr).toCelType(EMPTY_TYPE_PROVIDER);
checkDeclarable(type);
return type;
}

private static List<String> splitGenericArgs(String inner) {
List<String> result = new ArrayList<>();
int depth = 0;
StringBuilder current = new StringBuilder();
for (int i = 0; i < inner.length(); i++) {
char c = inner.charAt(i);
if (c == '<') {
depth++;
current.append(c);
} else if (c == '>') {
depth--;
current.append(c);
} else if (c == ',' && depth == 0) {
result.add(current.toString().trim());
current.setLength(0);
} else {
current.append(c);
}
}
if (current.length() > 0) {
result.add(current.toString().trim());
}
return result;
private static void checkDeclarable(CelType type) {
Preconditions.checkArgument(
!UNDECLARABLE_KINDS.contains(type.kind()), "Unsupported variable type: %s", type.name());
type.parameters().forEach(VerificationOptions::checkDeclarable);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public void repl_helpCommands() throws Exception {
assertThat(output[0]).contains("Query: valid <expression>");
assertThat(output[0]).contains("Query: equiv <expression1> <=> <expression2>");
assertThat(output[0]).contains("Well-known types: timestamp, duration");
assertThat(output[0]).contains("Optional types: optional<T>");
assertThat(output[0]).contains("Optional types: optional_type<T>");
assertThat(output[0]).contains("Protobuf types: coming soon");
}

Expand All @@ -99,7 +99,7 @@ public void repl_varDeclarations() throws Exception {
":var tags list<string>",
":var created_at timestamp",
":var timeout duration",
":var opt_user optional<string>",
":var opt_user optional_type<string>",
":vars",
":quit");

Expand Down Expand Up @@ -239,7 +239,7 @@ public void repl_durationSatisfyingInputFormat() throws Exception {
public void repl_optionalQueries() throws Exception {
String[] output =
runReplWithCommands(
":var opt_val optional<int>",
":var opt_val optional_type<int>",
"sat opt_val.hasValue() && opt_val.value() > 100",
"sat !opt_val.hasValue()",
":quit");
Expand Down Expand Up @@ -276,13 +276,15 @@ public void repl_unknownCommandsAndErrors() throws Exception {
":var",
":var invalid_spec",
":var x foo_type",
":var o optional_type",
":unknown",
"invalid + + syntax",
":quit");

assertThat(output[1]).contains("Unknown command: :unknowncommand");
assertThat(output[1]).contains("Usage: :var <name> <type>");
assertThat(output[1]).contains("Unsupported type");
assertThat(output[1]).contains("Undefined type name: foo_type");
assertThat(output[1]).contains("Optional type must have exactly 1 parameter");
assertThat(output[1]).contains("Usage: :unknown <identifier>");
assertThat(output[1]).contains("Compilation error");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
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.verifier.CelVerificationResult;
import dev.cel.verifier.CelVerificationResult.VerificationStatus;
Expand Down Expand Up @@ -137,7 +136,7 @@ public void celVerifierTool_checkSat_withTimestampDurationAndOptional() {
"--var",
"d:duration",
"--var",
"opt:optional<int>",
"opt:optional_type<int>",
"-fmt",
"json");

Expand All @@ -151,81 +150,13 @@ public void celVerifierTool_verifyPolicy_fileNotFound() {
assertThat(output).contains("File not found: non_existent_policy.yaml");
}

@Test
public void parseVariables_success() {
ImmutableMap<String, CelType> vars =
VerificationOptions.parseVariables(
Arrays.asList(
"x:int",
"role:string",
"is_admin:bool",
"tags:list<string>",
"scores:map<string, int>",
"created_at:timestamp",
"timeout:duration",
"opt_user:optional<string>"));

assertThat(vars).containsEntry("x", SimpleType.INT);
assertThat(vars).containsEntry("role", SimpleType.STRING);
assertThat(vars).containsEntry("is_admin", SimpleType.BOOL);
assertThat(vars).containsEntry("tags", ListType.create(SimpleType.STRING));
assertThat(vars).containsEntry("scores", MapType.create(SimpleType.STRING, SimpleType.INT));
assertThat(vars).containsEntry("created_at", SimpleType.TIMESTAMP);
assertThat(vars).containsEntry("timeout", SimpleType.DURATION);
assertThat(vars).containsEntry("opt_user", OptionalType.create(SimpleType.STRING));
}

@Test
public void parseVariables_allTypesIncludingDyn() {
ImmutableMap<String, CelType> vars =
VerificationOptions.parseVariables(
Arrays.asList(
"u:uint",
"d:double",
"fl:float",
"b:bytes",
"dyn_val:dyn",
"flag:boolean",
"t:google.protobuf.timestamp",
"dur:google.protobuf.duration",
"opt:optional<int>",
"nested_list:list<dyn>",
"nested_map:map<string, dyn>"));

assertThat(vars).containsEntry("u", SimpleType.UINT);
assertThat(vars).containsEntry("d", SimpleType.DOUBLE);
assertThat(vars).containsEntry("fl", SimpleType.DOUBLE);
assertThat(vars).containsEntry("b", SimpleType.BYTES);
assertThat(vars).containsEntry("dyn_val", SimpleType.DYN);
assertThat(vars).containsEntry("flag", SimpleType.BOOL);
assertThat(vars).containsEntry("t", SimpleType.TIMESTAMP);
assertThat(vars).containsEntry("dur", SimpleType.DURATION);
assertThat(vars).containsEntry("opt", OptionalType.create(SimpleType.INT));
assertThat(vars).containsEntry("nested_list", ListType.create(SimpleType.DYN));
assertThat(vars).containsEntry("nested_map", MapType.create(SimpleType.STRING, SimpleType.DYN));
}

@Test
public void parseVariables_invalidFormat_throws() {
assertThrows(
IllegalArgumentException.class,
() -> VerificationOptions.parseVariables(Arrays.asList("x_no_colon")));
}

@Test
public void parseVariables_unsupportedType_throws() {
IllegalArgumentException ex =
assertThrows(
IllegalArgumentException.class,
() -> VerificationOptions.parseVariables(Arrays.asList("x:foo_bar")));

assertThat(ex)
.hasMessageThat()
.contains(
"Supported types: int, uint, string, bool, double, bytes, dyn, timestamp,"
+ " duration, list<T>, map<K, V>, optional<T>.");
}

@Test
public void parseVariables_invalidMapFormat_throws() {
assertThrows(
Expand Down
Loading
Loading