diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java index dacf2daf4db77..6f780ea8f3865 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java @@ -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; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java index a66dcaad851a6..af823024fab50 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java @@ -437,6 +437,19 @@ 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 checkStaticSym) { if (base == null) return false; switch (base.getTag()) { @@ -444,9 +457,9 @@ public static boolean isStaticSelector(JCTree base, Names names) { 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: @@ -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) { diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnosOnMemberReferenceTest.java b/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnosOnMemberReferenceTest.java new file mode 100644 index 0000000000000..002b8d5bcb1bf --- /dev/null +++ b/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnosOnMemberReferenceTest.java @@ -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 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; + } + } +} diff --git a/test/langtools/tools/javac/parser/JavacParserTest.java b/test/langtools/tools/javac/parser/JavacParserTest.java index 7d34a14f1d7e4..4a42c17d38f10 100644 --- a/test/langtools/tools/javac/parser/JavacParserTest.java +++ b/test/langtools/tools/javac/parser/JavacParserTest.java @@ -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 @@ -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 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 codes = new LinkedList<>(); + + for (Diagnostic 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)