Search in sources :

Example 1 with Mapper

use of org.projectnessie.cel.common.types.traits.Mapper in project cel-java by projectnessie.

the class CELTest method GlobalVars.

@Test
void GlobalVars() {
    Type mapStrDyn = Decls.newMapType(Decls.String, Decls.Dyn);
    Env e = newEnv(declarations(Decls.newVar("attrs", mapStrDyn), Decls.newVar("default", Decls.Dyn), Decls.newFunction("get", Decls.newInstanceOverload("get_map", asList(mapStrDyn, Decls.String, Decls.Dyn), Decls.Dyn))));
    AstIssuesTuple astIss = e.compile("attrs.get(\"first\", attrs.get(\"second\", default))");
    // Create the program.
    ProgramOption funcs = functions(Overload.function("get", args -> {
        if (args.length != 3) {
            return newErr("invalid arguments to 'get'");
        }
        if (!(args[0] instanceof Mapper)) {
            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)) {
            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);
        }
        return defVal;
    }));
    // Global variables can be configured as a ProgramOption and optionally overridden on Eval.
    Program prg = e.program(astIss.getAst(), funcs, globals(mapOf("default", "third")));
    // t.Run("global_default", func(t *testing.T) {
    Object vars = mapOf("attrs", mapOf());
    EvalResult out = prg.eval(vars);
    assertThat(out.getVal().equal(stringOf("third"))).isSameAs(True);
    // })
    // t.Run("attrs_alt", func(t *testing.T) {
    vars = mapOf("attrs", mapOf("second", "yep"));
    out = prg.eval(vars);
    assertThat(out.getVal().equal(stringOf("yep"))).isSameAs(True);
    // })
    // t.Run("local_default", func(t *testing.T) {
    vars = mapOf("attrs", mapOf(), "default", "fourth");
    out = prg.eval(vars);
    assertThat(out.getVal().equal(stringOf("fourth"))).isSameAs(True);
