From ac8429885b5b532827ffab0882538abafa6338ea Mon Sep 17 00:00:00 2001
From: henrib
Date: Tue, 10 Nov 2026 15:26:58 +0100
Subject: [PATCH 1/2] JEXL-474: Declare antish variable names at parse time
through JexlFeatures
- JexlFeatures.antishTest(Predicate): the parser rewrites references rooted on a global so that
the longest declared dotted prefix is a single variable; a script parsed with declared names
does not solve antish variables at runtime
- with sideEffectGlobal(false) and declared names, assigning a property of a global value is not
a global side effect
- JexlFeatures.namePatterns(Collection), pragmaPatterns delegates to it
- Interpreter: pushBlock/popBlock helpers, AntishName helper for runtime antish resolution
- fix: a null local variable root is never solved as an antish variable (read was, assign was not)
- fix: for-loop lexical frame leaked when an initializer throws
- tests: AntishFeaturesTest, InterpreterCharacterizationTest; JMH InterpreterBenchmark (pom: jmh test deps)
Co-Authored-By: Claude Opus 5.5
---
pom.xml | 12 +
src/changes/changes.xml | 1 +
.../apache/commons/jexl3/JexlFeatures.java | 94 +++++-
.../apache/commons/jexl3/internal/Engine.java | 12 +
.../commons/jexl3/internal/Interpreter.java | 282 +++++++++++-------
.../jexl3/parser/FeatureController.java | 18 +-
.../commons/jexl3/parser/JexlParser.java | 73 +++++
.../apache/commons/jexl3/parser/Parser.jjt | 6 +
.../commons/jexl3/parser/SimpleNode.java | 2 +-
.../apache/commons/jexl3/AntishCallTest.java | 19 +-
.../commons/jexl3/AntishFeaturesTest.java | 265 ++++++++++++++++
.../InterpreterCharacterizationTest.java | 214 +++++++++++++
.../jexl3/benchmark/InterpreterBenchmark.java | 142 +++++++++
13 files changed, 1012 insertions(+), 128 deletions(-)
create mode 100644 src/test/java/org/apache/commons/jexl3/AntishFeaturesTest.java
create mode 100644 src/test/java/org/apache/commons/jexl3/InterpreterCharacterizationTest.java
create mode 100644 src/test/java/org/apache/commons/jexl3/benchmark/InterpreterBenchmark.java
diff --git a/pom.xml b/pom.xml
index ce74ae484..534af2f24 100644
--- a/pom.xml
+++ b/pom.xml
@@ -131,6 +131,18 @@
3.21.0test
+
+ 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..66e2f12a3 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,41 @@ 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.
+ *
+ *
+ * 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 +523,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 +582,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 +873,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 +916,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 +954,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 +1091,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/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..b3723eff0 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,44 +744,34 @@ 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;
+ final JexlNode init = (form & 1) != 0 ? node.jjtGetChild(nc++) : null;
+ ASTVar loopVariable = null;
+ if (init instanceof ASTAssignment) {
+ final JexlNode child = init.jjtGetChild(0);
+ if (child instanceof ASTVar) {
+ loopVariable = (ASTVar) child;
}
- // 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;
+ } else if (init instanceof ASTVar){
+ loopVariable = (ASTVar) init;
+ }
+ 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);
+ // other inits
+ for (JexlNode moreAssignment = node.jjtGetChild(nc);
+ moreAssignment instanceof ASTAssignment;
+ moreAssignment = node.jjtGetChild(++nc)) {
+ moreAssignment.jjtAccept(this, data);
+ }
+ }
// the loop condition
final JexlNode predicate = (form & 2) != 0? node.jjtGetChild(nc++) : null;
// the loop step
@@ -745,9 +798,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 +971,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 +1036,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();
}
}
@@ -1154,11 +1223,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 +1631,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,9 +1902,8 @@ 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;
main:
for (int c = 0; c < numChildren; c++) {
objectNode = node.jjtGetChild(c);
@@ -1847,7 +1915,6 @@ protected Object visit(final ASTReference node, final Object data) {
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,7 +1922,7 @@ protected Object visit(final ASTReference node, final Object data) {
continue;
}
// remove method name from antish
- ant.delete(alen, ant.length());
+ ant.setLength(alen);
ptyNode = objectNode;
}
}
@@ -1885,24 +1952,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());
@@ -2191,13 +2257,10 @@ protected Object visit(final ASTTryResources node, final Object data) {
final int bodyChild = node.jjtGetNumChildren() - 1;
final JexlNode tryBody = node.jjtGetChild(bodyChild);
final Queue
*
+ * 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.
*
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/Interpreter.java b/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java
index b3723eff0..9acb3908f 100644
--- a/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java
+++ b/src/main/java/org/apache/commons/jexl3/internal/Interpreter.java
@@ -748,14 +748,16 @@ private Object forLoop(final ASTForeachStatement node, final Object data) {
final int form = node.getLoopForm();
/* first child node might be the loop variable */
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 (init instanceof ASTAssignment) {
- final JexlNode child = init.jjtGetChild(0);
+ if (declaration instanceof ASTAssignment) {
+ final JexlNode child = declaration.jjtGetChild(0);
if (child instanceof ASTVar) {
loopVariable = (ASTVar) child;
}
- } else if (init instanceof ASTVar){
- loopVariable = (ASTVar) init;
+ } else if (declaration instanceof ASTVar){
+ loopVariable = (ASTVar) declaration;
}
final boolean lexical = loopVariable != null && (loopVariable.isLexical() || options.isLexical());
if (lexical) {
@@ -765,19 +767,13 @@ private Object forLoop(final ASTForeachStatement node, final Object data) {
if (init != 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);
- }
}
// 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);
@@ -1136,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);
}
@@ -1904,12 +1900,16 @@ protected Object visit(final ASTReference node, final Object data) {
JexlNode ptyNode = null;
AntishName ant = null;
boolean antish = !(parent instanceof ASTReference) && options.isAntish();
+ // 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);
@@ -1923,9 +1923,9 @@ protected Object visit(final ASTReference node, final Object data) {
}
// remove method name from antish
ant.setLength(alen);
- ptyNode = objectNode;
}
}
+ ptyNode = objectNode;
break;
}
} else if (objectNode instanceof ASTArrayAccess) {
@@ -1937,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
@@ -1981,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,
@@ -1997,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;
@@ -2008,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);
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/JexlParser.java b/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java
index 81e65c94e..0e5292775 100644
--- a/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java
+++ b/src/main/java/org/apache/commons/jexl3/parser/JexlParser.java
@@ -1069,8 +1069,9 @@ private JexlNode resolveAntish(final ASTReference reference) {
final StringBuilder name = new StringBuilder(root.getName());
String antish = null;
int last = 0;
- for (int c = 1; c < count; ++c) {
- final JexlNode child = reference.jjtGetChild(c);
+ 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;
@@ -1079,11 +1080,11 @@ private JexlNode resolveAntish(final ASTReference reference) {
final String candidate = name.toString();
if (declared.test(candidate)) {
antish = candidate;
- last = c;
+ last = stop;
}
}
if (antish == null) {
- return reference;
+ return stop < count ? resolveAntishFunctor(reference, name, stop) : reference;
}
root.setSymbol(antish);
if (last == count - 1) {
@@ -1099,6 +1100,48 @@ private JexlNode resolveAntish(final ASTReference reference) {
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/test/java/org/apache/commons/jexl3/AntishFeaturesTest.java b/src/test/java/org/apache/commons/jexl3/AntishFeaturesTest.java
index dc4a55081..a1512ef35 100644
--- a/src/test/java/org/apache/commons/jexl3/AntishFeaturesTest.java
+++ b/src/test/java/org/apache/commons/jexl3/AntishFeaturesTest.java
@@ -20,6 +20,7 @@
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;
@@ -120,6 +121,45 @@ void testMethodCall() throws Exception {
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");
@@ -144,6 +184,27 @@ void testSafeNavigationAndExpression() throws Exception {
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");
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
index 5a701f9d2..97ea3b008 100644
--- a/src/test/java/org/apache/commons/jexl3/InterpreterCharacterizationTest.java
+++ b/src/test/java/org/apache/commons/jexl3/InterpreterCharacterizationTest.java
@@ -38,6 +38,24 @@ class InterpreterCharacterizationTest extends JexlTestCase {
{"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"},
@@ -143,9 +161,85 @@ class InterpreterCharacterizationTest extends JexlTestCase {
{"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", "= null"},
+ {"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"},
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