Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/changes/changes.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
<!-- FIX -->
<action dev="henrib" due-to="Claude" type="fix" issue="JEXL-475">A jexl.options pragma modifies the engine options when evaluated with a plain context.</action>
<!-- ADD -->
<action dev="henrib" due-to="Claude" type="add" issue="JEXL-476">Add the safeUndefined option (JexlOptions.setSafeUndefined(boolean), JexlBuilder.safeUndefined(boolean)) to restrict safe navigation to null, undefined variables, properties and methods remaining errors; safe access operators treat properties, methods and array accesses alike.</action>
<action dev="henrib" due-to="Claude" type="add" issue="JEXL-474">Declare antish variable names at parse time through JexlFeatures.antishTest(Predicate), disabling runtime antish resolution; add JexlFeatures.namePatterns(Collection).</action>
<!-- UPDATE -->
<action type="update" dev="ggregory" due-to="Gary Gregory">Bump org.apache.commons:commons-parent from 105 to 107.</action>
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/org/apache/commons/jexl3/JexlBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -922,4 +922,31 @@ public JexlBuilder uberspect(final JexlUberspect u) {
this.uberspect = u;
return this;
}

/**
* Does safe navigation apply to what is undefined?
*
* @return true if safe navigation applies to undefined and null, false if it only applies to null
* @since 3.7.2
*/
public boolean safeUndefined() {
return options.isSafeUndefined();
}

