Search in sources :

Example 6 with EvalResult

use of org.projectnessie.cel.Program.EvalResult in project cel-java by projectnessie.

the class CELTest method Customtypes.

@Test
void Customtypes() {
    Type exprType = Decls.newObjectType("google.api.expr.v1alpha1.Expr");
    TypeRegistry reg = newEmptyRegistry();
    Env e = newEnv(customTypeAdapter(reg), customTypeProvider(reg), container("google.api.expr.v1alpha1"), types(Expr.getDefaultInstance(), BoolT.BoolType, IntT.IntType, StringT.StringType), declarations(Decls.newVar("expr", exprType)));
    AstIssuesTuple astIss = e.compile("expr == Expr{id: 2,\n" + "\t\t\tcall_expr: Expr.Call{\n" + "\t\t\t\tfunction: \"_==_\",\n" + "\t\t\t\targs: [\n" + "\t\t\t\t\tExpr{id: 1, ident_expr: Expr.Ident{ name: \"a\" }},\n" + "\t\t\t\t\tExpr{id: 3, ident_expr: Expr.Ident{ name: \"b\" }}]\n" + "\t\t\t}}");
    assertThat(astIss.getAst().getResultType()).isEqualTo(Decls.Bool);
    Program prg = e.program(astIss.getAst());
    Object vars = mapOf("expr", Expr.newBuilder().setId(2).setCallExpr(Call.newBuilder().setFunction("_==_").addAllArgs(asList(Expr.newBuilder().setId(1).setIdentExpr(Ident.newBuilder().setName("a")).build(), Expr.newBuilder().setId(3).setIdentExpr(Ident.newBuilder().setName("b")).build()))).build());
    EvalResult out = prg.eval(vars);
    assertThat(out.getVal()).isSameAs(True);
}
Also used : 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) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) Test(org.junit.jupiter.api.Test)

Example 7 with EvalResult

use of org.projectnessie.cel.Program.EvalResult in project cel-java by projectnessie.

the class Script method execute.

@SuppressWarnings("unchecked")
public <T> T execute(Class<T> resultType, Map<String, Object> arguments) throws ScriptException {
    Objects.requireNonNull(resultType, "resultType missing");
    Objects.requireNonNull(arguments, "arguments missing");
    EvalResult evalResult = prg.eval(arguments);
    Val result = evalResult.getVal();
    if (isError(result)) {
        Err err = (Err) result;
        throw new ScriptExecutionException(err.toString(), err.getCause());
    }
    if (isUnknown(result)) {
        if (resultType == Val.class || resultType == Object.class) {
            return (T) result;
        }
        throw new ScriptExecutionException(String.format("script returned unknown %s, but expected result type is %s", result, resultType.getName()));
    }
    return result.convertToNative(resultType);
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) Err(org.projectnessie.cel.common.types.Err) EvalResult(org.projectnessie.cel.Program.EvalResult)

Example 8 with EvalResult

use of org.projectnessie.cel.Program.EvalResult in project cel-java by projectnessie.

the class ConformanceServiceImpl method eval.

@Override
public void eval(EvalRequest request, io.grpc.stub.StreamObserver<EvalResponse> responseObserver) {
    try {
        Env env = newEnv(container(request.getContainer()), types(com.google.api.expr.test.v1.proto2.TestAllTypesProto.TestAllTypes.getDefaultInstance(), com.google.api.expr.test.v1.proto3.TestAllTypesProto.TestAllTypes.getDefaultInstance()));
        Program prg;
        Ast ast;
        switch(request.getExprKindCase()) {
            case PARSED_EXPR:
                ast = parsedExprToAst(request.getParsedExpr());
                break;
            case CHECKED_EXPR:
                ast = checkedExprToAst(request.getCheckedExpr());
                break;
            default:
                throw new IllegalArgumentException("No expression.");
        }
        prg = env.program(ast);
        Map<String, Object> args = new HashMap<>();
        request.getBindingsMap().forEach((name, exprValue) -> {
            Val refVal = exprValueToRefValue(env.getTypeAdapter(), exprValue);
            args.put(name, refVal);
        });
        // NOTE: the EvalState is currently discarded
        EvalResult res = prg.eval(args);
        ExprValue resultExprVal;
        if (!isError(res.getVal())) {
            resultExprVal = refValueToExprValue(res.getVal());
        } else {
            Err err = (Err) res.getVal();
            if (verboseEvalErrors) {
                System.err.printf("%n" + "Eval error (not necessarily a bug!!!):%n" + "  error: %s%n" + "%s", err, err.hasCause() ? (stacktrace(err.toRuntimeException()) + "\n") : "");
            }
            resultExprVal = ExprValue.newBuilder().setError(ErrorSet.newBuilder().addErrors(Status.newBuilder().setMessage(err.toString()))).build();
        }
        EvalResponse.Builder resp = EvalResponse.newBuilder().setResult(resultExprVal);
        responseObserver.onNext(resp.build());
        responseObserver.onCompleted();
    } catch (Exception e) {
        responseObserver.onError(io.grpc.Status.fromCode(io.grpc.Status.Code.UNKNOWN).withDescription(stacktrace(e)).asException());
    }
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) Program(org.projectnessie.cel.Program) Ast(org.projectnessie.cel.Ast) CEL.parsedExprToAst(org.projectnessie.cel.CEL.parsedExprToAst) CEL.checkedExprToAst(org.projectnessie.cel.CEL.checkedExprToAst) Err(org.projectnessie.cel.common.types.Err) Err.newErr(org.projectnessie.cel.common.types.Err.newErr) HashMap(java.util.HashMap) EvalResult(org.projectnessie.cel.Program.EvalResult) ByteString(com.google.protobuf.ByteString) Env.newEnv(org.projectnessie.cel.Env.newEnv) Env(org.projectnessie.cel.Env) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) EvalResponse(com.google.api.expr.v1alpha1.EvalResponse) ExprValue(com.google.api.expr.v1alpha1.ExprValue)

