use of org.projectnessie.cel.parser.Parser.ParseResult in project cel-java by projectnessie.
the class Env method check.
/**
* Check performs type-checking on the input Ast and yields a checked Ast and/or set of Issues.
*
* <p>Checking has failed if the returned Issues value and its Issues.Err() value are non-nil.
* Issues should be inspected if they are non-nil, but may not represent a fatal error.
*
* <p>It is possible to have both non-nil Ast and Issues values returned from this call: however,
* the mere presence of an Ast does not imply that it is valid for use.
*/
public AstIssuesTuple check(Ast ast) {
// Note, errors aren't currently possible on the Ast to ParsedExpr conversion.
ParsedExpr pe = astToParsedExpr(ast);
// Construct the internal checker env, erroring if there is an issue adding the declarations.
synchronized (once) {
if (chk == null && chkErr == null) {
CheckerEnv ce = CheckerEnv.newCheckerEnv(container, provider);
ce.enableDynamicAggregateLiterals(true);
if (hasFeature(FeatureDisableDynamicAggregateLiterals)) {
ce.enableDynamicAggregateLiterals(false);
}
try {
ce.add(declarations);
chk = ce;
} catch (RuntimeException e) {
chkErr = e;
} catch (Exception e) {
chkErr = new RuntimeException(e);
}
}
}
// The once call will ensure that this value is set or nil for all invocations.
if (chkErr != null) {
Errors errs = new Errors(ast.getSource());
errs.reportError(NoLocation, "%s", chkErr.toString());
return new AstIssuesTuple(null, newIssues(errs));
}
ParseResult pr = new ParseResult(pe.getExpr(), new Errors(ast.getSource()), pe.getSourceInfo());
CheckResult checkRes = Checker.Check(pr, ast.getSource(), chk);
if (checkRes.hasErrors()) {
return new AstIssuesTuple(null, newIssues(checkRes.getErrors()));
}
// Manually create the Ast to ensure that the Ast source information (which may be more
// detailed than the information provided by Check), is returned to the caller.
CheckedExpr ce = checkRes.getCheckedExpr();
ast = new Ast(ce.getExpr(), ce.getSourceInfo(), ast.getSource(), ce.getReferenceMapMap(), ce.getTypeMapMap());
return new AstIssuesTuple(ast, Issues.noIssues(ast.getSource()));
}
use of org.projectnessie.cel.parser.Parser.ParseResult in project cel-java by projectnessie.
the class CheckerTest method check.
@ParameterizedTest
@MethodSource("checkTestCases")
void check(TestCase tc) {
Assumptions.assumeTrue(tc.disabled == null, tc.disabled);
Source src = newTextSource(tc.i);
ParseResult parsed = Parser.parseAllMacros(src);
assertThat(parsed.getErrors().getErrors()).withFailMessage(parsed.getErrors()::toDisplayString).isEmpty();
TypeRegistry reg = ProtoTypeRegistry.newRegistry(com.google.api.expr.test.v1.proto2.TestAllTypesProto.TestAllTypes.getDefaultInstance(), com.google.api.expr.test.v1.proto3.TestAllTypesProto.TestAllTypes.getDefaultInstance());
Container cont = Container.newContainer(Container.name(tc.container));
CheckerEnv env = newStandardCheckerEnv(cont, reg);
if (tc.disableStdEnv) {
env = newCheckerEnv(cont, reg);
}
if (tc.homogeneousAggregateLiterals) {
env.enableDynamicAggregateLiterals(false);
}
if (tc.env != null) {
if (tc.env.idents != null) {
for (Decl ident : tc.env.idents) {
env.add(ident);
}
}
if (tc.env.functions != null) {
for (Decl fn : tc.env.functions) {
env.add(fn);
}
}
}
CheckResult checkResult = Checker.Check(parsed, src, env);
if (checkResult.hasErrors()) {
String errorString = checkResult.getErrors().toDisplayString();
if (tc.error != null) {
assertThat(errorString).isEqualTo(tc.error);
} else {
fail(String.format("Unexpected type-check errors: %s", errorString));
}
} else if (tc.error != null) {
assertThat(tc.error).withFailMessage(String.format("Expected error not thrown: %s", tc.error)).isNull();
}
Type actual = checkResult.getCheckedExpr().getTypeMapMap().get(parsed.getExpr().getId());
if (tc.error == null) {
if (actual == null || !actual.equals(tc.type)) {
fail(String.format("Type Error: '%s' vs expected '%s'", actual, tc.type));
}
}
if (tc.r != null) {
String actualStr = print(checkResult.getCheckedExpr().getExpr(), checkResult.getCheckedExpr());
String actualCmp = actualStr.replaceAll("[ \n\t]", "");
String rCmp = tc.r.replaceAll("[ \n\t]", "");
assertThat(actualCmp).isEqualTo(rCmp);
}
}
use of org.projectnessie.cel.parser.Parser.ParseResult in project cel-java by projectnessie.
the class AttributesTest method attributeStateTracking.
@ParameterizedTest
@MethodSource("attributeStateTrackingTests")
void attributeStateTracking(TestDef tc) {
Source src = Source.newTextSource(tc.expr);
ParseResult parsed = Parser.parseAllMacros(src);
assertThat(parsed.hasErrors()).isFalse();
Container cont = Container.defaultContainer;
TypeRegistry reg = newRegistry();
CheckerEnv env = newStandardCheckerEnv(cont, reg);
if (tc.env != null) {
env.add(tc.env);
}
CheckResult checkResult = Checker.Check(parsed, src, env);
if (parsed.hasErrors()) {
throw new IllegalArgumentException(parsed.getErrors().toDisplayString());
}
AttributeFactory attrs = newAttributeFactory(cont, reg, reg);
Interpreter interp = newStandardInterpreter(cont, reg, reg, attrs);
// Show that program planning will now produce an error.
EvalState st = newEvalState();
Interpretable i = interp.newInterpretable(checkResult.getCheckedExpr(), optimize(), trackState(st));
Activation in = newActivation(tc.in);
Val out = i.eval(in);
assertThat(out).extracting(o -> o.equal(tc.out)).isSameAs(True);
for (Entry<Object, Object> iv : tc.state.entrySet()) {
long id = ((Number) iv.getKey()).longValue();
Object val = iv.getValue();
Val stVal = st.value(id);
assertThat(stVal).withFailMessage(() -> String.format("id(%d), val=%s, stVal=%s", id, val, stVal)).isNotNull();
assertThat(stVal).withFailMessage(() -> String.format("id(%d), val=%s, stVal=%s", id, val, stVal)).isEqualTo(DefaultTypeAdapter.Instance.nativeToValue(val));
deepEquals(String.format("id(%d)", id), stVal.value(), val);
}
}
use of org.projectnessie.cel.parser.Parser.ParseResult in project cel-java by projectnessie.
the class InterpreterTest method typeConversionOpt.
@ParameterizedTest
@MethodSource("typeConversionOptTests")
void typeConversionOpt(ConvTestCase tc) {
Source src = newTextSource(tc.in);
ParseResult parsed = Parser.parseAllMacros(src);
assertThat(parsed.hasErrors()).withFailMessage(parsed.getErrors()::toDisplayString).isFalse();
Container cont = Container.defaultContainer;
TypeRegistry reg = newRegistry();
CheckerEnv env = newStandardCheckerEnv(cont, reg);
CheckResult checkResult = Checker.Check(parsed, src, env);
if (parsed.hasErrors()) {
throw new IllegalArgumentException(parsed.getErrors().toDisplayString());
}
AttributeFactory attrs = newAttributeFactory(cont, reg, reg);
Interpreter interp = newStandardInterpreter(cont, reg, reg, attrs);
if (!tc.fail) {
typeConversionOptCheck(tc, checkResult, interp);
} else {
Throwable err = catchThrowable(() -> typeConversionOptCheck(tc, checkResult, interp));
assertThat(err).withFailMessage(() -> format("Expected '%s' to fail with '%s'", tc.in, tc.err)).isNotNull();
// TODO 'err' below comes from "try-catch" of the preceding 'newInterpretable'
// Show how the error returned during program planning is the same as the runtime
// error which would be produced normally.
Interpretable i2 = interp.newInterpretable(checkResult.getCheckedExpr());
Val errVal = i2.eval(emptyActivation());
String errValStr = errVal.toString();
assertThat(errValStr).isEqualTo(err.getMessage());
if (tc.err != null) {
assertThat(errValStr).contains(tc.err);
}
}
}
use of org.projectnessie.cel.parser.Parser.ParseResult in project cel-java by projectnessie.
the class InterpreterTest method exhaustiveConditionalExpr.
@Test
void exhaustiveConditionalExpr() {
Source src = newTextSource("a ? b < 1.0 : c == ['hello']");
ParseResult parsed = Parser.parseAllMacros(src);
assertThat(parsed.hasErrors()).withFailMessage(parsed.getErrors()::toDisplayString).isFalse();
EvalState state = newEvalState();
Container cont = Container.defaultContainer;
TypeRegistry reg = newRegistry(ParsedExpr.getDefaultInstance());
AttributeFactory attrs = newAttributeFactory(cont, reg, reg);
Interpreter intr = newStandardInterpreter(cont, reg, reg, attrs);
Interpretable interpretable = intr.newUncheckedInterpretable(parsed.getExpr(), exhaustiveEval(state));
Activation vars = newActivation(mapOf("a", True, "b", doubleOf(0.999), "c", ListT.newStringArrayList(new String[] { "hello" })));
Val result = interpretable.eval(vars);
// Operator "_==_" is at Expr 7, should be evaluated in exhaustive mode
// even though "a" is true
Val ev = state.value(7);
// "==" should be evaluated in exhaustive mode though unnecessary
assertThat(ev).withFailMessage("Else expression expected to be true").isSameAs(True);
assertThat(result).isSameAs(True);
}
Aggregations