Search in sources :

Example 1 with NamespacedAttribute

use of org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute in project cel-java by projectnessie.

the class CELTest method CustomInterpreterDecorator.

@Test
void CustomInterpreterDecorator() {
    AtomicReference<Interpretable> lastInstruction = new AtomicReference<>();
    InterpretableDecorator optimizeArith = i -> {
        lastInstruction.set(i);
        // Only optimize the instruction if it is a call.
        if (!(i instanceof InterpretableCall)) {
            return i;
        }
        InterpretableCall call = (InterpretableCall) i;
        // Only optimize the math functions when they have constant arguments.
        switch(call.function()) {
            case "_+_":
            case "_-_":
            case "_*_":
            case "_/_":
                // These are all binary operators so they should have to arguments
                Interpretable[] args = call.args();
                // an empty activation and the value returns as a constant.
                if (!(args[0] instanceof InterpretableConst) || !(args[1] instanceof InterpretableConst)) {
                    return i;
                }
                Val val = call.eval(emptyActivation());
                if (isError(val)) {
                    throw new RuntimeException(val.toString());
                }
                return newConstValue(call.id(), val);
            default:
                return i;
        }
    };
    Env env = newEnv(declarations(Decls.newVar("foo", Decls.Int)));
    AstIssuesTuple astIss = env.compile("foo == -1 + 2 * 3 / 3");
    env.program(astIss.getAst(), evalOptions(OptPartialEval), customDecorator(optimizeArith));
    assertThat(lastInstruction.get()).isInstanceOf(InterpretableCall.class);
    InterpretableCall call = (InterpretableCall) lastInstruction.get();
    Interpretable[] args = call.args();
    Interpretable lhs = args[0];
    assertThat(lhs).isInstanceOf(InterpretableAttribute.class);
    InterpretableAttribute lastAttr = (InterpretableAttribute) lhs;
    NamespacedAttribute absAttr = (NamespacedAttribute) lastAttr.attr();
    String[] varNames = absAttr.candidateVariableNames();
    assertThat(varNames).containsExactly("foo");
    Interpretable rhs = args[1];
    assertThat(rhs).isInstanceOf(InterpretableConst.class);
    InterpretableConst lastConst = (InterpretableConst) rhs;
    // This is the last number produced by the optimization.
    assertThat(lastConst.value()).isSameAs(IntOne);
}
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) InterpretableConst(org.projectnessie.cel.interpreter.Interpretable.InterpretableConst) InterpretableDecorator(org.projectnessie.cel.interpreter.InterpretableDecorator) AtomicReference(java.util.concurrent.atomic.AtomicReference) CEL.astToString(org.projectnessie.cel.CEL.astToString) Env.newEnv(org.projectnessie.cel.Env.newEnv) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) InterpretableCall(org.projectnessie.cel.interpreter.Interpretable.InterpretableCall) AstIssuesTuple(org.projectnessie.cel.Env.AstIssuesTuple) Interpretable(org.projectnessie.cel.interpreter.Interpretable) InterpretableAttribute(org.projectnessie.cel.interpreter.Interpretable.InterpretableAttribute) Test(org.junit.jupiter.api.Test)

Example 2 with NamespacedAttribute

use of org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute in project cel-java by projectnessie.

the class AttributesBench method attributesConditionalAttr_FalseBranch.

