Search in sources :

Example 71 with Expr

use of com.google.api.expr.v1alpha1.Expr in project cel-java by projectnessie.

the class CEL method astToString.

/**
 * AstToString converts an Ast back to a string if possible.
 *
 * <p>Note, the conversion may not be an exact replica of the original expression, but will
 * produce a string that is semantically equivalent and whose textual representation is stable.
 */
public static String astToString(Ast a) {
    Expr expr = a.getExpr();
    SourceInfo info = a.getSourceInfo();
    return unparse(expr, info);
}
Also used : ParsedExpr(com.google.api.expr.v1alpha1.ParsedExpr) Expr(com.google.api.expr.v1alpha1.Expr) CheckedExpr(com.google.api.expr.v1alpha1.CheckedExpr) SourceInfo(com.google.api.expr.v1alpha1.SourceInfo)

Example 72 with Expr

use of com.google.api.expr.v1alpha1.Expr in project cel-java by projectnessie.

the class Env method residualAst.

/**
 * ResidualAst takes an Ast and its EvalDetails to produce a new Ast which only contains the
 * attribute references which are unknown.
 *
 * <p>Residual expressions are beneficial in a few scenarios:
 *
 * <ul>
 *   <li>Optimizing constant expression evaluations away.
 *   <li>Indexing and pruning expressions based on known input arguments.
 *   <li>Surfacing additional requirements that are needed in order to complete an evaluation.
 *   <li>Sharing the evaluation of an expression across multiple machines/nodes.
 * </ul>
 *
 * <p>For example, if an expression targets a 'resource' and 'request' attribute and the possible
 * values for the resource are known, a PartialActivation could mark the 'request' as an unknown
 * interpreter.AttributePattern and the resulting ResidualAst would be reduced to only the parts
 * of the expression that reference the 'request'.
 *
 * <p>Note, the expression ids within the residual AST generated through this method have no
 * correlation to the expression ids of the original AST.
 *
 * <p>See the PartialVars helper for how to construct a PartialActivation.
 *
 * <p>TODO: Consider adding an option to generate a Program.Residual to avoid round-tripping to an
 * Ast format and then Program again.
 */
public Ast residualAst(Ast a, EvalDetails details) {
    Expr pruned = pruneAst(a.getExpr(), details.getState());
    String expr = astToString(parsedExprToAst(ParsedExpr.newBuilder().setExpr(pruned).build()));
    AstIssuesTuple parsedIss = parse(expr);
    if (parsedIss.hasIssues()) {
        throw parsedIss.getIssues().err();
    }
    if (!a.isChecked()) {
        return parsedIss.ast;
    }
    AstIssuesTuple checkedIss = check(parsedIss.ast);
    if (checkedIss.hasIssues()) {
        throw checkedIss.getIssues().err();
    }
    return checkedIss.ast;
}
Also used : ParsedExpr(com.google.api.expr.v1alpha1.ParsedExpr) Expr(com.google.api.expr.v1alpha1.Expr) CheckedExpr(com.google.api.expr.v1alpha1.CheckedExpr) CEL.astToParsedExpr(org.projectnessie.cel.CEL.astToParsedExpr) CEL.astToString(org.projectnessie.cel.CEL.astToString)

Example 73 with Expr

use of com.google.api.expr.v1alpha1.Expr in project cel-java by projectnessie.

the class Container method toQualifiedName.

/**
 * ToQualifiedName converts an expression AST into a qualified name if possible, with a boolean +
 * 'found' value that indicates if the conversion is successful.
 */
public static String toQualifiedName(Expr e) {
    switch(e.getExprKindCase()) {
        case IDENT_EXPR:
            return e.getIdentExpr().getName();
        case SELECT_EXPR:
            Select sel = e.getSelectExpr();
            if (sel.getTestOnly()) {
                return null;
            }
            String qual = toQualifiedName(sel.getOperand());
            if (qual != null) {
                return qual + "." + sel.getField();
            }
            break;
    }
    return null;
}
Also used : Select(com.google.api.expr.v1alpha1.Expr.Select)

Example 74 with Expr

use of com.google.api.expr.v1alpha1.Expr 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 75 with Expr

use of com.google.api.expr.v1alpha1.Expr in project cel-java by projectnessie.

the class CELTest method ParseAndCheckConcurrently.

@SuppressWarnings("rawtypes")
@Test
void ParseAndCheckConcurrently() throws Exception {
    Env e = newEnv(container("google.api.expr.v1alpha1"), types(Expr.getDefaultInstance()), declarations(Decls.newVar("expr", Decls.newObjectType("google.api.expr.v1alpha1.Expr"))));
    Consumer<String> parseAndCheck = expr -> {
        AstIssuesTuple xIss = e.compile(expr);
        assertThat(xIss.hasIssues()).isFalse();
    };
    int concurrency = 10;
    ExecutorService executor = Executors.newFixedThreadPool(concurrency);
    try {
        CompletableFuture[] futures = IntStream.range(0, concurrency).mapToObj(i -> CompletableFuture.runAsync(() -> parseAndCheck.accept(String.format("expr.id + %d", i)), executor)).toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(futures).get(30, TimeUnit.SECONDS);
    } finally {
        executor.shutdown();
        assertThat(executor.awaitTermination(30, TimeUnit.SECONDS)).isTrue();
    }
}
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) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) CEL.astToString(org.projectnessie.cel.CEL.astToString) 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

Expr (edu.stanford.CVC4.Expr)57 Test (org.junit.Test)55 CVC4.vectorExpr (edu.stanford.CVC4.vectorExpr)49 SExpr (edu.stanford.CVC4.SExpr)42 Expr (com.microsoft.z3.Expr)32 Result (edu.stanford.CVC4.Result)32 Rational (edu.stanford.CVC4.Rational)28 Expr (com.google.api.expr.v1alpha1.Expr)23 BoolExpr (com.microsoft.z3.BoolExpr)22 ArrayType (edu.stanford.CVC4.ArrayType)12 BitVectorType (edu.stanford.CVC4.BitVectorType)12 Status (com.microsoft.z3.Status)11 Type (edu.stanford.CVC4.Type)11 HashMap (java.util.HashMap)11 Test (org.junit.jupiter.api.Test)11 ParsedExpr (com.google.api.expr.v1alpha1.ParsedExpr)10 CheckedExpr (com.google.api.expr.v1alpha1.CheckedExpr)9 ArithExpr (com.microsoft.z3.ArithExpr)8 BitVecExpr (com.microsoft.z3.BitVecExpr)8 Val (org.projectnessie.cel.common.types.ref.Val)7