use of org.projectnessie.cel.interpreter.Interpretable.InterpretableCall 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);
}
Aggregations