Skip to content

Commit

Permalink
fix: Print annotations for typerefs without parents (#5326)
Browse files Browse the repository at this point in the history
  • Loading branch information
I-Al-Istannen authored Jul 16, 2023
1 parent 223c956 commit 274acaa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2014,7 +2014,7 @@ private void visitCtTypeReference(CtTypeReference<?> ref, boolean withGenerics)
}
}
// You don't want to include annotations in import of an annotated object
if (ref.isParentInitialized() && !(ref.getParent() instanceof CtImport)) {
if (!ref.isParentInitialized() || !(ref.getParent() instanceof CtImport)) {
elementPrinterHelper.writeAnnotations(ref);
}
printer.writeIdentifier(ref.getSimpleName());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package spoon.reflect.visitor;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionContext;
Expand Down Expand Up @@ -48,6 +52,7 @@
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static spoon.test.SpoonTestHelpers.containsRegexMatch;

Expand Down Expand Up @@ -394,4 +399,30 @@ void throwsExceptionWhenPrintingInvalidFloatingLiteral(double value) {
assertThrows(SpoonException.class, () -> factory.createLiteral(value).toString());
assertThrows(SpoonException.class, () -> factory.createLiteral((float) value).toString());
}

@ModelTest("src/test/java/spoon/reflect/visitor/DefaultJavaPrettyPrinterTest.java")
void printAnnotationsInOrphanTypeReference(Factory factory) {
// contract: Spoon should print annotations for orphaned type references
// Used by the test
java.lang.@TypeUseAnnotation String ignored;

CtTypeReference<?> type = factory.Type()
.get(getClass().getName())
.getMethodsByName("printAnnotationsInOrphanTypeReference")
.get(0)
.getElements(new TypeFilter<>(CtLocalVariable.class))
.get(0)
.getType();

assertEquals(
"java.lang.@spoon.reflect.visitor.DefaultJavaPrettyPrinterTest.TypeUseAnnotation String",
type.toString().replace(System.lineSeparator(), " ")
);
}

@Target({ElementType.TYPE_USE})
@Retention(RetentionPolicy.SOURCE)
private @interface TypeUseAnnotation {

}
}

0 comments on commit 274acaa

Please sign in to comment.