/**
* Sets whether safe navigation applies to an undefined variable, property, method or function
* as it does to null.
* <p>{@code x?.y} if x is undefined or has no property y evaluates as null when the flag is true,
* which is the default, throws an exception when it is false; {@code x?.y} if x is null evaluates
* as null in both cases.</p>
*
* @see JexlOptions#setSafeUndefined(boolean)
* @param flag true means safe navigation applies to undefined and null, false means it only applies to null
* @return this builder
* @since 3.7.2
*/
public JexlBuilder safeUndefined(final boolean flag) {
options.setSafeUndefined(flag);
return this;
}
}
48 changes: 46 additions & 2 deletions src/main/java/org/apache/commons/jexl3/JexlOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
* <li>constCapture: whether captured variables will throw an error if an attempt is made to change their value</li>
* <li>strictInterpolation: whether interpolation strings always return a string or attempt to parse and return integer</li>
* <li>booleanLogical: whether logical expressions (&quot;&quot; , ||) coerce their result to boolean</li>
* <li>safeUndefined: whether safe navigation applies to what is undefined as it does to null</li>
* </ul>
* The sensible default is cancellable, strict and strictArithmetic.
* <p>This interface replaces the now deprecated JexlEngine.Options.
Expand All @@ -47,6 +48,9 @@
*/
public final class JexlOptions {

/** The safe navigation of undefined flag. */
private static final int SAFE_UNDEFINED = 12;

/** The namespace auto-instantiation flag. */
private static final int NAMESPACE_INSTANTIATE = 11;

Expand Down Expand Up @@ -87,12 +91,12 @@ public final class JexlOptions {
private static final String[] NAMES = {
"cancellable", "strict", "silent", "safe", "lexical", "antish",
"lexicalShade", "sharedInstance", "constCapture", "strictInterpolation",
"booleanShortCircuit", "namespaceInstantiation"
"booleanShortCircuit", "namespaceInstantiation", "safeUndefined"
};

/** Default mask .*/
private static int DEFAULT = 1 /*<< CANCELLABLE*/ | 1 << STRICT | 1 << ANTISH | 1 << SAFE
| 1 << NAMESPACE_INSTANTIATE;
| 1 << NAMESPACE_INSTANTIATE | 1 << SAFE_UNDEFINED;

/**
* Checks the value of a flag in the mask.
Expand Down Expand Up @@ -377,6 +381,18 @@ public boolean isStrictInterpolation() {
return isSet(STRICT_INTERPOLATION, flags);
}

/**
* Checks whether safe navigation applies to what is undefined.
*
* @return true if safe navigation evaluates what is undefined as null,
* false if it only applies to null
* @see #setSafeUndefined(boolean)
* @since 3.7.2
*/
public boolean isSafeUndefined() {
return isSet(SAFE_UNDEFINED, flags);
}

/**
* Sets options from engine.
*
Expand Down Expand Up @@ -535,6 +551,9 @@ public void setNamespaces(final Map<String, Object> ns) {
* <p>If safe, encountering null during a navigation expression - dereferencing a method or a field through a null
* object or property - will <em>not</em> be considered an error but evaluated as <em>null</em>. It is recommended
* to use <em>setSafe(false)</em> as an explicit default.</p>
* <p>If safe, an access through null behaves as a safe access, {@code x.y} as {@code x?.y} when {@code x}
* is null; what happens when a variable, property or method is undefined is determined by
* {@link #setSafeUndefined(boolean)}.</p>
*
* @param flag true if safe, false otherwise
*/
Expand Down Expand Up @@ -596,6 +615,31 @@ public void setStrictInterpolation(final boolean strict) {
flags = set(STRICT_INTERPOLATION, flags, strict);
}

/**
* Sets whether safe navigation applies to what is undefined.
* <p>A variable that is neither a local nor known to the context, a property or a method an object does
* not have, a function that cannot be solved are <em>undefined</em>; a strict engine reports them as errors.
* A safe access, {@code x?.y}, {@code x?.y()}, {@code x?[y]} or any access when {@link #setSafe(boolean)}
* is set, evaluates as null when {@code x} is null.</p>
* <p>When this flag is set, which is the default, {@code x?.y}, {@code x?.y()} and {@code x?[y]} also
* evaluate as null when {@code x} is undefined or does not have the member {@code y}, and what is undefined
* evaluates as null when the access that follows it is safe, as in {@code x.y?.z}.
* The {@link #setSafe(boolean) safe} option excuses an undefined variable or method in the same way,
* with two exceptions kept for compatibility: an undefined property remains an error, as in {@code x.y}
* when {@code x} does not have the property {@code y}, and an undefined variable that is the value
* of an assignment evaluates as null, as in {@code x = y}.
* When this flag is not set, safe navigation only applies to null and what is undefined is an error,
* without exception.</p>
* <p>In both cases, the condition of a ternary and the left-hand side of the elvis ({@code ?:}) and
* null-coalescing ({@code ??}) operators tolerate what is undefined.</p>
*
* @param flag true if safe navigation applies to undefined and null, false if it only applies to null
* @since 3.7.2
*/
public void setSafeUndefined(final boolean flag) {
flags = set(SAFE_UNDEFINED, flags, flag);
}

@Override public String toString() {
final StringBuilder strb = new StringBuilder();
for(int i = 0; i < NAMES.length; ++i) {
Expand Down
41 changes: 19 additions & 22 deletions src/main/java/org/apache/commons/jexl3/internal/Interpreter.java
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ protected Object call(final JexlNode node, final Object target, final Object fun
// ...(x)(y)
methodName = null;
cacheable = false;
} else if (!node.isSafeLhs(isSafe())) {
} else if (!isSafeUndefined() || !node.isSafeLhs(isSafe())) {
return unsolvableMethod(node, "?(...)");
} else {
// safe lhs
Expand Down Expand Up @@ -391,7 +391,7 @@ protected Object call(final JexlNode node, final Object target, final Object fun
throw invocationException(node, methodName, xany);
}
// we have either evaluated and returned or no method was found
return node.isSafeLhs(isSafe())
return isSafeUndefined() && node.isSafeLhs(isSafe())
? null
: unsolvableMethod(node, methodName, argv);
}
Expand Down Expand Up @@ -1721,7 +1721,7 @@ private Object visit(final ASTMethodNode node, final Object antish, final Object
object = data;
if (object == null) {
// no object, we fail
return node.isSafeLhs(isSafe())
return isSafe() || isSafeAccess(methodNode)
? null
: unsolvableMethod(methodNode, "<null>.<?>(...)");
Comment on lines 1721 to 1726

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cast could not throw, it is inside the if (methodNode instanceof ASTIdentifierAccess) branch. Replaced by isSafeAccess(methodNode) in 4e2f8b3 anyway, which is equivalent there and reads better.

}
Expand All @@ -1736,9 +1736,9 @@ private Object visit(final ASTMethodNode node, final Object antish, final Object
for (int a = 1; a < node.jjtGetNumChildren(); ++a) {
if (result == null) {
// no method, we fail// variable unknown in context and not a local
return node.isSafeLhs(isSafe())
return isSafeUndefined() && node.isSafeLhs(isSafe())
? null
: unsolvableMethod(methodNode, "<?>.<null>(...)");
: unsolvableMethod(node, "<?>.<null>(...)");

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intended: the ternary, ?: and ?? protection walks up from the node the error is raised on, and stops at the method node when started from its first child. Raised from methodNode, a call on a null result such as map.get('z')(1) ?? 1 is an error on a strict engine; raised from node, it evaluates as 1, as the other method errors do. 4e2f8b3 adds that expression to test476.

}
final ASTArguments argNode = (ASTArguments) node.jjtGetChild(a);
result = call(node, object, result, argNode);
Expand Down Expand Up @@ -1902,6 +1902,8 @@ protected Object visit(final ASTReference node, final Object data) {
boolean antish = !(parent instanceof ASTReference) && options.isAntish();
// the index of the access to apply to the object
int deref = 0;
// whether the variable the reference starts with is undefined
boolean undef = false;
main:
for (int c = 0; c < numChildren; c++) {
objectNode = node.jjtGetChild(c);
Expand Down Expand Up @@ -1939,6 +1941,10 @@ protected Object visit(final ASTReference node, final Object data) {
object = objectNode.jjtAccept(this, object);
deref = c + 1;
cancelCheck(node);
if (object == null && c == 0 && objectNode instanceof ASTIdentifier) {
// a null variable or an undefined one ?
undef = !isVariableDefined(frame, ((ASTIdentifier) objectNode).getName());
}
if (object != null) {
// disallow mixing antish variable & bean with same root; avoid ambiguity
antish = false;
Expand Down Expand Up @@ -1972,7 +1978,10 @@ protected Object visit(final ASTReference node, final Object data) {
break main;
}
// solve antish
object = context.get(ant.toString());
final String aname = ant.toString();
object = context.get(aname);
// an antish variable may be defined and null
undef = undef && object == null && !context.has(aname);
} else if (c != numChildren - 1) {
// only the last one may be null
ptyNode = c == 0 && numChildren > 1 ? node.jjtGetChild(1) : objectNode;
Expand All @@ -1981,9 +1990,11 @@ protected Object visit(final ASTReference node, final Object data) {
}
// dealing with null
if (object == null) {
// safe navigation applies to null, to an undefined variable as an option
final boolean nullable = !undef || isSafeUndefined();
if (ptyNode != null) {
// the access applied to null decides, as in x?.y, x?.y() or x?[y]
if (isSafe() || deref < numChildren && isSafeAccess(node.jjtGetChild(deref))) {
if (nullable && (isSafe() || deref < numChildren && isSafeAccess(node.jjtGetChild(deref)))) {
return null;
}
if (ant != null) {
Expand All @@ -1995,7 +2006,7 @@ protected Object visit(final ASTReference node, final Object data) {
stringifyProperty(ptyNode), ptyNode == objectNode, null);
}
if (antish) {
if (node.isSafeLhs(isSafe())) {
if (nullable && node.isSafeLhs(isSafe())) {
return null;
}
final String aname = Objects.toString(ant, "?");
Expand All @@ -2010,20 +2021,6 @@ 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -663,8 +663,8 @@ protected Object getAttribute(final Object object, final Object attribute, final
+ ", property: " + attribute;
throw new UnsupportedOperationException(error, xcause);
}
final boolean safe = node instanceof ASTIdentifierAccess && ((ASTIdentifierAccess) node).isSafe();
if (safe) {
// safe navigation may apply to an undefined property, an access that failed remains an error
if (xcause == null && isSafeUndefined(node)) {
return null;
}
final String attrStr = Objects.toString(attribute, null);
Expand Down Expand Up @@ -706,7 +706,8 @@ protected Object getVariable(final Frame frame, final LexicalScope block, final
if (!context.has(name)) {
// not defined, ignore in some cases...
final boolean ignore = identifier.jjtGetParent() instanceof ASTReference
|| isSafe() && (symbol >= 0 || identifier.jjtGetParent() instanceof ASTAssignment);
|| isSafeUndefined() && isSafe()
&& (symbol >= 0 || identifier.jjtGetParent() instanceof ASTAssignment);
if (!ignore) {
return undefinedVariable(identifier, name); // undefined
}
Expand Down Expand Up @@ -770,6 +771,82 @@ protected boolean isSilent() {
return options.isSilent();
}

/**
* Whether safe navigation applies to what is undefined in this interpreter.
*
* @return true if safe navigation applies to undefined and null, false if it only applies to null
*/
protected boolean isSafeUndefined() {
return options.isSafeUndefined();
}

/**
* Whether safe navigation excuses an undefined property.
* <p>The access to the property is explicitly safe, as in x?.y or x?[y], or the access that follows it is,
* as in x.y?.z; the safe option does not excuse an undefined property.</p>
*
* @param node the node accessing the property
* @return true if the property evaluates as null, false if it is an error
*/
protected boolean isSafeUndefined(final JexlNode node) {
if (!isSafeUndefined()) {
return false;
}
JexlNode access = node;
JexlNode parent = node.jjtGetParent();
if (parent instanceof ASTArrayAccess) {
// an index, as in x?[y] or x[y]?[z]
final ASTArrayAccess indexed = (ASTArrayAccess) parent;
final int next = indexOf(indexed, node) + 1;
if (indexed.isSafeChild(next - 1)) {
return true;
}
Comment on lines +800 to +803

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not an issue: indexed is node.jjtGetParent(), so node is always one of its children and indexOf cannot return -1 here. indexOf is a private helper, and isSafeChild only tests a bit, so it would not fail either.

if (next < indexed.jjtGetNumChildren()) {
return indexed.isSafeChild(next);
}
access = indexed;
parent = indexed.jjtGetParent();
} else if (isSafeAccess(node)) {
return true;
}
// the access that follows, as in x.y?.z
if (parent == null) {
return false;
}
final int next = indexOf(parent, access) + 1;
return next > 0 && next < parent.jjtGetNumChildren() && isSafeAccess(parent.jjtGetChild(next));
}

/**
* Seeks a node in its parent.
*
* @param parent the parent
* @param child the child
* @return the index of the child in its parent, -1 if not found
*/
private static int indexOf(final JexlNode parent, final JexlNode child) {
for (int c = 0; c < parent.jjtGetNumChildren(); ++c) {
if (parent.jjtGetChild(c) == child) {
return c;
}
}
return -1;
}

/**
* 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
*/
protected 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);
}

/**
* Whether this interpreter is currently evaluating with a strict engine flag.
*
Expand Down Expand Up @@ -1134,7 +1211,7 @@ protected Object unsolvableMethod(final JexlNode node, final String method) {
* @return throws JexlException if strict and not silent, null otherwise
*/
protected Object unsolvableMethod(final JexlNode node, final String method, final Object[] args) {
if (isStrictEngine()) {
if (isStrictEngine() && !isTernaryProtected(node)) {
throw new JexlException.Method(node, method, args);
}
if (logger.isDebugEnabled()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ && jjtGetChild(0) instanceof ASTIdentifierAccess
return true;
}
if (rsibling instanceof ASTArrayAccess) {
return safe;
return safe || ((ASTArrayAccess) rsibling).isSafeChild(0);
}
}
return false;
Expand Down
4 changes: 4 additions & 0 deletions src/site/xdoc/reference/syntax.xml
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,10 @@
In the previous expression, if 'foo' is null, the whole expression will evaluate as null.
Note that this can also be used in a chain as in <code>x?[y]?[z]</code>.
</p>
<p>Whether safe-access operators shortcut non-existent references - an undefined variable,
property, method or function - as they do null is determined by the <code>safeUndefined</code> option,
true by default; when false, only null is shortcut and a non-existent reference is an error.
</p>
<p>Access operators can be overloaded in <code>JexlArithmetic</code>, so that
the operator behavior will differ depending on the type of the operator arguments</p>
</td>
Expand Down
Loading
Loading