Skip to content
Open
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 @@ -1542,7 +1542,17 @@ protected JCExpression term3() {
switch (expr.getTag()) {
case REFERENCE: {
JCMemberReference mref = (JCMemberReference) expr;
mref.expr = toP(F.at(pos).AnnotatedType(typeAnnos, mref.expr));
if (TreeInfo.isType(mref.expr, names)) {
mref.expr = insertAnnotationsToMostInner(mref.expr, typeAnnos, false);
} else {
//the selector is not a type, error recovery:
JCAnnotatedType annotatedType =
toP(F.at(pos).AnnotatedType(typeAnnos, mref.expr));
int termStart = getStartPos(mref.expr);
mref.expr = syntaxError(termStart, List.of(annotatedType),
Errors.IllegalStartOfType);
}
mref.pos = getStartPos(mref.expr);
t = mref;
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,16 +437,29 @@ public static boolean isStatement(JCTree tree) {
* Return true if the AST corresponds to a static select of the kind A.B
*/
public static boolean isStaticSelector(JCTree base, Names names) {
return isTypeSelector(base, names, TreeInfo::isStaticSym);
}
//where
private static boolean isStaticSym(JCTree tree) {
Symbol sym = symbol(tree);
return (sym.kind == TYP || sym.kind == PCK);
}

public static boolean isType(JCTree base, Names names) {
return isTypeSelector(base, names, _ -> true);
}

private static boolean isTypeSelector(JCTree base, Names names, Predicate<JCTree> checkStaticSym) {
if (base == null)
return false;
switch (base.getTag()) {
case IDENT:
JCIdent id = (JCIdent)base;
return id.name != names._this &&
id.name != names._super &&
isStaticSym(base);
checkStaticSym.test(base);
case SELECT:
return isStaticSym(base) &&
return checkStaticSym.test(base) &&
isStaticSelector(((JCFieldAccess)base).selected, names);
case TYPEAPPLY:
case TYPEARRAY:
Expand All @@ -457,11 +470,6 @@ public static boolean isStaticSelector(JCTree base, Names names) {
return false;
}
}
//where
private static boolean isStaticSym(JCTree tree) {
Symbol sym = symbol(tree);
return (sym.kind == TYP || sym.kind == PCK);
}

/** Return true if a tree represents the null literal. */
public static boolean isNull(JCTree tree) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

/*
* @test
* @bug 8369489
* @summary Verify annotations on member references work reasonably.
* @library /tools/lib /tools/javac/lib
* @modules
* jdk.compiler/com.sun.tools.javac.api
* jdk.compiler/com.sun.tools.javac.main
* @build toolbox.ToolBox toolbox.JavacTask
* @run junit TypeAnnosOnMemberReferenceTest
*/

import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;

import org.junit.jupiter.api.Test;

import toolbox.JavacTask;
import toolbox.Task;
import toolbox.ToolBox;

public class TypeAnnosOnMemberReferenceTest {
private ToolBox tb = new ToolBox();

@Test
public void testAnnoOnMemberRef() throws Exception {
Path base = Paths.get(".");
Path src = base.resolve("src");
Path classes = base.resolve("classes");

Files.createDirectories(classes);

tb.writeJavaFiles(src,
"""
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class Test {
interface I {
void foo(int i);
}

@Target(ElementType.TYPE_USE)
@interface Ann1 {}
@Target(ElementType.TYPE_USE)
@interface Ann2 {}
I i = @Ann1 Test @Ann2 []::new;
}
""");

Path classDir = getClassDir();
new JavacTask(tb)
.classpath(classDir)
.outdir(classes)
.options("-processor", VerifyAnnotations.class.getName())
.files(tb.findJavaFiles(src))
.outdir(classes)
.run(Task.Expect.SUCCESS);
}

public Path getClassDir() {
String classes = ToolBox.testClasses;
if (classes == null) {
return Paths.get("build");
} else {
return Paths.get(classes);
}
}

@SupportedAnnotationTypes("*")
public static final class VerifyAnnotations extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
TypeElement testElement = processingEnv.getElementUtils().getTypeElement("Test");
VariableElement iElement = ElementFilter.fieldsIn(testElement.getEnclosedElements()).getFirst();
Trees trees = Trees.instance(processingEnv);
TreePath iPath = trees.getPath(iElement);
StringBuilder text = new StringBuilder();
new TreeScanner<>() {
int ident = 0;
@Override
public Object scan(Tree tree, Object p) {
if (tree != null) {
String indent =
Stream.generate(() -> " ")
.limit(ident)
.collect(Collectors.joining());

text.append("\n")
.append(indent)
.append("(")
.append(tree.getKind());
ident += 4;
super.scan(tree, p);
ident -= 4;
text.append("\n")
.append(indent)
.append(")");
}
return null;
}

@Override
public Object visitIdentifier(IdentifierTree node, Object p) {
text.append(" ").append(node.getName());
return super.visitIdentifier(node, p);
}
}.scan(((VariableTree) iPath.getLeaf()).getInitializer(), null);
String expected =
"""

(MEMBER_REFERENCE
(ANNOTATED_TYPE
(TYPE_ANNOTATION
(IDENTIFIER Ann2
)
)
(ARRAY_TYPE
(ANNOTATED_TYPE
(TYPE_ANNOTATION
(IDENTIFIER Ann1
)
)
(IDENTIFIER Test
)
)
)
)
)""";

String actual = text.toString();

if (!expected.equals(actual)) {
throw new AssertionError("Expected: " + expected + "," +
"got: " + actual);
}

return false;
}
}
}
29 changes: 28 additions & 1 deletion test/langtools/tools/javac/parser/JavacParserTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

/*
* @test
* @bug 7073631 7159445 7156633 8028235 8065753 8205418 8205913 8228451 8237041 8253584 8246774 8256411 8256149 8259050 8266436 8267221 8271928 8275097 8293897 8295401 8304671 8310326 8312093 8312204 8315452 8337976 8324859 8344706 8351260
* @bug 7073631 7159445 7156633 8028235 8065753 8205418 8205913 8228451 8237041 8253584 8246774 8256411 8256149 8259050 8266436 8267221 8271928 8275097 8293897 8295401 8304671 8310326 8312093 8312204 8315452 8337976 8324859 8344706 8351260 8369489
* @summary tests error and diagnostics positions
* @author Jan Lahoda
* @modules jdk.compiler/com.sun.tools.javac.api
Expand Down Expand Up @@ -3076,6 +3076,33 @@ void testVeryBrokenTypeWithAnnotationsMinimal() throws IOException {
ct.parse().iterator().next();
}

@Test //JDK-8369489
void testTypeAnnotationBrokenMethodRef() throws IOException {
String code = """
public class Test {
Object o1 = @Ann any()::test;
Object o2 = @Ann any().field::test;
}
""";
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll,
null,
null, Arrays.asList(new MyFileObject(code)));
//no exceptions:
ct.parse().iterator().next();
List<String> codes = new LinkedList<>();

for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
codes.add(d.getLineNumber() + ":" + d.getColumnNumber() + ":" + d.getCode());
}

assertEquals("testTypeAnnotationBrokenMethodRef: " + codes,
List.of("2:22:compiler.err.illegal.start.of.type",
"3:22:compiler.err.illegal.start.of.type"),
codes);
}

void run(String[] args) throws Exception {
int passed = 0, failed = 0;
final Pattern p = (args != null && args.length > 0)
Expand Down