Search in sources :

Example 11 with Val

use of org.projectnessie.cel.common.types.ref.Val in project cel-java by projectnessie.

the class DurationTest method durationNegate.

@Test
void durationNegate() {
    Val neg = durationOf(ofSeconds(1234, 1)).negate();
    Duration want = ofSeconds(-1234, -1);
    assertThat(neg.value()).isEqualTo(want);
    assertThat(durationOf(ofSeconds(Long.MIN_VALUE)).negate()).matches(Err::isError);
    assertThat(durationOf(ofSeconds(Long.MAX_VALUE)).negate().equal(durationOf(ofSeconds(Long.MIN_VALUE + 1)))).isSameAs(True);
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) Duration(java.time.Duration) Test(org.junit.jupiter.api.Test)

Example 12 with Val

use of org.projectnessie.cel.common.types.ref.Val in project cel-java by projectnessie.

the class ConformanceServiceImpl method refValueToValue.

// TODO(jimlarson): The following conversion code should be moved to
// common/types/provider.go and consolidated/refactored as appropriate.
// In particular, make judicious use of types.NativeToValue().
/**
 * RefValueToValue converts between ref.Val and Value. The ref.Val must not be error or unknown.
 */
static Value refValueToValue(Val res) {
    switch(res.type().typeEnum()) {
        case Bool:
            return Value.newBuilder().setBoolValue(res.booleanValue()).build();
        case Bytes:
            return Value.newBuilder().setBytesValue(res.convertToNative(ByteString.class)).build();
        case Double:
            return Value.newBuilder().setDoubleValue(res.convertToNative(Double.class)).build();
        case Int:
            return Value.newBuilder().setInt64Value(res.intValue()).build();
        case Null:
            return Value.newBuilder().setNullValueValue(0).build();
        case String:
            return Value.newBuilder().setStringValue(res.value().toString()).build();
        case Type:
            return Value.newBuilder().setTypeValue(((TypeT) res).typeName()).build();
        case Uint:
            return Value.newBuilder().setUint64Value(res.intValue()).build();
        case Duration:
            Duration d = res.convertToNative(Duration.class);
            return Value.newBuilder().setObjectValue(Any.pack(d)).build();
        case Timestamp:
            Timestamp t = res.convertToNative(Timestamp.class);
            return Value.newBuilder().setObjectValue(Any.pack(t)).build();
        case List:
            Lister l = (Lister) res;
            ListValue.Builder elts = ListValue.newBuilder();
            for (IteratorT i = l.iterator(); i.hasNext() == True; ) {
                Val v = i.next();
                elts.addValues(refValueToValue(v));
            }
            return Value.newBuilder().setListValue(elts).build();
        case Map:
            Mapper m = (Mapper) res;
            MapValue.Builder elems = MapValue.newBuilder();
            for (IteratorT i = m.iterator(); i.hasNext() == True; ) {
                Val k = i.next();
                Val v = m.get(k);
                Value kv = refValueToValue(k);
                Value vv = refValueToValue(v);
                elems.addEntriesBuilder().setKey(kv).setValue(vv);
            }
            return Value.newBuilder().setMapValue(elems).build();
        case Object:
            // Object type
            Message pb = (Message) res.value();
            Value.Builder v = Value.newBuilder();
            // Somehow the conformance tests
            if (pb instanceof ListValue) {
                v.setListValue((ListValue) pb);
            } else if (pb instanceof MapValue) {
                v.setMapValue((MapValue) pb);
            } else {
                v.setObjectValue(Any.pack(pb));
            }
            return v.build();
        default:
            throw new IllegalStateException(String.format("Unknown %s", res.type().typeEnum()));
    }
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) TypeT(org.projectnessie.cel.common.types.TypeT) Message(com.google.protobuf.Message) Lister(org.projectnessie.cel.common.types.traits.Lister) ListValue(com.google.api.expr.v1alpha1.ListValue) Duration(com.google.protobuf.Duration) MapValue(com.google.api.expr.v1alpha1.MapValue) Timestamp(com.google.protobuf.Timestamp) IteratorT(org.projectnessie.cel.common.types.IteratorT) Mapper(org.projectnessie.cel.common.types.traits.Mapper) MapValue(com.google.api.expr.v1alpha1.MapValue) Value(com.google.api.expr.v1alpha1.Value) ExprValue(com.google.api.expr.v1alpha1.ExprValue) ListValue(com.google.api.expr.v1alpha1.ListValue) TypeT.newObjectTypeValue(org.projectnessie.cel.common.types.TypeT.newObjectTypeValue)

