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

feat: Use inferred generic type in invocations #4844

Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -132,6 +132,9 @@
import java.util.Set;
import java.util.stream.Collectors;

import static spoon.reflect.visitor.ElementPrinterHelper.PrintTypeArguments.INCLUDE_IF_IMPLICIT;
import static spoon.reflect.visitor.ElementPrinterHelper.PrintTypeArguments.OMIT_IF_IMPLICIT;

/**
* A visitor for generating Java code from the program compile-time model.
*/
Expand Down Expand Up @@ -1356,7 +1359,7 @@ public <T> void visitCtInvocation(CtInvocation<T> invocation) {
enterCtExpression(invocation);
if (invocation.getExecutable().isConstructor()) {
// It's a constructor (super or this)
elementPrinterHelper.writeActualTypeArguments(invocation.getExecutable());
elementPrinterHelper.writeActualTypeArguments(invocation.getExecutable(), OMIT_IF_IMPLICIT);
CtType<?> parentType = invocation.getParent(CtType.class);
if (parentType == null || parentType.getQualifiedName() != null && parentType.getQualifiedName().equals(invocation.getExecutable().getDeclaringType().getQualifiedName())) {
printer.writeKeyword("this");
Expand All @@ -1381,7 +1384,7 @@ public <T> void visitCtInvocation(CtInvocation<T> invocation) {
}
}

elementPrinterHelper.writeActualTypeArguments(invocation);
elementPrinterHelper.writeActualTypeArguments(invocation, OMIT_IF_IMPLICIT);
if (env.isPreserveLineNumbers()) {
getPrinterHelper().adjustStartPosition(invocation);
}
Expand Down Expand Up @@ -1605,7 +1608,7 @@ private <T> void printConstructorCall(CtConstructorCall<T> ctConstructorCall) {
printer.writeKeyword("new").writeSpace();

if (!ctConstructorCall.getActualTypeArguments().isEmpty()) {
I-Al-Istannen marked this conversation as resolved.
Show resolved Hide resolved
elementPrinterHelper.writeActualTypeArguments(ctConstructorCall);
elementPrinterHelper.writeActualTypeArguments(ctConstructorCall, INCLUDE_IF_IMPLICIT);
}

scan(ctConstructorCall.getType());
Expand Down Expand Up @@ -1990,7 +1993,7 @@ private void visitCtTypeReference(CtTypeReference<?> ref, boolean withGenerics)
}
if (withGenerics && !context.ignoreGenerics()) {
try (Writable _context = context.modify().ignoreEnclosingClass(false)) {
elementPrinterHelper.writeActualTypeArguments(ref);
elementPrinterHelper.writeActualTypeArguments(ref, INCLUDE_IF_IMPLICIT);
}
}
}
Expand Down
43 changes: 29 additions & 14 deletions src/main/java/spoon/reflect/visitor/ElementPrinterHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -241,22 +241,32 @@ public void writeFormalTypeParameters(CtFormalTypeDeclarer ctFormalTypeDeclarer)
/**
* Writes actual type arguments in a {@link CtActualTypeContainer} element.
*
* @param ctGenericElementReference
* Reference with actual type arguments.
* @param ctGenericElementReference Reference with actual type arguments.
* @param handleImplicit Whether to print type arguments if they are all implicit
*/
public void writeActualTypeArguments(CtActualTypeContainer ctGenericElementReference) {
final Collection<CtTypeReference<?>> arguments = ctGenericElementReference.getActualTypeArguments();
if (arguments != null && !arguments.isEmpty()) {
printList(arguments.stream().filter(a -> !a.isImplicit())::iterator,
null, false, "<", false, false, ",", true, false, ">",
argument -> {
if (prettyPrinter.getContext().forceWildcardGenerics()) {
printer.writeSeparator("?");
} else {
prettyPrinter.scan(argument);
}
});
public void writeActualTypeArguments(
CtActualTypeContainer ctGenericElementReference,
PrintTypeArguments handleImplicit
) {
Collection<CtTypeReference<?>> arguments = ctGenericElementReference.getActualTypeArguments();
if (arguments == null || arguments.isEmpty()) {
return;
}

boolean allImplicit = arguments.stream().allMatch(CtElement::isImplicit);
if (allImplicit && handleImplicit == PrintTypeArguments.OMIT_IF_IMPLICIT) {
return;
}

printList(arguments.stream().filter(a -> !a.isImplicit())::iterator,
null, false, "<", false, false, ",", true, false, ">",
argument -> {
if (prettyPrinter.getContext().forceWildcardGenerics()) {
printer.writeSeparator("?");
} else {
prettyPrinter.scan(argument);
}
});
}

private boolean isJavaLangClasses(String importType) {
Expand Down Expand Up @@ -565,4 +575,9 @@ protected void printPermits(CtSealable sealable) {
printList(sealable.getPermittedTypes(), null, false, null, false, false, ",", true, false, null, prettyPrinter::scan);
printer.decTab();
}

public enum PrintTypeArguments {
OMIT_IF_IMPLICIT,
INCLUDE_IF_IMPLICIT
}
}
11 changes: 11 additions & 0 deletions src/main/java/spoon/support/compiler/jdt/JDTTreeBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
package spoon.support.compiler.jdt;

import java.util.Set;

import org.eclipse.jdt.internal.compiler.lookup.ParameterizedGenericMethodBinding;
import org.slf4j.Logger;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
Expand Down Expand Up @@ -1425,6 +1427,15 @@ public boolean visit(MessageSend messageSend, BlockScope scope) {
inv.getExecutable().setType(references.getTypeReference(messageSend.expectedType()));
}
}
// No explicit type arguments given for call, but JDT inferred them (e.g. in a List.of("foo") call)
if (messageSend.binding instanceof ParameterizedGenericMethodBinding && messageSend.typeArguments == null) {
ParameterizedGenericMethodBinding binding = (ParameterizedGenericMethodBinding) messageSend.binding;
for (TypeBinding argument : binding.typeArguments) {
CtTypeReference<Object> reference = getReferencesBuilder().getTypeReference(argument);
reference.setImplicit(true);
inv.addActualTypeArgument(reference);
}
}
context.enter(inv, messageSend);
return true;
}
Expand Down
22 changes: 19 additions & 3 deletions src/test/java/spoon/test/generics/GenericsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import spoon.reflect.code.CtLocalVariable;
import spoon.reflect.code.CtNewClass;
import spoon.reflect.code.CtReturn;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtConstructor;
import spoon.reflect.declaration.CtElement;
Expand Down Expand Up @@ -467,7 +468,7 @@ public void testInvocationGenerics() {
assertEquals("this.<java.lang.String>makeTacos(null)", invocation1.toString());

final CtInvocation invocation2 = m.getBody().getStatement(1).getElements(new TypeFilter<>(CtInvocation.class)).get(0);
assertEquals(0, invocation2.getExecutable().getActualTypeArguments().size());
assertEquals(1, invocation2.getExecutable().getActualTypeArguments().size());
assertEquals("this.makeTacos(null)", invocation2.toString());

canBeBuilt("./target/spooned/spoon/test/generics/testclasses/", 8);
Expand Down Expand Up @@ -513,7 +514,7 @@ public void testMethodsWithGenericsWhoExtendsObject() {
assertEquals("spoon.test.generics.testclasses.Tacos.<V, C>makeTacos()", invocation1.toString());

final CtInvocation<?> invocation2 = m.getBody().getStatement(1).getElements(new TypeFilter<>(CtInvocation.class)).get(0);
assertEquals(0, invocation2.getExecutable().getActualTypeArguments().size());
assertEquals(2, invocation2.getExecutable().getActualTypeArguments().size());
assertEquals("spoon.test.generics.testclasses.Tacos.makeTacos()", invocation2.toString());
}

Expand Down Expand Up @@ -1563,7 +1564,7 @@ public void testExecutableTypeParameter() {
assertNull(m1.getType().getTypeParameterDeclaration());
}

@org.junit.jupiter.api.Test
@Test
void testGenericMethodReference() {
// contract: method references keep their generic parameters
CtClass<?> parsed = Launcher.parseClass("class X {\n" +
Expand All @@ -1575,4 +1576,19 @@ void testGenericMethodReference() {
assertThat(expression.getExecutable().getActualTypeArguments().size(), equalTo(1));
assertThat(expression.getExecutable().getActualTypeArguments().get(0).toString(), equalTo("java.lang.Integer"));
}

@Test
void testInferredTypesReturnedInInvocation() {
// contract: Inferred generic types for invocations are returned by getActualTypeArguments
CtClass<?> ctClass = Launcher.parseClass("class Foo {\n" +
" <T> T reflect(T t) { return t; }\n" +
" String user() { return reflect(\"hey\"); }\n" +
"}");
CtMethod<?> user = ctClass.getMethodsByName("user").get(0);
CtReturn<?> ret = user.getBody().getStatement(0);
CtInvocation<?> invocation = (CtInvocation<?>) ret.getReturnedExpression();

assertEquals(1, invocation.getActualTypeArguments().size());
assertEquals("java.lang.String", invocation.getActualTypeArguments().get(0).getQualifiedName());
}
}