diff --git a/pom.xml b/pom.xml index ce74ae484..534af2f24 100644 --- a/pom.xml +++ b/pom.xml @@ -131,6 +131,18 @@ 3.21.0 test + + org.openjdk.jmh + jmh-core + ${commons.jmh.version} + test + + + org.openjdk.jmh + jmh-generator-annprocess + ${commons.jmh.version} + test + clean verify apache-rat:check spotbugs:check japicmp:cmp checkstyle:check javadoc:javadoc diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 5e8b71c17..33beeb12c 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -31,6 +31,7 @@ A jexl.options pragma modifies the engine options when evaluated with a plain context. + Declare antish variable names at parse time through JexlFeatures.antishTest(Predicate), disabling runtime antish resolution; add JexlFeatures.namePatterns(Collection). Bump org.apache.commons:commons-parent from 105 to 107. diff --git a/src/main/java/org/apache/commons/jexl3/JexlFeatures.java b/src/main/java/org/apache/commons/jexl3/JexlFeatures.java index 55b5f401f..7d915c710 100644 --- a/src/main/java/org/apache/commons/jexl3/JexlFeatures.java +++ b/src/main/java/org/apache/commons/jexl3/JexlFeatures.java @@ -332,6 +332,9 @@ public static String stringify(final int feature) { /** The allowed pragma keys. */ private Predicate pragmas = TEST_STR_TRUE; + /** The declared antish variable names. */ + private Predicate antishNames = TEST_STR_FALSE; + /** * Creates default instance, equivalent to the result of calling the preferred alternative * {@link JexlFeatures#createDefault()} @@ -348,6 +351,7 @@ public JexlFeatures() { public JexlFeatures(final JexlFeatures features) { this(features.flags, features.reservedNames, features.nameSpaces); this.pragmas = features.pragmas; + this.antishNames = features.antishNames; } /** @@ -365,6 +369,45 @@ protected JexlFeatures(final long f, final Set r, final Predicate antishTest() { + return antishNames; + } + + /** + * Sets a test to declare antish variable names, resolved at parse time. + *

+ * An antish variable is a global variable whose name contains dots, like x.y. + * When set, the parser rewrites a reference rooted on a global variable, like x.y.z, + * so that its longest dotted prefix satisfying the predicate, like x.y, is a single variable; + * the remaining segments, like .z, are property accesses on that variable value. + * A local variable root, a safe navigation segment (?.) or an expression segment + * (`...`) stops the rewrite. + *

+ *

+ * When no such prefix exists and the root is not itself a declared name, a method name may complete + * a declared variable, like f.g in f.g(42); that variable is then called as a functor. + *

+ *

+ * Declaring antish names means they are all known beforehand: a script parsed with such features + * does not solve antish variables at runtime, regardless of the {@link JexlOptions#setAntish(boolean)} option. + *

+ *

{@link #namePatterns(Collection)} creates such a test from name patterns.

+ * + * @param names The antish variable name predicate; must be stateless or thread-safe; null declares none + * @return this features instance + * @since 3.7.2 + */ + public JexlFeatures antishTest(final Predicate names) { + antishNames = names == null ? TEST_STR_FALSE : names; + return this; + } + /** * Sets whether annotation constructs are enabled. *

@@ -484,6 +527,9 @@ public boolean equals(final Object obj) { if (!this.pragmas.equals(other.pragmas)) { return false; } + if (!this.antishNames.equals(other.antishNames)) { + return false; + } if (!Objects.equals(this.reservedNames, other.reservedNames)) { return false; } @@ -540,6 +586,7 @@ public int hashCode() { //CSOFF: MagicNumber hash = 53 * hash + Long.hashCode(this.flags); hash = 53 * hash + (this.reservedNames != null ? this.reservedNames.hashCode() : 0); hash = 53 * hash + this.pragmas.hashCode(); + hash = 53 * hash + this.antishNames.hashCode(); return hash; } @@ -830,19 +877,34 @@ public JexlFeatures pragmaTest(final Predicate keys) { /** * Creates a pragma key test from a collection of patterns, meant for {@link #pragmaTest(Predicate)}. - *

- * A pattern ending with * matches any key starting with what precedes it, any other - * pattern matches the key exactly. For instance, dlm.* matches dlm.foo and - * dlm.foo.bar; * matches any key. Patterns are trimmed, null or empty - * patterns are ignored. - *

- *

Tests created from the same patterns are equal, so are the features using them.

+ *

This is equivalent to {@link #namePatterns(Collection)}.

* * @param patterns The allowed pragma key patterns; null or empty allows no pragma key * @return The pragma key test * @since 3.7.1 */ public static Predicate pragmaPatterns(final Collection patterns) { + return namePatterns(patterns); + } + + /** + * Creates a dotted name test from a collection of patterns. + *

+ * Meant for features that test names, like {@link #pragmaTest(Predicate)} or {@link #antishTest(Predicate)}. + *

+ *

+ * A pattern ending with * matches any name starting with what precedes it, any other + * pattern matches the name exactly. For instance, dlm.* matches dlm.foo and + * dlm.foo.bar; * matches any name. Patterns are trimmed, null or empty + * patterns are ignored. + *

+ *

Tests created from the same patterns are equal, so are the features using them.

+ * + * @param patterns The name patterns; null or empty matches no name + * @return The name test + * @since 3.7.2 + */ + public static Predicate namePatterns(final Collection patterns) { final Set exact = new TreeSet<>(); final Set prefixes = new TreeSet<>(); if (patterns != null) { @@ -858,19 +920,19 @@ public static Predicate pragmaPatterns(final Collection patterns } } } - return exact.isEmpty() && prefixes.isEmpty() ? TEST_STR_FALSE : new PragmaPatterns(exact, prefixes); + return exact.isEmpty() && prefixes.isEmpty() ? TEST_STR_FALSE : new NamePatterns(exact, prefixes); } /** - * A pragma key test made of exact keys and key prefixes. + * A name test made of exact names and name prefixes. */ - private static final class PragmaPatterns implements Predicate { - /** The exactly matched keys. */ + private static final class NamePatterns implements Predicate { + /** The exactly matched names. */ private final Set exact; - /** The matched key prefixes. */ + /** The matched name prefixes. */ private final Set prefixes; - PragmaPatterns(final Set exact, final Set prefixes) { + NamePatterns(final Set exact, final Set prefixes) { this.exact = exact; this.prefixes = prefixes; } @@ -896,10 +958,10 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if (!(obj instanceof PragmaPatterns)) { + if (!(obj instanceof NamePatterns)) { return false; } - final PragmaPatterns other = (PragmaPatterns) obj; + final NamePatterns other = (NamePatterns) obj; return exact.equals(other.exact) && prefixes.equals(other.prefixes); } @@ -1033,6 +1095,12 @@ public JexlFeatures sideEffect(final boolean flag) { * When disabled, parsing a script/expression using syntactical constructs modifying variables * including all potentially ant-ish variables will throw a parsing exception. *

+ *

+ * When antish variable names are declared ({@link #antishTest(Predicate)}), they are all solved at parse time; + * only assigning a global variable, like x = 1 or x.y = 1 when x.y + * is declared, is then a global side effect. Assigning a property of a global variable value, like + * x.y.z = 1, is not. + *

* * @param flag true to enable, false to disable * @return this features instance diff --git a/src/main/java/org/apache/commons/jexl3/internal/Debugger.java b/src/main/java/org/apache/commons/jexl3/internal/Debugger.java index f8940a2e4..b2717eb1d 100644 --- a/src/main/java/org/apache/commons/jexl3/internal/Debugger.java +++ b/src/main/java/org/apache/commons/jexl3/internal/Debugger.java @@ -58,10 +58,14 @@ private static boolean isStatement(final JexlNode child) { if (child instanceof ASTCaseStatement) { return child.jjtGetNumChildren() > 0 && isStatement(child.jjtGetChild(0)); } + if (child instanceof ASTForeachStatement) { + // a loop whose body is not a statement needs a terminator, as in for (...) x += 1; + final int num = child.jjtGetNumChildren(); + return num == 0 || isStatement(child.jjtGetChild(num - 1)); + } return child instanceof ASTJexlScript || child instanceof ASTBlock || child instanceof ASTIfStatement - || child instanceof ASTForeachStatement || child instanceof ASTTryStatement || child instanceof ASTWhileStatement || child instanceof ASTDoWhileStatement @@ -933,7 +937,7 @@ protected Object visit(final ASTForeachStatement node, final Object data) { // the loop step final JexlNode step = (form & 4) != 0 ? node.jjtGetChild(nc++) : null; // last child is body - body = (form & 8) != 0 ? node.jjtGetChild(nc) : null; + body = (form & 8) != 0 && nc < node.jjtGetNumChildren() ? node.jjtGetChild(nc) : null; if (vars != null) { accept(vars, data); } @@ -1110,7 +1114,8 @@ protected Object visit(final ASTJexlScript node, final Object arg) { } // no parameters or done with them final int num = node.jjtGetNumChildren(); - if (num == 1 && !(node instanceof ASTJexlLambda)) { + if (num == 1 && (!(node instanceof ASTJexlLambda) || isLambdaExpr((ASTJexlLambda) node))) { + // a lambda expression is not a statement, it may be an argument or an operand data = accept(node.jjtGetChild(0), data); } else { for (int i = named? 1 : 0; i < num; ++i) { @@ -1169,12 +1174,15 @@ protected Object visit(final ASTMapLiteral node, final Object data) { @Override protected Object visit(final ASTMethodNode node, final Object data) { final int num = node.jjtGetNumChildren(); - if (num == 2) { + if (num > 1) { accept(node.jjtGetChild(0), data); - if (depth <= 0) { - builder.append("(...)"); - } else { - accept(node.jjtGetChild(1), data); + // more than one arguments node when curried + for (int i = 1; i < num; ++i) { + if (depth <= 0) { + builder.append("(...)"); + } else { + accept(node.jjtGetChild(i), data); + } } } return data; diff --git a/src/main/java/org/apache/commons/jexl3/internal/Engine.java b/src/main/java/org/apache/commons/jexl3/internal/Engine.java index 06fbc8cc6..5a8aeafbd 100644 --- a/src/main/java/org/apache/commons/jexl3/internal/Engine.java +++ b/src/main/java/org/apache/commons/jexl3/internal/Engine.java @@ -408,6 +408,10 @@ public Engine(final JexlBuilder conf) { if (!features.supportsNamespaceInstantiation()) { options.setNamespaceInstantiation(false); } + // declared antish names are all solved at parse time: no run-time solving + if (features.antishTest() != JexlFeatures.TEST_STR_FALSE) { + options.setAntish(false); + } this.charset = conf.charset(); // caching: final IntFunction> factory = conf.cacheFactory(); @@ -545,6 +549,14 @@ protected JexlOptions evalOptions(final ASTJexlScript script, final JexlContext if (opts != options && !scriptFeatures.supportsNamespaceInstantiation()) { opts.setNamespaceInstantiation(false); } + // declared antish names are all solved at parse time: no run-time solving + final JexlFeatures features = script != null && script.getFeatures() != null ? script.getFeatures() : scriptFeatures; + if (features.antishTest() != JexlFeatures.TEST_STR_FALSE && opts.isAntish()) { + if (opts == options) { + opts = opts.copy(); + } + opts.setAntish(false); + } return opts; } diff --git a/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java b/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java index 227c337e4..9acb3908f 100644 --- a/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java +++ b/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java @@ -37,6 +37,7 @@ import org.apache.commons.jexl3.introspection.JexlMethod; import org.apache.commons.jexl3.introspection.JexlPropertyGet; import org.apache.commons.jexl3.parser.*; +import org.apache.commons.logging.Log; /** * An interpreter of JEXL syntax. @@ -100,6 +101,87 @@ public boolean isProcessed() { } } + /** + * The dotted name of an antish variable, like {@code x.y.z}, built from the children of a reference. + *

The first child of the reference is the root identifier; the following children are appended + * as they are traversed, as long as they are plain identifier accesses.

+ */ + private static final class AntishName { + + /** + * Checks whether an identifier access can be part of an antish variable name. + * + * @param access The identifier access + * @return true if neither safe navigation nor an expression, false otherwise + */ + static boolean isPlain(final ASTIdentifierAccess access) { + return !access.isSafe() && !access.isExpression(); + } + + /** The name. */ + private final StringBuilder name; + + /** The index of the next reference child to append. */ + private int next = 1; + + /** + * Creates an antish name. + * + * @param root The root identifier name + */ + AntishName(final String root) { + name = new StringBuilder(root); + } + + /** + * Appends a dot and a name segment. + * + * @param segment The name segment + */ + void append(final String segment) { + name.append('.').append(segment); + } + + /** + * Appends the names of the reference children not yet appended, up to and including an index. + * + * @param reference The reference node + * @param index The index of the last child to append + * @return null if all children were appended, the first child that can not be part of an antish name otherwise + */ + JexlNode appendUpTo(final JexlNode reference, final int index) { + for (; next <= index; ++next) { + final JexlNode child = reference.jjtGetChild(next); + if (!(child instanceof ASTIdentifierAccess) || !isPlain((ASTIdentifierAccess) child)) { + return child; + } + append(((ASTIdentifierAccess) child).getName()); + } + return null; + } + + /** + * @return The name length + */ + int length() { + return name.length(); + } + + /** + * Truncates the name. + * + * @param length The new name length + */ + void setLength(final int length) { + name.setLength(length); + } + + @Override + public String toString() { + return name.toString(); + } + } + /** * The thread local interpreter. */ @@ -330,28 +412,25 @@ private Object evalCatch(final ASTReference catchVar, final JexlNode catchBody, final int symbol = catchVariable.getSymbol(); final boolean lexical = catchVariable.isLexical() || options.isLexical(); if (lexical) { - // create lexical frame - final LexicalFrame locals = new LexicalFrame(frame, block); + pushBlock(); + } + try { // it may be a local previously declared - final boolean trySymbol = symbol >= 0 && catchVariable instanceof ASTVar; - if (trySymbol && !defineVariable((ASTVar) catchVariable, locals)) { + final boolean trySymbol = lexical && symbol >= 0 && catchVariable instanceof ASTVar; + if (trySymbol && !defineVariable((ASTVar) catchVariable, block)) { return redefinedVariable(catchVar.jjtGetParent(), catchVariable.getName()); } - block = locals; - } - if (symbol < 0) { - setContextVariable(catchVar.jjtGetParent(), catchVariable.getName(), caught); - } else { - final Throwable cause = caught.getCause(); - frame.set(symbol, cause == null? caught : cause); - } - try { + if (symbol < 0) { + setContextVariable(catchVar.jjtGetParent(), catchVariable.getName(), caught); + } else { + final Throwable cause = caught.getCause(); + frame.set(symbol, cause == null? caught : cause); + } // evaluate body return catchBody.jjtAccept(this, data); } finally { - // restore lexical frame if (lexical) { - block = block.pop(); + popBlock(); } } } @@ -503,8 +582,7 @@ protected Object executeAssign(final JexlNode node, final JexlOperator assignop, } // 1: follow children till penultimate, resolve dot/array JexlNode objectNode = null; - StringBuilder ant = null; - int v = 1; + AntishName ant = null; // start at 1 if symbol main: for (int c = symbol >= 0 ? 1 : 0; c < last; ++c) { objectNode = left.jjtGetChild(c); @@ -524,21 +602,12 @@ protected Object executeAssign(final JexlNode node, final JexlOperator assignop, antish = false; break main; } - ant = new StringBuilder(firstId.getName()); + ant = new AntishName(firstId.getName()); } - // catch up to current child - for (; v <= c; ++v) { - final JexlNode child = left.jjtGetChild(v); - final ASTIdentifierAccess aid = child instanceof ASTIdentifierAccess - ? (ASTIdentifierAccess) child - : null; - // remain antish only if unsafe navigation - if (aid == null || aid.isSafe() || aid.isExpression()) { - antish = false; - break main; - } - ant.append('.'); - ant.append(aid.getName()); + // catch up to current child, remain antish only if unsafe navigation + if (ant.appendUpTo(left, c) != null) { + antish = false; + break main; } // solve antish object = context.get(ant.toString()); @@ -554,8 +623,7 @@ protected Object executeAssign(final JexlNode node, final JexlOperator assignop, final Object property; if (propertyId != null) { // deal with creating/assigning antish variable - if (antish && ant != null && object == null && !propertyId.isSafe() && !propertyId.isExpression()) { - ant.append('.'); + if (antish && ant != null && object == null && AntishName.isPlain(propertyId)) { ant.append(propertyId.getName()); final String name = ant.toString(); if (assignop == null) { @@ -609,18 +677,14 @@ private Object forIterator(final ASTForeachStatement node, final Object data) { final ASTIdentifier loopVariable = (ASTIdentifier) loopReference.jjtGetChild(0); final int symbol = loopVariable.getSymbol(); final boolean lexical = loopVariable.isLexical() || options.isLexical(); - final LexicalFrame locals = lexical? new LexicalFrame(frame, block) : null; + final LexicalFrame locals = lexical ? pushBlock() : null; final boolean loopSymbol = symbol >= 0 && loopVariable instanceof ASTVar; - if (lexical) { - // create lexical frame + Object forEach = null; + try { // it may be a local previously declared - if (loopSymbol && !defineVariable((ASTVar) loopVariable, locals)) { + if (lexical && loopSymbol && !defineVariable((ASTVar) loopVariable, locals)) { return redefinedVariable(node, loopVariable.getName()); } - block = locals; - } - Object forEach = null; - try { /* second objectNode is the variable to iterate */ final Object iterableValue = node.jjtGetChild(1).jjtAccept(this, data); // make sure there is a value to iterate upon @@ -671,9 +735,8 @@ private Object forIterator(final ASTForeachStatement node, final Object data) { } finally { // closeable iterator handling closeIfSupported(forEach); - // restore lexical frame if (lexical) { - block = block.pop(); + popBlock(); } } return result; @@ -681,50 +744,36 @@ private Object forIterator(final ASTForeachStatement node, final Object data) { private Object forLoop(final ASTForeachStatement node, final Object data) { Object result = null; - int nc; + int nc = 0; final int form = node.getLoopForm(); - final LexicalFrame locals; /* first child node might be the loop variable */ - if ((form & 1) != 0) { - nc = 1; - final JexlNode init = node.jjtGetChild(0); - ASTVar loopVariable = null; - if (init instanceof ASTAssignment) { - final JexlNode child = init.jjtGetChild(0); - if (child instanceof ASTVar) { - loopVariable = (ASTVar) child; - } - } else if (init instanceof ASTVar){ - loopVariable = (ASTVar) init; - } - if (loopVariable != null) { - final boolean lexical = loopVariable.isLexical() || options.isLexical(); - locals = lexical ? new LexicalFrame(frame, block) : null; - if (locals != null) { - block = locals; - } - } else { - locals = null; - } - // initialize after eventual creation of local lexical frame - init.jjtAccept(this, data); - // other inits - for (JexlNode moreAssignment = node.jjtGetChild(nc); - moreAssignment instanceof ASTAssignment; - moreAssignment = node.jjtGetChild(++nc)) { - moreAssignment.jjtAccept(this, data); - } - } else { - locals = null; - nc = 0; + final JexlNode init = (form & 1) != 0 ? node.jjtGetChild(nc++) : null; + // multiple declarations share the same kind, as in let i = 0, j = 1 + final JexlNode declaration = init instanceof ASTDefineVars ? init.jjtGetChild(0) : init; + ASTVar loopVariable = null; + if (declaration instanceof ASTAssignment) { + final JexlNode child = declaration.jjtGetChild(0); + if (child instanceof ASTVar) { + loopVariable = (ASTVar) child; + } + } else if (declaration instanceof ASTVar){ + loopVariable = (ASTVar) declaration; + } + final boolean lexical = loopVariable != null && (loopVariable.isLexical() || options.isLexical()); + if (lexical) { + pushBlock(); } try { + if (init != null) { + // initialize after eventual creation of local lexical frame + init.jjtAccept(this, data); + } // the loop condition final JexlNode predicate = (form & 2) != 0? node.jjtGetChild(nc++) : null; // the loop step final JexlNode step = (form & 4) != 0? node.jjtGetChild(nc++) : null; - // last child is body - final JexlNode statement = (form & 8) != 0 ? node.jjtGetChild(nc) : null; + // last child is body, if any + final JexlNode statement = (form & 8) != 0 && nc < node.jjtGetNumChildren() ? node.jjtGetChild(nc) : null; // while(predicate())... while (predicate == null || testPredicate(predicate, predicate.jjtAccept(this, data))) { cancelCheck(node); @@ -745,9 +794,8 @@ private Object forLoop(final ASTForeachStatement node, final Object data) { } } } finally { - // restore lexical frame - if (locals != null) { - block = block.pop(); + if (lexical) { + popBlock(); } } return result; @@ -919,6 +967,23 @@ protected Object processAnnotation(final String annotation, final Object[] args, : stmt.call(); } + /** + * Pops the current lexical frame, restoring the enclosing one. + */ + private void popBlock() { + block = block.pop(); + } + + /** + * Pushes a new lexical frame, enclosed by the current one, as the current block. + * + * @return the new current block + */ + private LexicalFrame pushBlock() { + block = new LexicalFrame(frame, block); + return block; + } + /** * Swaps the current thread local interpreter. * @@ -967,14 +1032,14 @@ protected Object runClosure(final Closure closure) { if (numChildren == 0) { return null; } - block = new LexicalFrame(frame, block).defineArgs(); + pushBlock().defineArgs(); try { final JexlNode body = script instanceof ASTJexlLambda ? script.jjtGetChild(numChildren - 1) : script; return interpret(body); } finally { - block = block.pop(); + popBlock(); } } @@ -1067,7 +1132,7 @@ protected Object visit(final ASTArrayAccess node, final Object data) { final JexlNode nindex = node.jjtGetChild(i); if (object == null) { // safe navigation access - return node.isSafeChild(i) + return isSafe() || node.isSafeChild(i) ? null :unsolvableProperty(nindex, stringifyProperty(nindex), false, null); } @@ -1154,11 +1219,11 @@ protected Object visit(final ASTBlock node, final Object data) { if (cnt <= 0) { return visitBlock(node, data); } + pushBlock(); try { - block = new LexicalFrame(frame, block); return visitBlock(node, data); } finally { - block = block.pop(); + popBlock(); } } @@ -1562,11 +1627,11 @@ protected Object visit(final ASTJexlScript script, final Object data) { } return closure; } - block = new LexicalFrame(frame, block).defineArgs(); + pushBlock().defineArgs(); try { return runScript(script, data); } finally { - block = block.pop(); + popBlock(); } } @@ -1833,21 +1898,23 @@ protected Object visit(final ASTReference node, final Object data) { Object object = null; JexlNode objectNode = null; JexlNode ptyNode = null; - StringBuilder ant = null; + AntishName ant = null; boolean antish = !(parent instanceof ASTReference) && options.isAntish(); - int v = 1; + // the index of the access to apply to the object + int deref = 0; main: for (int c = 0; c < numChildren; c++) { objectNode = node.jjtGetChild(c); + deref = c; if (objectNode instanceof ASTMethodNode) { antish = false; - if (object == null) { + // a leading method node evaluates its own functor, as in (f)(x).y + if (object == null && c > 0) { // we may be performing a method call on an antish var if (ant != null) { final JexlNode child = objectNode.jjtGetChild(0); if (child instanceof ASTIdentifierAccess) { final int alen = ant.length(); - ant.append('.'); ant.append(((ASTIdentifierAccess) child).getName()); object = context.get(ant.toString()); if (object != null) { @@ -1855,10 +1922,10 @@ protected Object visit(final ASTReference node, final Object data) { continue; } // remove method name from antish - ant.delete(alen, ant.length()); - ptyNode = objectNode; + ant.setLength(alen); } } + ptyNode = objectNode; break; } } else if (objectNode instanceof ASTArrayAccess) { @@ -1870,6 +1937,7 @@ protected Object visit(final ASTReference node, final Object data) { } // attempt to evaluate the property within the object (visit(ASTIdentifierAccess node)) object = objectNode.jjtAccept(this, object); + deref = c + 1; cancelCheck(node); if (object != null) { // disallow mixing antish variable & bean with same root; avoid ambiguity @@ -1885,24 +1953,23 @@ protected Object visit(final ASTReference node, final Object data) { break main; } final ASTIdentifier afirst = (ASTIdentifier) first; - ant = new StringBuilder(afirst.getName()); + ant = new AntishName(afirst.getName()); + if (afirst.getSymbol() >= 0) { + // top level is a symbol (a null local variable), cannot be an antish var; same as in executeAssign + ptyNode = numChildren > 1 ? node.jjtGetChild(1) : objectNode; + break main; + } continue; // skip the first node case since it was trialed in jjtAccept above and returned null } // catch up to current node - for (; v <= c; ++v) { - final JexlNode child = node.jjtGetChild(v); - if (!(child instanceof ASTIdentifierAccess)) { + final JexlNode stop = ant.appendUpTo(node, c); + if (stop != null) { + if (!(stop instanceof ASTIdentifierAccess)) { // not an identifier, not antish ptyNode = objectNode; - break main; } - final ASTIdentifierAccess achild = (ASTIdentifierAccess) child; - if (achild.isSafe() || achild.isExpression()) { - break main; - } - ant.append('.'); - ant.append(achild.getName()); + break main; } // solve antish object = context.get(ant.toString()); @@ -1915,12 +1982,13 @@ protected Object visit(final ASTReference node, final Object data) { // dealing with null if (object == null) { if (ptyNode != null) { - if (ptyNode.isSafeLhs(isSafe())) { + // the access applied to null decides, as in x?.y, x?.y() or x?[y] + if (isSafe() || deref < numChildren && isSafeAccess(node.jjtGetChild(deref))) { return null; } if (ant != null) { final String aname = ant.toString(); - final boolean defined = isVariableDefined(frame, block, aname); + final boolean defined = isVariableDefined(frame, aname); return unsolvableVariable(node, aname, !defined); } return unsolvableProperty(node, @@ -1931,7 +1999,7 @@ protected Object visit(final ASTReference node, final Object data) { return null; } final String aname = Objects.toString(ant, "?"); - final boolean defined = isVariableDefined(frame, block, aname); + final boolean defined = isVariableDefined(frame, aname); // defined but null; arg of a strict operator? if (defined && !isStrictOperand(node)) { return null; @@ -1942,6 +2010,20 @@ protected Object visit(final ASTReference node, final Object data) { return object; } + /** + * Checks whether an access in a reference is explicitly safe, as in ?.y, ?.y() or ?[y]. + * + * @param access the access, a method node being checked through the member it calls + * @return true if the access is safe, false otherwise + */ + private static boolean isSafeAccess(final JexlNode access) { + final JexlNode member = access instanceof ASTMethodNode ? access.jjtGetChild(0) : access; + if (member instanceof ASTIdentifierAccess) { + return ((ASTIdentifierAccess) member).isSafe(); + } + return member instanceof ASTArrayAccess && ((ASTArrayAccess) member).isSafeChild(0); + } + @Override protected Object visit(final ASTReferenceExpression node, final Object data) { return node.jjtGetChild(0).jjtAccept(this, data); @@ -2191,13 +2273,10 @@ protected Object visit(final ASTTryResources node, final Object data) { final int bodyChild = node.jjtGetNumChildren() - 1; final JexlNode tryBody = node.jjtGetChild(bodyChild); final Queue tryResult = new ArrayDeque<>(bodyChild); - final LexicalFrame locals; // sequence of var declarations with/without assignment - if (node.getSymbolCount() > 0) { - locals = new LexicalFrame(frame, block); - block = locals; - } else { - locals = null; + final boolean lexical = node.getSymbolCount() > 0; + if (lexical) { + pushBlock(); } try { for(int c = 0; c < bodyChild; ++c) { @@ -2211,9 +2290,8 @@ protected Object visit(final ASTTryResources node, final Object data) { return tryBody.jjtAccept(this, data); } finally { closeIfSupported(tryResult); - // restore lexical frame - if (locals != null) { - block = block.pop(); + if (lexical) { + popBlock(); } } } @@ -2408,7 +2486,7 @@ protected Object visitLexicalNode(final JexlNode node, final Object data) { try { return node.jjtAccept(this, data); } finally { - block = block.pop(); + popBlock(); } } } diff --git a/src/main/java/org/apache/commons/jexl3/internal/InterpreterBase.java b/src/main/java/org/apache/commons/jexl3/internal/InterpreterBase.java index f13161b49..61396ae5c 100644 --- a/src/main/java/org/apache/commons/jexl3/internal/InterpreterBase.java +++ b/src/main/java/org/apache/commons/jexl3/internal/InterpreterBase.java @@ -816,20 +816,19 @@ protected boolean isTernaryProtected(final JexlNode startNode) { /** * Checks whether a variable is defined. *

The var may be either a local variable declared in the frame and - * visible from the block or defined in the context. + * in scope or defined in the context. * * @param frame The frame - * @param block The block * @param name The variable name * @return true if variable is defined, false otherwise */ - protected boolean isVariableDefined(final Frame frame, final LexicalScope block, final String name) { - if (frame != null && block != null) { + protected boolean isVariableDefined(final Frame frame, final String name) { + if (frame != null) { final Integer ref = frame.getScope().getSymbol(name); final int symbol = ref != null ? ref : -1; - if (symbol >= 0 && block.hasSymbol(symbol)) { - final Object value = frame.get(symbol); - return value != Scope.UNDEFINED && value != Scope.UNDECLARED; + // a local var, not out of scope; same as in getVariable + if (symbol >= 0 && frame.has(symbol) && frame.get(symbol) != Scope.UNDEFINED) { + return true; } } return context.has(name); diff --git a/src/main/java/org/apache/commons/jexl3/parser/FeatureController.java b/src/main/java/org/apache/commons/jexl3/parser/FeatureController.java index d19a2e178..de398cb82 100644 --- a/src/main/java/org/apache/commons/jexl3/parser/FeatureController.java +++ b/src/main/java/org/apache/commons/jexl3/parser/FeatureController.java @@ -48,9 +48,25 @@ public void controlNode(final JexlNode node) { node.jjtAccept(this, null); } + /** + * Checks whether assigning a left value is a global side effect. + *

When antish variables are declared, they are all solved at parse time; only assigning + * a global variable is a global side effect, assigning a property of its value is not. + * Otherwise, assigning any property of a global may create an antish variable.

+ * + * @param lv the left value + * @return true if the assignment modifies a global variable + */ + private boolean isGlobalSideEffect(final JexlNode lv) { + if (features.antishTest() != JexlFeatures.TEST_STR_FALSE) { + return lv instanceof ASTIdentifier && lv.isGlobalVar(); + } + return lv.isGlobalVar(); + } + private Object controlSideEffect(final JexlNode node, final Object data) { final JexlNode lv = node.jjtGetChild(0); - if (!features.supportsSideEffectGlobal() && lv.isGlobalVar()) { + if (!features.supportsSideEffectGlobal() && isGlobalSideEffect(lv)) { throwFeatureException(JexlFeatures.SIDE_EFFECT_GLOBAL, lv); } if (features.supportsConstCapture() && lv instanceof ASTIdentifier && ((ASTIdentifier) lv).isCaptured()) { diff --git a/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java b/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java index c45115742..0e5292775 100644 --- a/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java +++ b/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java @@ -32,6 +32,7 @@ import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Predicate; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.JexlException; @@ -791,6 +792,13 @@ protected Scope getScope() { */ protected abstract Token getToken(int index); + /** + * Overridden in actual parser to replace the node on top of the tree-building stack. + * + * @param replacement The node replacing the top node + */ + protected abstract void jjtreeReplaceTop(JexlNode replacement); + /** * Gets the lexical unit used by this parser. * @@ -1005,6 +1013,14 @@ protected void jjtreeCloseNodeScope(final JexlNode node) { if (script.getScope() != scope) { script.setScope(scope); } + } else if (node instanceof ASTReference) { + final JexlNode antish = resolveAntish((ASTReference) node); + if (antish != node) { + // the whole reference is a declared antish variable + jjtreeReplaceTop(antish); + featureController.controlNode(antish); + return; + } } else if (ASSIGN_NODES.contains(node.getClass())) { final JexlNode lv = node.jjtGetChild(0); if (!lv.isLeftValue()) { @@ -1026,6 +1042,106 @@ protected void jjtreeCloseNodeScope(final JexlNode node) { featureController.controlNode(node); } + /** + * Resolves a declared antish variable in a reference. + *

When the features declare antish variable names, the longest dotted prefix satisfying the + * declaration test of a reference rooted on a global variable, like x.y in + * x.y.z, is rewritten as a single identifier.

+ * + * @param reference The reference node + * @return the reference (rewritten or not) or the identifier if the whole reference is an antish variable + * @see JexlFeatures#antishTest(Predicate) + */ + private JexlNode resolveAntish(final ASTReference reference) { + final Predicate declared = getFeatures().antishTest(); + if (declared == JexlFeatures.TEST_STR_FALSE) { + return reference; + } + final JexlNode first = reference.jjtGetChild(0); + // a local variable or a namespace can not be the root of an antish variable + if (!(first instanceof ASTIdentifier) + || ((ASTIdentifier) first).getSymbol() >= 0 + || ((ASTIdentifier) first).getNamespace() != null) { + return reference; + } + final ASTIdentifier root = (ASTIdentifier) first; + final int count = reference.jjtGetNumChildren(); + final StringBuilder name = new StringBuilder(root.getName()); + String antish = null; + int last = 0; + int stop = 1; + for (; stop < count; ++stop) { + final JexlNode child = reference.jjtGetChild(stop); + // only plain identifier access, no safe navigation nor expression + if (child.getClass() != ASTIdentifierAccess.class) { + break; + } + name.append('.').append(((ASTIdentifierAccess) child).getName()); + final String candidate = name.toString(); + if (declared.test(candidate)) { + antish = candidate; + last = stop; + } + } + if (antish == null) { + return stop < count ? resolveAntishFunctor(reference, name, stop) : reference; + } + root.setSymbol(antish); + if (last == count - 1) { + root.jjtSetParent(null); + return root; + } + final JexlNode[] children = new JexlNode[count - last]; + children[0] = root; + for (int c = last + 1; c < count; ++c) { + children[c - last] = reference.jjtGetChild(c); + } + reference.jjtSetChildren(children); + return reference; + } + + /** + * Resolves a declared antish variable called as a functor in a reference. + *

When no prefix of the reference is a declared antish variable, the name of the method + * that follows may complete one, like f.g in f.g(42); the method call + * is then rewritten as a call of that variable.

+ * + * @param reference The reference node + * @param prefix The dotted name that precedes the method name + * @param at The index of the method node in the reference + * @return the reference (rewritten or not) or the method node if the call starts and ends the reference + */ + private JexlNode resolveAntishFunctor(final ASTReference reference, final StringBuilder prefix, final int at) { + final Predicate declared = getFeatures().antishTest(); + final ASTIdentifier root = (ASTIdentifier) reference.jjtGetChild(0); + final JexlNode call = reference.jjtGetChild(at); + // only a plain method name; a declared root is a variable, the method is called on its value + if (!(call instanceof ASTMethodNode) + || call.jjtGetChild(0).getClass() != ASTIdentifierAccess.class + || declared.test(root.getName())) { + return reference; + } + final String functor = prefix.append('.').append(((ASTIdentifierAccess) call.jjtGetChild(0)).getName()).toString(); + if (!declared.test(functor)) { + return reference; + } + // the antish variable replaces the method name + root.setSymbol(functor); + root.jjtSetParent(call); + call.jjtAddChild(root, 0); + final int count = reference.jjtGetNumChildren(); + if (at == count - 1) { + call.jjtSetParent(null); + return call; + } + final JexlNode[] children = new JexlNode[count - at]; + for (int c = at; c < count; ++c) { + children[c - at] = reference.jjtGetChild(c); + } + reference.jjtSetChildren(children); + return reference; + } + /** * Parses an embedded Jexl expression within an interpolation node. *

This creates a sub-parser that shares the scopes of the parent parser.

diff --git a/src/main/java/org/apache/commons/jexl3/parser/Parser.jjt b/src/main/java/org/apache/commons/jexl3/parser/Parser.jjt index 572b525d6..a0e56ae90 100644 --- a/src/main/java/org/apache/commons/jexl3/parser/Parser.jjt +++ b/src/main/java/org/apache/commons/jexl3/parser/Parser.jjt @@ -59,6 +59,12 @@ public final class Parser extends JexlParser token.next = jj_nt = token_source.getNextToken(); } + @Override + protected void jjtreeReplaceTop(JexlNode replacement) { + jjtree.popNode(); + jjtree.pushNode(replacement); + } + /** * Parses a JEXL source string and returns the corresponding AST. * @param jexlInfo the JEXL info to use, may be null diff --git a/src/main/java/org/apache/commons/jexl3/parser/SimpleNode.java b/src/main/java/org/apache/commons/jexl3/parser/SimpleNode.java index 8caba16f5..b912d6608 100644 --- a/src/main/java/org/apache/commons/jexl3/parser/SimpleNode.java +++ b/src/main/java/org/apache/commons/jexl3/parser/SimpleNode.java @@ -191,7 +191,7 @@ public Object jjtGetValue() { public void jjtOpen() { } - // For use by ASTJexlScript only + // For use by ASTJexlScript and the parser antish variable resolution only void jjtSetChildren(final JexlNode[] jexlNodes) { children = jexlNodes; } diff --git a/src/test/java/org/apache/commons/jexl3/AntishCallTest.java b/src/test/java/org/apache/commons/jexl3/AntishCallTest.java index 65d1ea314..14a130b6c 100644 --- a/src/test/java/org/apache/commons/jexl3/AntishCallTest.java +++ b/src/test/java/org/apache/commons/jexl3/AntishCallTest.java @@ -17,6 +17,7 @@ package org.apache.commons.jexl3; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -170,6 +171,22 @@ void testAntishContextVar() throws Exception { runTestCall(JEXL, jc); } + @Test + void testLocalRootShadowsAntish() { + final JexlEvalContext ctxt = new JexlEvalContext(); + ctxt.set("x.y", 42); + // a global root resolves as an antish variable + assertEquals(42, JEXL.createScript("x.y").execute(ctxt)); + // a local variable root shadows the antish variable, when reading... + final JexlException.Variable xvar = assertThrows(JexlException.Variable.class, + () -> JEXL.createScript("var x; x.y").execute(ctxt)); + assertEquals("x", xvar.getVariable()); + assertFalse(xvar.isUndefined()); + // ...as when assigning + assertThrows(JexlException.Property.class, () -> JEXL.createScript("var x; x.y = 1").execute(ctxt)); + assertEquals(42, ctxt.get("x.y")); + } + // JEXL-300 @Test void testSafeAnt() throws Exception { @@ -205,4 +222,4 @@ void testSafeAnt() throws Exception { assertThrows(JexlException.class, () -> script4.execute(ctxt), "x not defined"); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/jexl3/AntishFeaturesTest.java b/src/test/java/org/apache/commons/jexl3/AntishFeaturesTest.java new file mode 100644 index 000000000..a1512ef35 --- /dev/null +++ b/src/test/java/org/apache/commons/jexl3/AntishFeaturesTest.java @@ -0,0 +1,326 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.jexl3; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +/** + * Tests antish variables declared at parse time through {@link JexlFeatures#antishTest(java.util.function.Predicate)}. + */ +class AntishFeaturesTest extends JexlTestCase { + + public AntishFeaturesTest() { + super("AntishFeaturesTest"); + } + + private static JexlEngine createEngine(final String... names) { + final JexlFeatures features = JexlFeatures.createDefault().antishTest(JexlFeatures.namePatterns(Arrays.asList(names))); + return new JexlBuilder().features(features).strict(true).create(); + } + + private static Map map(final String key, final Object value) { + final Map map = new HashMap<>(); + map.put(key, value); + return map; + } + + @Test + void testRead() throws Exception { + final JexlEngine jexl = createEngine("x.y"); + final JexlContext ctxt = new MapContext(); + ctxt.set("x.y", map("z", 42)); + final JexlScript script = jexl.createScript("x.y.z"); + assertEquals(42, script.execute(ctxt)); + // x.y is one variable, z a property + final Set> vars = script.getVariables(); + assertEquals(Collections.singleton(Arrays.asList("x.y", "z")), vars); + assertEquals("x.y.z", script.getParsedText()); + debuggerCheck(jexl); + } + + @Test + void testWholeReference() throws Exception { + final JexlEngine jexl = createEngine("x.y"); + final JexlContext ctxt = new MapContext(); + ctxt.set("x.y", 42); + assertEquals(42, jexl.createScript("x.y").execute(ctxt)); + assertEquals(43, jexl.createScript("x.y = x.y + 1").execute(ctxt)); + assertEquals(43, ctxt.get("x.y")); + assertEquals(44, jexl.createScript("x.y += 1").execute(ctxt)); + assertEquals(44, ctxt.get("x.y")); + debuggerCheck(jexl); + } + + @Test + void testAssignProperty() throws Exception { + final JexlEngine jexl = createEngine("x.y"); + final JexlContext ctxt = new MapContext(); + final Map xy = map("z", 1); + ctxt.set("x.y", xy); + assertEquals(2, jexl.createScript("x.y.z = 2").execute(ctxt)); + assertEquals(2, xy.get("z")); + debuggerCheck(jexl); + } + + @Test + void testLongestPrefix() throws Exception { + final JexlEngine jexl = createEngine("x.y", "x.y.z"); + final JexlContext ctxt = new MapContext(); + ctxt.set("x.y", map("z", map("w", 1))); + ctxt.set("x.y.z", map("w", 2)); + assertEquals(2, jexl.createScript("x.y.z.w").execute(ctxt)); + assertEquals(1, jexl.createScript("x.y['z'].w").execute(ctxt)); + debuggerCheck(jexl); + } + + @Test + void testPatterns() throws Exception { + final JexlEngine jexl = createEngine("build.*"); + final JexlContext ctxt = new MapContext(); + ctxt.set("build.version", "1.2"); + ctxt.set("build.dir", "target"); + assertEquals("target/1.2", jexl.createScript("build.dir + '/' + build.version").execute(ctxt)); + debuggerCheck(jexl); + } + + @Test + void testMethodCall() throws Exception { + final JexlEngine jexl = createEngine("x.y"); + final JexlContext ctxt = new MapContext(); + ctxt.set("x.y", Arrays.asList(1, 2, 3)); + assertEquals(3, jexl.createScript("x.y.size()").execute(ctxt)); + debuggerCheck(jexl); + } + + @Test + void testFunctor() throws Exception { + final JexlEngine jexl = createEngine("f.g", "f.h", "x.*"); + final JexlContext ctxt = new MapContext(); + ctxt.set("f.g", jexl.createScript("a + 1", "a")); + ctxt.set("f.h", jexl.createScript("a -> b -> a + b")); + ctxt.set("x.y", "abc"); + // a declared antish variable is called as a functor + JexlScript script = jexl.createScript("f.g(41)"); + assertEquals(42, script.execute(ctxt)); + assertEquals("f.g(41)", script.getParsedText()); + assertEquals("42", jexl.createScript("f.g(41).toString()").execute(ctxt)); + // curried + script = jexl.createScript("f.h(1)(2)"); + assertEquals(3, script.execute(ctxt)); + assertEquals("f.h(1)(2)", script.getParsedText()); + assertEquals("3", jexl.createScript("f.h(1)(2).toString()").execute(ctxt)); + // a method is called on the longest declared prefix + assertEquals(3, jexl.createScript("x.y.length()").execute(ctxt)); + // safe navigation is not rewritten, g is a method of f + assertNull(jexl.createScript("f?.g(41)").execute(ctxt)); + // declared but undefined + final JexlException.Variable xvar = assertThrows(JexlException.Variable.class, () -> jexl.createScript("x.q(1)").execute(ctxt)); + assertEquals("x.q", xvar.getVariable()); + debuggerCheck(jexl); + } + + @Test + void testFunctorDeclaredRoot() throws Exception { + // all names are declared, including the root: the method is called on its value + final JexlEngine jexl = createEngine("*"); + final JexlContext ctxt = new MapContext(); + ctxt.set("s", "abc"); + ctxt.set("f.g", jexl.createScript("a + 1", "a")); + assertEquals(3, jexl.createScript("s.length()").execute(ctxt)); + assertEquals(42, jexl.createScript("(f.g)(41)").execute(ctxt)); + debuggerCheck(jexl); + } + + @Test + void testLocalRoot() throws Exception { + final JexlEngine jexl = createEngine("x.y"); + final JexlContext ctxt = new MapContext(); + ctxt.set("x.y", 42); + // a local variable is never the root of an antish variable + assertEquals(1, jexl.createScript("var x = { 'y' : 1 }; x.y").execute(ctxt)); + assertEquals(1, jexl.createScript("x.y", "x").execute(ctxt, map("y", 1))); + debuggerCheck(jexl); + } + + @Test + void testSafeNavigationAndExpression() throws Exception { + final JexlEngine jexl = createEngine("x.y"); + final JexlEvalContext ctxt = new JexlEvalContext(); + ctxt.set("x.y", 42); + ctxt.set("x", map("y", 1)); + assertEquals(42, jexl.createScript("x.y").execute(ctxt)); + // safe navigation or expression segments are not rewritten, y is a property of x + assertEquals(1, jexl.createScript("x?.y").execute(ctxt)); + assertEquals(1, jexl.createScript("x.`y`").execute(ctxt)); + debuggerCheck(jexl); + } + + @Test + void testSafeNavigationNullRoot() { + final JexlFeatures features = JexlFeatures.createDefault().antishTest(JexlFeatures.namePatterns(Collections.singletonList("x.y"))); + final JexlContext ctxt = new MapContext(); + ctxt.set("a", null); + final JexlEngine jexl = new JexlBuilder().features(features).strict(true).safe(false).create(); + // safe navigation protects from a null or undefined root + assertNull(jexl.createScript("a?.b").execute(ctxt)); + assertNull(jexl.createScript("a?.b.c").execute(ctxt)); + assertNull(jexl.createScript("u?.b").execute(ctxt)); + assertNull(jexl.createScript("var v; v?.b").execute(ctxt)); + // but only when it follows the root + assertThrows(JexlException.Property.class, () -> jexl.createScript("a.b").execute(ctxt)); + assertThrows(JexlException.Property.class, () -> jexl.createScript("a.b?.c").execute(ctxt)); + assertThrows(JexlException.Property.class, () -> jexl.createScript("var v; v.b?.c").execute(ctxt)); + // unless the engine is safe + final JexlEngine safe = new JexlBuilder().features(features).strict(true).safe(true).create(); + assertNull(safe.createScript("a.b").execute(ctxt)); + assertNull(safe.createScript("var v; v.b").execute(ctxt)); + } + + @Test + void testUndeclared() { + final JexlEngine jexl = createEngine("x.y"); + final JexlEvalContext ctxt = new JexlEvalContext(); + ctxt.set("a.b", 42); + // not declared, not resolved: declaring antish names disables runtime antish + assertThrows(JexlException.Property.class, () -> jexl.createScript("a.b").execute(ctxt)); + // declared but undefined + final JexlException.Variable xvar = assertThrows(JexlException.Variable.class, () -> jexl.createScript("x.y").execute(ctxt)); + assertEquals("x.y", xvar.getVariable()); + assertTrue(xvar.isUndefined()); + } + + @Test + void testPartialDeclaration() { + final JexlEngine jexl = createEngine("x.y"); + final JexlEvalContext ctxt = new JexlEvalContext(); + // even if the context options ask for it + ctxt.getEngineOptions().setAntish(true); + ctxt.set("x.y.z", 42); + // x.y is the declared variable, z its property; x.y.z is never solved at runtime + final JexlException.Property xp = assertThrows(JexlException.Property.class, () -> jexl.createScript("x.y.z").execute(ctxt)); + assertEquals(".z", xp.getProperty()); + // same with the engine options + final JexlContext mctxt = new MapContext(); + mctxt.set("x.y.z", 42); + assertThrows(JexlException.Property.class, () -> jexl.createScript("x.y.z").execute(mctxt)); + } + + @Test + void testSideEffectGlobal() { + final JexlFeatures features = JexlFeatures.createDefault() + .sideEffectGlobal(false) + .antishTest(JexlFeatures.namePatterns(Collections.singletonList("x.y"))); + final JexlEngine jexl = new JexlBuilder().features(features).create(); + // an antish variable is a global variable + assertThrows(JexlException.Feature.class, () -> jexl.createScript("x.y = 1")); + assertThrows(JexlException.Feature.class, () -> jexl.createScript("x.y += 1")); + assertThrows(JexlException.Feature.class, () -> jexl.createScript("x = 1")); + // assigning a property of a global value is not assigning a global + final JexlContext ctxt = new MapContext(); + final Map xy = map("z", 0); + ctxt.set("x.y", xy); + ctxt.set("x", new HashMap<>()); + assertEquals(43, jexl.createScript("x.y.z = 43").execute(ctxt)); + assertEquals(43, xy.get("z")); + assertEquals(44, jexl.createScript("x.y.z += 1").execute(ctxt)); + assertEquals(1, jexl.createScript("x.w = 1").execute(ctxt)); + assertEquals(1, ((Map) ctxt.get("x")).get("w")); + // without declared antish names, any property assignment on a global may create an antish variable + final JexlEngine jexl0 = new JexlBuilder().features(JexlFeatures.createDefault().sideEffectGlobal(false)).create(); + assertThrows(JexlException.Feature.class, () -> jexl0.createScript("x.y.z = 43")); + } + + @Test + void testSideEffectGlobalScripts() { + final JexlFeatures features = JexlFeatures.createDefault().sideEffectGlobal(false); + final JexlEngine jexl0 = new JexlBuilder().features(new JexlFeatures(features)).create(); + final JexlEngine jexl = new JexlBuilder() + .features(features.antishTest(JexlFeatures.namePatterns(Collections.singletonList("x.y")))) + .create(); + // assigning a global: always fails + final String[] globals = { + "x = 1", "x += 1", "x++", "--x", "x.y = 1", "x.y -= 1", "x.y++", "++x.y", "if (true) x.y = 4", "4 + (x.y = 1)" + }; + // assigning a property of a global value: only fails without declared antish names + final String[] properties = { + "x.y.z = 1", "x.y.z *= 2", "x.y.z++", "--x.y.z", "x.y['z'] = 1", "x.y[0] = 1", "x['y'] = 1", "x[0] = 1", + "x.w = 1", "x?.y = 1", "x.`y` = 1", "x().y = 1", "if (true) x.y.z = 4", "4 + (x.y.z = 1)" + }; + for (final String src : globals) { + assertThrows(JexlException.Feature.class, () -> jexl.createScript(src), src); + assertThrows(JexlException.Feature.class, () -> jexl0.createScript(src), src); + } + for (final String src : properties) { + assertNotNull(jexl.createScript(src), src); + assertThrows(JexlException.Feature.class, () -> jexl0.createScript(src), src); + } + // with a local root, nothing is global + for (final String src : globals) { + assertNotNull(jexl.createScript("var x = {}; " + src), src); + assertNotNull(jexl0.createScript("var x = {}; " + src), src); + } + // reading is never a side effect + assertNotNull(jexl.createScript("x.y.z + x.y + x")); + assertNotNull(jexl0.createScript("x.y.z + x.y + x")); + } + + @Test + void testScriptFeatures() { + // engine without declared antish names, runtime antish solving + final JexlEngine jexl = new JexlBuilder().strict(true).create(); + final JexlFeatures features = JexlFeatures.createDefault() + .sideEffectGlobal(false) + .antishTest(JexlFeatures.namePatterns(Collections.singletonList("x.y"))); + final JexlContext ctxt = new MapContext(); + ctxt.set("a.b.c", 42); + // a script parsed with declared antish names does not solve antish variables at runtime + final JexlScript assign = jexl.createScript(features, null, "a.b = 1"); + assertThrows(JexlException.class, () -> assign.execute(ctxt)); + assertFalse(ctxt.has("a.b")); + final JexlScript read = jexl.createScript(features, null, "a.b.c"); + assertThrows(JexlException.class, () -> read.execute(ctxt)); + // the engine still solves antish variables for its own scripts + assertEquals(42, jexl.createScript("a.b.c").execute(ctxt)); + } + + @Test + void testFeaturesEquality() { + final JexlFeatures f0 = JexlFeatures.createDefault().antishTest(JexlFeatures.namePatterns(Arrays.asList("x.y", "a.*"))); + final JexlFeatures f1 = JexlFeatures.createDefault().antishTest(JexlFeatures.namePatterns(Arrays.asList("a.*", "x.y"))); + final JexlFeatures f2 = JexlFeatures.createDefault().antishTest(JexlFeatures.namePatterns(Arrays.asList("x.y"))); + assertEquals(f0, f1); + assertEquals(f0.hashCode(), f1.hashCode()); + assertEquals(f0, new JexlFeatures(f0)); + assertNotEquals(f0, f2); + assertNotEquals(f0, JexlFeatures.createDefault()); + } +} diff --git a/src/test/java/org/apache/commons/jexl3/ForEachTest.java b/src/test/java/org/apache/commons/jexl3/ForEachTest.java index 1a28a8bf7..cb8ea113b 100644 --- a/src/test/java/org/apache/commons/jexl3/ForEachTest.java +++ b/src/test/java/org/apache/commons/jexl3/ForEachTest.java @@ -199,7 +199,7 @@ void testForEachWithProperty() throws Exception { } @Test void testForLoop0b0() { - final String src = "(l)->{ for (let x = 0, y = 0; x < 4; ++x) l.add(x) }"; + final String src = "(l)->{ for (let x = 0, y = 0; x < 4; ++x) l.add(x); }"; final JexlEngine jexl = new JexlBuilder().safe(false).create(); final JexlScript script = jexl.createScript(src); final List l = new ArrayList<>(); diff --git a/src/test/java/org/apache/commons/jexl3/InterpreterCharacterizationTest.java b/src/test/java/org/apache/commons/jexl3/InterpreterCharacterizationTest.java new file mode 100644 index 000000000..97ea3b008 --- /dev/null +++ b/src/test/java/org/apache/commons/jexl3/InterpreterCharacterizationTest.java @@ -0,0 +1,308 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.jexl3; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.junit.jupiter.api.Test; + +/** + * Characterization tests pinning the current behavior of loops, catch, lexical blocks + * and antish variable resolution/assignment in the interpreter. + *

Each case is {mode, script, expected} where expected is either "= value" or + * "ExceptionSimpleName: @line:col message".

+ */ +class InterpreterCharacterizationTest extends JexlTestCase { + + private static final String[][] CASES = { + {"lex", "var s = 0; for (var i = 0; i < 10; ++i) { if (i == 2) continue; if (i == 5) break; s += i; } s", "= 8"}, + {"nolex", "var s = 0; for (var i = 0; i < 10; ++i) { if (i == 2) continue; if (i == 5) break; s += i; } s", "= 8"}, + {"lex", "var s = 0; for (var i = 0, j = 5; i < j; ++i) { s += i; } s", "= 10"}, + {"nolex", "var s = 0; for (var i = 0, j = 5; i < j; ++i) { s += i; } s", "= 10"}, + {"lex", "var i = 0; for (; i < 3; ++i); i", "= 3"}, + {"nolex", "var i = 0; for (; i < 3; ++i); i", "= 3"}, + {"lex", "for (var i = 0; i < 3; ++i); 42", "= 42"}, + {"nolex", "for (var i = 0; i < 3; ++i); 42", "= 42"}, + {"lex", "var i = 0; for (;;) { if (++i > 2) break; } i", "= 3"}, + {"nolex", "var i = 0; for (;;) { if (++i > 2) break; } i", "= 3"}, + {"lex", "var n = 0; var c = true; for (var i = 0; c = i < 3; ++i) { n += 1 } n", "= 3"}, + {"nolex", "var n = 0; var c = true; for (var i = 0; c = i < 3; ++i) { n += 1 } n", "= 3"}, + {"lex", "var n = 0; for (var i = 0; ; i = i + 1) { if (i > 2) break; n += 1 } n", "= 3"}, + {"nolex", "var n = 0; for (var i = 0; ; i = i + 1) { if (i > 2) break; n += 1 } n", "= 3"}, + {"lex", "var k = 0; for (var i = 0, j = 2; i < j; ++i) ++k; k", "= 2"}, + {"nolex", "var k = 0; for (var i = 0, j = 2; i < j; ++i) ++k; k", "= 2"}, + {"lex", "var n = 0; for (var i = 0, j = 2; i < j; ++i) { n += 1 } for (var i = 0, j = 3; i < j; ++i) { n += 1 } n", "= 5"}, + {"nolex", "var n = 0; for (var i = 0, j = 2; i < j; ++i) { n += 1 } for (var i = 0, j = 3; i < j; ++i) { n += 1 } n", "= 5"}, + {"lex", "var n = 0; for (let i = 0, j = 2; i < j; ++i) { n += 1 } for (let i = 0, j = 3; i < j; ++i) { n += 1 } n", "= 5"}, + {"nolex", "var n = 0; for (let i = 0, j = 2; i < j; ++i) { n += 1 } for (let i = 0, j = 3; i < j; ++i) { n += 1 } n", "= 5"}, + {"lex", "var n = 0; for (var x : [1, 2, 3]) n += x; n", "= 6"}, + {"nolex", "var n = 0; for (var x : [1, 2, 3]) n += x; n", "= 6"}, + {"lex", "var i = 0; var s = 0; do { i++; if (i == 2) continue; if (i == 4) break; s += i; } while (i < 10); s", "= 4"}, + {"nolex", "var i = 0; var s = 0; do { i++; if (i == 2) continue; if (i == 4) break; s += i; } while (i < 10); s", "= 4"}, + {"lex", "var i = 0; var s = 0; while (i < 5) { i++; if (i % 2 == 0) continue; s += i; } s", "= 9"}, + {"nolex", "var i = 0; var s = 0; while (i < 5) { i++; if (i % 2 == 0) continue; s += i; } s", "= 9"}, + {"lex", "var s = 0; for (var x : [1, 2, 3]); s", "= 0"}, + {"nolex", "var s = 0; for (var x : [1, 2, 3]); s", "= 0"}, + {"lex", "var s = 0; for (var x : [1, 2, 3, 4]) { if (x == 2) continue; if (x == 4) break; s += x; } s", "= 4"}, + {"nolex", "var s = 0; for (var x : [1, 2, 3, 4]) { if (x == 2) continue; if (x == 4) break; s += x; } s", "= 4"}, + {"lex", "var s = 0; for (x : [1, 2, 3]) { s += x; } s + x", "= 9"}, + {"nolex", "var s = 0; for (x : [1, 2, 3]) { s += x; } s + x", "= 9"}, + {"lex", "var s = 0; for (let x : [1, 2, 3]) { s += x; } s", "= 6"}, + {"nolex", "var s = 0; for (let x : [1, 2, 3]) { s += x; } s", "= 6"}, + {"lex", "var s = 0; var k = 3; switch (k) { case 1: s = 1; break; case 3: s = 3; break; default: s = 9; } s", "= 3"}, + {"nolex", "var s = 0; var k = 3; switch (k) { case 1: s = 1; break; case 3: s = 3; break; default: s = 9; } s", "= 3"}, + {"lex", "try { throw 'a' } catch (e) { e }", "= Throw"}, + {"nolex", "try { throw 'a' } catch (e) { e }", "= Throw"}, + {"lex", "try { throw 'a' } catch (var e) { e }", "= Throw"}, + {"nolex", "try { throw 'a' } catch (var e) { e }", "= Throw"}, + {"lex", "try { throw 'a' } catch (let e) { e }", "= Throw"}, + {"nolex", "try { throw 'a' } catch (let e) { e }", "= Throw"}, + {"lex", "let e = 1; try { throw 'a' } catch (let e) { e }", "Parsing: @1:41 parsing error in 'e: variable is already declared'"}, + {"nolex", "let e = 1; try { throw 'a' } catch (let e) { e }", "Parsing: @1:41 parsing error in 'e: variable is already declared'"}, + {"lex", "try { throw 'a' } catch (e) { 1 }; e", "= Throw"}, + {"nolex", "try { throw 'a' } catch (e) { 1 }; e", "= Throw"}, + {"lex", "var r = 0; { let y = 2; r = y; } r", "= 2"}, + {"nolex", "var r = 0; { let y = 2; r = y; } r", "= 2"}, + {"lex", "let x = 1; { let x = 2; }", "Parsing: @1:18 parsing error in 'x: variable is already declared'"}, + {"nolex", "let x = 1; { let x = 2; }", "Parsing: @1:18 parsing error in 'x: variable is already declared'"}, + {"ant", "x.y.z", "Property: @1:5 undefined property 'z'"}, + {"noant", "x.y.z", "Property: @1:1 null value property '.y'"}, + {"strict", "x.y.z", "Property: @1:5 undefined property 'z'"}, + {"safe", "x.y.z", "Property: @1:5 undefined property 'z'"}, + {"ant", "x.y.z = 3", "Property: @1:7 undefined property 'z'"}, + {"noant", "x.y.z = 3", "JexlException: @1:1 JEXL error : illegal assignment form"}, + {"strict", "x.y.z = 3", "Property: @1:7 undefined property 'z'"}, + {"safe", "x.y.z = 3", "Property: @1:7 undefined property 'z'"}, + {"ant", "x.y.z += 2", "Property: @1:7 undefined property 'z'"}, + {"noant", "x.y.z += 2", "JexlException: @1:1 JEXL error : illegal assignment form"}, + {"strict", "x.y.z += 2", "Property: @1:7 undefined property 'z'"}, + {"safe", "x.y.z += 2", "Property: @1:7 undefined property 'z'"}, + {"ant", "x.y?.z.w = 3", "Property: @1:7 undefined property '.'"}, + {"noant", "x.y?.z.w = 3", "JexlException: @1:1 JEXL error : illegal assignment form"}, + {"strict", "x.y?.z.w = 3", "Property: @1:7 undefined property '.'"}, + {"safe", "x.y?.z.w = 3", "Property: @1:7 undefined property '.'"}, + {"ant", "x.y.`'z'`.w = 3", "Property: @1:10 undefined property ''z''"}, + {"noant", "x.y.`'z'`.w = 3", "JexlException: @1:1 JEXL error : illegal assignment form"}, + {"strict", "x.y.`'z'`.w = 3", "Property: @1:10 undefined property ''z''"}, + {"safe", "x.y.`'z'`.w = 3", "Property: @1:10 undefined property ''z''"}, + {"ant", "x.y.size()", "= 2"}, + {"noant", "x.y.size()", "Property: @1:1 null value property '.y'"}, + {"strict", "x.y.size()", "= 2"}, + {"safe", "x.y.size()", "= 2"}, + {"ant", "x.y.foo()", "Method: @1:4 unsolvable function/method 'foo'"}, + {"noant", "x.y.foo()", "Property: @1:1 null value property '.y'"}, + {"strict", "x.y.foo()", "Method: @1:4 unsolvable function/method 'foo'"}, + {"safe", "x.y.foo()", "= null"}, + {"ant", "x.a.b", "Variable: @1:1 variable 'x.a.b' is undefined"}, + {"noant", "x.a.b", "Property: @1:1 null value property '.a'"}, + {"strict", "x.a.b", "Variable: @1:1 variable 'x.a.b' is undefined"}, + {"safe", "x.a.b", "= null"}, + {"ant", "x.y.z.w", "Property: @1:6 undefined property 'z'"}, + {"noant", "x.y.z.w", "Property: @1:1 null value property '.y'"}, + {"strict", "x.y.z.w", "Property: @1:6 undefined property 'z'"}, + {"safe", "x.y.z.w", "Property: @1:6 undefined property 'z'"}, + {"ant", "var x; x.y.z", "Variable: @1:8 variable 'x' is null"}, + {"noant", "var x; x.y.z", "Property: @1:8 null value property '.y'"}, + {"strict", "var x; x.y.z", "Variable: @1:8 variable 'x' is null"}, + {"safe", "var x; x.y.z", "= null"}, + {"ant", "var x; x.y.z = 1", "Property: @1:8 undefined property '.'"}, + {"noant", "var x; x.y.z = 1", "JexlException: @1:8 JEXL error : illegal assignment form"}, + {"strict", "var x; x.y.z = 1", "Property: @1:8 undefined property '.'"}, + {"safe", "var x; x.y.z = 1", "Property: @1:8 undefined property '.'"}, + {"ant", "m.y = 3; m.y", "= 3"}, + {"noant", "m.y = 3; m.y", "= 3"}, + {"strict", "m.y = 3; m.y", "= 3"}, + {"safe", "m.y = 3; m.y", "= 3"}, + {"ant", "m.y.z = 3", "JexlException: @1:4 JEXL error : illegal assignment form"}, + {"noant", "m.y.z = 3", "JexlException: @1:4 JEXL error : illegal assignment form"}, + {"strict", "m.y.z = 3", "JexlException: @1:4 JEXL error : illegal assignment form"}, + {"safe", "m.y.z = 3", "JexlException: @1:4 JEXL error : illegal assignment form"}, + {"ant", "m.q.z", "Property: @1:1 undefined property '.q'"}, + {"noant", "m.q.z", "Property: @1:1 undefined property '.q'"}, + {"strict", "m.q.z", "Property: @1:1 undefined property '.q'"}, + {"safe", "m.q.z", "= null"}, + {"ant", "x.y[0]", "= 1"}, + {"noant", "x.y[0]", "Property: @1:1 null value property '.y'"}, + {"strict", "x.y[0]", "= 1"}, + {"safe", "x.y[0]", "= 1"}, + {"ant", "x.y[0] = 1", "= 1"}, + {"noant", "x.y[0] = 1", "JexlException: @1:1 JEXL error : illegal assignment form"}, + {"strict", "x.y[0] = 1", "= 1"}, + {"safe", "x.y[0] = 1", "= 1"}, + {"ant", "(x.y).z", "Property: @1:7 undefined property 'z'"}, + {"noant", "(x.y).z", "Property: @1:2 null value property '.y'"}, + {"strict", "(x.y).z", "Property: @1:7 undefined property 'z'"}, + {"safe", "(x.y).z", "Property: @1:7 undefined property 'z'"}, + {"ant", "x.y.z.size()", "Property: @1:6 undefined property 'z'"}, + {"noant", "x.y.z.size()", "Property: @1:1 null value property '.y'"}, + {"strict", "x.y.z.size()", "Property: @1:6 undefined property 'z'"}, + {"safe", "x.y.z.size()", "Property: @1:6 undefined property 'z'"}, + {"ant", "a.b.c?.d", "= null"}, + {"noant", "a.b.c?.d", "Property: @1:1 null value property '.b'"}, + {"strict", "a.b.c?.d", "= null"}, + {"safe", "a.b.c?.d", "= null"}, + {"ant", "a.b?.c.d", "Variable: @1:1 variable 'a.b' is undefined"}, + {"noant", "a.b?.c.d", "Property: @1:1 null value property '.b'"}, + {"strict", "a.b?.c.d", "Variable: @1:1 variable 'a.b' is undefined"}, + {"safe", "a.b?.c.d", "= null"}, + {"ant", "nul?.y", "= null"}, + {"noant", "nul?.y", "= null"}, + {"ant", "nul?.y.z", "= null"}, + {"noant", "nul?.y.z", "= null"}, + {"ant", "nul.y?.z", "Variable: @1:1 variable 'nul.y' is undefined"}, + {"noant", "nul.y?.z", "Property: @1:1 null value property '.y'"}, + {"safe", "nul.y?.z", "= null"}, + {"ant", "var x; x?.y", "= null"}, + {"noant", "var x; x?.y", "= null"}, + {"ant", "var x; x?.y.z", "= null"}, + {"noant", "var x; x?.y.z", "= null"}, + {"ant", "var x; x.y?.z", "Variable: @1:8 variable 'x' is null"}, + {"noant", "var x; x.y?.z", "Property: @1:8 null value property '.y'"}, + {"safe", "var x; x.y?.z", "= null"}, + {"ant", "var x; x.y", "Variable: @1:8 variable 'x' is null"}, + {"noant", "var x; x.y", "Property: @1:8 null value property '.y'"}, + {"safe", "var x; x.y", "= null"}, + {"ant", "nul.size()?.y", "Variable: @1:1 variable 'nul' is null"}, + {"noant", "nul.size()?.y", "Property: @1:1 null value property '.'size''"}, + {"ant", "nul[0]?.y", "Variable: @1:1 variable 'nul' is null"}, + {"noant", "nul[0]?.y", "Property: @1:1 null value property '[0]'"}, + {"ant", "var x; x.size()?.y", "Variable: @1:8 variable 'x' is null"}, + {"noant", "var x; x.size()?.y", "Property: @1:8 null value property '.'size''"}, + {"nolex", "var x; x.size()", "Variable: @1:8 variable 'x' is null"}, + {"ant", "nul[0]", "Variable: @1:1 variable 'nul' is null"}, + {"noant", "nul[0]", "Property: @1:1 null value property '[0]'"}, + {"safe", "nul[0]", "= null"}, + {"ant", "var x; x[0]", "Variable: @1:8 variable 'x' is null"}, + {"noant", "var x; x[0]", "Property: @1:8 null value property '[0]'"}, + {"safe", "var x; x[0]", "= null"}, + {"ant", "nul.y[0]", "Variable: @1:1 variable 'nul.y' is undefined"}, + {"noant", "nul.y[0]", "Property: @1:1 null value property '.y'"}, + {"safe", "nul.y[0]", "= null"}, + {"ant", "m['a'][0]", "Property: @1:8 null value property '0'"}, + {"noant", "m['a'][0]", "Property: @1:8 null value property '0'"}, + {"safe", "m['a'][0]", "= null"}, + {"safe", "var f = () -> null; f()[0]", "= null"}, + {"ant", "m.a?[0]", "= null"}, + {"noant", "m.a?[0]", "= null"}, + {"ant", "m.a?[0].y", "= null"}, + {"noant", "m.a?[0].y", "= null"}, + {"ant", "m.a[0]", "Property: @1:1 undefined property '.a'"}, + {"noant", "m.a[0]", "Property: @1:1 undefined property '.a'"}, + {"safe", "m.a[0]", "= null"}, + {"ant", "m.get('z')?[0]", "= null"}, + {"noant", "m.get('z')?[0]", "= null"}, + {"ant", "m.get('z')[0]", "Property: @1:1 undefined property '.get'"}, + {"noant", "m.get('z')[0]", "Property: @1:1 undefined property '.get'"}, + {"ant", "m?.get('z').y", "Property: @1:1 undefined property '?.get'"}, + {"noant", "m?.get('z').y", "Property: @1:1 undefined property '?.get'"}, + {"ant", "m?.get('z')?.y", "= null"}, + {"noant", "m?.get('z')?.y", "= null"}, + {"ant", "nul?.get('z').y", "= null"}, + {"noant", "nul?.get('z').y", "= null"}, + {"ant", "m?['z'].y", "Property: @1:1 undefined property '['z']'"}, + {"noant", "m?['z'].y", "Property: @1:1 undefined property '['z']'"}, + {"ant", "m.get('z')?.y", "= null"}, + {"noant", "m.get('z')?.y", "= null"}, + {"ant", "m.get('z').y", "Property: @1:1 undefined property '.get'"}, + {"noant", "m.get('z').y", "Property: @1:1 undefined property '.get'"}, + {"ant", "nul?[0](1)", "= null"}, + {"noant", "nul?[0](1)", "= null"}, + {"safe", "nul?[0](1)", "= null"}, + {"ant", "nul[0](1)", "Variable: @1:1 variable 'nul' is null"}, + {"noant", "nul[0](1)", "Property: @1:1 null value property '[...]'"}, + {"safe", "nul[0](1)", "= null"}, + {"ant", "nul.y[0](1)", "Variable: @1:1 variable 'nul.y' is undefined"}, + {"noant", "nul.y[0](1)", "Property: @1:1 null value property '.y'"}, + {"safe", "nul.y[0](1)", "= null"}, + {"lex", "var f = v -> { return { 'a' : v }; }; (f)(1).a", "= 1"}, + {"lex", "var f = v -> [v, v + 1]; (f)(1)[1]", "= 2"}, + {"lex", "var f = v -> 'abc'; (f)(1).length()", "= 3"}, + {"lex", "var f = v -> w -> v + w; (f)(1)(2)", "= 3"}, + {"lex", "(v -> { 'a' : v })(1).a", "= 1"}, + {"lex", "(v -> w -> v + w)(1)(2)", "= 3"}, + {"lex", "[v -> v + 1, 2][0](41)", "= 42"}, + {"ant", "nul.y", "Variable: @1:1 variable 'nul.y' is undefined"}, + {"noant", "nul.y", "Property: @1:1 null value property '.y'"}, + {"strict", "nul.y", "Variable: @1:1 variable 'nul.y' is undefined"}, + {"safe", "nul.y", "= null"}, + {"ant", "nul.y.z", "Variable: @1:1 variable 'nul.y.z' is undefined"}, + {"noant", "nul.y.z", "Property: @1:1 null value property '.y'"}, + {"strict", "nul.y.z", "Variable: @1:1 variable 'nul.y.z' is undefined"}, + {"safe", "nul.y.z", "= null"}, + {"ant", "nul.y = 1", "= 1"}, + {"noant", "nul.y = 1", "JexlException: @1:1 JEXL error : illegal assignment form"}, + {"strict", "nul.y = 1", "= 1"}, + {"safe", "nul.y = 1", "= 1"}, + }; + + public InterpreterCharacterizationTest() { + super("InterpreterCharacterizationTest"); + } + + /** + * Creates a context for a given mode. + *

The context carries antish variables {@code x.y.z}, {@code x.y}, {@code a.b.c} + * and the globals {@code m} (a map) and {@code nul} (null).

+ * + * @param mode the mode + * @return the context + */ + private static JexlEvalContext createContext(final String mode) { + final JexlEvalContext ctxt = new JexlEvalContext(); + ctxt.set("x.y.z", 40); + ctxt.set("x.y", new ArrayList<>(Arrays.asList(1, 2))); + ctxt.set("a.b.c", null); + ctxt.set("m", new HashMap()); + ctxt.set("nul", null); + final JexlOptions options = ctxt.getEngineOptions(); + switch (mode) { + case "nolex": options.setLexical(false); break; + case "noant": options.setAntish(false); break; + case "strict": options.setStrict(true); break; + case "safe": options.setSafe(true); break; + default: break; + } + return ctxt; + } + + private String run(final String src, final JexlContext ctxt) { + try { + final Object o = JEXL.createScript(src).execute(ctxt); + return o instanceof Throwable ? "= " + o.getClass().getSimpleName() : "= " + o; + } catch (final JexlException x) { + final String m = x.getMessage(); + return x.getClass().getSimpleName() + ": " + m.substring(m.indexOf('@')); + } + } + + @Test + void testCharacterization() { + final List failures = new ArrayList<>(); + for (final String[] c : CASES) { + final String actual = run(c[1], createContext(c[0])); + if (!c[2].equals(actual)) { + failures.add("[" + c[0] + "] " + c[1] + "\n expected: " + c[2] + "\n actual: " + actual); + } + } + assertEquals("", String.join("\n", failures)); + } +} diff --git a/src/test/java/org/apache/commons/jexl3/Issues200Test.java b/src/test/java/org/apache/commons/jexl3/Issues200Test.java index f0a3b9c12..e2866faea 100644 --- a/src/test/java/org/apache/commons/jexl3/Issues200Test.java +++ b/src/test/java/org/apache/commons/jexl3/Issues200Test.java @@ -911,13 +911,18 @@ void test290b() { final String[] srcs = { "(x)->{ x?.nothing()?.toString() }", "(x)->{ x.toString()?.nothing() }", - "(x)->{ x?.nothing().nothing() }",}; + "(x)->{ x?.nothing()?.nothing() }",}; final JexlEngine jexl = new JexlBuilder().strict(true).create(); for (final String src : srcs) { script = jexl.createScript(src); result = script.execute(null, "abc"); assertNull(result); } + // a safe access does not protect the next one... + final JexlScript unsafe = jexl.createScript("(x)->{ x?.nothing().nothing() }"); + assertThrows(JexlException.class, () -> unsafe.execute(null, "abc")); + // ...but shortcuts the whole expression when applied to null + assertNull(unsafe.execute(null, (Object) null)); } @Test diff --git a/src/test/java/org/apache/commons/jexl3/ScriptCallableTest.java b/src/test/java/org/apache/commons/jexl3/ScriptCallableTest.java index 9e0b97856..46f6aa0ed 100644 --- a/src/test/java/org/apache/commons/jexl3/ScriptCallableTest.java +++ b/src/test/java/org/apache/commons/jexl3/ScriptCallableTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -147,7 +148,6 @@ private void runInterrupt(final JexlEngine jexl) throws Exception { final ExecutorService executorService = Executors.newFixedThreadPool(2); try { final JexlContext ctxt = new TestContext(); - // run an interrupt final JexlScript sint = jexl.createScript("interrupt(); return 42"); Object t = null; @@ -231,7 +231,7 @@ void testCallableCancel() throws Exception { final Future kfc = executor.submit(kc); assertTrue((Boolean) kfc.get()); final ExecutionException xexec = assertThrows(ExecutionException.class, future::get); - assertTrue(xexec.getCause() instanceof JexlException.Cancel); + assertInstanceOf(JexlException.Cancel.class, xexec.getCause()); } finally { list = executor.shutdownNow(); } @@ -262,7 +262,7 @@ void testCallableCancellation() throws Exception { final Future kfc = executor.submit(kc); assertTrue((Boolean) kfc.get()); final ExecutionException xexec = assertThrows(ExecutionException.class, future::get); - assertTrue(xexec.getCause() instanceof JexlException.Cancel); + assertInstanceOf(JexlException.Cancel.class, xexec.getCause()); } finally { list = executor.shutdownNow(); } @@ -271,7 +271,7 @@ void testCallableCancellation() throws Exception { } @Test - void testCallableClosure() throws Exception { + void testCallableClosure() { final JexlScript e = JEXL.createScript("function(t) {while(t);}"); final Callable c = e.callable(null, Boolean.TRUE); final List list; diff --git a/src/test/java/org/apache/commons/jexl3/TryCatchFinallyTest.java b/src/test/java/org/apache/commons/jexl3/TryCatchFinallyTest.java index e59bda2f4..334d6a88a 100644 --- a/src/test/java/org/apache/commons/jexl3/TryCatchFinallyTest.java +++ b/src/test/java/org/apache/commons/jexl3/TryCatchFinallyTest.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; class TryCatchFinallyTest extends JexlTestCase { @@ -73,25 +72,6 @@ void testCloseable0x3b() { assertFalse(circuit.isOpened()); } - @Disabled - void testEdgeTry() throws Exception { - int i = 0; - while (i++ < 5) { - // System.out.println("i: " + i); - try { - throw new JexlException.Continue(null); - } finally { - continue; - } - } - // System.out.println("iii: " + i); - - // int x = 0; - try (AutoCloseable x = new Circuit()) { - // empty - } - } - @Test void testExceptionType() throws Exception { final JexlScript e = JEXL.createScript("try { 'asb'.getBytes('NoSuchCharacterSet'); } catch (let ex) { ex }"); diff --git a/src/test/java/org/apache/commons/jexl3/benchmark/InterpreterBenchmark.java b/src/test/java/org/apache/commons/jexl3/benchmark/InterpreterBenchmark.java new file mode 100644 index 000000000..ec9d5f771 --- /dev/null +++ b/src/test/java/org/apache/commons/jexl3/benchmark/InterpreterBenchmark.java @@ -0,0 +1,142 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.jexl3.benchmark; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.jexl3.JexlBuilder; +import org.apache.commons.jexl3.JexlContext; +import org.apache.commons.jexl3.JexlEngine; +import org.apache.commons.jexl3.JexlFeatures; +import org.apache.commons.jexl3.JexlScript; +import org.apache.commons.jexl3.MapContext; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +/** + * Interpreter hot-path benchmarks: property access, method calls, loops, lexical blocks, + * assignments and antish variables (resolved at runtime or declared at parse time). + *

Run with: {@code mvn clean test -Pbenchmark -Dbenchmark=InterpreterBenchmark}

+ */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@State(Scope.Benchmark) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(1) +public class InterpreterBenchmark { + + private JexlContext context; + private JexlScript propertyAccess; + private JexlScript methodCall; + private JexlScript forEachLoop; + private JexlScript forLoop; + private JexlScript whileLoop; + private JexlScript lexicalBlocks; + private JexlScript assignments; + private JexlScript antish; + private JexlScript antishDeclared; + + @Setup + public void setup() { + final JexlEngine jexl = new JexlBuilder() + .features(JexlFeatures.createDefault()) + .cache(64) + .create(); + final Map map = new HashMap<>(); + map.put("a", 1); + map.put("b", new HashMap<>(map)); + final List list = new ArrayList<>(); + for (int i = 0; i < 100; ++i) { + list.add(i); + } + context = new MapContext(); + context.set("map", map); + context.set("list", list); + context.set("x.y.z", 1); + propertyAccess = jexl.createScript("var s = 0; for (var i : list) { s += map.a + map.b.a; } s"); + methodCall = jexl.createScript("var s = 0; for (var i : list) { s += list.size() + list.get(i); } s"); + forEachLoop = jexl.createScript("var s = 0; for (var i : list) { if (i % 2 == 0) continue; if (i > 90) break; s += i; } s"); + forLoop = jexl.createScript("var s = 0; for (var i = 0; i < 100; ++i) { if (i % 2 == 0) continue; s += i; } s"); + whileLoop = jexl.createScript("var s = 0; var i = 0; while (i < 100) { i += 1; if (i % 2 == 0) continue; s += i; } s"); + lexicalBlocks = jexl.createScript("var s = 0; for (let i : list) { let j = i; { let k = j; s += k; } } s"); + assignments = jexl.createScript("var s = 0; for (var i : list) { map.c = i; map['d'] = i; s += map.c; } s"); + final String antishSrc = "var s = 0; for (var i : list) { x.y.w = i; s += x.y.z + x.y.w; } s"; + antish = jexl.createScript(antishSrc); + final JexlFeatures declared = JexlFeatures.createDefault() + .antishTest(JexlFeatures.namePatterns(Arrays.asList("x.y.z", "x.y.w"))); + antishDeclared = new JexlBuilder().features(declared).cache(64).create().createScript(antishSrc); + } + + @Benchmark + public Object propertyAccess() { + return propertyAccess.execute(context); + } + + @Benchmark + public Object methodCall() { + return methodCall.execute(context); + } + + @Benchmark + public Object forEachLoop() { + return forEachLoop.execute(context); + } + + @Benchmark + public Object forLoop() { + return forLoop.execute(context); + } + + @Benchmark + public Object whileLoop() { + return whileLoop.execute(context); + } + + @Benchmark + public Object lexicalBlocks() { + return lexicalBlocks.execute(context); + } + + @Benchmark + public Object antishDeclared() { + return antishDeclared.execute(context); + } + + @Benchmark + public Object assignments() { + return assignments.execute(context); + } + + @Benchmark + public Object antish() { + return antish.execute(context); + } +}