From d821618d12b1690861ceb4c31edbbcc51b653f8f Mon Sep 17 00:00:00 2001 From: Robert Stupp Date: Fri, 17 Jul 2026 20:37:23 +0200 Subject: [PATCH] Code style and Java language level adoptions * Replace `Arrays.asList()` with single element with `List.of()` * enhanced switch expression * pattern variable * Use String.repeat() * Use `.isEmpty()` * Remove unused `ParseError` * Remove unused function in TypeErrors * Remove duplicate `if` --- .../conformance/SimpleConformanceTest.java | 16 +- .../projectnessie/cel/CompileBuildBench.java | 22 +- .../common/types/AdapterAllocationBench.java | 37 ++-- .../main/java/org/projectnessie/cel/Env.java | 5 +- .../java/org/projectnessie/cel/EnvOption.java | 3 +- .../projectnessie/cel/checker/Printer.java | 3 +- .../projectnessie/cel/checker/TypeErrors.java | 4 - .../org/projectnessie/cel/checker/Types.java | 148 +++++--------- .../projectnessie/cel/common/CELError.java | 4 +- .../projectnessie/cel/common/debug/Debug.java | 4 +- .../projectnessie/cel/common/types/BoolT.java | 37 +--- .../cel/common/types/BytesT.java | 22 +- .../cel/common/types/DurationT.java | 31 ++- .../projectnessie/cel/common/types/Err.java | 3 +- .../projectnessie/cel/common/types/IntT.java | 32 ++- .../projectnessie/cel/common/types/ListT.java | 24 +-- .../projectnessie/cel/common/types/MapT.java | 19 +- .../projectnessie/cel/common/types/NullT.java | 37 +--- .../cel/common/types/OptionalT.java | 69 +++---- .../cel/common/types/Overloads.java | 29 ++- .../cel/common/types/StringT.java | 35 +--- .../cel/common/types/TimestampT.java | 33 ++- .../projectnessie/cel/common/types/TypeT.java | 15 +- .../projectnessie/cel/common/types/UintT.java | 29 ++- .../projectnessie/cel/common/types/Util.java | 24 +-- .../common/types/pb/DefaultTypeAdapter.java | 6 +- .../cel/common/types/pb/FieldDescription.java | 91 +++------ .../cel/common/types/pb/PbObjectT.java | 8 +- .../common/types/pb/PbTypeDescription.java | 49 ++--- .../common/types/pb/ProtoTypeRegistry.java | 55 ++--- .../common/types/ref/TypeAdapterSupport.java | 3 +- .../cel/extension/NetworkLib.java | 66 +++--- .../cel/extension/StringsLib.java | 192 +++++++----------- .../cel/interpreter/AstPruner.java | 6 +- .../cel/interpreter/AttributeFactory.java | 40 ++-- .../cel/interpreter/AttributePattern.java | 6 +- .../cel/interpreter/Interpretable.java | 66 +++--- .../interpreter/InterpretableDecorator.java | 26 +-- .../cel/interpreter/InterpretablePlanner.java | 98 ++++----- .../org/projectnessie/cel/parser/Macro.java | 7 +- .../projectnessie/cel/parser/ParseError.java | 31 --- .../java/org/projectnessie/cel/CELTest.java | 9 +- .../projectnessie/cel/parser/ParserTest.java | 6 +- .../java/org/projectnessie/cel/Util.java | 6 +- 44 files changed, 530 insertions(+), 926 deletions(-) delete mode 100644 core/src/main/java/org/projectnessie/cel/parser/ParseError.java diff --git a/conformance/src/test/java/org/projectnessie/cel/conformance/SimpleConformanceTest.java b/conformance/src/test/java/org/projectnessie/cel/conformance/SimpleConformanceTest.java index 15d7bfe5..825a5d61 100644 --- a/conformance/src/test/java/org/projectnessie/cel/conformance/SimpleConformanceTest.java +++ b/conformance/src/test/java/org/projectnessie/cel/conformance/SimpleConformanceTest.java @@ -619,16 +619,12 @@ private static Val exprValueToRefValue(TypeAdapter adapter, dev.cel.expr.ExprVal } private static Val exprValueToRefValue(TypeAdapter adapter, ExprValue ev) { - switch (ev.getKindCase()) { - case VALUE: - return valueToRefValue(adapter, ev.getValue()); - case ERROR: - return newErr("XXX add details later"); - case UNKNOWN: - return unknownOf(ev.getUnknown().getExprs(0)); - default: - throw new IllegalArgumentException("unknown ExprValue kind " + ev.getKindCase()); - } + return switch (ev.getKindCase()) { + case VALUE -> valueToRefValue(adapter, ev.getValue()); + case ERROR -> newErr("XXX add details later"); + case UNKNOWN -> unknownOf(ev.getUnknown().getExprs(0)); + default -> throw new IllegalArgumentException("unknown ExprValue kind " + ev.getKindCase()); + }; } private static Val valueToRefValue(TypeAdapter adapter, Value v) { diff --git a/core/src/jmh/java/org/projectnessie/cel/CompileBuildBench.java b/core/src/jmh/java/org/projectnessie/cel/CompileBuildBench.java index 76bb13ab..8fe49da5 100644 --- a/core/src/jmh/java/org/projectnessie/cel/CompileBuildBench.java +++ b/core/src/jmh/java/org/projectnessie/cel/CompileBuildBench.java @@ -51,17 +51,17 @@ public static class CompileState { public String expression; String source() { - switch (expression) { - case "simplePredicate": - return "resource == 'projects/p1' && user == 'alice'"; - case "deepSelectors": - return "request.auth.claims.email.endsWith('@example.com')" - + " && request.resource.labels['env'] == 'prod'"; - case "macroPipeline": - return "items.filter(i, i.score > 10).map(i, i.name).exists(n, n.startsWith('a'))"; - default: - throw new IllegalArgumentException("Unknown compile benchmark expression: " + expression); - } + return switch (expression) { + case "simplePredicate" -> "resource == 'projects/p1' && user == 'alice'"; + case "deepSelectors" -> + "request.auth.claims.email.endsWith('@example.com')" + + " && request.resource.labels['env'] == 'prod'"; + case "macroPipeline" -> + "items.filter(i, i.score > 10).map(i, i.name).exists(n, n.startsWith('a'))"; + default -> + throw new IllegalArgumentException( + "Unknown compile benchmark expression: " + expression); + }; } } diff --git a/core/src/jmh/java/org/projectnessie/cel/common/types/AdapterAllocationBench.java b/core/src/jmh/java/org/projectnessie/cel/common/types/AdapterAllocationBench.java index 6c44576e..6d398054 100644 --- a/core/src/jmh/java/org/projectnessie/cel/common/types/AdapterAllocationBench.java +++ b/core/src/jmh/java/org/projectnessie/cel/common/types/AdapterAllocationBench.java @@ -87,30 +87,19 @@ public void nativeToValue(NativeValueState state, Blackhole blackhole) { } private static Object value(String kind, int size) { - switch (kind) { - case "arrayList": - return list(size); - case "linkedHashSet": - return set(size); - case "objectArray": - return list(size).toArray(); - case "stringArray": - return stringArray(size); - case "intArray": - return intArray(size); - case "longArray": - return longArray(size); - case "doubleArray": - return doubleArray(size); - case "mapStringInt": - return mapStringInt(size); - case "mapValVal": - return mapValVal(size); - case "listValue": - return listValue(size); - default: - throw new IllegalArgumentException("Unknown native value kind: " + kind); - } + return switch (kind) { + case "arrayList" -> list(size); + case "linkedHashSet" -> set(size); + case "objectArray" -> list(size).toArray(); + case "stringArray" -> stringArray(size); + case "intArray" -> intArray(size); + case "longArray" -> longArray(size); + case "doubleArray" -> doubleArray(size); + case "mapStringInt" -> mapStringInt(size); + case "mapValVal" -> mapValVal(size); + case "listValue" -> listValue(size); + default -> throw new IllegalArgumentException("Unknown native value kind: " + kind); + }; } private static List list(int size) { diff --git a/core/src/main/java/org/projectnessie/cel/Env.java b/core/src/main/java/org/projectnessie/cel/Env.java index 02b27346..0ddbb0f6 100644 --- a/core/src/main/java/org/projectnessie/cel/Env.java +++ b/core/src/main/java/org/projectnessie/cel/Env.java @@ -281,9 +281,8 @@ public Env extend(List opts) { // be immutable. Since it is possible to set the TypeProvider separately // from the TypeAdapter, the possible configurations which could use a // TypeRegistry as the base implementation are captured below. - if (this.adapter instanceof TypeRegistry && this.provider instanceof TypeRegistry) { - TypeRegistry adapterReg = (TypeRegistry) this.adapter; - TypeRegistry providerReg = (TypeRegistry) this.provider; + if (this.adapter instanceof TypeRegistry adapterReg + && this.provider instanceof TypeRegistry providerReg) { TypeRegistry reg = providerReg.copy(); provider = reg; // If the adapter and provider are the same object, set the adapter diff --git a/core/src/main/java/org/projectnessie/cel/EnvOption.java b/core/src/main/java/org/projectnessie/cel/EnvOption.java index 71f824af..9ddc2ba5 100644 --- a/core/src/main/java/org/projectnessie/cel/EnvOption.java +++ b/core/src/main/java/org/projectnessie/cel/EnvOption.java @@ -229,12 +229,11 @@ static EnvOption abbrevs(String... qualifiedNames) { */ static EnvOption types(List addTypes) { return e -> { - if (!(e.provider instanceof TypeRegistry)) { + if (!(e.provider instanceof TypeRegistry reg)) { throw new RuntimeException( String.format( "custom types not supported by provider: %s", e.provider.getClass().getName())); } - TypeRegistry reg = (TypeRegistry) e.provider; for (Object t : addTypes) { reg.register(t); } diff --git a/core/src/main/java/org/projectnessie/cel/checker/Printer.java b/core/src/main/java/org/projectnessie/cel/checker/Printer.java index 6a62054b..c8152d80 100644 --- a/core/src/main/java/org/projectnessie/cel/checker/Printer.java +++ b/core/src/main/java/org/projectnessie/cel/checker/Printer.java @@ -35,11 +35,10 @@ static final class SemanticAdorner implements Adorner { @Override public String getMetadata(Object elem) { - if (!(elem instanceof Expr)) { + if (!(elem instanceof Expr e)) { return ""; } StringBuilder result = new StringBuilder(); - Expr e = (Expr) elem; Type t = checks.getTypeMapMap().get(e.getId()); if (t != null) { result.append("~"); diff --git a/core/src/main/java/org/projectnessie/cel/checker/TypeErrors.java b/core/src/main/java/org/projectnessie/cel/checker/TypeErrors.java index 303e7b6c..10f1efda 100644 --- a/core/src/main/java/org/projectnessie/cel/checker/TypeErrors.java +++ b/core/src/main/java/org/projectnessie/cel/checker/TypeErrors.java @@ -117,10 +117,6 @@ void typeMismatch(Location l, Type expected, Type actual) { formatCheckedType(actual)); } - public void unknownType(Location l, String info) { - // reportError(l, "unknown type%s", info != null ? " for: " + info : ""); - } - static String formatFunction(Type resultType, List argTypes, boolean isInstance) { StringBuilder result = new StringBuilder(); formatFunction(result, resultType, argTypes, isInstance); diff --git a/core/src/main/java/org/projectnessie/cel/checker/Types.java b/core/src/main/java/org/projectnessie/cel/checker/Types.java index 682837a6..4209bd9a 100644 --- a/core/src/main/java/org/projectnessie/cel/checker/Types.java +++ b/core/src/main/java/org/projectnessie/cel/checker/Types.java @@ -62,22 +62,17 @@ public static String formatCheckedType(Type t) { case kindNull: return "null"; case kindPrimitive: - switch (t.getPrimitive()) { - case UINT64: - return "uint"; - case INT64: - return "int"; - case BOOL: - return "bool"; - case BYTES: - return "bytes"; - case DOUBLE: - return "double"; - case STRING: - return "string"; - } - // unrecognizes & not-specified - ignore above - return t.getPrimitive().toString().toLowerCase(Locale.ROOT).trim(); + return switch (t.getPrimitive()) { + case UINT64 -> "uint"; + case INT64 -> "int"; + case BOOL -> "bool"; + case BYTES -> "bytes"; + case DOUBLE -> "double"; + case STRING -> "string"; + default -> + // unrecognizes & not-specified - ignore above + t.getPrimitive().toString().toLowerCase(Locale.ROOT).trim(); + }; case kindWellKnown: switch (t.getWellKnown()) { case ANY: @@ -196,14 +191,11 @@ private static void formatCheckedTypePrimitive(StringBuilder sb, Type.PrimitiveT static boolean isDyn(Type t) { // Note: object type values that are well-known and map to a DYN value in practice // are sanitized prior to being added to the environment. - switch (kindOf(t)) { - case kindDyn: - return true; - case kindWellKnown: - return t.getWellKnown() == WellKnownType.ANY; - default: - return false; - } + return switch (kindOf(t)) { + case kindDyn -> true; + case kindWellKnown -> t.getWellKnown() == WellKnownType.ANY; + default -> false; + }; } /** isDynOrError returns true if the input is either an Error, DYN, or well-known ANY message. */ @@ -356,28 +348,22 @@ static boolean internalIsAssignable(Mapping m, Type t1, Type t2) { } // Test for when the types must agree. - switch (kind1) { + return switch (kind1) { // ERROR, TYPE_PARAM, and DYN handled above. - case kindAbstract: - return internalIsAssignableAbstractType(m, t1.getAbstractType(), t2.getAbstractType()); - case kindFunction: - return internalIsAssignableFunction(m, t1.getFunction(), t2.getFunction()); - case kindList: - return internalIsAssignable( - m, t1.getListType().getElemType(), t2.getListType().getElemType()); - case kindMap: - return internalIsAssignableMap(m, t1.getMapType(), t2.getMapType()); - case kindObject: - return t1.getMessageType().equals(t2.getMessageType()); - case kindType: - // A type is a type is a type, any additional parameterization of the - // type cannot affect method resolution or assignability. - return true; - case kindWellKnown: - return t1.getWellKnown() == t2.getWellKnown(); - default: - return false; - } + case kindAbstract -> + internalIsAssignableAbstractType(m, t1.getAbstractType(), t2.getAbstractType()); + case kindFunction -> internalIsAssignableFunction(m, t1.getFunction(), t2.getFunction()); + case kindList -> + internalIsAssignable(m, t1.getListType().getElemType(), t2.getListType().getElemType()); + case kindMap -> internalIsAssignableMap(m, t1.getMapType(), t2.getMapType()); + case kindObject -> t1.getMessageType().equals(t2.getMessageType()); + case kindType -> + // A type is a type is a type, any additional parameterization of the + // type cannot affect method resolution or assignability. + true; + case kindWellKnown -> t1.getWellKnown() == t2.getWellKnown(); + default -> false; + }; } /** @@ -429,16 +415,10 @@ static boolean internalIsAssignableMap(Mapping m, MapType m1, MapType m2) { /** internalIsAssignableNull returns true if the type is nullable. */ static boolean internalIsAssignableNull(Type t) { - switch (kindOf(t)) { - case kindAbstract: - case kindObject: - case kindNull: - case kindWellKnown: - case kindWrapper: - return true; - default: - return false; - } + return switch (kindOf(t)) { + case kindAbstract, kindObject, kindNull, kindWellKnown, kindWrapper -> true; + default -> false; + }; } /** @@ -446,14 +426,11 @@ static boolean internalIsAssignableNull(Type t) { * for the primitive type. */ static boolean internalIsAssignablePrimitive(PrimitiveType p, Type target) { - switch (kindOf(target)) { - case kindPrimitive: - return p == target.getPrimitive(); - case kindWrapper: - return p == target.getWrapper(); - default: - return false; - } + return switch (kindOf(target)) { + case kindPrimitive -> p == target.getPrimitive(); + case kindWrapper -> p == target.getWrapper(); + default -> false; + }; } /** isAssignable returns an updated type substitution mapping if t1 is assignable to t2. */ @@ -479,35 +456,22 @@ static Kind kindOf(Type t) { if (t == null || t.getTypeKindCase() == TypeKindCase.TYPEKIND_NOT_SET) { return Kind.kindUnknown; } - switch (t.getTypeKindCase()) { - case ERROR: - return Kind.kindError; - case FUNCTION: - return Kind.kindFunction; - case DYN: - return Kind.kindDyn; - case PRIMITIVE: - return Kind.kindPrimitive; - case WELL_KNOWN: - return Kind.kindWellKnown; - case WRAPPER: - return Kind.kindWrapper; - case NULL: - return Kind.kindNull; - case ABSTRACT_TYPE: - return Kind.kindAbstract; - case TYPE: - return Kind.kindType; - case LIST_TYPE: - return Kind.kindList; - case MAP_TYPE: - return Kind.kindMap; - case MESSAGE_TYPE: - return Kind.kindObject; - case TYPE_PARAM: - return Kind.kindTypeParam; - } - return Kind.kindUnknown; + return switch (t.getTypeKindCase()) { + case ERROR -> Kind.kindError; + case FUNCTION -> Kind.kindFunction; + case DYN -> Kind.kindDyn; + case PRIMITIVE -> Kind.kindPrimitive; + case WELL_KNOWN -> Kind.kindWellKnown; + case WRAPPER -> Kind.kindWrapper; + case NULL -> Kind.kindNull; + case ABSTRACT_TYPE -> Kind.kindAbstract; + case TYPE -> Kind.kindType; + case LIST_TYPE -> Kind.kindList; + case MAP_TYPE -> Kind.kindMap; + case MESSAGE_TYPE -> Kind.kindObject; + case TYPE_PARAM -> Kind.kindTypeParam; + default -> Kind.kindUnknown; + }; } /** mostGeneral returns the more general of two types which are known to unify. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/CELError.java b/core/src/main/java/org/projectnessie/cel/common/CELError.java index 7bb93511..88d039c4 100644 --- a/core/src/main/java/org/projectnessie/cel/common/CELError.java +++ b/core/src/main/java/org/projectnessie/cel/common/CELError.java @@ -102,9 +102,7 @@ public String toDisplayString(Source source) { // sophisticated way, maybe use jline's WCWidth, but that one is also quite rudimentary wrt // code-blocks (e.g. doesn't know about emojis). result.append("\n | "); - for (int i = 0; i < location.column(); i++) { - result.append(dot); - } + result.append(String.valueOf(dot).repeat(Math.max(0, location.column()))); result.append(ind); } return result.toString(); diff --git a/core/src/main/java/org/projectnessie/cel/common/debug/Debug.java b/core/src/main/java/org/projectnessie/cel/common/debug/Debug.java index 8ea2e168..d3cbde99 100644 --- a/core/src/main/java/org/projectnessie/cel/common/debug/Debug.java +++ b/core/src/main/java/org/projectnessie/cel/common/debug/Debug.java @@ -363,9 +363,7 @@ void appendFormat(String f, Object... args) { void doIndent() { if (lineStart) { lineStart = false; - for (int i = 0; i < indent; i++) { - buffer.append(" "); - } + buffer.append(" ".repeat(Math.max(0, indent))); } } diff --git a/core/src/main/java/org/projectnessie/cel/common/types/BoolT.java b/core/src/main/java/org/projectnessie/cel/common/types/BoolT.java index 3f0549e8..2868ad4e 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/BoolT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/BoolT.java @@ -93,37 +93,22 @@ public T convertToNative(Class typeDesc) { /** ConvertToType implements the ref.Val interface method. */ @Override public Val convertToType(Type typeVal) { - switch (typeVal.typeEnum()) { - case String: - return stringOf(Boolean.toString(b)); - case Bool: - return this; - case Type: - return BoolType; - } - return newTypeConversionError(BoolType, typeVal); + return switch (typeVal.typeEnum()) { + case String -> stringOf(Boolean.toString(b)); + case Bool -> this; + case Type -> BoolType; + default -> newTypeConversionError(BoolType, typeVal); + }; } /** Equal implements the ref.Val interface method. */ @Override public Val equal(Val other) { - switch (other.type().typeEnum()) { - case Bool: - return Types.boolOf(b == ((BoolT) other).b); - case Null: - case Bytes: - case Double: - case Int: - case List: - case Map: - case Object: - case String: - case Type: - case Uint: - return False; - default: - return noSuchOverload(this, "equal", other); - } + return switch (other.type().typeEnum()) { + case Bool -> Types.boolOf(b == ((BoolT) other).b); + case Null, Bytes, Double, Int, List, Map, Object, String, Type, Uint -> False; + default -> noSuchOverload(this, "equal", other); + }; } /** Negate implements the traits.Negater interface method. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/types/BytesT.java b/core/src/main/java/org/projectnessie/cel/common/types/BytesT.java index dfc5a15f..ca2025bb 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/BytesT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/BytesT.java @@ -163,23 +163,11 @@ public Val convertToType(Type typeValue) { /** Equal implements the ref.Val interface method. */ @Override public Val equal(Val other) { - switch (other.type().typeEnum()) { - case Bytes: - return boolOf(Arrays.equals(b, ((BytesT) other).b)); - case Null: - case Bool: - case Double: - case Int: - case List: - case Map: - case Object: - case String: - case Type: - case Uint: - return False; - default: - return noSuchOverload(this, "equal", other); - } + return switch (other.type().typeEnum()) { + case Bytes -> boolOf(Arrays.equals(b, ((BytesT) other).b)); + case Null, Bool, Double, Int, List, Map, Object, String, Type, Uint -> False; + default -> noSuchOverload(this, "equal", other); + }; } /** Size implements the traits.Sizer interface method. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/types/DurationT.java b/core/src/main/java/org/projectnessie/cel/common/types/DurationT.java index 2d629db6..fde847bd 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/DurationT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/DurationT.java @@ -212,30 +212,23 @@ private String toPbString() { /** ConvertToType implements ref.Val.ConvertToType. */ @Override public Val convertToType(Type typeValue) { - switch (typeValue.typeEnum()) { - case String: - return stringOf(toPbString()); - case Int: - return IntT.intOf(toJavaLong()); - case Duration: - return this; - case Type: - return DurationType; - } - return newTypeConversionError(DurationType, typeValue); + return switch (typeValue.typeEnum()) { + case String -> stringOf(toPbString()); + case Int -> IntT.intOf(toJavaLong()); + case Duration -> this; + case Type -> DurationType; + default -> newTypeConversionError(DurationType, typeValue); + }; } /** Equal implements ref.Val.Equal. */ @Override public Val equal(Val other) { - switch (other.type().typeEnum()) { - case Duration: - return boolOf(d.equals(((DurationT) other).d)); - case Null: - return False; - default: - return noSuchOverload(this, "equal", other); - } + return switch (other.type().typeEnum()) { + case Duration -> boolOf(d.equals(((DurationT) other).d)); + case Null -> False; + default -> noSuchOverload(this, "equal", other); + }; } /** Negate implements traits.Negater.Negate. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/types/Err.java b/core/src/main/java/org/projectnessie/cel/common/types/Err.java index 216324bd..e84ff00c 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/Err.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/Err.java @@ -268,8 +268,7 @@ public RuntimeException toRuntimeException() { } public static void throwErrorAsIllegalStateException(Val val) { - if (val instanceof Err) { - Err e = (Err) val; + if (val instanceof Err e) { if (e.cause != null) { throw new IllegalStateException(e.error, e.cause); } else { diff --git a/core/src/main/java/org/projectnessie/cel/common/types/IntT.java b/core/src/main/java/org/projectnessie/cel/common/types/IntT.java index c098531f..056575a0 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/IntT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/IntT.java @@ -178,29 +178,27 @@ public T convertToNative(Class typeDesc) { /** ConvertToType implements ref.Val.ConvertToType. */ @Override public Val convertToType(Type typeValue) { - switch (typeValue.typeEnum()) { - case Int: - return this; - case Uint: + return switch (typeValue.typeEnum()) { + case Int -> this; + case Uint -> { if (i < 0) { - return rangeError(i, "uint"); + yield rangeError(i, "uint"); } - return uintOf(i); - case Double: - return doubleOf(i); - case String: - return stringOf(Long.toString(i)); - case Timestamp: + yield uintOf(i); + } + case Double -> doubleOf(i); + case String -> stringOf(Long.toString(i)); + case Timestamp -> { // The maximum positive value that can be passed to time.Unix is math.MaxInt64 minus the // number of seconds between year 1 and year 1970. See comments on unixToInternal. if (i < minUnixTime || i > maxUnixTime) { - return errTimestampOverflow; + yield errTimestampOverflow; } - return timestampOf(Instant.ofEpochSecond(i).atZone(ZoneIdZ)); - case Type: - return IntType; - } - return newTypeConversionError(IntType, typeValue); + yield timestampOf(Instant.ofEpochSecond(i).atZone(ZoneIdZ)); + } + case Type -> IntType; + default -> newTypeConversionError(IntType, typeValue); + }; } /** Compare implements traits.Comparer.Compare. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/types/ListT.java b/core/src/main/java/org/projectnessie/cel/common/types/ListT.java index f40c6cd6..a202e70b 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/ListT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/ListT.java @@ -180,13 +180,11 @@ private Object toJavaArray(Class typeDesc) { @Override public Val convertToType(Type typeValue) { - switch (typeValue.typeEnum()) { - case List: - return this; - case Type: - return ListType; - } - return newTypeConversionError(ListType, typeValue); + return switch (typeValue.typeEnum()) { + case List -> this; + case Type -> ListType; + default -> newTypeConversionError(ListType, typeValue); + }; } @Override @@ -357,10 +355,9 @@ public Object value() { @Override public Val add(Val other) { - if (!(other instanceof Lister)) { + if (!(other instanceof Lister otherList)) { return noSuchOverload(this, "add", other); } - Lister otherList = (Lister) other; int otherSize = (int) otherList.size().intValue(); Object[] newArray = Arrays.copyOf(array, array.length + otherSize); Class componentType = array.getClass().getComponentType(); @@ -414,10 +411,9 @@ public Object value() { @Override public Val add(Val other) { - if (!(other instanceof Lister)) { + if (!(other instanceof Lister otherList)) { return noSuchOverload(this, "add", other); } - Lister otherList = (Lister) other; int otherSize = (int) otherList.size().intValue(); Object[] newArray = new Object[list.size() + otherSize]; for (int i = 0; i < list.size(); i++) { @@ -461,7 +457,7 @@ public Object value() { @Override public Val add(Val other) { - if (!(other instanceof Lister)) { + if (!(other instanceof Lister otherLister)) { return noSuchOverload(this, "add", other); } if (other instanceof ValListT) { @@ -470,7 +466,6 @@ public Val add(Val other) { System.arraycopy(otherArray, 0, newArray, array.length, otherArray.length); return new ValListT(adapter, newArray); } else { - Lister otherLister = (Lister) other; int otherSIze = (int) otherLister.size().intValue(); Val[] newArray = Arrays.copyOf(array, array.length + otherSIze); for (int i = 0; i < otherSIze; i++) { @@ -511,10 +506,9 @@ abstract static class PrimitiveArrayListT extends BaseListT { @Override public Val add(Val other) { - if (!(other instanceof Lister)) { + if (!(other instanceof Lister otherLister)) { return noSuchOverload(this, "add", other); } - Lister otherLister = (Lister) other; int thisSize = (int) size; int otherSize = (int) otherLister.size().intValue(); Val[] newArray = new Val[thisSize + otherSize]; diff --git a/core/src/main/java/org/projectnessie/cel/common/types/MapT.java b/core/src/main/java/org/projectnessie/cel/common/types/MapT.java index 788c0bff..d96ef276 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/MapT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/MapT.java @@ -58,11 +58,10 @@ public static Val newWrappedMap(TypeAdapter adapter, Map value) { public static Val newMaybeWrappedMap(TypeAdapter adapter, Map value) { boolean alreadyWrapped = true; for (Map.Entry entry : value.entrySet()) { - if (!(entry.getKey() instanceof Val) || !(entry.getValue() instanceof Val)) { + if (!(entry.getKey() instanceof Val key) || !(entry.getValue() instanceof Val)) { alreadyWrapped = false; break; } - Val key = (Val) entry.getKey(); if (key.type().typeEnum() == TypeEnum.Null) { return newErr("unsupported key type"); } @@ -87,15 +86,10 @@ public static Val newMaybeWrappedMap(TypeAdapter adapter, Map value) { } public static boolean isSupportedLiteralKeyType(Val key) { - switch (key.type().typeEnum()) { - case Bool: - case Int: - case String: - case Uint: - return true; - default: - return false; - } + return switch (key.type().typeEnum()) { + case Bool, Int, String, Uint -> true; + default -> false; + }; } @Override @@ -182,10 +176,9 @@ public IteratorT iterator() { @Override public Val equal(Val other) { // TODO this is expensive :( - if (!(other instanceof MapT)) { + if (!(other instanceof MapT o)) { return False; } - MapT o = (MapT) other; if (!size().equal(o.size()).booleanValue()) { return False; } diff --git a/core/src/main/java/org/projectnessie/cel/common/types/NullT.java b/core/src/main/java/org/projectnessie/cel/common/types/NullT.java index 415d479f..3ef11a2e 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/NullT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/NullT.java @@ -82,37 +82,22 @@ public T convertToNative(Class typeDesc) { /** ConvertToType implements ref.Val.ConvertToType. */ @Override public Val convertToType(Type typeValue) { - switch (typeValue.typeEnum()) { - case String: - return stringOf("null"); - case Null: - return this; - case Type: - return NullType; - } - return newTypeConversionError(NullType, typeValue); + return switch (typeValue.typeEnum()) { + case String -> stringOf("null"); + case Null -> this; + case Type -> NullType; + default -> newTypeConversionError(NullType, typeValue); + }; } /** Equal implements ref.Val.Equal. */ @Override public Val equal(Val other) { - switch (other.type().typeEnum()) { - case Null: - return True; - case Int: - case Uint: - case Double: - case String: - case Bytes: - case Bool: - case List: - case Map: - case Object: - case Type: - return False; - default: - return noSuchOverload(this, "equal", other); - } + return switch (other.type().typeEnum()) { + case Null -> True; + case Int, Uint, Double, String, Bytes, Bool, List, Map, Object, Type -> False; + default -> noSuchOverload(this, "equal", other); + }; } /** Type implements ref.Val.Type. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/types/OptionalT.java b/core/src/main/java/org/projectnessie/cel/common/types/OptionalT.java index 838af151..4bbffbc3 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/OptionalT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/OptionalT.java @@ -112,10 +112,9 @@ public Val convertToType(Type typeValue) { @Override public Val equal(Val other) { - if (!(other instanceof OptionalT)) { + if (!(other instanceof OptionalT optional)) { return False; } - OptionalT optional = (OptionalT) other; if (!present || !optional.present) { return present == optional.present ? True : False; } @@ -157,20 +156,16 @@ public Val get(Val index) { @Override public Val receive(String function, String overload, Val... args) { - switch (function) { - case "hasValue": - return args.length == 0 - ? (present ? True : False) - : noSuchOverload(this, function, overload, args); - case "value": - return value(args, function, overload); - case "or": - return or(args, function, overload); - case "orValue": - return orValue(args, function, overload); - default: - return noSuchOverload(this, function, overload, args); - } + return switch (function) { + case "hasValue" -> + args.length == 0 + ? (present ? True : False) + : noSuchOverload(this, function, overload, args); + case "value" -> value(args, function, overload); + case "or" -> or(args, function, overload); + case "orValue" -> orValue(args, function, overload); + default -> noSuchOverload(this, function, overload, args); + }; } private Val value(Val[] args, String function, String overload) { @@ -195,33 +190,21 @@ private Val orValue(Val[] args, String function, String overload) { } private static boolean isZeroValue(Val value) { - switch (value.type().typeEnum()) { - case Null: - return true; - case Bool: - return value == False || !value.booleanValue(); - case Int: - case Uint: - return value.intValue() == 0L; - case Double: - return value.doubleValue() == 0.0d; - case Duration: - return Duration.ZERO.equals(value.value()); - case Timestamp: - return value.value() instanceof ZonedDateTime timestamp - && timestamp.toInstant().equals(Instant.EPOCH); - case String: - case Bytes: - case List: - case Map: - return value.type().hasTrait(Trait.SizerType) - && ((Sizer) value).size().equal(IntZero) == True; - case Object: - return value.value() instanceof Message - && ((Message) value.value()).getAllFields().isEmpty(); - default: - return false; - } + return switch (value.type().typeEnum()) { + case Null -> true; + case Bool -> value == False || !value.booleanValue(); + case Int, Uint -> value.intValue() == 0L; + case Double -> value.doubleValue() == 0.0d; + case Duration -> Duration.ZERO.equals(value.value()); + case Timestamp -> + value.value() instanceof ZonedDateTime timestamp + && timestamp.toInstant().equals(Instant.EPOCH); + case String, Bytes, List, Map -> + value.type().hasTrait(Trait.SizerType) && ((Sizer) value).size().equal(IntZero) == True; + case Object -> + value.value() instanceof Message && ((Message) value.value()).getAllFields().isEmpty(); + default -> false; + }; } private static Val optionalAccess(Val operand, Val index) { diff --git a/core/src/main/java/org/projectnessie/cel/common/types/Overloads.java b/core/src/main/java/org/projectnessie/cel/common/types/Overloads.java index 805167f6..3ad5a035 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/Overloads.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/Overloads.java @@ -236,20 +236,19 @@ private Overloads() {} // IsTypeConversionFunction returns whether the input function is a standard library type // conversion function. public static boolean isTypeConversionFunction(String function) { - switch (function) { - case TypeConvertBool: - case TypeConvertBytes: - case TypeConvertDouble: - case TypeConvertDuration: - case TypeConvertDyn: - case TypeConvertInt: - case TypeConvertString: - case TypeConvertTimestamp: - case TypeConvertType: - case TypeConvertUint: - return true; - default: - return false; - } + return switch (function) { + case TypeConvertBool, + TypeConvertBytes, + TypeConvertDouble, + TypeConvertDuration, + TypeConvertDyn, + TypeConvertInt, + TypeConvertString, + TypeConvertTimestamp, + TypeConvertType, + TypeConvertUint -> + true; + default -> false; + }; } } diff --git a/core/src/main/java/org/projectnessie/cel/common/types/StringT.java b/core/src/main/java/org/projectnessie/cel/common/types/StringT.java index bc214752..b275e4c7 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/StringT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/StringT.java @@ -164,36 +164,21 @@ public Val convertToType(Type typeVal) { /** Compare implements traits.Comparer.Compare. */ @Override public Val compare(Val other) { - switch (other.type().typeEnum()) { - case String: - return intOfCompare(s.compareTo(((StringT) other).s)); - case Null: - return False; - default: - return noSuchOverload(this, "compare", other); - } + return switch (other.type().typeEnum()) { + case String -> intOfCompare(s.compareTo(((StringT) other).s)); + case Null -> False; + default -> noSuchOverload(this, "compare", other); + }; } /** Equal implements ref.Val.Equal. */ @Override public Val equal(Val other) { - switch (other.type().typeEnum()) { - case String: - return boolOf(s.equals(((StringT) other).s)); - case Null: - case Bool: - case Bytes: - case Int: - case Uint: - case Double: - case List: - case Map: - case Object: - case Type: - return False; - default: - return noSuchOverload(this, "equal", other); - } + return switch (other.type().typeEnum()) { + case String -> boolOf(s.equals(((StringT) other).s)); + case Null, Bool, Bytes, Int, Uint, Double, List, Map, Object, Type -> False; + default -> noSuchOverload(this, "equal", other); + }; } /** Match implements traits.Matcher.Match. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/types/TimestampT.java b/core/src/main/java/org/projectnessie/cel/common/types/TimestampT.java index e853b092..3d9e9bfb 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/TimestampT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/TimestampT.java @@ -269,18 +269,16 @@ private Timestamp toPbTimestamp() { /** ConvertToType implements ref.Val.ConvertToType. */ @Override public Val convertToType(Type typeValue) { - switch (typeValue.typeEnum()) { - case String: + return switch (typeValue.typeEnum()) { + case String -> { DateTimeFormatter df = (t.getNano() > 0L) ? rfc3339nanoFormatter : rfc3339formatter; - return stringOf(df.format(t)); - case Int: - return intOf(t.toEpochSecond()); - case Timestamp: - return this; - case Type: - return TimestampType; - } - return newTypeConversionError(TimestampType, typeValue); + yield stringOf(df.format(t)); + } + case Int -> intOf(t.toEpochSecond()); + case Timestamp -> this; + case Type -> TimestampType; + default -> newTypeConversionError(TimestampType, typeValue); + }; } /** Only used for format a string, never for parsing. */ @@ -345,14 +343,11 @@ public Val convertToType(Type typeValue) { /** Equal implements ref.Val.Equal. */ @Override public Val equal(Val other) { - switch (other.type().typeEnum()) { - case Timestamp: - return boolOf(t.equals(((TimestampT) other).t)); - case Null: - return False; - default: - return noSuchOverload(this, "equal", other); - } + return switch (other.type().typeEnum()) { + case Timestamp -> boolOf(t.equals(((TimestampT) other).t)); + case Null -> False; + default -> noSuchOverload(this, "equal", other); + }; } /** Receive implements traits.Reciever.Receive. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/types/TypeT.java b/core/src/main/java/org/projectnessie/cel/common/types/TypeT.java index 06c9c345..17e8f62f 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/TypeT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/TypeT.java @@ -102,13 +102,11 @@ public T convertToNative(Class typeDesc) { /** ConvertToType implements ref.Val.ConvertToType. */ @Override public Val convertToType(Type typeVal) { - switch (typeVal.typeEnum()) { - case Type: - return TypeType; - case String: - return stringOf(typeName()); - } - return newTypeConversionError(TypeType, typeVal); + return switch (typeVal.typeEnum()) { + case Type -> TypeType; + case String -> stringOf(typeName()); + default -> newTypeConversionError(TypeType, typeVal); + }; } /** Equal implements ref.Val.Equal. */ @@ -166,10 +164,9 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof Type)) { + if (!(o instanceof Type typeValue)) { return false; } - Type typeValue = (Type) o; return typeName().equals(typeValue.typeName()); } diff --git a/core/src/main/java/org/projectnessie/cel/common/types/UintT.java b/core/src/main/java/org/projectnessie/cel/common/types/UintT.java index 1c229ea3..b392ed2a 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/UintT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/UintT.java @@ -147,25 +147,24 @@ public T convertToNative(Class typeDesc) { /** ConvertToType implements ref.Val.ConvertToType. */ @Override public Val convertToType(Type typeValue) { - switch (typeValue.typeEnum()) { - case Int: + return switch (typeValue.typeEnum()) { + case Int -> { if (i < 0L) { - return rangeError(Long.toUnsignedString(i), "int"); + yield rangeError(Long.toUnsignedString(i), "int"); } - return intOf(i); - case Uint: - return this; - case Double: + yield intOf(i); + } + case Uint -> this; + case Double -> { if (i < 0L) { - return doubleOf(new BigInteger(Long.toUnsignedString(i)).doubleValue()); + yield doubleOf(new BigInteger(Long.toUnsignedString(i)).doubleValue()); } - return doubleOf(i); - case String: - return stringOf(Long.toUnsignedString(i)); - case Type: - return UintType; - } - return newTypeConversionError(UintType, typeValue); + yield doubleOf(i); + } + case String -> stringOf(Long.toUnsignedString(i)); + case Type -> UintType; + default -> newTypeConversionError(UintType, typeValue); + }; } /** Compare implements traits.Comparer.Compare. */ diff --git a/core/src/main/java/org/projectnessie/cel/common/types/Util.java b/core/src/main/java/org/projectnessie/cel/common/types/Util.java index 4eea3dc0..6d737461 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/Util.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/Util.java @@ -21,12 +21,10 @@ public final class Util { /** IsUnknownOrError returns whether the input element ref.Val is an ErrType or UnknonwType. */ public static boolean isUnknownOrError(Val val) { - switch (val.type().typeEnum()) { - case Unknown: - case Err: - return true; - } - return false; + return switch (val.type().typeEnum()) { + case Unknown, Err -> true; + default -> false; + }; } /** @@ -34,15 +32,9 @@ public static boolean isUnknownOrError(Val val) { * types do not include well-known types such as Duration and Timestamp. */ public static boolean isPrimitiveType(Val val) { - switch (val.type().typeEnum()) { - case Bool: - case Bytes: - case Double: - case Int: - case String: - case Uint: - return true; - } - return false; + return switch (val.type().typeEnum()) { + case Bool, Bytes, Double, Int, String, Uint -> true; + default -> false; + }; } } diff --git a/core/src/main/java/org/projectnessie/cel/common/types/pb/DefaultTypeAdapter.java b/core/src/main/java/org/projectnessie/cel/common/types/pb/DefaultTypeAdapter.java index f20c5d45..097bb003 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/pb/DefaultTypeAdapter.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/pb/DefaultTypeAdapter.java @@ -64,8 +64,7 @@ public static Val nativeToValue(Db db, TypeAdapter a, Object value) { if (value instanceof Val) { return (Val) value; } - if (value instanceof Message) { - Message msg = (Message) value; + if (value instanceof Message msg) { String typeName = typeNameFromMessage(msg); if (typeName.isEmpty()) { return anyWithEmptyType(); @@ -84,8 +83,7 @@ public static Val nativeToValue(Db db, TypeAdapter a, Object value) { } static Object maybeUnwrapValue(Object value) { - if (value instanceof Value) { - Value v = (Value) value; + if (value instanceof Value v) { switch (v.getKindCase()) { case BOOL_VALUE: return v.getBoolValue(); diff --git a/core/src/main/java/org/projectnessie/cel/common/types/pb/FieldDescription.java b/core/src/main/java/org/projectnessie/cel/common/types/pb/FieldDescription.java index d5f6be7b..1bf6be71 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/pb/FieldDescription.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/pb/FieldDescription.java @@ -135,34 +135,18 @@ public static FieldDescription newFieldDescription(FieldDescriptor fieldDesc) { } private static Class reflectTypeOfField(FieldDescriptor fieldDesc) { - switch (fieldDesc.getType()) { - case DOUBLE: - return Double.class; - case FLOAT: - return Float.class; - case STRING: - return String.class; - case BOOL: - return Boolean.class; - case BYTES: - return ByteString.class; - case INT32: - case SFIXED32: - case SINT32: - return Integer.class; - case INT64: - case SFIXED64: - case SINT64: - return Long.class; - case UINT32: - case UINT64: - case FIXED32: - case FIXED64: - return ULong.class; - case ENUM: - return Enum.class; - } - return reflectTypeOf(fieldDesc.getDefaultValue()); + return switch (fieldDesc.getType()) { + case DOUBLE -> Double.class; + case FLOAT -> Float.class; + case STRING -> String.class; + case BOOL -> Boolean.class; + case BYTES -> ByteString.class; + case INT32, SFIXED32, SINT32 -> Integer.class; + case INT64, SFIXED64, SINT64 -> Long.class; + case UINT32, UINT64, FIXED32, FIXED64 -> ULong.class; + case ENUM -> Enum.class; + default -> reflectTypeOf(fieldDesc.getDefaultValue()); + }; } private FieldDescription( @@ -209,8 +193,7 @@ public FieldDescriptor descriptor() { * on more than just protobuf field accesses; however, the target here must be a protobuf.Message. */ public boolean isSet(Object target) { - if (target instanceof Message) { - Message v = (Message) target; + if (target instanceof Message v) { FieldDescriptor fd = fieldDescriptorFor(v); return fd != null && FieldDescription.hasValueForField(fd, v); } @@ -227,12 +210,11 @@ public boolean isSet(Object target) { * protobuf.Message. */ public Object getFrom(Db db, Object target) { - if (!(target instanceof Message)) { + if (!(target instanceof Message v)) { throw new IllegalArgumentException( String.format( "unsupported field selection target: (%s)%s", target.getClass().getName(), target)); } - Message v = (Message) target; // pbRef = v.protoReflect(); FieldDescriptor fd = fieldDescriptorFor(v); Object fieldVal = getValueFromField(fd, v); @@ -332,26 +314,16 @@ public Class reflectType() { if (r && desc.isMapField()) { return Map.class; } - switch (desc.getJavaType()) { - case ENUM: - case MESSAGE: - return reflectType; - case BOOLEAN: - return r ? Boolean[].class : Boolean.class; - case BYTE_STRING: - return r ? ByteString[].class : ByteString.class; - case DOUBLE: - return r ? Double[].class : Double.class; - case FLOAT: - return r ? Float[].class : Float.class; - case INT: - return r ? Integer[].class : Integer.class; - case LONG: - return r ? Long[].class : Long.class; - case STRING: - return r ? String[].class : String.class; - } - return reflectType; + return switch (desc.getJavaType()) { + case ENUM, MESSAGE -> reflectType; + case BOOLEAN -> r ? Boolean[].class : Boolean.class; + case BYTE_STRING -> r ? ByteString[].class : ByteString.class; + case DOUBLE -> r ? Double[].class : Double.class; + case FLOAT -> r ? Float[].class : Float.class; + case INT -> r ? Integer[].class : Integer.class; + case LONG -> r ? Long[].class : Long.class; + case STRING -> r ? String[].class : String.class; + }; } /** @@ -427,10 +399,9 @@ public int hashCode() { } public boolean hasField(Object target) { - if (!(target instanceof Message)) { + if (!(target instanceof Message message)) { return false; } - Message message = (Message) target; FieldDescriptor fd = fieldDescriptorFor(message); return fd != null && hasValueForField(fd, message); } @@ -474,8 +445,7 @@ public static Object getValueFromField(FieldDescriptor desc, Message message) { // is very inefficient. // There is no way to do a "message.getMapField(desc, key)" (aka a "reflective counterpart" // for the generated map accessor methods like 'getXXXTypeOrThrow()'), too. - if (v instanceof List) { - List lst = (List) v; + if (v instanceof List lst) { Map map = new HashMap<>(lst.size() * 4 / 3 + 1); FieldDescriptor keyDesc = desc.getMessageType().findFieldByNumber(1); FieldDescriptor valueDesc = desc.getMessageType().findFieldByNumber(2); @@ -485,8 +455,7 @@ public static Object getValueFromField(FieldDescriptor desc, Message message) { if (e instanceof MapEntry) { key = normalizeUnsignedValue(keyDesc, ((MapEntry) e).getKey()); value = normalizeUnsignedValue(valueDesc, ((MapEntry) e).getValue()); - } else if (e instanceof DynamicMessage) { - DynamicMessage dynMsg = (DynamicMessage) e; + } else if (e instanceof DynamicMessage dynMsg) { List fields = dynMsg.getDescriptorForType().getFields(); if (fields.size() == 2) { FieldDescriptor dynKeyDesc = fields.get(0); @@ -700,12 +669,10 @@ private FieldDescriptor entryValueDescriptor(Object entry) { } private Object rawMapEntryValue(Object entry, int fieldNumber) { - if (entry instanceof MapEntry) { - MapEntry mapEntry = (MapEntry) entry; + if (entry instanceof MapEntry mapEntry) { return fieldNumber == 1 ? mapEntry.getKey() : mapEntry.getValue(); } - if (entry instanceof DynamicMessage) { - DynamicMessage dynMsg = (DynamicMessage) entry; + if (entry instanceof DynamicMessage dynMsg) { List fields = dynMsg.getDescriptorForType().getFields(); if (fields.size() == 2) { return dynMsg.getField(fields.get(fieldNumber - 1)); diff --git a/core/src/main/java/org/projectnessie/cel/common/types/pb/PbObjectT.java b/core/src/main/java/org/projectnessie/cel/common/types/pb/PbObjectT.java index cb8c8ced..fae8e40e 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/pb/PbObjectT.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/pb/PbObjectT.java @@ -85,11 +85,10 @@ public Val get(Val index) { @Override public Val equal(Val other) { - if (!(other instanceof PbObjectT)) { + if (!(other instanceof PbObjectT otherObject)) { return super.equal(other); } - PbObjectT otherObject = (PbObjectT) other; if (!typeDesc().name().equals(otherObject.typeDesc().name())) { return boolOf(false); } @@ -108,9 +107,6 @@ public T convertToNative(Class typeDesc) { if (typeDesc.isAssignableFrom(getClass())) { return (T) this; } - if (typeDesc.isAssignableFrom(value.getClass())) { - return (T) value; - } if (typeDesc == DynamicMessage.class) { return (T) DynamicMessage.newBuilder(message().getDescriptorForType()).mergeFrom(message()).build(); @@ -188,7 +184,7 @@ private static boolean containsNaN(FieldDescriptor field, Object value) { private static String fieldMaskJsonValue(FieldMask fieldMask) { StringBuilder value = new StringBuilder(); for (String path : fieldMask.getPathsList()) { - if (value.length() > 0) { + if (!value.isEmpty()) { value.append(','); } value.append(fieldMaskPathJsonValue(path)); diff --git a/core/src/main/java/org/projectnessie/cel/common/types/pb/PbTypeDescription.java b/core/src/main/java/org/projectnessie/cel/common/types/pb/PbTypeDescription.java index 782b6ec2..09bb4dcb 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/pb/PbTypeDescription.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/pb/PbTypeDescription.java @@ -119,15 +119,13 @@ public Object maybeUnwrap(Db db, Object m) { if (this.reflectType == Any.class) { String realTypeUrl; ByteString realValue; - if (msg instanceof DynamicMessage) { - DynamicMessage dyn = (DynamicMessage) msg; + if (msg instanceof DynamicMessage dyn) { Descriptor dynDesc = dyn.getDescriptorForType(); FieldDescriptor fTypeUrl = dynDesc.findFieldByName("type_url"); FieldDescriptor fValue = dynDesc.findFieldByName("value"); realTypeUrl = (String) dyn.getField(fTypeUrl); realValue = (ByteString) dyn.getField(fValue); - } else if (msg instanceof Any) { - Any any = (Any) msg; + } else if (msg instanceof Any any) { realTypeUrl = any.getTypeUrl(); realValue = any.getValue(); } else { @@ -145,11 +143,9 @@ public Object maybeUnwrap(Db db, Object m) { } if (!(zeroMsg instanceof DynamicMessage)) { - if (msg instanceof Any) { - Any any = (Any) msg; + if (msg instanceof Any any) { msg = DynamicMessage.parseFrom(getDescriptor(), any.getValue(), db.extensionRegistry()); - } else if (msg instanceof DynamicMessage && !hasExtensions(msg)) { - DynamicMessage dyn = (DynamicMessage) msg; + } else if (msg instanceof DynamicMessage dyn && !hasExtensions(msg)) { msg = zeroMsg.getParserForType().parseFrom(dyn.toByteString(), db.extensionRegistry()); } } @@ -246,32 +242,23 @@ static Object unwrap(Db db, Description desc, Message msg) { return conv.apply(msg); } - if (msg instanceof Any) { - Any v = (Any) msg; + if (msg instanceof Any v) { DynamicMessage dyn = DynamicMessage.newBuilder(v).build(); return unwrapDynamic(db, desc, dyn); } if (msg instanceof DynamicMessage) { return unwrapDynamic(db, desc, msg); } - if (msg instanceof Value) { - Value v = (Value) msg; - switch (v.getKindCase()) { - case BOOL_VALUE: - return v.getBoolValue(); - case LIST_VALUE: - return v.getListValue(); - case NULL_VALUE: - return v.getNullValue(); - case NUMBER_VALUE: - return v.getNumberValue(); - case STRING_VALUE: - return v.getStringValue(); - case STRUCT_VALUE: - return v.getStructValue(); - default: - return NullValue.NULL_VALUE; - } + if (msg instanceof Value v) { + return switch (v.getKindCase()) { + case BOOL_VALUE -> v.getBoolValue(); + case LIST_VALUE -> v.getListValue(); + case NULL_VALUE -> v.getNullValue(); + case NUMBER_VALUE -> v.getNumberValue(); + case STRING_VALUE -> v.getStringValue(); + case STRUCT_VALUE -> v.getStructValue(); + default -> NullValue.NULL_VALUE; + }; } return msg; @@ -382,16 +369,14 @@ private static Object unwrapDynamicAny(Db db, Description desc, Message refMsg) } public static String typeNameFromMessage(Message message) { - if (message instanceof DynamicMessage) { - DynamicMessage dyn = (DynamicMessage) message; + if (message instanceof DynamicMessage dyn) { Descriptor dynDesc = dyn.getDescriptorForType(); if (dynDesc.getFullName().equals("google.protobuf.Any")) { FieldDescriptor f = dynDesc.findFieldByName("type_url"); String typeUrl = (String) dyn.getField(f); return typeNameFromUrl(typeUrl); } - } else if (message instanceof Any) { - Any any = (Any) message; + } else if (message instanceof Any any) { String typeUrl = any.getTypeUrl(); return typeNameFromUrl(typeUrl); } diff --git a/core/src/main/java/org/projectnessie/cel/common/types/pb/ProtoTypeRegistry.java b/core/src/main/java/org/projectnessie/cel/common/types/pb/ProtoTypeRegistry.java index dd567ead..96414259 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/pb/ProtoTypeRegistry.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/pb/ProtoTypeRegistry.java @@ -366,38 +366,23 @@ private static boolean isNullPrunedMessageField(FieldDescriptor field) { } private static Class messageNativeType(FieldDescriptor field) { - switch (field.getMessageType().getFullName()) { - case "google.protobuf.Any": - return Any.class; - case "google.protobuf.BoolValue": - return BoolValue.class; - case "google.protobuf.BytesValue": - return BytesValue.class; - case "google.protobuf.DoubleValue": - return DoubleValue.class; - case "google.protobuf.Duration": - return Duration.class; - case "google.protobuf.FieldMask": - return FieldMask.class; - case "google.protobuf.FloatValue": - return FloatValue.class; - case "google.protobuf.Int32Value": - return Int32Value.class; - case "google.protobuf.Int64Value": - return Int64Value.class; - case "google.protobuf.StringValue": - return StringValue.class; - case "google.protobuf.Timestamp": - return Timestamp.class; - case "google.protobuf.UInt32Value": - return UInt32Value.class; - case "google.protobuf.UInt64Value": - return UInt64Value.class; - case "google.protobuf.Value": - return Value.class; - default: - return Message.class; - } + return switch (field.getMessageType().getFullName()) { + case "google.protobuf.Any" -> Any.class; + case "google.protobuf.BoolValue" -> BoolValue.class; + case "google.protobuf.BytesValue" -> BytesValue.class; + case "google.protobuf.DoubleValue" -> DoubleValue.class; + case "google.protobuf.Duration" -> Duration.class; + case "google.protobuf.FieldMask" -> FieldMask.class; + case "google.protobuf.FloatValue" -> FloatValue.class; + case "google.protobuf.Int32Value" -> Int32Value.class; + case "google.protobuf.Int64Value" -> Int64Value.class; + case "google.protobuf.StringValue" -> StringValue.class; + case "google.protobuf.Timestamp" -> Timestamp.class; + case "google.protobuf.UInt32Value" -> UInt32Value.class; + case "google.protobuf.UInt64Value" -> UInt64Value.class; + case "google.protobuf.Value" -> Value.class; + default -> Message.class; + }; } /** @@ -454,8 +439,7 @@ private Object intToProtoEnumValues(FieldDescription field, Object value) { if (value instanceof Number) { int enumValue = ((Number) value).intValue(); value = enumType.findValueByNumberCreatingIfUnknown(enumValue); - } else if (value instanceof List) { - List list = (List) value; + } else if (value instanceof List list) { List newList = new ArrayList(list.size()); for (Object o : list) { int enumValue = ((Number) o).intValue(); @@ -502,8 +486,7 @@ public void registerType(org.projectnessie.cel.common.types.ref.Type... types) { */ @Override public Val nativeToValue(Object value) { - if (value instanceof Message) { - Message v = (Message) value; + if (value instanceof Message v) { String typeName = typeNameFromMessage(v); if (typeName.isEmpty()) { return anyWithEmptyType(); diff --git a/core/src/main/java/org/projectnessie/cel/common/types/ref/TypeAdapterSupport.java b/core/src/main/java/org/projectnessie/cel/common/types/ref/TypeAdapterSupport.java index a4ed052f..9c029a3d 100644 --- a/core/src/main/java/org/projectnessie/cel/common/types/ref/TypeAdapterSupport.java +++ b/core/src/main/java/org/projectnessie/cel/common/types/ref/TypeAdapterSupport.java @@ -125,8 +125,7 @@ public static Val maybeNativeToValue(TypeAdapter a, Object value) { if (value instanceof Collection) { return newGenericArrayList(a, ((Collection) value).toArray()); } - if (value instanceof Optional) { - Optional optional = (Optional) value; + if (value instanceof Optional optional) { return optional.map(a::nativeToValue).orElse(NullT.NullValue); } if (value instanceof Map) { diff --git a/core/src/main/java/org/projectnessie/cel/extension/NetworkLib.java b/core/src/main/java/org/projectnessie/cel/extension/NetworkLib.java index a84cce82..2e53bd97 100644 --- a/core/src/main/java/org/projectnessie/cel/extension/NetworkLib.java +++ b/core/src/main/java/org/projectnessie/cel/extension/NetworkLib.java @@ -387,29 +387,25 @@ public Val receive(String function, String overload, Val... args) { if (args.length != 0) { return noSuchOverload(this, function, overload, args); } - switch (function) { - case "family": - return intOf(family); - case "isUnspecified": - return boolOf(unsigned(bytes).signum() == 0); - case "isLoopback": - return boolOf( - family == 4 ? (bytes[0] & 0xff) == 127 : unsigned(bytes).equals(BigInteger.ONE)); - case "isGlobalUnicast": - return boolOf(!isMulticast() && unsigned(bytes).signum() != 0 && !isBroadcast()); - case "isLinkLocalMulticast": - return boolOf( - family == 4 - ? canonical.startsWith("224.0.0.") - : (bytes[0] & 0xff) == 0xff && (bytes[1] & 0xff) == 0x02); - case "isLinkLocalUnicast": - return boolOf( - family == 4 - ? (bytes[0] & 0xff) == 169 && (bytes[1] & 0xff) == 254 - : (bytes[0] & 0xff) == 0xfe && ((bytes[1] & 0xc0) == 0x80)); - default: - return noSuchOverload(this, function, overload, args); - } + return switch (function) { + case "family" -> intOf(family); + case "isUnspecified" -> boolOf(unsigned(bytes).signum() == 0); + case "isLoopback" -> + boolOf(family == 4 ? (bytes[0] & 0xff) == 127 : unsigned(bytes).equals(BigInteger.ONE)); + case "isGlobalUnicast" -> + boolOf(!isMulticast() && unsigned(bytes).signum() != 0 && !isBroadcast()); + case "isLinkLocalMulticast" -> + boolOf( + family == 4 + ? canonical.startsWith("224.0.0.") + : (bytes[0] & 0xff) == 0xff && (bytes[1] & 0xff) == 0x02); + case "isLinkLocalUnicast" -> + boolOf( + family == 4 + ? (bytes[0] & 0xff) == 169 && (bytes[1] & 0xff) == 254 + : (bytes[0] & 0xff) == 0xfe && ((bytes[1] & 0xc0) == 0x80)); + default -> noSuchOverload(this, function, overload, args); + }; } private boolean isMulticast() { @@ -477,20 +473,16 @@ public Val equal(Val other) { @Override public Val receive(String function, String overload, Val... args) { - switch (function) { - case "containsIP": - return containsIp(args); - case "containsCIDR": - return containsCidr(args); - case "ip": - return args.length == 0 ? ip : noSuchOverload(this, function, overload, args); - case "masked": - return args.length == 0 ? masked() : noSuchOverload(this, function, overload, args); - case "prefixLength": - return args.length == 0 ? intOf(prefix) : noSuchOverload(this, function, overload, args); - default: - return noSuchOverload(this, function, overload, args); - } + return switch (function) { + case "containsIP" -> containsIp(args); + case "containsCIDR" -> containsCidr(args); + case "ip" -> args.length == 0 ? ip : noSuchOverload(this, function, overload, args); + case "masked" -> + args.length == 0 ? masked() : noSuchOverload(this, function, overload, args); + case "prefixLength" -> + args.length == 0 ? intOf(prefix) : noSuchOverload(this, function, overload, args); + default -> noSuchOverload(this, function, overload, args); + }; } private Val containsIp(Val[] args) { diff --git a/core/src/main/java/org/projectnessie/cel/extension/StringsLib.java b/core/src/main/java/org/projectnessie/cel/extension/StringsLib.java index 32056c91..571ebcd1 100644 --- a/core/src/main/java/org/projectnessie/cel/extension/StringsLib.java +++ b/core/src/main/java/org/projectnessie/cel/extension/StringsLib.java @@ -297,84 +297,79 @@ public List getCompileOptions() { Decls.newFunction( CHAR_AT, Decls.newInstanceOverload( - "string_char_at_int", Arrays.asList(Decls.String, Decls.Int), Decls.String)), + "string_char_at_int", List.of(Decls.String, Decls.Int), Decls.String)), Decls.newFunction( INDEX_OF, Decls.newInstanceOverload( - "string_index_of_string", Arrays.asList(Decls.String, Decls.String), Decls.Int), + "string_index_of_string", List.of(Decls.String, Decls.String), Decls.Int), Decls.newInstanceOverload( "string_index_of_string_int", - Arrays.asList(Decls.String, Decls.String, Decls.Int), + List.of(Decls.String, Decls.String, Decls.Int), Decls.Int)), Decls.newFunction( JOIN, Decls.newInstanceOverload( - "list_join", Arrays.asList(Decls.newListType(Decls.String)), Decls.String), + "list_join", List.of(Decls.newListType(Decls.String)), Decls.String), Decls.newInstanceOverload( "list_join_string", - Arrays.asList(Decls.newListType(Decls.String), Decls.String), + List.of(Decls.newListType(Decls.String), Decls.String), Decls.String)), Decls.newFunction( LAST_INDEX_OF, Decls.newInstanceOverload( - "string_last_index_of_string", - Arrays.asList(Decls.String, Decls.String), - Decls.Int), + "string_last_index_of_string", List.of(Decls.String, Decls.String), Decls.Int), Decls.newInstanceOverload( "string_last_index_of_string_int", - Arrays.asList(Decls.String, Decls.String, Decls.Int), + List.of(Decls.String, Decls.String, Decls.Int), Decls.Int)), Decls.newFunction( LOWER_ASCII, Decls.newInstanceOverload( - "string_lower_ascii", Arrays.asList(Decls.String), Decls.String)), + "string_lower_ascii", List.of(Decls.String), Decls.String)), Decls.newFunction( REPLACE, Decls.newInstanceOverload( "string_replace_string_string", - Arrays.asList(Decls.String, Decls.String, Decls.String), + List.of(Decls.String, Decls.String, Decls.String), Decls.String), Decls.newInstanceOverload( "string_replace_string_string_int", - Arrays.asList(Decls.String, Decls.String, Decls.String, Decls.Int), + List.of(Decls.String, Decls.String, Decls.String, Decls.Int), Decls.String)), Decls.newFunction( REVERSE, - Decls.newInstanceOverload( - "string_reverse", Arrays.asList(Decls.String), Decls.String)), + Decls.newInstanceOverload("string_reverse", List.of(Decls.String), Decls.String)), Decls.newFunction( SPLIT, Decls.newInstanceOverload( - "string_split_string", Arrays.asList(Decls.String, Decls.String), Decls.Dyn), + "string_split_string", List.of(Decls.String, Decls.String), Decls.Dyn), Decls.newInstanceOverload( "string_split_string_int", - Arrays.asList(Decls.String, Decls.String, Decls.Int), + List.of(Decls.String, Decls.String, Decls.Int), Decls.Dyn)), Decls.newFunction( SUBSTR, Decls.newInstanceOverload( - "string_substring_int", Arrays.asList(Decls.String, Decls.Int), Decls.String), + "string_substring_int", List.of(Decls.String, Decls.Int), Decls.String), Decls.newInstanceOverload( "string_substring_int_int", - Arrays.asList(Decls.String, Decls.Int, Decls.Int), + List.of(Decls.String, Decls.Int, Decls.Int), Decls.String)), Decls.newFunction( TRIM_SPACE, - Decls.newInstanceOverload( - "string_trim", Arrays.asList(Decls.String), Decls.String)), + Decls.newInstanceOverload("string_trim", List.of(Decls.String), Decls.String)), Decls.newFunction( UPPER_ASCII, Decls.newInstanceOverload( - "string_upper_ascii", Arrays.asList(Decls.String), Decls.String)), + "string_upper_ascii", List.of(Decls.String), Decls.String)), Decls.newFunction( FORMAT, Decls.newInstanceOverload( "string_format", - Arrays.asList(Decls.String, Decls.newListType(Decls.Dyn)), + List.of(Decls.String, Decls.newListType(Decls.Dyn)), Decls.String)), Decls.newFunction( - QUOTE, - Decls.newOverload("strings_quote", Arrays.asList(Decls.String), Decls.String))); + QUOTE, Decls.newOverload("strings_quote", List.of(Decls.String), Decls.String))); return List.of(option); } @@ -572,7 +567,7 @@ static String replaceN(String str, String old, String replacement, int n) { int count = 0; for (; count < n && index < str.length(); count++) { - if (old.length() == 0) { + if (old.isEmpty()) { stringBuilder.append(replacement).append(str, index, index + 1); index++; } else { @@ -623,7 +618,7 @@ static String[] splitN(String s, String sep, int n) { if (n == 1) { return new String[] {s}; } - if (sep.length() == 0) { + if (sep.isEmpty()) { return explode(s, n); } @@ -789,57 +784,37 @@ private static String formatPattern(String pattern, Sizer argsSizer, Indexer arg } private static String formatValue(char clause, int precision, Val arg) { - switch (clause) { - case 's': - return renderStringClause(arg); - case 'd': - return renderDecimalClause(arg); - case 'b': - return renderBinaryClause(arg); - case 'o': - return renderOctalClause(arg); - case 'x': - case 'X': - return renderHexClause(arg, clause == 'X'); - case 'f': - return renderFixedPointClause(arg, precision >= 0 ? precision : 6); - case 'e': - return renderScientificClause(arg, precision >= 0 ? precision : 6); - default: - throw new FormatException( - "could not parse formatting clause: unrecognized formatting clause \"%s\"", clause); - } + return switch (clause) { + case 's' -> renderStringClause(arg); + case 'd' -> renderDecimalClause(arg); + case 'b' -> renderBinaryClause(arg); + case 'o' -> renderOctalClause(arg); + case 'x', 'X' -> renderHexClause(arg, clause == 'X'); + case 'f' -> renderFixedPointClause(arg, precision >= 0 ? precision : 6); + case 'e' -> renderScientificClause(arg, precision >= 0 ? precision : 6); + default -> + throw new FormatException( + "could not parse formatting clause: unrecognized formatting clause \"%s\"", clause); + }; } private static String renderStringClause(Val value) { - switch (value.type().typeEnum()) { - case String: - return value.value().toString(); - case Bool: - return Boolean.toString(value.booleanValue()); - case Bytes: - return new String(value.convertToNative(byte[].class), UTF_8); - case Int: - return Long.toString(value.intValue()); - case Uint: - return Long.toUnsignedString(value.intValue()); - case Double: - return renderDouble(value.doubleValue()); - case Null: - return "null"; - case Type: - case Duration: - case Timestamp: - return value.convertToType(StringT.StringType).value().toString(); - case List: - return renderList(value); - case Map: - return renderMap(value); - default: - throw new FormatException( - "error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given %s", - value.type().typeName()); - } + return switch (value.type().typeEnum()) { + case String -> value.value().toString(); + case Bool -> Boolean.toString(value.booleanValue()); + case Bytes -> new String(value.convertToNative(byte[].class), UTF_8); + case Int -> Long.toString(value.intValue()); + case Uint -> Long.toUnsignedString(value.intValue()); + case Double -> renderDouble(value.doubleValue()); + case Null -> "null"; + case Type, Duration, Timestamp -> value.convertToType(StringT.StringType).value().toString(); + case List -> renderList(value); + case Map -> renderMap(value); + default -> + throw new FormatException( + "error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given %s", + value.type().typeName()); + }; } private static String renderDecimalClause(Val value) { @@ -862,53 +837,40 @@ private static String renderDecimalClause(Val value) { } private static String renderBinaryClause(Val value) { - switch (value.type().typeEnum()) { - case Int: - return Long.toBinaryString(value.intValue()); - case Uint: - return Long.toUnsignedString(value.intValue(), 2); - case Bool: - return value.booleanValue() ? "1" : "0"; - default: - throw new FormatException( - "error during formatting: only integers and bools can be formatted as binary, was given %s", - value.type().typeName()); - } + return switch (value.type().typeEnum()) { + case Int -> Long.toBinaryString(value.intValue()); + case Uint -> Long.toUnsignedString(value.intValue(), 2); + case Bool -> value.booleanValue() ? "1" : "0"; + default -> + throw new FormatException( + "error during formatting: only integers and bools can be formatted as binary, was given %s", + value.type().typeName()); + }; } private static String renderOctalClause(Val value) { - switch (value.type().typeEnum()) { - case Int: - return Long.toOctalString(value.intValue()); - case Uint: - return Long.toUnsignedString(value.intValue(), 8); - default: - throw new FormatException( - "error during formatting: octal clause can only be used on integers, was given %s", - value.type().typeName()); - } + return switch (value.type().typeEnum()) { + case Int -> Long.toOctalString(value.intValue()); + case Uint -> Long.toUnsignedString(value.intValue(), 8); + default -> + throw new FormatException( + "error during formatting: octal clause can only be used on integers, was given %s", + value.type().typeName()); + }; } private static String renderHexClause(Val value, boolean upperCase) { - String hex; - switch (value.type().typeEnum()) { - case Int: - hex = Long.toHexString(value.intValue()); - break; - case Uint: - hex = Long.toUnsignedString(value.intValue(), 16); - break; - case String: - hex = bytesToHex(value.value().toString().getBytes(UTF_8)); - break; - case Bytes: - hex = bytesToHex(value.convertToNative(byte[].class)); - break; - default: - throw new FormatException( - "error during formatting: only integers, byte buffers, and strings can be formatted as hex, was given %s", - value.type().typeName()); - } + String hex = + switch (value.type().typeEnum()) { + case Int -> Long.toHexString(value.intValue()); + case Uint -> Long.toUnsignedString(value.intValue(), 16); + case String -> bytesToHex(value.value().toString().getBytes(UTF_8)); + case Bytes -> bytesToHex(value.convertToNative(byte[].class)); + default -> + throw new FormatException( + "error during formatting: only integers, byte buffers, and strings can be formatted as hex, was given %s", + value.type().typeName()); + }; return upperCase ? hex.toUpperCase(Locale.ROOT) : hex; } diff --git a/core/src/main/java/org/projectnessie/cel/interpreter/AstPruner.java b/core/src/main/java/org/projectnessie/cel/interpreter/AstPruner.java index e8b701f1..17f911cd 100644 --- a/core/src/main/java/org/projectnessie/cel/interpreter/AstPruner.java +++ b/core/src/main/java/org/projectnessie/cel/interpreter/AstPruner.java @@ -124,8 +124,7 @@ Expr maybeCreateLiteral(long id, Val v) { } // Attempt to build a list literal. - if (v instanceof Lister) { - Lister list = (Lister) v; + if (v instanceof Lister list) { int sz = (int) list.size().intValue(); List elemExprs = new ArrayList<>(sz); for (int i = 0; i < sz; i++) { @@ -146,8 +145,7 @@ Expr maybeCreateLiteral(long id, Val v) { } // Create a map literal if possible. - if (v instanceof Mapper) { - Mapper mp = (Mapper) v; + if (v instanceof Mapper mp) { IteratorT it = mp.iterator(); List entries = new ArrayList<>((int) mp.size().intValue()); while (it.hasNext() == True) { diff --git a/core/src/main/java/org/projectnessie/cel/interpreter/AttributeFactory.java b/core/src/main/java/org/projectnessie/cel/interpreter/AttributeFactory.java index 04b6e856..44618e0e 100644 --- a/core/src/main/java/org/projectnessie/cel/interpreter/AttributeFactory.java +++ b/core/src/main/java/org/projectnessie/cel/interpreter/AttributeFactory.java @@ -235,8 +235,7 @@ public AttributeFactory.Qualifier newQualifier(Type objType, long qualID, Object // Before creating a new qualifier check to see if this is a protobuf message field access. // If so, use the precomputed GetFrom qualification method rather than the standard // stringQualifier. - if (val instanceof String) { - String str = (String) val; + if (val instanceof String str) { if (objType != null && !objType.getMessageType().isEmpty()) { FieldType ft = provider.findFieldType(objType.getMessageType(), str); if (ft != null && ft.isSet != null && ft.getFrom != null) { @@ -384,10 +383,8 @@ public Object tryResolve(org.projectnessie.cel.interpreter.Activation vars) { } private Object tryResolveCurrentVar(org.projectnessie.cel.interpreter.Activation vars) { - if (vars instanceof org.projectnessie.cel.interpreter.Activation.VarActivation + if (vars instanceof Activation.VarActivation var && (namespaceNames.length > 1 || !qualifiers.isEmpty())) { - org.projectnessie.cel.interpreter.Activation.VarActivation var = - (org.projectnessie.cel.interpreter.Activation.VarActivation) vars; String localName = namespaceNames[namespaceNames.length - 1]; if (localName.equals(var.name)) { return resolveQualifiers(vars, var.val); @@ -602,8 +599,7 @@ public Cost cost() { public Attribute addQualifier(AttributeFactory.Qualifier qual) { String str = ""; boolean isStr = false; - if (qual instanceof ConstantQualifier) { - ConstantQualifier cq = (ConstantQualifier) qual; + if (qual instanceof ConstantQualifier cq) { Object cqv = cq.value().value(); if (cqv instanceof String) { str = (String) cqv; @@ -779,8 +775,7 @@ static Qualifier newQualifierStatic(TypeAdapter adapter, long id, Object v) { Class c = v.getClass(); - if (v instanceof Val) { - Val val = (Val) v; + if (v instanceof Val val) { switch (val.type().typeEnum()) { case String: return new StringQualifier(id, (String) val.value(), val, adapter); @@ -888,8 +883,7 @@ public long id() { @Override public Object qualify(org.projectnessie.cel.interpreter.Activation vars, Object obj) { String s = value; - if (obj instanceof Map) { - Map m = (Map) obj; + if (obj instanceof Map m) { obj = m.get(s); if (obj == null) { if (m.containsKey(s)) { @@ -965,8 +959,7 @@ public long id() { @Override public Object qualify(org.projectnessie.cel.interpreter.Activation vars, Object obj) { double i = value; - if (obj instanceof Map) { - Map m = (Map) obj; + if (obj instanceof Map m) { obj = m.get(i); if (obj == null) { obj = m.get((int) i); @@ -987,8 +980,7 @@ public Object qualify(org.projectnessie.cel.interpreter.Activation vars, Object obj = Array.get(obj, (int) i); return obj; } - if (obj instanceof List) { - List list = (List) obj; + if (obj instanceof List list) { int l = list.size(); if (i < 0 || i >= l) { throw indexOutOfBoundsException(i); @@ -1064,8 +1056,7 @@ public long id() { @Override public Object qualify(org.projectnessie.cel.interpreter.Activation vars, Object obj) { long i = value; - if (obj instanceof Map) { - Map m = (Map) obj; + if (obj instanceof Map m) { obj = m.get(i); if (obj == null) { obj = m.get((int) i); @@ -1086,8 +1077,7 @@ public Object qualify(org.projectnessie.cel.interpreter.Activation vars, Object obj = Array.get(obj, (int) i); return obj; } - if (obj instanceof List) { - List list = (List) obj; + if (obj instanceof List list) { int l = list.size(); if (i < 0 || i >= l) { throw indexOutOfBoundsException(i); @@ -1163,8 +1153,7 @@ public long id() { @Override public Object qualify(org.projectnessie.cel.interpreter.Activation vars, Object obj) { long i = value; - if (obj instanceof Map) { - Map m = (Map) obj; + if (obj instanceof Map m) { obj = m.get(ULong.valueOf(i)); if (obj == null) { throw noSuchKeyException(i); @@ -1244,8 +1233,7 @@ public long id() { @Override public Object qualify(org.projectnessie.cel.interpreter.Activation vars, Object obj) { boolean b = value; - if (obj instanceof Map) { - Map m = (Map) obj; + if (obj instanceof Map m) { obj = m.get(b); if (obj == null) { if (m.containsKey(b)) { @@ -1433,16 +1421,14 @@ public String toString() { */ static Val refResolve(TypeAdapter adapter, Val idx, Object obj) { Val celVal = adapter.nativeToValue(obj); - if (celVal instanceof Mapper) { - Mapper mapper = (Mapper) celVal; + if (celVal instanceof Mapper mapper) { Val elem = mapper.find(idx); if (elem == null) { return noSuchKey(idx); } return elem; } - if (celVal instanceof Indexer) { - Indexer indexer = (Indexer) celVal; + if (celVal instanceof Indexer indexer) { return indexer.get(idx); } if (isUnknown(celVal)) { diff --git a/core/src/main/java/org/projectnessie/cel/interpreter/AttributePattern.java b/core/src/main/java/org/projectnessie/cel/interpreter/AttributePattern.java index 44788c08..b8281d38 100644 --- a/core/src/main/java/org/projectnessie/cel/interpreter/AttributePattern.java +++ b/core/src/main/java/org/projectnessie/cel/interpreter/AttributePattern.java @@ -165,8 +165,7 @@ public boolean matches(Qualifier q) { if (wildcard) { return true; } - if (q instanceof QualifierValueEquator) { - QualifierValueEquator qve = (QualifierValueEquator) q; + if (q instanceof QualifierValueEquator qve) { return qve.qualifierValueEquals(value); } return false; @@ -419,8 +418,7 @@ public Object resolve(org.projectnessie.cel.interpreter.Activation vars) { @Override public Object tryResolve(org.projectnessie.cel.interpreter.Activation vars) { long id = attr.id(); - if (vars instanceof PartialActivation) { - PartialActivation partial = (PartialActivation) vars; + if (vars instanceof PartialActivation partial) { Object unk = fac.matchesUnknownPatterns(partial, id, candidateVariableNames(), qualifiers); if (unk != null) { return unk; diff --git a/core/src/main/java/org/projectnessie/cel/interpreter/Interpretable.java b/core/src/main/java/org/projectnessie/cel/interpreter/Interpretable.java index 0da9f719..c01caf66 100644 --- a/core/src/main/java/org/projectnessie/cel/interpreter/Interpretable.java +++ b/core/src/main/java/org/projectnessie/cel/interpreter/Interpretable.java @@ -215,11 +215,9 @@ public long id() { public Val eval(org.projectnessie.cel.interpreter.Activation ctx) { // Handle field selection on a proto in the most efficient way possible. if (fieldType != null) { - if (op instanceof InterpretableAttribute) { - InterpretableAttribute opAttr = (InterpretableAttribute) op; + if (op instanceof InterpretableAttribute opAttr) { Object opVal = opAttr.resolve(ctx); - if (opVal instanceof Val) { - Val refVal = (Val) opVal; + if (opVal instanceof Val refVal) { opVal = refVal.value(); } if (fieldType.isSet.isSet(opVal)) { @@ -586,13 +584,11 @@ public Val eval(org.projectnessie.cel.interpreter.Activation ctx) { return rVal; } Val eqVal = lVal.equal(rVal); - switch (eqVal.type().typeEnum()) { - case Err: - return eqVal; - case Bool: - return ((Negater) eqVal).negate(); - } - return noSuchOverload(lVal, Operator.NotEquals.id, rVal); + return switch (eqVal.type().typeEnum()) { + case Err -> eqVal; + case Bool -> ((Negater) eqVal).negate(); + default -> noSuchOverload(lVal, Operator.NotEquals.id, rVal); + }; } /** Cost implements the Coster interface method. */ @@ -983,10 +979,9 @@ public Val eval(org.projectnessie.cel.interpreter.Activation ctx) { return elemVal; } if (optionalIndices[i]) { - if (!(elemVal instanceof OptionalT)) { + if (!(elemVal instanceof OptionalT optional)) { return newErr("optional list element is not optional"); } - OptionalT optional = (OptionalT) elemVal; if (!optional.hasValue()) { continue; } @@ -1051,10 +1046,9 @@ public Val eval(org.projectnessie.cel.interpreter.Activation ctx) { return valVal; } if (optionalEntries[i]) { - if (!(valVal instanceof OptionalT)) { + if (!(valVal instanceof OptionalT optional)) { return newErr("optional map entry is not optional"); } - OptionalT optional = (OptionalT) valVal; if (!optional.hasValue()) { continue; } @@ -1128,10 +1122,9 @@ public Val eval(org.projectnessie.cel.interpreter.Activation ctx) { return val; } if (optionalEntries[i]) { - if (!(val instanceof OptionalT)) { + if (!(val instanceof OptionalT optional)) { return newErr("optional message field is not optional"); } - OptionalT optional = (OptionalT) val; if (!optional.hasValue()) { continue; } @@ -1678,14 +1671,11 @@ public Val eval(org.projectnessie.cel.interpreter.Activation ctx) { return arg0; } - switch (args.length) { - case 3: - return evalReceiverTail2(ctx, arg0); - case 4: - return evalReceiverTail3(ctx, arg0); - default: - return evalReceiverTail(ctx, arg0); - } + return switch (args.length) { + case 3 -> evalReceiverTail2(ctx, arg0); + case 4 -> evalReceiverTail3(ctx, arg0); + default -> evalReceiverTail(ctx, arg0); + }; } private Val evalReceiverTail2(org.projectnessie.cel.interpreter.Activation ctx, Val arg0) { @@ -1778,18 +1768,14 @@ public String toString() { } static Val receiveVarArgs(Receiver receiver, String function, String overload, Val[] argVals) { - switch (argVals.length) { - case 1: - return receiver.receive(function, overload); - case 2: - return receiver.receive(function, overload, argVals[1]); - case 3: - return receiver.receive(function, overload, argVals[1], argVals[2]); - case 4: - return receiver.receive(function, overload, argVals[1], argVals[2], argVals[3]); - default: - return receiver.receive(function, overload, Arrays.copyOfRange(argVals, 1, argVals.length)); - } + return switch (argVals.length) { + case 1 -> receiver.receive(function, overload); + case 2 -> receiver.receive(function, overload, argVals[1]); + case 3 -> receiver.receive(function, overload, argVals[1], argVals[2]); + case 4 -> receiver.receive(function, overload, argVals[1], argVals[2], argVals[3]); + default -> + receiver.receive(function, overload, Arrays.copyOfRange(argVals, 1, argVals.length)); + }; } /** @@ -1856,11 +1842,9 @@ public long id() { */ @Override public Attribute addQualifier(AttributeFactory.Qualifier q) { - if (q instanceof ConstantQualifierEquator) { - ConstantQualifierEquator cq = (ConstantQualifierEquator) q; + if (q instanceof ConstantQualifierEquator cq) { q = new EvalWatchConstQualEquat(cq, observer, attr.adapter()); - } else if (q instanceof ConstantQualifier) { - ConstantQualifier cq = (ConstantQualifier) q; + } else if (q instanceof ConstantQualifier cq) { q = new EvalWatchConstQual(cq, observer, attr.adapter()); } else { q = new EvalWatchQual(q, observer, attr.adapter()); diff --git a/core/src/main/java/org/projectnessie/cel/interpreter/InterpretableDecorator.java b/core/src/main/java/org/projectnessie/cel/interpreter/InterpretableDecorator.java index a7665ef1..dfc43d6b 100644 --- a/core/src/main/java/org/projectnessie/cel/interpreter/InterpretableDecorator.java +++ b/core/src/main/java/org/projectnessie/cel/interpreter/InterpretableDecorator.java @@ -91,16 +91,13 @@ static InterpretableDecorator decObserveEval(EvalObserver observer) { */ static InterpretableDecorator decDisableShortcircuits() { return i -> { - if (i instanceof EvalOr) { - EvalOr expr = (EvalOr) i; + if (i instanceof EvalOr expr) { return new EvalExhaustiveOr(expr.id, expr.lhs, expr.rhs); } - if (i instanceof EvalAnd) { - EvalAnd expr = (EvalAnd) i; + if (i instanceof EvalAnd expr) { return new EvalExhaustiveAnd(expr.id, expr.lhs, expr.rhs); } - if (i instanceof EvalFold) { - EvalFold expr = (EvalFold) i; + if (i instanceof EvalFold expr) { return new EvalExhaustiveFold( expr.id, expr.accu, @@ -112,14 +109,13 @@ static InterpretableDecorator decDisableShortcircuits() { expr.step, expr.result); } - if (i instanceof EvalListFold) { - return new EvalExhaustiveListFold((EvalListFold) i); + if (i instanceof EvalListFold fold) { + return new EvalExhaustiveListFold(fold); } - if (i instanceof EvalMapFold) { - return new EvalExhaustiveMapFold((EvalMapFold) i); + if (i instanceof EvalMapFold fold) { + return new EvalExhaustiveMapFold(fold); } - if (i instanceof InterpretableAttribute) { - InterpretableAttribute expr = (InterpretableAttribute) i; + if (i instanceof InterpretableAttribute expr) { if (expr.attr() instanceof ConditionalAttribute) { return new EvalExhaustiveConditional( i.id(), expr.adapter(), (ConditionalAttribute) expr.attr()); @@ -146,8 +142,7 @@ static InterpretableDecorator decOptimize() { if (i instanceof EvalMap) { return maybeBuildMapLiteral(i, (EvalMap) i); } - if (i instanceof InterpretableCall) { - InterpretableCall inst = (InterpretableCall) i; + if (i instanceof InterpretableCall inst) { if (inst.overloadID().equals(Overloads.InList)) { return maybeOptimizeSetMembership(i, inst); } @@ -206,10 +201,9 @@ static Interpretable maybeOptimizeSetMembership(Interpretable i, InterpretableCa Interpretable[] args = inlist.args(); Interpretable lhs = args[0]; Interpretable rhs = args[1]; - if (!(rhs instanceof InterpretableConst)) { + if (!(rhs instanceof InterpretableConst l)) { return i; } - InterpretableConst l = (InterpretableConst) rhs; // When the incoming binary call is flagged with as the InList overload, the value will // always be convertible to a `traits.Lister` type. Lister list = (Lister) l.value(); diff --git a/core/src/main/java/org/projectnessie/cel/interpreter/InterpretablePlanner.java b/core/src/main/java/org/projectnessie/cel/interpreter/InterpretablePlanner.java index 07a72709..44745005 100644 --- a/core/src/main/java/org/projectnessie/cel/interpreter/InterpretablePlanner.java +++ b/core/src/main/java/org/projectnessie/cel/interpreter/InterpretablePlanner.java @@ -178,24 +178,18 @@ static final class Planner implements InterpretablePlanner { */ @Override public Interpretable plan(Expr expr) { - switch (expr.getExprKindCase()) { - case CALL_EXPR: - return decorate(planCall(expr)); - case IDENT_EXPR: - return decorate(planIdent(expr)); - case SELECT_EXPR: - return decorate(planSelect(expr)); - case LIST_EXPR: - return decorate(planCreateList(expr)); - case STRUCT_EXPR: - return decorate(planCreateStruct(expr)); - case COMPREHENSION_EXPR: - return decorate(planComprehension(expr)); - case CONST_EXPR: - return decorate(planConst(expr)); - } - throw new IllegalArgumentException( - String.format("unsupported expr of kind %s: '%s'", expr.getExprKindCase(), expr)); + return switch (expr.getExprKindCase()) { + case CALL_EXPR -> decorate(planCall(expr)); + case IDENT_EXPR -> decorate(planIdent(expr)); + case SELECT_EXPR -> decorate(planSelect(expr)); + case LIST_EXPR -> decorate(planCreateList(expr)); + case STRUCT_EXPR -> decorate(planCreateStruct(expr)); + case COMPREHENSION_EXPR -> decorate(planComprehension(expr)); + case CONST_EXPR -> decorate(planConst(expr)); + default -> + throw new IllegalArgumentException( + String.format("unsupported expr of kind %s: '%s'", expr.getExprKindCase(), expr)); + }; } /** @@ -311,8 +305,7 @@ Interpretable planSelect(Expr expr) { return null; } // Lastly, create a field selection Interpretable. - if (op instanceof InterpretableAttribute) { - InterpretableAttribute attr = (InterpretableAttribute) op; + if (op instanceof InterpretableAttribute attr) { attr.addQualifier(qual); return attr; } @@ -418,16 +411,12 @@ Interpretable planCall(Expr expr) { if (fnDef == null) { fnDef = disp.findOverload(resolvedFunc.fnName); } - switch (argCount) { - case 0: - return planCallZero(expr, resolvedFunc.fnName, resolvedFunc.overloadId, fnDef); - case 1: - return planCallUnary(expr, resolvedFunc.fnName, resolvedFunc.overloadId, fnDef, args); - case 2: - return planCallBinary(expr, resolvedFunc.fnName, resolvedFunc.overloadId, fnDef, args); - default: - return planCallVarArgs(expr, resolvedFunc.fnName, resolvedFunc.overloadId, fnDef, args); - } + return switch (argCount) { + case 0 -> planCallZero(expr, resolvedFunc.fnName, resolvedFunc.overloadId, fnDef); + case 1 -> planCallUnary(expr, resolvedFunc.fnName, resolvedFunc.overloadId, fnDef, args); + case 2 -> planCallBinary(expr, resolvedFunc.fnName, resolvedFunc.overloadId, fnDef, args); + default -> planCallVarArgs(expr, resolvedFunc.fnName, resolvedFunc.overloadId, fnDef, args); + }; } /** planCallZero generates a zero-arity callable Interpretable. */ @@ -511,8 +500,7 @@ Interpretable planCallConditional(Expr expr, Interpretable... args) { Interpretable t = args[1]; Attribute tAttr; - if (t instanceof InterpretableAttribute) { - InterpretableAttribute truthyAttr = (InterpretableAttribute) t; + if (t instanceof InterpretableAttribute truthyAttr) { tAttr = truthyAttr.attr(); } else { tAttr = attrFactory.relativeAttribute(t.id(), t); @@ -520,8 +508,7 @@ Interpretable planCallConditional(Expr expr, Interpretable... args) { Interpretable f = args[2]; Attribute fAttr; - if (f instanceof InterpretableAttribute) { - InterpretableAttribute falsyAttr = (InterpretableAttribute) f; + if (f instanceof InterpretableAttribute falsyAttr) { fAttr = falsyAttr.attr(); } else { fAttr = attrFactory.relativeAttribute(f.id(), f); @@ -543,8 +530,7 @@ Interpretable planCallIndex(Expr expr, Interpretable... args) { return null; } Type opType = typeMap.get(expr.getCallExpr().getTarget().getId()); - if (ind instanceof InterpretableConst) { - InterpretableConst indConst = (InterpretableConst) ind; + if (ind instanceof InterpretableConst indConst) { Qualifier qual = attrFactory.newQualifier(opType, expr.getId(), indConst.value()); if (qual == null) { return null; @@ -552,8 +538,7 @@ Interpretable planCallIndex(Expr expr, Interpretable... args) { opAttr.addQualifier(qual); return opAttr; } - if (ind instanceof InterpretableAttribute) { - InterpretableAttribute indAttr = (InterpretableAttribute) ind; + if (ind instanceof InterpretableAttribute indAttr) { Qualifier qual = attrFactory.newQualifier(opType, expr.getId(), indAttr); if (qual == null) { return null; @@ -923,28 +908,21 @@ static Interpretable planConst(Expr expr) { /** constValue converts a proto Constant value to a ref.Val. */ @SuppressWarnings("deprecation") static Val constValue(Constant c) { - switch (c.getConstantKindCase()) { - case BOOL_VALUE: - return boolOf(c.getBoolValue()); - case BYTES_VALUE: - return bytesOf(c.getBytesValue()); - case DOUBLE_VALUE: - return doubleOf(c.getDoubleValue()); - case DURATION_VALUE: - return durationOf(c.getDurationValue()); - case INT64_VALUE: - return intOf(c.getInt64Value()); - case NULL_VALUE: - return NullT.NullValue; - case STRING_VALUE: - return stringOf(c.getStringValue()); - case TIMESTAMP_VALUE: - return timestampOf(c.getTimestampValue()); - case UINT64_VALUE: - return uintOf(c.getUint64Value()); - } - throw new IllegalArgumentException( - String.format("unknown constant type: '%s' of kind '%s'", c, c.getConstantKindCase())); + return switch (c.getConstantKindCase()) { + case BOOL_VALUE -> boolOf(c.getBoolValue()); + case BYTES_VALUE -> bytesOf(c.getBytesValue()); + case DOUBLE_VALUE -> doubleOf(c.getDoubleValue()); + case DURATION_VALUE -> durationOf(c.getDurationValue()); + case INT64_VALUE -> intOf(c.getInt64Value()); + case NULL_VALUE -> NullT.NullValue; + case STRING_VALUE -> stringOf(c.getStringValue()); + case TIMESTAMP_VALUE -> timestampOf(c.getTimestampValue()); + case UINT64_VALUE -> uintOf(c.getUint64Value()); + default -> + throw new IllegalArgumentException( + String.format( + "unknown constant type: '%s' of kind '%s'", c, c.getConstantKindCase())); + }; } /** diff --git a/core/src/main/java/org/projectnessie/cel/parser/Macro.java b/core/src/main/java/org/projectnessie/cel/parser/Macro.java index 374289c1..ac7e4c52 100644 --- a/core/src/main/java/org/projectnessie/cel/parser/Macro.java +++ b/core/src/main/java/org/projectnessie/cel/parser/Macro.java @@ -15,7 +15,6 @@ */ package org.projectnessie.cel.parser; -import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import com.google.api.expr.v1alpha1.Expr; @@ -36,7 +35,7 @@ public final class Macro { /** AllMacros includes the list of all spec-supported macros. */ public static final List AllMacros = - asList( + List.of( /* The macro "has(m.f)" which tests the presence of a field, avoiding the need to specify * the field as a string. */ @@ -87,7 +86,7 @@ public final class Macro { /** TestOnlyBlockMacros includes the test-only macros used by CEL-Spec block conformance tests. */ public static final List TestOnlyBlockMacros = - asList( + List.of( newReceiverMacro("block", 2, Macro::makeBlock), newReceiverMacro("index", 1, Macro::makeIndex), newReceiverMacro("iterVar", 2, Macro::makeIterVar), @@ -389,7 +388,7 @@ static Expr makeTransformMap(ExprHelper eh, Expr target, List args) { Expr init = eh.newMap(emptyList()); Expr condition = eh.literalBool(true); Entry transformedEntry = eh.newMapEntry(eh.ident(v), fn); - Expr step = eh.newMap(asList(transformedEntry)); + Expr step = eh.newMap(List.of(transformedEntry)); if (filter != null) { step = eh.globalCall(Operator.Conditional.id, filter, step, accuExpr); diff --git a/core/src/main/java/org/projectnessie/cel/parser/ParseError.java b/core/src/main/java/org/projectnessie/cel/parser/ParseError.java deleted file mode 100644 index 16103c77..00000000 --- a/core/src/main/java/org/projectnessie/cel/parser/ParseError.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2021 The Authors of CEL-Java - * - * 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 - * - * http://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 org.projectnessie.cel.parser; - -import org.projectnessie.cel.common.Location; - -public final class ParseError extends RuntimeException { - private final Location location; - - public ParseError(Location location, String message) { - super(message); - this.location = location; - } - - public Location getLocation() { - return location; - } -} diff --git a/core/src/test/java/org/projectnessie/cel/CELTest.java b/core/src/test/java/org/projectnessie/cel/CELTest.java index 389f0dec..356a2b4f 100644 --- a/core/src/test/java/org/projectnessie/cel/CELTest.java +++ b/core/src/test/java/org/projectnessie/cel/CELTest.java @@ -653,15 +653,13 @@ void GlobalVars() { if (args.length != 3) { return newErr("invalid arguments to 'get'"); } - if (!(args[0] instanceof Mapper)) { + if (!(args[0] instanceof Mapper attrs)) { return newErr( "invalid operand of type '%s' to obj.get(key, def)", args[0].type()); } - Mapper attrs = (Mapper) args[0]; - if (!(args[1] instanceof StringT)) { + if (!(args[1] instanceof StringT key)) { return newErr("invalid key of type '%s' to obj.get(key, def)", args[1].type()); } - StringT key = (StringT) args[1]; Val defVal = args[2]; if (attrs.contains(key) == True) { return attrs.get(key); @@ -922,10 +920,9 @@ void CustomInterpreterDecorator() { i -> { lastInstruction.set(i); // Only optimize the instruction if it is a call. - if (!(i instanceof InterpretableCall)) { + if (!(i instanceof InterpretableCall call)) { return i; } - InterpretableCall call = (InterpretableCall) i; // Only optimize the math functions when they have constant arguments. switch (call.function()) { case "_+_": diff --git a/core/src/test/java/org/projectnessie/cel/parser/ParserTest.java b/core/src/test/java/org/projectnessie/cel/parser/ParserTest.java index e719a0d8..de35b8c2 100644 --- a/core/src/test/java/org/projectnessie/cel/parser/ParserTest.java +++ b/core/src/test/java/org/projectnessie/cel/parser/ParserTest.java @@ -1374,16 +1374,14 @@ static class KindAndIdAdorner implements Debug.Adorner { @Override public String getMetadata(Object elem) { - if (elem instanceof Expr) { - Expr e = (Expr) elem; + if (elem instanceof Expr e) { if (e.getExprKindCase() == ExprKindCase.CONST_EXPR) { return String.format( "^#%d:*expr.Constant_%s#", e.getId(), e.getConstExpr().getConstantKindCase().name()); } else { return String.format("^#%d:*expr.Expr_%s#", e.getId(), e.getExprKindCase().name()); } - } else if (elem instanceof Entry) { - Entry entry = (Entry) elem; + } else if (elem instanceof Entry entry) { return String.format("^#%d:%s#", entry.getId(), "*expr.Expr_CreateStruct_Entry"); } return ""; diff --git a/core/src/testFixtures/java/org/projectnessie/cel/Util.java b/core/src/testFixtures/java/org/projectnessie/cel/Util.java index 479f4899..6d6fbd76 100644 --- a/core/src/testFixtures/java/org/projectnessie/cel/Util.java +++ b/core/src/testFixtures/java/org/projectnessie/cel/Util.java @@ -81,8 +81,7 @@ public static void deepEquals(String context, Object a, Object b) { Object bv = Array.get(b, i); deepEquals(context + '[' + i + ']', av, bv); } - } else if (a instanceof List) { - List al = (List) a; + } else if (a instanceof List al) { List bl = (List) b; int as = al.size(); int bs = bl.size(); @@ -95,8 +94,7 @@ public static void deepEquals(String context, Object a, Object b) { for (int i = 0; i < as; i++) { deepEquals(context + '[' + i + ']', al.get(i), bl.get(i)); } - } else if (a instanceof Map) { - Map am = (Map) a; + } else if (a instanceof Map am) { Map bm = (Map) b; int as = am.size(); int bs = bm.size();