Example 9 with EvalResult

use of org.projectnessie.cel.Program.EvalResult in project cel-java by projectnessie.

the class CELTest method Abbrevs_Disambiguation.

@Test
void Abbrevs_Disambiguation() {
    Env env = newEnv(abbrevs("external.Expr"), container("google.api.expr.v1alpha1"), types(Expr.getDefaultInstance()), declarations(Decls.newVar("test", Decls.Bool), Decls.newVar("external.Expr", Decls.String)));
    // This expression will return either a string or a protobuf Expr value depending on the value
    // of the 'test' argument. The fully qualified type name is used indicate that the protobuf
    // typed 'Expr' should be used rather than the abbreviatation for 'external.Expr'.
    AstIssuesTuple astIss = env.compile("test ? dyn(Expr) : google.api.expr.v1alpha1.Expr{id: 1}");
    assertThat(astIss.hasIssues()).isFalse();
    Program prg = env.program(astIss.getAst());
    EvalResult out = prg.eval(mapOf("test", true, "external.Expr", "string expr"));
    assertThat(out.getVal().value()).isEqualTo("string expr");
    out = prg.eval(mapOf("test", false, "external.Expr", "wrong expr"));
    Expr want = Expr.newBuilder().setId(1).build();
    Expr got = out.getVal().convertToNative(Expr.class);
    assertThat(got).isEqualTo(want);
}
Also used : ParsedExpr(com.google.api.expr.v1alpha1.ParsedExpr) Expr(com.google.api.expr.v1alpha1.Expr) CEL.astToCheckedExpr(org.projectnessie.cel.CEL.astToCheckedExpr) CheckedExpr(com.google.api.expr.v1alpha1.CheckedExpr) CEL.astToParsedExpr(org.projectnessie.cel.CEL.astToParsedExpr) 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) Test(org.junit.jupiter.api.Test)

Example 10 with EvalResult

use of org.projectnessie.cel.Program.EvalResult in project cel-java by projectnessie.

the class CELTest method exampleWithBuiltins.

@Test
void exampleWithBuiltins() {
    // Variables used within this expression environment.
    EnvOption decls = declarations(Decls.newVar("i", Decls.String), Decls.newVar("you", Decls.String));
    Env env = newEnv(decls);
    // Compile the expression.
    AstIssuesTuple astIss = env.compile("\"Hello \" + you + \"! I'm \" + i + \".\"");
    assertThat(astIss.hasIssues()).isFalse();
    // Create the program, and evaluate it against some input.
    Program prg = env.program(astIss.getAst());
    // If the Eval() call were provided with cel.evalOptions(OptTrackState) the details response
    // (2nd return) would be non-nil.
    EvalResult out = prg.eval(mapOf("i", "CEL", "you", "world"));
    assertThat(out.getVal().equal(stringOf("Hello world! I'm CEL."))).isSameAs(True);
}
Also used : 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) Test(org.junit.jupiter.api.Test)

Aggregations

EvalResult (org.projectnessie.cel.Program.EvalResult)16 Env.newCustomEnv (org.projectnessie.cel.Env.newCustomEnv)15 Env.newEnv (org.projectnessie.cel.Env.newEnv)15 Test (org.junit.jupiter.api.Test)14 AstIssuesTuple (org.projectnessie.cel.Env.AstIssuesTuple)14 CEL.checkedExprToAst (org.projectnessie.cel.CEL.checkedExprToAst)7 CEL.parsedExprToAst (org.projectnessie.cel.CEL.parsedExprToAst)7 CEL.astToString (org.projectnessie.cel.CEL.astToString)6 Val (org.projectnessie.cel.common.types.ref.Val)5 CheckedExpr (com.google.api.expr.v1alpha1.CheckedExpr)4 Expr (com.google.api.expr.v1alpha1.Expr)4 ParsedExpr (com.google.api.expr.v1alpha1.ParsedExpr)4 CEL.astToCheckedExpr (org.projectnessie.cel.CEL.astToCheckedExpr)4 CEL.astToParsedExpr (org.projectnessie.cel.CEL.astToParsedExpr)4 UnknownT (org.projectnessie.cel.common.types.UnknownT)4 PartialActivation (org.projectnessie.cel.interpreter.Activation.PartialActivation)4 Type (com.google.api.expr.v1alpha1.Type)3 TypeRegistry (org.projectnessie.cel.common.types.ref.TypeRegistry)3 EvalState (org.projectnessie.cel.interpreter.EvalState)3 Macro (org.projectnessie.cel.parser.Macro)3