@Benchmark
public void attributesConditionalAttr_FalseBranch() {
    TypeRegistry reg = newRegistry();
    AttributeFactory attrs = newAttributeFactory(Container.defaultContainer, reg, reg);
    Map<Object, Object> data = mapOf("a", mapOf(-1, new int[] { 2, 42 }), "b", mapOf("c", mapOf(-1, new int[] { 2, 42 })));
    Activation vars = newActivation(data);
    // (false ? a : b.c)[-1][1]
    NamespacedAttribute tv = attrs.absoluteAttribute(2, "a");
    Attribute fv = attrs.maybeAttribute(3, "b");
    Qualifier qualC = attrs.newQualifier(null, 4, "c");
    fv.addQualifier(qualC);
    Attribute cond = attrs.conditionalAttribute(1, newConstValue(0, False), tv, fv);
    Qualifier qualNeg1 = attrs.newQualifier(null, 5, intOf(-1));
    Qualifier qual1 = attrs.newQualifier(null, 6, intOf(1));
    cond.addQualifier(qualNeg1);
    cond.addQualifier(qual1);
    Object out = cond.resolve(vars);
    assertThat(out).isEqualTo(42);
    assertThat(estimateCost(fv)).extracting("min", "max").containsExactly(1L, 1L);
}
Also used : NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) Attribute(org.projectnessie.cel.interpreter.AttributeFactory.Attribute) AttributeFactory.newAttributeFactory(org.projectnessie.cel.interpreter.AttributeFactory.newAttributeFactory) Activation.newActivation(org.projectnessie.cel.interpreter.Activation.newActivation) Qualifier(org.projectnessie.cel.interpreter.AttributeFactory.Qualifier) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) Benchmark(org.openjdk.jmh.annotations.Benchmark)

Example 3 with NamespacedAttribute

use of org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute in project cel-java by projectnessie.

the class AttributesBench method attributesConditionalAttr_TrueBranch.

@Benchmark
public void attributesConditionalAttr_TrueBranch() {
    TypeRegistry reg = newRegistry();
    AttributeFactory attrs = newAttributeFactory(Container.defaultContainer, reg, reg);
    Map<Object, Object> data = mapOf("a", mapOf(-1, new int[] { 2, 42 }), "b", mapOf("c", mapOf(-1, new int[] { 2, 42 })));
    Activation vars = newActivation(data);
    // (true ? a : b.c)[-1][1]
    NamespacedAttribute tv = attrs.absoluteAttribute(2, "a");
    Attribute fv = attrs.maybeAttribute(3, "b");
    Qualifier qualC = attrs.newQualifier(null, 4, "c");
    fv.addQualifier(qualC);
    Attribute cond = attrs.conditionalAttribute(1, newConstValue(0, True), tv, fv);
    Qualifier qualNeg1 = attrs.newQualifier(null, 5, intOf(-1));
    Qualifier qual1 = attrs.newQualifier(null, 6, intOf(1));
    cond.addQualifier(qualNeg1);
    cond.addQualifier(qual1);
    Object out = cond.resolve(vars);
    assertThat(out).isEqualTo(42);
    assertThat(estimateCost(fv)).extracting("min", "max").containsExactly(1L, 1L);
}
Also used : NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) Attribute(org.projectnessie.cel.interpreter.AttributeFactory.Attribute) AttributeFactory.newAttributeFactory(org.projectnessie.cel.interpreter.AttributeFactory.newAttributeFactory) Activation.newActivation(org.projectnessie.cel.interpreter.Activation.newActivation) Qualifier(org.projectnessie.cel.interpreter.AttributeFactory.Qualifier) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) Benchmark(org.openjdk.jmh.annotations.Benchmark)

Example 4 with NamespacedAttribute

use of org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute in project cel-java by projectnessie.

the class AttributesTest method benchmarkResolverFieldQualifier.

@Test
void benchmarkResolverFieldQualifier() {
    TestAllTypes msg = TestAllTypes.newBuilder().setSingleNestedMessage(NestedMessage.newBuilder().setBb(123)).build();
    TypeRegistry reg = newRegistry(msg);
    AttributeFactory attrs = newAttributeFactory(Container.defaultContainer, reg, reg);
    Activation vars = newActivation(mapOf("msg", msg));
    NamespacedAttribute attr = attrs.absoluteAttribute(1, "msg");
    Type opType = reg.findType("google.api.expr.test.v1.proto3.TestAllTypes");
    assertThat(opType).isNotNull();
    Type fieldType = reg.findType("google.api.expr.test.v1.proto3.TestAllTypes.NestedMessage");
    assertThat(fieldType).isNotNull();
    attr.addQualifier(makeQualifier(attrs, opType.getType(), 2, "single_nested_message"));
    attr.addQualifier(makeQualifier(attrs, fieldType.getType(), 3, "bb"));
// Note: migrated to JMH
}
Also used : IntType(org.projectnessie.cel.common.types.IntT.IntType) Type(com.google.api.expr.v1alpha1.Type) NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) AttributePattern.newPartialAttributeFactory(org.projectnessie.cel.interpreter.AttributePattern.newPartialAttributeFactory) AttributeFactory.newAttributeFactory(org.projectnessie.cel.interpreter.AttributeFactory.newAttributeFactory) Activation.emptyActivation(org.projectnessie.cel.interpreter.Activation.emptyActivation) Activation.newPartialActivation(org.projectnessie.cel.interpreter.Activation.newPartialActivation) Activation.newActivation(org.projectnessie.cel.interpreter.Activation.newActivation) TestAllTypes(com.google.api.expr.test.v1.proto3.TestAllTypesProto.TestAllTypes) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 5 with NamespacedAttribute