Example 13 with Val

use of org.projectnessie.cel.common.types.ref.Val in project cel-java by projectnessie.

the class ConformanceServiceImpl method valueToRefValue.

/**
 * ValueToRefValue converts between exprpb.Value and ref.Val.
 */
static Val valueToRefValue(TypeAdapter adapter, Value v) {
    switch(v.getKindCase()) {
        case NULL_VALUE:
            return NullT.NullValue;
        case BOOL_VALUE:
            return boolOf(v.getBoolValue());
        case INT64_VALUE:
            return intOf(v.getInt64Value());
        case UINT64_VALUE:
            return uintOf(v.getUint64Value());
        case DOUBLE_VALUE:
            return doubleOf(v.getDoubleValue());
        case STRING_VALUE:
            return stringOf(v.getStringValue());
        case BYTES_VALUE:
            return bytesOf(v.getBytesValue().toByteArray());
        case OBJECT_VALUE:
            Any any = v.getObjectValue();
            return adapter.nativeToValue(any);
        case MAP_VALUE:
            MapValue m = v.getMapValue();
            Map<Val, Val> entries = new HashMap<>();
            for (Entry entry : m.getEntriesList()) {
                Val key = valueToRefValue(adapter, entry.getKey());
                Val pb = valueToRefValue(adapter, entry.getValue());
                entries.put(key, pb);
            }
            return adapter.nativeToValue(entries);
        case LIST_VALUE:
            ListValue l = v.getListValue();
            List<Val> elts = l.getValuesList().stream().map(el -> valueToRefValue(adapter, el)).collect(Collectors.toList());
            return adapter.nativeToValue(elts);
        case TYPE_VALUE:
            String typeName = v.getTypeValue();
            Type tv = Types.getTypeByName(typeName);
            if (tv != null) {
                return tv;
            }
            return newObjectTypeValue(typeName);
        default:
            throw new IllegalArgumentException("unknown value " + v.getKindCase());
    }
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) MapValue(com.google.api.expr.v1alpha1.MapValue) Lister(org.projectnessie.cel.common.types.traits.Lister) EnvOption.container(org.projectnessie.cel.EnvOption.container) CheckRequest(com.google.api.expr.v1alpha1.CheckRequest) Err(org.projectnessie.cel.common.types.Err) True(org.projectnessie.cel.common.types.BoolT.True) Err.isError(org.projectnessie.cel.common.types.Err.isError) Ast(org.projectnessie.cel.Ast) CheckResponse(com.google.api.expr.v1alpha1.CheckResponse) Map(java.util.Map) Value(com.google.api.expr.v1alpha1.Value) UnknownSet(com.google.api.expr.v1alpha1.UnknownSet) Val(org.projectnessie.cel.common.types.ref.Val) PrintWriter(java.io.PrintWriter) IteratorT(org.projectnessie.cel.common.types.IteratorT) DoubleT.doubleOf(org.projectnessie.cel.common.types.DoubleT.doubleOf) Status(com.google.rpc.Status) EnvOption.clearMacros(org.projectnessie.cel.EnvOption.clearMacros) StringT.stringOf(org.projectnessie.cel.common.types.StringT.stringOf) EnvOption(org.projectnessie.cel.EnvOption) ExprValue(com.google.api.expr.v1alpha1.ExprValue) Collectors(java.util.stream.Collectors) IntT.intOf(org.projectnessie.cel.common.types.IntT.intOf) UintT.uintOf(org.projectnessie.cel.common.types.UintT.uintOf) ByteString(com.google.protobuf.ByteString) List(java.util.List) ErrorSet(com.google.api.expr.v1alpha1.ErrorSet) UnknownT.unknownOf(org.projectnessie.cel.common.types.UnknownT.unknownOf) Type(org.projectnessie.cel.common.types.ref.Type) Any(com.google.protobuf.Any) EvalResult(org.projectnessie.cel.Program.EvalResult) ParseRequest(com.google.api.expr.v1alpha1.ParseRequest) Err.newErr(org.projectnessie.cel.common.types.Err.newErr) Env.newEnv(org.projectnessie.cel.Env.newEnv) Entry(com.google.api.expr.v1alpha1.MapValue.Entry) ParseResponse(com.google.api.expr.v1alpha1.ParseResponse) StdLib(org.projectnessie.cel.Library.StdLib) EnvOption.declarations(org.projectnessie.cel.EnvOption.declarations) ConformanceServiceImplBase(com.google.api.expr.v1alpha1.ConformanceServiceGrpc.ConformanceServiceImplBase) HashMap(java.util.HashMap) Timestamp(com.google.protobuf.Timestamp) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) AstIssuesTuple(org.projectnessie.cel.Env.AstIssuesTuple) Mapper(org.projectnessie.cel.common.types.traits.Mapper) Types(org.projectnessie.cel.common.types.Types) IssueDetails(com.google.api.expr.v1alpha1.IssueDetails) CEL.astToCheckedExpr(org.projectnessie.cel.CEL.astToCheckedExpr) EvalRequest(com.google.api.expr.v1alpha1.EvalRequest) Code(com.google.rpc.Code) StringWriter(java.io.StringWriter) EnvOption.types(org.projectnessie.cel.EnvOption.types) NullT(org.projectnessie.cel.common.types.NullT) Types.boolOf(org.projectnessie.cel.common.types.Types.boolOf) TypeAdapter(org.projectnessie.cel.common.types.ref.TypeAdapter) UnknownT.isUnknown(org.projectnessie.cel.common.types.UnknownT.isUnknown) ListValue(com.google.api.expr.v1alpha1.ListValue) CEL.parsedExprToAst(org.projectnessie.cel.CEL.parsedExprToAst) BytesT.bytesOf(org.projectnessie.cel.common.types.BytesT.bytesOf) CELError(org.projectnessie.cel.common.CELError) SourcePosition(com.google.api.expr.v1alpha1.SourcePosition) TypeT(org.projectnessie.cel.common.types.TypeT) Duration(com.google.protobuf.Duration) CEL.astToParsedExpr(org.projectnessie.cel.CEL.astToParsedExpr) CEL.checkedExprToAst(org.projectnessie.cel.CEL.checkedExprToAst) Program(org.projectnessie.cel.Program) EvalResponse(com.google.api.expr.v1alpha1.EvalResponse) TypeT.newObjectTypeValue(org.projectnessie.cel.common.types.TypeT.newObjectTypeValue) Message(com.google.protobuf.Message) Env(org.projectnessie.cel.Env) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) Entry(com.google.api.expr.v1alpha1.MapValue.Entry) Type(org.projectnessie.cel.common.types.ref.Type) HashMap(java.util.HashMap) ListValue(com.google.api.expr.v1alpha1.ListValue) MapValue(com.google.api.expr.v1alpha1.MapValue) ByteString(com.google.protobuf.ByteString) Any(com.google.protobuf.Any)

