cel-java
cel-java copied to clipboard
How to use library for functions?
How can I convert the "greet" example into a lib please?
This does not work:
import org.projectnessie.cel.EnvOption;
import org.projectnessie.cel.Library;
import org.projectnessie.cel.ProgramOption;
import org.projectnessie.cel.checker.Decls;
import org.projectnessie.cel.interpreter.functions.Overload;
import java.util.List;
import static org.projectnessie.cel.common.types.StringT.stringOf;
public class GreetLib implements Library {
@Override
public List<EnvOption> getCompileOptions() {
return List.of(
EnvOption.declarations(
List.of(
Decls.newVar("i", Decls.String),
Decls.newVar("you", Decls.String),
Decls.newFunction(
"greet",
Decls.newInstanceOverload(
"string_greet_string", List.of(Decls.String, Decls.String), Decls.String)))
)
);
}
@Override
public List<ProgramOption> getProgramOptions() {
return List.of(
ProgramOption.functions(
Overload.binary(
"string_greet_string",
(lhs, rhs) ->
stringOf(String.format("Hello %s! Nice to meet you, I'm %s.\n", rhs,
lhs))))
);
}
}
@Test
void merge() throws Exception {
String greeting = ScriptHost
.newBuilder()
.build()
.buildScript("i.greet(you)")
.withLibraries(new GreetLib())
.build()
.execute(String.class, Map.of("i", "alex", "you", "you"));
assertEquals("hello alex", greeting);
}
Results in:
org.projectnessie.cel.tools.ScriptExecutionException: no such overload: string.greet[](string)
at org.projectnessie.cel.tools.Script.evaluate(Script.java:59)
at org.projectnessie.cel.tools.Script.execute(Script.java:45)
at com.intuit.pavedroad.apimanagement.exteventingestorapp.rest.services.cel.GreetLibTest.merge(GreetLibTest.java:33)
Looks like it might be a bug:
https://github.com/projectnessie/cel-java/blob/c966875913fbf9800a1ac5f7ca73031977cda520/tools/src/main/java/org/projectnessie/cel/tools/ScriptHost.java#L138
Where is the call to getProgramOptions
this func should contain?
@snazy thoughts? Is this a bug?
getProgramOptions
is used here:
https://github.com/projectnessie/cel-java/blob/c966875913fbf9800a1ac5f7ca73031977cda520/core/src/main/java/org/projectnessie/cel/Library.java#L54-L66
which gets used here in ScriptHost
:
https://github.com/projectnessie/cel-java/blob/c966875913fbf9800a1ac5f7ca73031977cda520/tools/src/main/java/org/projectnessie/cel/tools/ScriptHost.java#L123-L125
also note that we have a test for ScriptHost
with a custom library here:
https://github.com/projectnessie/cel-java/blob/5749d573772fd34673c7f41456e4ebb59ff6a415/tools/src/test/java/org/projectnessie/cel/tools/ScriptHostTest.java#L116-L139
from that example i am guessing you should be using "greet"
instead of "string_greet_string"
in your getProgramOptions()
?
if not, feel free to extend the testcase with a failing example and possible fix in a PR please