Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unwrap optionals with safe navigation in expressions #9024

Merged
merged 1 commit into from
Mar 30, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,23 @@
package io.micronaut.expressions.parser.ast.access;

import io.micronaut.core.annotation.Internal;
import io.micronaut.core.reflect.ReflectionUtils;
import io.micronaut.expressions.parser.ast.ExpressionNode;
import io.micronaut.expressions.parser.ast.types.TypeIdentifier;
import io.micronaut.expressions.parser.compilation.ExpressionVisitorContext;
import io.micronaut.expressions.parser.exception.ExpressionCompilationException;
import io.micronaut.inject.ast.ClassElement;
import io.micronaut.inject.ast.ElementQuery;
import io.micronaut.inject.ast.MethodElement;
import io.micronaut.inject.visitor.VisitorContext;
import io.micronaut.inject.processing.JavaModelUtils;
import org.objectweb.asm.Label;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;

import java.util.List;
import java.util.Optional;

import static io.micronaut.expressions.parser.ast.util.EvaluatedExpressionCompilationUtils.getRequiredClassElement;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;

Expand All @@ -46,6 +47,8 @@
@Internal
public sealed class ElementMethodCall extends AbstractMethodCall permits PropertyAccess {

private static final Type TYPE_OPTIONAL = Type.getType(Optional.class);
private static final Method METHOD_OR_ELSE = Method.getMethod(ReflectionUtils.getRequiredInternalMethod(Optional.class, "orElse", Object.class));
protected final ExpressionNode callee;
private final boolean nullSafe;

Expand All @@ -58,14 +61,19 @@ public ElementMethodCall(ExpressionNode callee,
this.nullSafe = nullSafe;
}

/**
* @return Is the method call null safe
*/
protected boolean isNullSafe() {
return nullSafe;
}

@Override
protected void generateBytecode(ExpressionVisitorContext ctx) {
GeneratorAdapter mv = ctx.methodVisitor();
VisitorContext visitorContext = ctx.visitorContext();
Type calleeType = callee.resolveType(ctx);
ClassElement calleeClass = callee.resolveClassElement(ctx);
Method method = usedMethod.toAsmMethod();

ClassElement calleeClass = getRequiredClassElement(calleeType, visitorContext);
Type calleeType = JavaModelUtils.getTypeReference(calleeClass);

if (callee instanceof TypeIdentifier) {
compileArguments(ctx);
Expand All @@ -78,16 +86,25 @@ protected void generateBytecode(ExpressionVisitorContext ctx) {
} else {
callee.compile(ctx);
if (nullSafe) {
if (calleeClass.isAssignable(Optional.class)) {
mv.checkCast(TYPE_OPTIONAL);
// safe navigate optional
mv.visitInsn(ACONST_NULL);
mv.invokeVirtual(TYPE_OPTIONAL, METHOD_OR_ELSE);
// recompute new return type
calleeClass = calleeClass.getFirstTypeArgument().orElse(ClassElement.of(Object.class));
calleeType = JavaModelUtils.getTypeReference(calleeClass);
mv.checkCast(calleeType);
}
// null safe operator is used so we need to check the result is null
Type returnType = method.getReturnType();
mv.storeLocal(2, returnType);
mv.loadLocal(2, returnType);
mv.storeLocal(2, calleeType);
mv.loadLocal(2, calleeType);
Label proceed = new Label();
mv.ifNonNull(proceed);
mv.visitInsn(ACONST_NULL);
mv.returnValue();
mv.visitLabel(proceed);
mv.loadLocal(2, returnType);
mv.loadLocal(2, calleeType);
}
compileArguments(ctx);
if (calleeClass.isInterface()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,11 @@
import io.micronaut.inject.ast.MethodElement;
import io.micronaut.inject.ast.PropertyElement;
import io.micronaut.inject.ast.PropertyElementQuery;
import org.objectweb.asm.Type;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static io.micronaut.expressions.parser.ast.util.EvaluatedExpressionCompilationUtils.getRequiredClassElement;
import static java.util.Collections.emptyList;
import static java.util.function.Predicate.not;

Expand All @@ -48,30 +47,36 @@ public PropertyAccess(ExpressionNode callee, String name, boolean nullSafe) {

@Override
protected CandidateMethod resolveUsedMethod(ExpressionVisitorContext ctx) {
Type calleeType = callee.resolveType(ctx);
ClassElement classElement = getRequiredClassElement(calleeType, ctx.visitorContext());
ClassElement classElement = callee.resolveClassElement(ctx);

if (isNullSafe() && classElement.isAssignable(Optional.class)) {
// safe navigate optional
classElement = classElement.getFirstTypeArgument().orElse(classElement);
}

List<PropertyElement> propertyElements =
classElement.getBeanProperties(
PropertyElementQuery.of(classElement.getAnnotationMetadata())
.allowStaticProperties(false)
.includes(Collections.singleton(name))).stream()
.filter(not(PropertyElement::isExcluded))
.toList();

if (propertyElements.size() == 0) {
if (propertyElements.isEmpty()) {
throw new ExpressionCompilationException(
"Can not find property with name [" + name + "] in class " + calleeType);
"Can not find property with name [" + name + "] in class " + classElement.getName());
} else if (propertyElements.size() > 1) {
throw new ExpressionCompilationException(
"Ambiguous property access. Found " + propertyElements.size() +
" matching properties with name [" + name + "] in class " + calleeType);
" matching properties with name [" + name + "] in class " + classElement.getName());
}

PropertyElement property = propertyElements.iterator().next();
ClassElement finalClassElement = classElement;
MethodElement methodElement =
property.getReadMethod()
.orElseThrow(() -> new ExpressionCompilationException(
"Can not resolve access method for property [" + name + "] in class " + calleeType));
"Can not resolve access method for property [" + name + "] in class " + finalClassElement.getName()));

return new CandidateMethod(methodElement);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,101 @@ class ContextPropertyAccessExpressionsSpec extends AbstractEvaluatedExpressionsS
expr == null
}

void "test multi-level context property access safe navigation - success"() {
given:
Object expr = evaluateAgainstContext("#{ foo?.bar?.name }",
"""
@jakarta.inject.Singleton
class Context {
public Foo getFoo() {
return new Foo();
}
}

class Foo {
private Bar bar = new Bar();
public Bar getBar() {
return bar;
}
}

class Bar {
private String name = "test";
public String getName() {
return name;
}
}
""")

expect:
expr == "test"
}

void "test multi-level context property access safe navigation with optionals"() {
given:
Object expr = evaluateAgainstContext("#{ foo?.bar?.name }",
"""
import java.util.Optional;

@jakarta.inject.Singleton
class Context {
public Optional<Foo> getFoo() {
return Optional.of(new Foo());
}
}

class Foo {
private Bar bar;
public Optional<Bar> getBar() {
return Optional.ofNullable(bar);
}
}

class Bar {
private String name = "test";
public String getName() {
return name;
}
}
""")

expect:
expr == null
}

void "test multi-level context property access safe navigation with optionals - success"() {
given:
Object expr = evaluateAgainstContext("#{ foo?.bar?.name }",
"""
import java.util.Optional;

@jakarta.inject.Singleton
class Context {
public Optional<Foo> getFoo() {
return Optional.of(new Foo());
}
}

class Foo {
private Bar bar = new Bar();
public Optional<Bar> getBar() {
return Optional.ofNullable(bar);
}
}

class Bar {
private String name = "test";
public String getName() {
return name;
}
}
""")

expect:
expr == "test"
}


void "test multi-level context property access non-safe navigation"() {
when:
Object expr = evaluateAgainstContext("#{ foo.bar.name }",
Expand Down
2 changes: 2 additions & 0 deletions src/main/docs/guide/config/evaluatedExpressions.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,8 @@ You can also use the safe dereference operator `?.` to navigate paths in a null
#{ foo?.bar?.name == "Fred" }
----

TIP: When used, the safe dereference operator will also automatically unwrap Java's `Optional` type.

=== Type References

A predefined syntax construct `T(...)` can be used to reference a class. The value inside brackets should be fully
Expand Down