use of org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute in project cel-java by projectnessie.

the class AttributesTest method attributeMissingMsg_UnknownField.

@Test
void attributeMissingMsg_UnknownField() {
    TypeRegistry reg = newRegistry();
    AttributeFactory attrs = newPartialAttributeFactory(Container.defaultContainer, reg, reg);
    Any any = Any.pack(TestAllTypes.getDefaultInstance());
    Activation vars = newPartialActivation(mapOf("missing_msg", any), newAttributePattern("missing_msg").qualString("field"));
    // missing_msg.field
    NamespacedAttribute attr = attrs.absoluteAttribute(1, "missing_msg");
    Qualifier field = attrs.newQualifier(null, 2, "field");
    attr.addQualifier(field);
    Object out = attr.resolve(vars);
    assertThat(out).isInstanceOf(UnknownT.class);
}
Also used : NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) AttributePattern.newPartialAttributeFactory(org.projectnessie.cel.interpreter.AttributePattern.newPartialAttributeFactory) AttributeFactory.newAttributeFactory(org.projectnessie.cel.interpreter.AttributeFactory.newAttributeFactory) Activation.emptyActivation(org.projectnessie.cel.interpreter.Activation.emptyActivation) Activation.newPartialActivation(org.projectnessie.cel.interpreter.Activation.newPartialActivation) Activation.newActivation(org.projectnessie.cel.interpreter.Activation.newActivation) Qualifier(org.projectnessie.cel.interpreter.AttributeFactory.Qualifier) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) Any(com.google.protobuf.Any) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

NamespacedAttribute (org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute)15 TypeRegistry (org.projectnessie.cel.common.types.ref.TypeRegistry)14 Test (org.junit.jupiter.api.Test)13 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)12 AttributeFactory.newAttributeFactory (org.projectnessie.cel.interpreter.AttributeFactory.newAttributeFactory)12 Qualifier (org.projectnessie.cel.interpreter.AttributeFactory.Qualifier)11 AttributePattern.newPartialAttributeFactory (org.projectnessie.cel.interpreter.AttributePattern.newPartialAttributeFactory)11 Activation.newActivation (org.projectnessie.cel.interpreter.Activation.newActivation)10 Activation.emptyActivation (org.projectnessie.cel.interpreter.Activation.emptyActivation)9 Activation.newPartialActivation (org.projectnessie.cel.interpreter.Activation.newPartialActivation)9 Attribute (org.projectnessie.cel.interpreter.AttributeFactory.Attribute)5 NestedMessage (com.google.api.expr.test.v1.proto3.TestAllTypesProto.TestAllTypes.NestedMessage)2 Type (com.google.api.expr.v1alpha1.Type)2 Any (com.google.protobuf.Any)2 Benchmark (org.openjdk.jmh.annotations.Benchmark)2 InterpretableAttribute (org.projectnessie.cel.interpreter.Interpretable.InterpretableAttribute)2 TestAllTypes (com.google.api.expr.test.v1.proto3.TestAllTypesProto.TestAllTypes)1 CheckedExpr (com.google.api.expr.v1alpha1.CheckedExpr)1 Expr (com.google.api.expr.v1alpha1.Expr)1 Call (com.google.api.expr.v1alpha1.Expr.Call)1