// })
}
Also used : BoolT(org.projectnessie.cel.common.types.BoolT) Interpretable(org.projectnessie.cel.interpreter.Interpretable) Macro(org.projectnessie.cel.parser.Macro) Call(com.google.api.expr.v1alpha1.Expr.Call) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) PartialActivation(org.projectnessie.cel.interpreter.Activation.PartialActivation) EnvOption.container(org.projectnessie.cel.EnvOption.container) Macro.newReceiverMacro(org.projectnessie.cel.parser.Macro.newReceiverMacro) Activation.emptyActivation(org.projectnessie.cel.interpreter.Activation.emptyActivation) Disabled(org.junit.jupiter.api.Disabled) InterpretableDecorator(org.projectnessie.cel.interpreter.InterpretableDecorator) Collections.singletonList(java.util.Collections.singletonList) True(org.projectnessie.cel.common.types.BoolT.True) Err.isError(org.projectnessie.cel.common.types.Err.isError) Container(org.projectnessie.cel.common.types.traits.Container) Arrays.asList(java.util.Arrays.asList) CEL.estimateCost(org.projectnessie.cel.CEL.estimateCost) OptPartialEval(org.projectnessie.cel.EvalOption.OptPartialEval) ProtoTypeRegistry.newEmptyRegistry(org.projectnessie.cel.common.types.pb.ProtoTypeRegistry.newEmptyRegistry) ParsedExpr(com.google.api.expr.v1alpha1.ParsedExpr) EnvOption.customTypeProvider(org.projectnessie.cel.EnvOption.customTypeProvider) Val(org.projectnessie.cel.common.types.ref.Val) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) InterpretableAttribute(org.projectnessie.cel.interpreter.Interpretable.InterpretableAttribute) Collections.emptyList(java.util.Collections.emptyList) Expr(com.google.api.expr.v1alpha1.Expr) Ident(com.google.api.expr.v1alpha1.Expr.Ident) InterpretableCall(org.projectnessie.cel.interpreter.Interpretable.InterpretableCall) OptExhaustiveEval(org.projectnessie.cel.EvalOption.OptExhaustiveEval) OptTrackState(org.projectnessie.cel.EvalOption.OptTrackState) StringT.stringOf(org.projectnessie.cel.common.types.StringT.stringOf) Decls(org.projectnessie.cel.checker.Decls) CEL.attributePattern(org.projectnessie.cel.CEL.attributePattern) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) ProgramOption.functions(org.projectnessie.cel.ProgramOption.functions) DefaultTypeAdapter(org.projectnessie.cel.common.types.pb.DefaultTypeAdapter) Overload(org.projectnessie.cel.interpreter.functions.Overload) EvalResult(org.projectnessie.cel.Program.EvalResult) Err.newErr(org.projectnessie.cel.common.types.Err.newErr) IntOne(org.projectnessie.cel.common.types.IntT.IntOne) IntStream(java.util.stream.IntStream) Overloads(org.projectnessie.cel.common.types.Overloads) Env.newEnv(org.projectnessie.cel.Env.newEnv) StdLib(org.projectnessie.cel.Library.StdLib) IntT(org.projectnessie.cel.common.types.IntT) Trait(org.projectnessie.cel.common.types.traits.Trait) EnvOption.declarations(org.projectnessie.cel.EnvOption.declarations) CompletableFuture(java.util.concurrent.CompletableFuture) Err.valOrErr(org.projectnessie.cel.common.types.Err.valOrErr) CEL.partialVars(org.projectnessie.cel.CEL.partialVars) AtomicReference(java.util.concurrent.atomic.AtomicReference) EnvOption.customTypeAdapter(org.projectnessie.cel.EnvOption.customTypeAdapter) AstIssuesTuple(org.projectnessie.cel.Env.AstIssuesTuple) Mapper(org.projectnessie.cel.common.types.traits.Mapper) ProgramOption.evalOptions(org.projectnessie.cel.ProgramOption.evalOptions) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Type(com.google.api.expr.v1alpha1.Type) CEL.astToCheckedExpr(org.projectnessie.cel.CEL.astToCheckedExpr) CEL.noVars(org.projectnessie.cel.CEL.noVars) ExecutorService(java.util.concurrent.ExecutorService) Collections.emptyMap(java.util.Collections.emptyMap) CEL.astToString(org.projectnessie.cel.CEL.astToString) ProgramOption.globals(org.projectnessie.cel.ProgramOption.globals) Operator(org.projectnessie.cel.common.operators.Operator) NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) UnknownT(org.projectnessie.cel.common.types.UnknownT) Cost(org.projectnessie.cel.interpreter.Coster.Cost) EnvOption.types(org.projectnessie.cel.EnvOption.types) ProgramOption.customDecorator(org.projectnessie.cel.ProgramOption.customDecorator) EnvOption.macros(org.projectnessie.cel.EnvOption.macros) Interpretable.newConstValue(org.projectnessie.cel.interpreter.Interpretable.newConstValue) CheckedExpr(com.google.api.expr.v1alpha1.CheckedExpr) CEL.parsedExprToAst(org.projectnessie.cel.CEL.parsedExprToAst) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) InterpretableConst(org.projectnessie.cel.interpreter.Interpretable.InterpretableConst) CEL.astToParsedExpr(org.projectnessie.cel.CEL.astToParsedExpr) CEL.checkedExprToAst(org.projectnessie.cel.CEL.checkedExprToAst) EvalState(org.projectnessie.cel.interpreter.EvalState) Util.mapOf(org.projectnessie.cel.Util.mapOf) StringT(org.projectnessie.cel.common.types.StringT) EnvOption.homogeneousAggregateLiterals(org.projectnessie.cel.EnvOption.homogeneousAggregateLiterals) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) EnvOption.abbrevs(org.projectnessie.cel.EnvOption.abbrevs) Val(org.projectnessie.cel.common.types.ref.Val) Mapper(org.projectnessie.cel.common.types.traits.Mapper) Type(com.google.api.expr.v1alpha1.Type) EvalResult(org.projectnessie.cel.Program.EvalResult) Env.newEnv(org.projectnessie.cel.Env.newEnv) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) AstIssuesTuple(org.projectnessie.cel.Env.AstIssuesTuple) StringT(org.projectnessie.cel.common.types.StringT) Test(org.junit.jupiter.api.Test)

Example 2 with Mapper

use of org.projectnessie.cel.common.types.traits.Mapper 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 3 with Mapper

use of org.projectnessie.cel.common.types.traits.Mapper in project cel-java by projectnessie.

the class AstPruner method maybeCreateLiteral.