Example 14 with Val

use of org.projectnessie.cel.common.types.ref.Val in project cel-java by projectnessie.

the class CheckerEnv method lookupIdent.

/**
 * LookupIdent returns a Decl proto for typeName as an identifier in the Env. Returns nil if no
 * such identifier is found in the Env.
 */
public Decl lookupIdent(String name) {
    for (String candidate : container.resolveCandidateNames(name)) {
        Decl ident = declarations.findIdent(candidate);
        if (ident != null) {
            return ident;
        }
        // Next try to import the name as a reference to a message type. If found,
        // the declaration is added to the outest (global) scope of the
        // environment, so next time we can access it faster.
        Type t = provider.findType(candidate);
        if (t != null) {
            Decl decl = Decls.newVar(candidate, t);
            declarations.addIdent(decl);
            return decl;
        }
        // Next try to import this as an enum value by splitting the name in a type prefix and
        // the enum inside.
        Val enumValue = provider.enumValue(candidate);
        if (enumValue.type() != ErrType) {
            Decl decl = Decls.newIdent(candidate, Decls.Int, Constant.newBuilder().setInt64Value(enumValue.intValue()).build());
            declarations.addIdent(decl);
            return decl;
        }
    }
    return null;
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) Types.formatCheckedType(org.projectnessie.cel.checker.Types.formatCheckedType) Type(com.google.api.expr.v1alpha1.Type) ErrType(org.projectnessie.cel.common.types.Err.ErrType) FunctionDecl(com.google.api.expr.v1alpha1.Decl.FunctionDecl) Decl(com.google.api.expr.v1alpha1.Decl) IdentDecl(com.google.api.expr.v1alpha1.Decl.IdentDecl)