Expr maybeCreateLiteral(long id, Val v) {
    Type t = v.type();
    switch(t.typeEnum()) {
        case Bool:
            return createLiteral(id, Constant.newBuilder().setBoolValue((Boolean) v.value()).build());
        case Int:
            return createLiteral(id, Constant.newBuilder().setInt64Value(((Number) v.value()).longValue()).build());
        case Uint:
            return createLiteral(id, Constant.newBuilder().setUint64Value(((Number) v.value()).longValue()).build());
        case String:
            return createLiteral(id, Constant.newBuilder().setStringValue(v.value().toString()).build());
        case Double:
            return createLiteral(id, Constant.newBuilder().setDoubleValue(((Number) v.value()).doubleValue()).build());
        case Bytes:
            return createLiteral(id, Constant.newBuilder().setBytesValue(ByteString.copyFrom((byte[]) v.value())).build());
        case Null:
            return createLiteral(id, Constant.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
    }
    // Attempt to build a list literal.
    if (v instanceof Lister) {
        Lister list = (Lister) v;
        int sz = (int) list.size().intValue();
        List<Expr> elemExprs = new ArrayList<>(sz);
        for (int i = 0; i < sz; i++) {
            Val elem = list.get(intOf(i));
            if (isUnknownOrError(elem)) {
                return null;
            }
            Expr elemExpr = maybeCreateLiteral(nextID(), elem);
            if (elemExpr == null) {
                return null;
            }
            elemExprs.add(elemExpr);
        }
        return Expr.newBuilder().setId(id).setListExpr(CreateList.newBuilder().addAllElements(elemExprs).build()).build();
    }
    // Create a map literal if possible.
    if (v instanceof Mapper) {
        Mapper mp = (Mapper) v;
        IteratorT it = mp.iterator();
        List<Entry> entries = new ArrayList<>((int) mp.size().intValue());
        while (it.hasNext() == True) {
            Val key = it.next();
            Val val = mp.get(key);
            if (isUnknownOrError(key) || isUnknownOrError(val)) {
                return null;
            }
            Expr keyExpr = maybeCreateLiteral(nextID(), key);
            if (keyExpr == null) {
                return null;
            }
            Expr valExpr = maybeCreateLiteral(nextID(), val);
            if (valExpr == null) {
                return null;
            }
            Entry entry = Entry.newBuilder().setId(nextID()).setMapKey(keyExpr).setValue(valExpr).build();
            entries.add(entry);
        }
        return Expr.newBuilder().setId(id).setStructExpr(CreateStruct.newBuilder().addAllEntries(entries)).build();
    }
    // the enumeration the fields for a given message.
    return null;
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) Mapper(org.projectnessie.cel.common.types.traits.Mapper) IteratorT(org.projectnessie.cel.common.types.IteratorT) Type(org.projectnessie.cel.common.types.ref.Type) Entry(com.google.api.expr.v1alpha1.Expr.CreateStruct.Entry) Expr(com.google.api.expr.v1alpha1.Expr) Lister(org.projectnessie.cel.common.types.traits.Lister) ArrayList(java.util.ArrayList)

Example 4 with Mapper

use of org.projectnessie.cel.common.types.traits.Mapper in project cel-java by projectnessie.

the class AttributeFactory method refResolve.

/**
 * refResolve attempts to convert the value to a CEL value and then uses reflection methods to try
 * and resolve the qualifier.
 */
static Val refResolve(TypeAdapter adapter, Val idx, Object obj) {
    Val celVal = adapter.nativeToValue(obj);
    if (celVal instanceof Mapper) {
        Mapper mapper = (Mapper) celVal;
        Val elem = mapper.find(idx);
        if (elem == null) {
            return noSuchKey(idx);
        }
        return elem;
    }
    if (celVal instanceof Indexer) {
        Indexer indexer = (Indexer) celVal;
        return indexer.get(idx);
    }
    if (isUnknown(celVal)) {
        return celVal;
    }
    // TODO: If the types.Err value contains more than just an error message at some point in the
    // future, then it would be reasonable to return error values as ref.Val types rather than
    // simple go error types.
    throwErrorAsIllegalStateException(celVal);
    return noSuchOverload(celVal, "ref-resolve", null);
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) Mapper(org.projectnessie.cel.common.types.traits.Mapper) Indexer(org.projectnessie.cel.common.types.traits.Indexer)

Aggregations

Val (org.projectnessie.cel.common.types.ref.Val)4 Mapper (org.projectnessie.cel.common.types.traits.Mapper)4 Expr (com.google.api.expr.v1alpha1.Expr)2 CheckedExpr (com.google.api.expr.v1alpha1.CheckedExpr)1 Call (com.google.api.expr.v1alpha1.Expr.Call)1 Entry (com.google.api.expr.v1alpha1.Expr.CreateStruct.Entry)1 Ident (com.google.api.expr.v1alpha1.Expr.Ident)1 ExprValue (com.google.api.expr.v1alpha1.ExprValue)1 ListValue (com.google.api.expr.v1alpha1.ListValue)1 MapValue (com.google.api.expr.v1alpha1.MapValue)1 ParsedExpr (com.google.api.expr.v1alpha1.ParsedExpr)1 Type (com.google.api.expr.v1alpha1.Type)1 Value (com.google.api.expr.v1alpha1.Value)1 Duration (com.google.protobuf.Duration)1 Message (com.google.protobuf.Message)1 Timestamp (com.google.protobuf.Timestamp)1 ArrayList (java.util.ArrayList)1 Arrays.asList (java.util.Arrays.asList)1 Collections.emptyList (java.util.Collections.emptyList)1 Collections.emptyMap (java.util.Collections.emptyMap)1