Example 15 with Val

use of org.projectnessie.cel.common.types.ref.Val in project cel-java by projectnessie.

the class DefaultTypeAdapter method nativeToValue.

/**
 * nativeToValue returns the converted (ref.Val, true) of a conversion is found, otherwise (nil,
 * false)
 */
public static Val nativeToValue(Db db, TypeAdapter a, Object value) {
    Val v = maybeNativeToValue(a, value);
    if (v != null) {
        return v;
    }
    // additional specializations may be added upon request / need.
    if (value instanceof Val) {
        return (Val) value;
    }
    if (value instanceof Message) {
        Message msg = (Message) value;
        String typeName = typeNameFromMessage(msg);
        if (typeName.isEmpty()) {
            return anyWithEmptyType();
        }
        PbTypeDescription type = db.describeType(typeName);
        if (type == null) {
            return unknownType(typeName);
        }
        value = type.maybeUnwrap(db, msg);
        if (value instanceof Message) {
            value = type.maybeUnwrap(db, value);
        }
        return a.nativeToValue(value);
    }
    return newErr("unsupported conversion from '%s' to value", value.getClass());
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) PbTypeDescription.typeNameFromMessage(org.projectnessie.cel.common.types.pb.PbTypeDescription.typeNameFromMessage) Message(com.google.protobuf.Message)

Aggregations

Val (org.projectnessie.cel.common.types.ref.Val)67 Test (org.junit.jupiter.api.Test)42 TypeRegistry (org.projectnessie.cel.common.types.ref.TypeRegistry)22 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)16 ByteString (com.google.protobuf.ByteString)10 ParsedExpr (com.google.api.expr.v1alpha1.ParsedExpr)9 MethodSource (org.junit.jupiter.params.provider.MethodSource)9 Message (com.google.protobuf.Message)8 Err (org.projectnessie.cel.common.types.Err)8 ObjectT (org.projectnessie.cel.common.types.ObjectT)7 Activation.emptyActivation (org.projectnessie.cel.interpreter.Activation.emptyActivation)7 Expr (com.google.api.expr.v1alpha1.Expr)6 Source (org.projectnessie.cel.common.Source)6 Mapper (org.projectnessie.cel.common.types.traits.Mapper)6 HashMap (java.util.HashMap)5 EvalResult (org.projectnessie.cel.Program.EvalResult)5 True (org.projectnessie.cel.common.types.BoolT.True)5 StringT.stringOf (org.projectnessie.cel.common.types.StringT.stringOf)5 ProtoTypeRegistry (org.projectnessie.cel.common.types.pb.ProtoTypeRegistry)5 Call (com.google.api.expr.v1alpha1.Expr.Call)4