diff --git a/test/langtools/tools/javac/4241573/T4241573.java b/test/langtools/tools/javac/4241573/T4241573.java index 9f4244bb834..f6b6acb8347 100644 --- a/test/langtools/tools/javac/4241573/T4241573.java +++ b/test/langtools/tools/javac/4241573/T4241573.java @@ -25,12 +25,17 @@ * @test * @bug 4241573 * @summary SourceFile attribute includes full path - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl */ -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.SourceFile_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.Attributes; +import jdk.internal.classfile.attribute.*; import java.io.*; import java.util.*; import java.util.jar.*; @@ -107,9 +112,9 @@ public class T4241573 { void verifySourceFileAttribute(File f) { System.err.println("verify: " + f); try { - ClassFile cf = ClassFile.read(f); - SourceFile_attribute sfa = (SourceFile_attribute) cf.getAttribute(Attribute.SourceFile); - String found = sfa.getSourceFile(cf.constant_pool); + ClassModel cf = Classfile.of().parse(f.toPath()); + SourceFileAttribute sfa = cf.findAttribute(Attributes.SOURCE_FILE).orElseThrow(); + String found = sfa.sourceFile().stringValue(); String expect = f.getName().replaceAll("([$.].*)?\\.class", ".java"); if (!expect.equals(found)) { error("bad value found: " + found + ", expected: " + expect); diff --git a/test/langtools/tools/javac/7003595/T7003595.java b/test/langtools/tools/javac/7003595/T7003595.java index 34e17f0d7a3..517b1064571 100644 --- a/test/langtools/tools/javac/7003595/T7003595.java +++ b/test/langtools/tools/javac/7003595/T7003595.java @@ -25,16 +25,19 @@ * @test * @bug 7003595 * @summary IncompatibleClassChangeError with unreferenced local class with subclass - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.file */ import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.InnerClasses_attribute; -import com.sun.tools.classfile.ConstantPool.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import com.sun.tools.javac.api.JavacTool; import java.io.File; @@ -159,17 +162,17 @@ public class T7003595 { String filename = cks[i].getClassfileName(cnames, cks, i); File compiledTest = new File(filename + ".class"); try { - ClassFile cf = ClassFile.read(compiledTest); + ClassModel cf = Classfile.of().parse(compiledTest.toPath()); if (cf == null) { throw new Error("Classfile not found: " + filename); } - InnerClasses_attribute innerClasses = (InnerClasses_attribute)cf.getAttribute(Attribute.InnerClasses); + InnerClassesAttribute innerClasses = cf.findAttribute(Attributes.INNER_CLASSES).orElse(null); ArrayList foundInnerSig = new ArrayList<>(); if (innerClasses != null) { - for (InnerClasses_attribute.Info info : innerClasses.classes) { - String foundSig = info.getInnerClassInfo(cf.constant_pool).getName(); + for (InnerClassInfo info : innerClasses.classes()) { + String foundSig = info.innerClass().asInternalName(); foundInnerSig.add(foundSig); } } @@ -187,7 +190,7 @@ public class T7003595 { if (expectedInnerSig.size() != foundInnerSig.size()) { throw new Error("InnerClasses attribute for " + cnames[i] + " has wrong size\n" + "expected " + expectedInnerSig.size() + "\n" + - "found " + innerClasses.number_of_classes + "\n" + + "found " + (innerClasses == null? 0: innerClasses.classes().size()) + "\n" + source); } diff --git a/test/langtools/tools/javac/7153958/CPoolRefClassContainingInlinedCts.java b/test/langtools/tools/javac/7153958/CPoolRefClassContainingInlinedCts.java index 54899094186..41598200841 100644 --- a/test/langtools/tools/javac/7153958/CPoolRefClassContainingInlinedCts.java +++ b/test/langtools/tools/javac/7153958/CPoolRefClassContainingInlinedCts.java @@ -25,15 +25,19 @@ * @test * @bug 7153958 8073372 * @summary add constant pool reference to class containing inlined constants - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile pkg/ClassToBeStaticallyImportedA.java pkg/ClassToBeStaticallyImportedB.java CPoolRefClassContainingInlinedCts.java * @run main CPoolRefClassContainingInlinedCts */ -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; -import com.sun.tools.classfile.ConstantPoolException; +import jdk.internal.classfile.*; +import jdk.internal.classfile.constantpool.ClassEntry; +import jdk.internal.classfile.constantpool.PoolEntry; import java.io.File; import java.io.IOException; @@ -66,19 +70,19 @@ public class CPoolRefClassContainingInlinedCts { } } - void checkReferences() throws IOException, ConstantPoolException { + void checkReferences() throws IOException { File testClasses = new File(System.getProperty("test.classes")); File file = new File(testClasses, CPoolRefClassContainingInlinedCts.class.getName() + ".class"); - ClassFile classFile = ClassFile.read(file); + ClassModel classFile = Classfile.of().parse(file.toPath()); int i = 1; - CPInfo cpInfo; - while (i < classFile.constant_pool.size()) { - cpInfo = classFile.constant_pool.get(i); - if (cpInfo instanceof CONSTANT_Class_info) { - checkClassName(((CONSTANT_Class_info)cpInfo).getName()); + PoolEntry cpInfo; + while (i < classFile.constantPool().entryCount()) { + cpInfo = classFile.constantPool().entryByIndex(i); + if (cpInfo instanceof ClassEntry classEntry) { + checkClassName(classEntry.asInternalName()); } - i += cpInfo.size(); + i += cpInfo.width(); } if (numberOfReferencedClassesToBeChecked != 16) { throw new AssertionError("Class reference missing in the constant pool"); diff --git a/test/langtools/tools/javac/7166455/CheckACC_STRICTFlagOnclinitTest.java b/test/langtools/tools/javac/7166455/CheckACC_STRICTFlagOnclinitTest.java index 5cb9261b29c..b5d3c8b55b5 100644 --- a/test/langtools/tools/javac/7166455/CheckACC_STRICTFlagOnclinitTest.java +++ b/test/langtools/tools/javac/7166455/CheckACC_STRICTFlagOnclinitTest.java @@ -25,7 +25,12 @@ * @test * @bug 7166455 * @summary javac doesn't set ACC_STRICT bit on for strictfp class - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -source 16 -target 16 CheckACC_STRICTFlagOnclinitTest.java * @run main CheckACC_STRICTFlagOnclinitTest */ @@ -34,13 +39,7 @@ import java.util.ArrayList; import java.util.List; import java.io.File; import java.io.IOException; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Descriptor; -import com.sun.tools.classfile.Descriptor.InvalidDescriptor; -import com.sun.tools.classfile.Method; - -import static com.sun.tools.classfile.AccessFlags.ACC_STRICT; +import jdk.internal.classfile.*; public strictfp class CheckACC_STRICTFlagOnclinitTest { private static final String AssertionErrorMessage = @@ -65,13 +64,11 @@ public strictfp class CheckACC_STRICTFlagOnclinitTest { private List errors = new ArrayList<>(); - public static void main(String[] args) - throws IOException, ConstantPoolException, InvalidDescriptor { + public static void main(String[] args) throws IOException { new CheckACC_STRICTFlagOnclinitTest().run(); } - private void run() - throws IOException, ConstantPoolException, InvalidDescriptor { + private void run() throws IOException { String testClasses = System.getProperty("test.classes"); check(testClasses, "CheckACC_STRICTFlagOnclinitTest.class", @@ -86,19 +83,15 @@ public strictfp class CheckACC_STRICTFlagOnclinitTest { } } - void check(String dir, String... fileNames) - throws - IOException, - ConstantPoolException, - Descriptor.InvalidDescriptor { + void check(String dir, String... fileNames) throws IOException{ for (String fileName : fileNames) { - ClassFile classFileToCheck = ClassFile.read(new File(dir, fileName)); + ClassModel classFileToCheck = Classfile.of().parse(new File(dir, fileName).toPath()); - for (Method method : classFileToCheck.methods) { - if ((method.access_flags.flags & ACC_STRICT) == 0) { + for (MethodModel method : classFileToCheck.methods()) { + if ((method.flags().flagsMask() & Classfile.ACC_STRICT) == 0) { errors.add(String.format(offendingMethodErrorMessage, - method.getName(classFileToCheck.constant_pool), - classFileToCheck.getName())); + method.methodName().stringValue(), + classFileToCheck.thisClass().asInternalName())); } } } diff --git a/test/langtools/tools/javac/7199823/InnerClassCannotBeVerified.java b/test/langtools/tools/javac/7199823/InnerClassCannotBeVerified.java index f8b4e1cd05f..ae081a8c0a6 100644 --- a/test/langtools/tools/javac/7199823/InnerClassCannotBeVerified.java +++ b/test/langtools/tools/javac/7199823/InnerClassCannotBeVerified.java @@ -25,7 +25,12 @@ * @test * @bug 7199823 * @summary javac generates inner class that can't be verified - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @run main InnerClassCannotBeVerified */ @@ -37,8 +42,7 @@ import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; import javax.tools.JavaCompiler; import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; +import jdk.internal.classfile.*; import java.io.File; import java.io.IOException; @@ -85,17 +89,17 @@ public class InnerClassCannotBeVerified { } } - private void check(CompilationKind ck) throws IOException, ConstantPoolException { + private void check(CompilationKind ck) throws IOException { try { File file = new File("Test$1.class"); - ClassFile classFile = ClassFile.read(file); + ClassModel classFile = Classfile.of().parse(file.toPath()); if (ck == CompilationKind.POST_NESTMATES) { throw new AssertionError("Unexpected constructor tag class!"); } boolean inheritsFromObject = - classFile.getSuperclassName().equals("java/lang/Object"); - boolean implementsNoInterface = classFile.interfaces.length == 0; - boolean noMethods = classFile.methods.length == 0; + classFile.superclass().orElseThrow().asInternalName().equals("java/lang/Object"); + boolean implementsNoInterface = classFile.interfaces().size() == 0; + boolean noMethods = classFile.methods().size() == 0; if (!(inheritsFromObject && implementsNoInterface && noMethods)) { diff --git a/test/langtools/tools/javac/8000518/DuplicateConstantPoolEntry.java b/test/langtools/tools/javac/8000518/DuplicateConstantPoolEntry.java index 4b4ee2cd69c..20bd3b6fb64 100644 --- a/test/langtools/tools/javac/8000518/DuplicateConstantPoolEntry.java +++ b/test/langtools/tools/javac/8000518/DuplicateConstantPoolEntry.java @@ -26,13 +26,18 @@ * @bug 8000518 * @summary Javac generates duplicate name_and_type constant pool entry for * class BinaryOpValueExp.java - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @run main DuplicateConstantPoolEntry */ import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; +import jdk.internal.classfile.*; +import jdk.internal.classfile.constantpool.ConstantPool; import java.io.File; import java.io.IOException; import java.net.URI; @@ -87,17 +92,18 @@ public class DuplicateConstantPoolEntry { } } - void checkReference() throws IOException, ConstantPoolException { + void checkReference() throws IOException { File file = new File("A.class"); - ClassFile classFile = ClassFile.read(file); + ClassModel classFile = Classfile.of().parse(file.toPath()); + ConstantPool constantPool = classFile.constantPool(); for (int i = 1; - i < classFile.constant_pool.size() - 1; - i += classFile.constant_pool.get(i).size()) { - for (int j = i + classFile.constant_pool.get(i).size(); - j < classFile.constant_pool.size(); - j += classFile.constant_pool.get(j).size()) { - if (classFile.constant_pool.get(i).toString(). - equals(classFile.constant_pool.get(j).toString())) { + i < constantPool.entryCount() - 1; + i += constantPool.entryByIndex(i).width()) { + for (int j = i + constantPool.entryByIndex(i).width(); + j < constantPool.entryCount(); + j += constantPool.entryByIndex(j).width()) { + if (constantPool.entryByIndex(i).toString(). + equals(constantPool.entryByIndex(j).toString())) { throw new AssertionError( "Duplicate entries in the constant pool at positions " + i + " and " + j); diff --git a/test/langtools/tools/javac/8005931/CheckACC_STRICTFlagOnPkgAccessClassTest.java b/test/langtools/tools/javac/8005931/CheckACC_STRICTFlagOnPkgAccessClassTest.java index 08530b5c89a..5bd67b2b87e 100644 --- a/test/langtools/tools/javac/8005931/CheckACC_STRICTFlagOnPkgAccessClassTest.java +++ b/test/langtools/tools/javac/8005931/CheckACC_STRICTFlagOnPkgAccessClassTest.java @@ -25,7 +25,12 @@ * @test * @bug 8005931 * @summary javac doesn't set ACC_STRICT for classes with package access - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.impl * @run main CheckACC_STRICTFlagOnPkgAccessClassTest */ @@ -40,13 +45,7 @@ import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Descriptor; -import com.sun.tools.classfile.Descriptor.InvalidDescriptor; -import com.sun.tools.classfile.Method; - -import static com.sun.tools.classfile.AccessFlags.ACC_STRICT; +import jdk.internal.classfile.*; public class CheckACC_STRICTFlagOnPkgAccessClassTest { @@ -62,14 +61,12 @@ public class CheckACC_STRICTFlagOnPkgAccessClassTest { private List errors = new ArrayList<>(); - public static void main(String[] args) - throws IOException, ConstantPoolException, InvalidDescriptor { + public static void main(String[] args) throws IOException { JavaCompiler comp = ToolProvider.getSystemJavaCompiler(); new CheckACC_STRICTFlagOnPkgAccessClassTest().run(comp); } - private void run(JavaCompiler comp) - throws IOException, ConstantPoolException, InvalidDescriptor { + private void run(JavaCompiler comp) throws IOException { compile(comp); check(); if (errors.size() > 0) { @@ -95,18 +92,14 @@ public class CheckACC_STRICTFlagOnPkgAccessClassTest { } } - void check() - throws - IOException, - ConstantPoolException, - Descriptor.InvalidDescriptor { - ClassFile classFileToCheck = ClassFile.read(new File("Test.class")); + void check() throws IOException { + ClassModel classFileToCheck = Classfile.of().parse(new File("Test.class").toPath()); - for (Method method : classFileToCheck.methods) { - if ((method.access_flags.flags & ACC_STRICT) == 0) { + for (MethodModel method : classFileToCheck.methods()) { + if ((method.flags().flagsMask() & Classfile.ACC_STRICT) == 0) { errors.add(String.format(offendingMethodErrorMessage, - method.getName(classFileToCheck.constant_pool), - classFileToCheck.getName())); + method.methodName().stringValue(), + classFileToCheck.thisClass().asInternalName())); } } } diff --git a/test/langtools/tools/javac/AnonymousClass/AnonymousClassFlags.java b/test/langtools/tools/javac/AnonymousClass/AnonymousClassFlags.java index bfe31eb14d9..12df490a6f6 100644 --- a/test/langtools/tools/javac/AnonymousClass/AnonymousClassFlags.java +++ b/test/langtools/tools/javac/AnonymousClass/AnonymousClassFlags.java @@ -25,7 +25,12 @@ * @test * @bug 8161013 * @summary Verify that anonymous class binaries have the correct flags set - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @run main AnonymousClassFlags */ @@ -33,8 +38,9 @@ import java.util.*; import java.nio.file.Path; import java.nio.file.Paths; -import com.sun.tools.classfile.*; -import static com.sun.tools.classfile.AccessFlags.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.InnerClassInfo; +import jdk.internal.classfile.attribute.InnerClassesAttribute; public class AnonymousClassFlags { public static void main(String[] args) throws Exception { @@ -89,10 +95,10 @@ public class AnonymousClassFlags { instanceMethod(); Path outerFile = Paths.get(classesDir, getClass().getName() + ".class"); - ClassFile outerClass = ClassFile.read(outerFile); + ClassModel outerClass = Classfile.of().parse(outerFile); for (Map.Entry entry : anonClasses.entrySet()) { Path innerFile = Paths.get(classesDir, entry.getKey() + ".class"); - ClassFile innerClass = ClassFile.read(innerFile); + ClassModel innerClass = Classfile.of().parse(innerFile); String name = entry.getKey(); int expected = entry.getValue(); assertInnerFlags(outerClass, name, expected); @@ -101,11 +107,11 @@ public class AnonymousClassFlags { } } - static void assertClassFlags(ClassFile classFile, String name, int expected) { - int mask = ACC_PUBLIC | ACC_FINAL | ACC_INTERFACE | ACC_ABSTRACT | - ACC_SYNTHETIC | ACC_ANNOTATION | ACC_ENUM; - int classExpected = (expected & mask) | ACC_SUPER; - int classActual = classFile.access_flags.flags; + static void assertClassFlags(ClassModel classFile, String name, int expected) { + int mask = Classfile.ACC_PUBLIC | Classfile.ACC_FINAL | Classfile.ACC_INTERFACE | Classfile.ACC_ABSTRACT | + Classfile.ACC_SYNTHETIC | Classfile.ACC_ANNOTATION | Classfile.ACC_ENUM; + int classExpected = (expected & mask) | Classfile.ACC_SUPER; + int classActual = classFile.flags().flagsMask(); if (classActual != classExpected) { throw new AssertionError("Incorrect access_flags for class " + name + ": expected=" + classExpected + ", actual=" + classActual); @@ -113,27 +119,27 @@ public class AnonymousClassFlags { } - static void assertInnerFlags(ClassFile classFile, String name, int expected) throws ConstantPoolException { - int innerActual = lookupInnerFlags(classFile, name).flags; + static void assertInnerFlags(ClassModel classFile, String name, int expected) { + int innerActual = lookupInnerFlags(classFile, name); if (innerActual != expected) { throw new AssertionError("Incorrect inner_class_access_flags for class " + name + - " in class " + classFile.getName() + + " in class " + classFile.thisClass().asInternalName() + ": expected=" + expected + ", actual=" + innerActual); } } - private static AccessFlags lookupInnerFlags(ClassFile classFile, String innerName) throws ConstantPoolException { - InnerClasses_attribute inners = (InnerClasses_attribute) classFile.getAttribute("InnerClasses"); + private static int lookupInnerFlags(ClassModel classFile, String innerName) { + InnerClassesAttribute inners = classFile.findAttribute(Attributes.INNER_CLASSES).orElse(null); if (inners == null) { - throw new AssertionError("InnerClasses attribute missing in class " + classFile.getName()); + throw new AssertionError("InnerClasses attribute missing in class " + classFile.thisClass().asInternalName()); } - for (InnerClasses_attribute.Info info : inners.classes) { - String entryName = info.getInnerClassInfo(classFile.constant_pool).getName(); + for (InnerClassInfo info: inners.classes()) { + String entryName = info.innerClass().asInternalName(); if (innerName.equals(entryName)) { - return info.inner_class_access_flags; + return info.flagsMask(); } } - throw new AssertionError("No InnerClasses entry in class " + classFile.getName() + " for class " + innerName); + throw new AssertionError("No InnerClasses entry in class " + classFile.thisClass().asInternalName() + " for class " + innerName); } } diff --git a/test/langtools/tools/javac/MethodParameters/AnnotationTest.java b/test/langtools/tools/javac/MethodParameters/AnnotationTest.java index 68ef14f5b93..25f99a00888 100644 --- a/test/langtools/tools/javac/MethodParameters/AnnotationTest.java +++ b/test/langtools/tools/javac/MethodParameters/AnnotationTest.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters AnnotationTest.java * @run main MethodParametersTester AnnotationTest AnnotationTest.out diff --git a/test/langtools/tools/javac/MethodParameters/AnonymousClass.java b/test/langtools/tools/javac/MethodParameters/AnonymousClass.java index 42acefe6be9..11c31a4a384 100644 --- a/test/langtools/tools/javac/MethodParameters/AnonymousClass.java +++ b/test/langtools/tools/javac/MethodParameters/AnonymousClass.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters AnonymousClass.java * @run main MethodParametersTester AnonymousClass AnonymousClass.out diff --git a/test/langtools/tools/javac/MethodParameters/AttributeVisitor.java b/test/langtools/tools/javac/MethodParameters/AttributeVisitor.java deleted file mode 100644 index d2e2fa7b620..00000000000 --- a/test/langtools/tools/javac/MethodParameters/AttributeVisitor.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2013, 2020, 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. - */ - -import com.sun.tools.classfile.*; - -/** - * Trivial {@code Attribute.Visitor} implementation, to make it easy to - * write visitors for specific attributes. - */ -class AttributeVisitor implements Attribute.Visitor { - public R visitBootstrapMethods(BootstrapMethods_attribute attr, P p) { return null; } - public R visitDefault(DefaultAttribute attr, P p) { return null; } - public R visitAnnotationDefault(AnnotationDefault_attribute attr, P p) { return null; } - public R visitCharacterRangeTable(CharacterRangeTable_attribute attr, P p) { return null; } - public R visitCode(Code_attribute attr, P p) { return null; } - public R visitCompilationID(CompilationID_attribute attr, P p) { return null; } - public R visitConstantValue(ConstantValue_attribute attr, P p) { return null; } - public R visitDeprecated(Deprecated_attribute attr, P p) { return null; } - public R visitEnclosingMethod(EnclosingMethod_attribute attr, P p) { return null; } - public R visitExceptions(Exceptions_attribute attr, P p) { return null; } - public R visitInnerClasses(InnerClasses_attribute attr, P p) { return null; } - public R visitLineNumberTable(LineNumberTable_attribute attr, P p) { return null; } - public R visitLocalVariableTable(LocalVariableTable_attribute attr, P p) { return null; } - public R visitLocalVariableTypeTable(LocalVariableTypeTable_attribute attr, P p) { return null; } - public R visitNestHost(NestHost_attribute attr, P p) { return null; } - public R visitMethodParameters(MethodParameters_attribute attr, P p) { return null; } - public R visitModule(Module_attribute attr, P p) { return null; } - public R visitModuleHashes(ModuleHashes_attribute attr, P p) { return null; } - public R visitModuleMainClass(ModuleMainClass_attribute attr, P p) { return null; } - public R visitModulePackages(ModulePackages_attribute attr, P p) { return null; } - public R visitModuleResolution(ModuleResolution_attribute attr, P p) { return null; } - public R visitModuleTarget(ModuleTarget_attribute attr, P p) { return null; } - public R visitNestMembers(NestMembers_attribute attr, P p) { return null; } - public R visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, P p) { return null; } - public R visitRuntimeInvisibleAnnotations(RuntimeInvisibleAnnotations_attribute attr, P p) { return null; } - public R visitRuntimeVisibleParameterAnnotations(RuntimeVisibleParameterAnnotations_attribute attr, P p) { return null; } - public R visitRuntimeInvisibleParameterAnnotations(RuntimeInvisibleParameterAnnotations_attribute attr, P p) { return null; } - public R visitRuntimeVisibleTypeAnnotations(RuntimeVisibleTypeAnnotations_attribute attr, P p) { return null; } - public R visitRuntimeInvisibleTypeAnnotations(RuntimeInvisibleTypeAnnotations_attribute attr, P p) { return null; } - public R visitSignature(Signature_attribute attr, P p) { return null; } - public R visitSourceDebugExtension(SourceDebugExtension_attribute attr, P p) { return null; } - public R visitSourceFile(SourceFile_attribute attr, P p) { return null; } - public R visitSourceID(SourceID_attribute attr, P p) { return null; } - public R visitStackMap(StackMap_attribute attr, P p) { return null; } - public R visitStackMapTable(StackMapTable_attribute attr, P p) { return null; } - public R visitSynthetic(Synthetic_attribute attr, P p) { return null; } - public R visitPermittedSubclasses(PermittedSubclasses_attribute attr, P p) { return null; } - public R visitRecord(Record_attribute attr, P p) { return null; } -} diff --git a/test/langtools/tools/javac/MethodParameters/ClassFileVisitor.java b/test/langtools/tools/javac/MethodParameters/ClassFileVisitor.java index d37302e4b5c..644261d46fa 100644 --- a/test/langtools/tools/javac/MethodParameters/ClassFileVisitor.java +++ b/test/langtools/tools/javac/MethodParameters/ClassFileVisitor.java @@ -21,12 +21,15 @@ * questions. */ +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.Utf8Entry; import java.io.*; -import com.sun.tools.classfile.*; +import java.lang.constant.MethodTypeDesc; /** * The {@code ClassFileVisitor} reads a class file using the - * {@code com.sun.tools.classfile} library. It iterates over the methods + * {@code jdk.internal.classfile} library. It iterates over the methods * in a class, and checks MethodParameters attributes against JLS * requirements, as well as assumptions about the javac implementations. *

@@ -63,7 +66,7 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { public boolean isPublic; public boolean isStatic; public boolean isAnon; - public ClassFile classFile; + public ClassModel classFile; public ClassFileVisitor(MethodParametersTester tester) { @@ -84,16 +87,15 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { */ void visitClass(final String cname, final File cfile, final StringBuilder sb) throws Exception { this.cname = cname; - classFile = ClassFile.read(cfile); - isEnum = classFile.access_flags.is(AccessFlags.ACC_ENUM); - isInterface = classFile.access_flags.is(AccessFlags.ACC_INTERFACE); - isPublic = classFile.access_flags.is(AccessFlags.ACC_PUBLIC); + classFile = Classfile.of().parse(cfile.toPath()); + isEnum = (classFile.flags().flagsMask() & Classfile.ACC_ENUM) != 0; + isInterface = (classFile.flags().flagsMask() & Classfile.ACC_INTERFACE) != 0; + isPublic = (classFile.flags().flagsMask() & Classfile.ACC_PUBLIC) != 0; isInner = false; isStatic = false; isAnon = false; - Attribute attr = classFile.getAttribute("InnerClasses"); - if (attr != null) attr.accept(new InnerClassVisitor(), null); + classFile.findAttribute(Attributes.INNER_CLASSES).ifPresent(this::visitInnerClasses); isAnon = isInner & isAnon; sb.append(isStatic ? "static " : "") @@ -105,44 +107,41 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { } sb.append("\n"); - for (Method method : classFile.methods) { + for (MethodModel method : classFile.methods()) { new MethodVisitor().visitMethod(method, sb); } } /** - * Used to visit InnerClasses_attribute of a class, + * Used to visit InnerClassesAttribute of a class, * to determne if this class is an local class, and anonymous * inner class or a none-static member class. These types of * classes all have an containing class instances field that * requires an implicit or synthetic constructor argument. */ - class InnerClassVisitor extends AttributeVisitor { - public Void visitInnerClasses(InnerClasses_attribute iattr, Void v) { - try{ - for (InnerClasses_attribute.Info info : iattr.classes) { - if (info.getInnerClassInfo(classFile.constant_pool) == null) continue; - String in = info.getInnerClassInfo(classFile.constant_pool).getName(); - if (in == null || !cname.equals(in)) continue; - isInner = true; - isAnon = null == info.getInnerName(classFile.constant_pool); - isStatic = info.inner_class_access_flags.is(AccessFlags.ACC_STATIC); - break; - } - } catch(Exception e) { - throw new IllegalStateException(e); + void visitInnerClasses(InnerClassesAttribute iattr) { + try{ + for (InnerClassInfo info : iattr.classes()) { + if (info.innerClass() == null) continue; + String in = info.innerClass().name().stringValue(); + if (!cname.equals(in)) continue; + isInner = true; + isAnon = null == info.innerName().orElse(null); + isStatic = (info.flagsMask() & Classfile.ACC_STATIC) != 0; + break; } - return null; + } catch(Exception e) { + throw new IllegalStateException(e); } } /** * Check the MethodParameters attribute of a method. */ - class MethodVisitor extends AttributeVisitor { + class MethodVisitor { public String mName; - public Descriptor mDesc; + public MethodTypeDesc mDesc; public int mParams; public int mAttrs; public int mNumParams; @@ -153,26 +152,27 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { public boolean isFinal; public String prefix; - void visitMethod(Method method, StringBuilder sb) throws Exception { + void visitMethod(MethodModel method, StringBuilder sb) { - mName = method.getName(classFile.constant_pool); - mDesc = method.descriptor; - mParams = mDesc.getParameterCount(classFile.constant_pool); - mAttrs = method.attributes.attrs.length; + mName = method.methodName().stringValue(); + mDesc = method.methodTypeSymbol(); + mParams = mDesc.parameterCount(); + mAttrs = method.attributes().size(); mNumParams = -1; // no MethodParameters attribute found - mSynthetic = method.access_flags.is(AccessFlags.ACC_SYNTHETIC); + mSynthetic = (method.flags().flagsMask() & Classfile.ACC_SYNTHETIC) != 0; mIsConstructor = mName.equals(""); mIsClinit = mName.equals(""); prefix = cname + "." + mName + "() - "; - mIsBridge = method.access_flags.is(AccessFlags.ACC_BRIDGE); + mIsBridge = (method.flags().flagsMask() & Classfile.ACC_BRIDGE) != 0; if (mIsClinit) { sb = new StringBuilder(); // Discard output } sb.append(cname).append(".").append(mName).append("("); - for (Attribute a : method.attributes) { - a.accept(this, sb); + for (Attribute a : method.attributes()) { + if (a instanceof MethodParametersAttribute pa) + visitMethodParameters(pa, sb); } if (mNumParams == -1) { if (mSynthetic) { @@ -199,28 +199,28 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { } } - public Void visitMethodParameters(MethodParameters_attribute mp, + public void visitMethodParameters(MethodParametersAttribute mp, StringBuilder sb) { // SPEC: At most one MethodParameters attribute allowed if (mNumParams != -1) { error(prefix + "Multiple MethodParameters attributes"); - return null; + return; } - mNumParams = mp.method_parameter_table_length; + mNumParams = mp.parameters().size(); // SPEC: An empty attribute is not allowed! if (mNumParams == 0) { error(prefix + "0 length MethodParameters attribute"); - return null; + return; } // SPEC: one name per parameter. if (mNumParams != mParams) { error(prefix + "found " + mNumParams + " parameters, expected " + mParams); - return null; + return; } // IMPL: Whether MethodParameters attributes will be generated @@ -232,33 +232,23 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { String sep = ""; String userParam = null; for (int x = 0; x < mNumParams; x++) { - isFinal = (mp.method_parameter_table[x].flags & AccessFlags.ACC_FINAL) != 0; + isFinal = (mp.parameters().get(x).flagsMask() & Classfile.ACC_FINAL) != 0; // IMPL: Assume all parameters are named, something. - int cpi = mp.method_parameter_table[x].name_index; - if (cpi == 0) { + Utf8Entry paramEntry = mp.parameters().get(x).name().orElse(null); + if (paramEntry == null) { error(prefix + "name expected, param[" + x + "]"); - return null; + return; } - - // SPEC: a non 0 index, must be valid! - String param = null; - try { - param = classFile.constant_pool.getUTF8Value(cpi); - if (isFinal) - param = "final " + param; - sb.append(sep).append(param); - sep = ", "; - } catch(ConstantPoolException e) { - error(prefix + "invalid index " + cpi + " for param[" - + x + "]"); - return null; - } - + String param = paramEntry.stringValue(); + if (isFinal) + param = "final " + paramEntry.stringValue(); + sb.append(sep).append(param); + sep = ", "; // Check availability, flags and special names int check = checkParam(mp, param, x, sb, isFinal); if (check < 0) { - return null; + return; } // TEST: check test assumptions about parameter name. @@ -282,7 +272,7 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { if (check > 0 && expect != null && !param.equals(expect)) { error(prefix + "param[" + x + "]='" + param + "' expected '" + expect + "'"); - return null; + return; } } if (mSynthetic) { @@ -290,7 +280,6 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { } else { sb.append(")"); } - return null; } /* @@ -300,13 +289,13 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { * the parameter is compiler generated, or 1 for an (presumably) * explicitly declared parameter. */ - int checkParam(MethodParameters_attribute mp, String param, int index, + int checkParam(MethodParametersAttribute mp, String param, int index, StringBuilder sb, boolean isFinal) { - boolean synthetic = (mp.method_parameter_table[index].flags - & AccessFlags.ACC_SYNTHETIC) != 0; - boolean mandated = (mp.method_parameter_table[index].flags - & AccessFlags.ACC_MANDATED) != 0; + boolean synthetic = (mp.parameters().get(index).flagsMask() + & Classfile.ACC_SYNTHETIC) != 0; + boolean mandated = (mp.parameters().get(index).flagsMask() + & Classfile.ACC_MANDATED) != 0; // Setup expectations for flags and special names String expect = null; @@ -362,7 +351,7 @@ class ClassFileVisitor extends MethodParametersTester.Visitor { allowMandated = true; } else if (mIsBridge) { allowSynthetic = true; - /* you can't expect an special name for bridges' parameters. + /* you can't expect a special name for bridges' parameters. * The name of the original parameters are now copied. */ expect = null; diff --git a/test/langtools/tools/javac/MethodParameters/Constructors.java b/test/langtools/tools/javac/MethodParameters/Constructors.java index b7629ce98fb..0624f88f11b 100644 --- a/test/langtools/tools/javac/MethodParameters/Constructors.java +++ b/test/langtools/tools/javac/MethodParameters/Constructors.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters Constructors.java * @run main MethodParametersTester Constructors Constructors.out diff --git a/test/langtools/tools/javac/MethodParameters/EnumTest.java b/test/langtools/tools/javac/MethodParameters/EnumTest.java index 3c7bdd6e6a7..b2df35aa757 100644 --- a/test/langtools/tools/javac/MethodParameters/EnumTest.java +++ b/test/langtools/tools/javac/MethodParameters/EnumTest.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 8008658 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters EnumTest.java * @run main MethodParametersTester EnumTest EnumTest.out diff --git a/test/langtools/tools/javac/MethodParameters/InstanceMethods.java b/test/langtools/tools/javac/MethodParameters/InstanceMethods.java index 980cee378c3..019d84c3873 100644 --- a/test/langtools/tools/javac/MethodParameters/InstanceMethods.java +++ b/test/langtools/tools/javac/MethodParameters/InstanceMethods.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters InstanceMethods.java * @run main MethodParametersTester InstanceMethods InstanceMethods.out diff --git a/test/langtools/tools/javac/MethodParameters/LambdaTest.java b/test/langtools/tools/javac/MethodParameters/LambdaTest.java index 0326888b6e6..69309694791 100644 --- a/test/langtools/tools/javac/MethodParameters/LambdaTest.java +++ b/test/langtools/tools/javac/MethodParameters/LambdaTest.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 8037546 8138729 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters LambdaTest.java * @run main MethodParametersTester LambdaTest LambdaTest.out diff --git a/test/langtools/tools/javac/MethodParameters/LegacyOutputTest/LegacyOutputTest.java b/test/langtools/tools/javac/MethodParameters/LegacyOutputTest/LegacyOutputTest.java index d6f96332df5..3a9d3d155c9 100644 --- a/test/langtools/tools/javac/MethodParameters/LegacyOutputTest/LegacyOutputTest.java +++ b/test/langtools/tools/javac/MethodParameters/LegacyOutputTest/LegacyOutputTest.java @@ -25,21 +25,26 @@ * @test * @bug 8190452 * @summary javac should not add MethodParameters attributes to v51 and earlier class files - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build LegacyOutputTest * @run main LegacyOutputTest */ -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.MethodParameters_attribute; -import com.sun.tools.classfile.MethodParameters_attribute.Entry; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.MethodParameterInfo; +import jdk.internal.classfile.attribute.MethodParametersAttribute; import java.io.IOException; import java.net.URI; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject; @@ -90,23 +95,22 @@ public class LegacyOutputTest { if (!task.call()) { throw new AssertionError("compilation failed"); } - ClassFile classFile = ClassFile.read(Paths.get("Test.class")); - Method method = getMethod(classFile, "f"); - MethodParameters_attribute attribute = - (MethodParameters_attribute) method.attributes.get("MethodParameters"); + ClassModel classFile = Classfile.of().parse(Paths.get("Test.class")); + MethodModel method = getMethod(classFile, "f"); + MethodParametersAttribute attribute = method.findAttribute(Attributes.METHOD_PARAMETERS).orElse(null); if (attribute == null) { return null; } List parameterNames = new ArrayList<>(); - for (Entry e : attribute.method_parameter_table) { - parameterNames.add(classFile.constant_pool.getUTF8Value(e.name_index)); + for (MethodParameterInfo e : attribute.parameters()) { + parameterNames.add(e.name().orElseThrow().stringValue()); } return parameterNames; } - private static Method getMethod(ClassFile classFile, String name) throws Exception { - for (Method method : classFile.methods) { - if (classFile.constant_pool.getUTF8Value(method.name_index).equals(name)) { + private static MethodModel getMethod(ClassModel classFile, String name) throws Exception { + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString(name)) { return method; } } diff --git a/test/langtools/tools/javac/MethodParameters/LocalClassTest.java b/test/langtools/tools/javac/MethodParameters/LocalClassTest.java index 21d141f7a6e..27020e31fdf 100644 --- a/test/langtools/tools/javac/MethodParameters/LocalClassTest.java +++ b/test/langtools/tools/javac/MethodParameters/LocalClassTest.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 8008658 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters LocalClassTest.java * @run main MethodParametersTester LocalClassTest LocalClassTest.out diff --git a/test/langtools/tools/javac/MethodParameters/MemberClassTest.java b/test/langtools/tools/javac/MethodParameters/MemberClassTest.java index 04e3cf79326..39fd09027ed 100644 --- a/test/langtools/tools/javac/MethodParameters/MemberClassTest.java +++ b/test/langtools/tools/javac/MethodParameters/MemberClassTest.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 8008658 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters MemberClassTest.java * @run main MethodParametersTester MemberClassTest MemberClassTest.out diff --git a/test/langtools/tools/javac/MethodParameters/StaticMethods.java b/test/langtools/tools/javac/MethodParameters/StaticMethods.java index 186d6b5b640..4373e328acc 100644 --- a/test/langtools/tools/javac/MethodParameters/StaticMethods.java +++ b/test/langtools/tools/javac/MethodParameters/StaticMethods.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters StaticMethods.java * @run main MethodParametersTester StaticMethods StaticMethods.out diff --git a/test/langtools/tools/javac/MethodParameters/UncommonParamNames.java b/test/langtools/tools/javac/MethodParameters/UncommonParamNames.java index ab6dbc38841..8bfe8215ae1 100644 --- a/test/langtools/tools/javac/MethodParameters/UncommonParamNames.java +++ b/test/langtools/tools/javac/MethodParameters/UncommonParamNames.java @@ -25,7 +25,12 @@ * @test * @bug 8006582 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build MethodParametersTester ClassFileVisitor ReflectionVisitor * @compile -parameters UncommonParamNames.java * @run main MethodParametersTester UncommonParamNames UncommonParamNames.out diff --git a/test/langtools/tools/javac/MethodParametersTest.java b/test/langtools/tools/javac/MethodParametersTest.java index ebb277efc63..4f4ad15bd6b 100644 --- a/test/langtools/tools/javac/MethodParametersTest.java +++ b/test/langtools/tools/javac/MethodParametersTest.java @@ -25,7 +25,12 @@ * @test * @bug 8004727 * @summary javac should generate method parameters correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.comp * jdk.compiler/com.sun.tools.javac.file @@ -34,7 +39,8 @@ * jdk.compiler/com.sun.tools.javac.util */ // key: opt.arg.parameters -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.main.Main; @@ -43,6 +49,7 @@ import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Names; import java.io.*; import javax.lang.model.element.*; +import java.nio.file.Files; import java.util.*; public class MethodParametersTest { @@ -147,8 +154,7 @@ public class MethodParametersTest { // parameter. final Element baz = cf.loadClass(syms.unnamedModule, name); for (Element e : baz.getEnclosedElements()) { - if (e instanceof ExecutableElement) { - final ExecutableElement ee = (ExecutableElement) e; + if (e instanceof ExecutableElement ee) { final List params = ee.getParameters(); if (1 != params.size()) @@ -165,156 +171,117 @@ public class MethodParametersTest { void modifyBaz(boolean flip) throws Exception { final File Baz_class = new File(classesdir, Baz_name + ".class"); - final ClassFile baz = ClassFile.read(Baz_class); - final int ind = baz.constant_pool.getUTF8Index("baz"); - MethodParameters_attribute mpattr = null; - int mpind = 0; - Code_attribute cattr = null; - int cind = 0; + final ClassModel baz = Classfile.of().parse(Baz_class.toPath()); - // Find the indexes of the MethodParameters and the Code attributes - if (baz.methods.length != 1) + // Find MethodParameters and the Code attributes + if (baz.methods().size() != 1) throw new Exception("Classfile Baz badly formed: wrong number of methods"); - if (!baz.methods[0].getName(baz.constant_pool).equals("")) + if (!baz.methods().get(0).methodName().equalsString("")) throw new Exception("Classfile Baz badly formed: method has name " + - baz.methods[0].getName(baz.constant_pool)); - for (int i = 0; i < baz.methods[0].attributes.attrs.length; i++) { - if (baz.methods[0].attributes.attrs[i] instanceof - MethodParameters_attribute) { - mpattr = (MethodParameters_attribute) - baz.methods[0].attributes.attrs[i]; - mpind = i; - } else if (baz.methods[0].attributes.attrs[i] instanceof - Code_attribute) { - cattr = (Code_attribute) baz.methods[0].attributes.attrs[i]; - cind = i; - } - } + baz.methods().get(0).methodName().stringValue()); + MethodParametersAttribute mpattr = baz.methods().get(0).findAttribute(Attributes.METHOD_PARAMETERS).orElse(null); + CodeAttribute cattr = baz.methods().get(0).findAttribute(Attributes.CODE).orElse(null);; if (null == mpattr) throw new Exception("Classfile Baz badly formed: no method parameters info"); if (null == cattr) throw new Exception("Classfile Baz badly formed: no local variable table"); - int flags = mpattr.method_parameter_table[0].flags; - // Alter the MethodParameters attribute, changing the name of - // the parameter from i to baz. This requires Black Magic... - // - // The (well-designed) classfile library (correctly) does not - // allow us to mess around with the attribute data structures, - // or arbitrarily generate new ones. - // - // Instead, we install a new subclass of Attribute that - // hijacks the Visitor pattern and outputs the sequence of - // bytes that we want. This only works in this particular - // instance, because we know we'll only every see one kind of - // visitor. - // - // If anyone ever changes the makeup of the Baz class, or - // tries to install some kind of visitor that gets run prior - // to serialization, this will break. - baz.methods[0].attributes.attrs[mpind] = - new Attribute(mpattr.attribute_name_index, - mpattr.attribute_length) { - public R accept(Visitor visitor, D data) { - if (data instanceof ByteArrayOutputStream) { - ByteArrayOutputStream out = - (ByteArrayOutputStream) data; - out.write(1); - out.write((ind >> 8) & 0xff); - out.write(ind & 0xff); - out.write((flags >> 24) & 0xff); - out.write((flags >> 16) & 0xff); - out.write((flags >> 8) & 0xff); - out.write(flags & 0xff); - } else - throw new RuntimeException("Output stream is of type " + data.getClass() + ", which is not handled by this test. Update the test and it should work."); - return null; + // the parameter from i to baz. + byte[] bazBytes = Classfile.of().transform(baz, ClassTransform.transformingMethods((methodBuilder, methodElement) -> { + if (methodElement instanceof MethodParametersAttribute a) { + List newParameterInfos = new ArrayList<>(); + for (MethodParameterInfo info : a.parameters()) { + newParameterInfos.add(MethodParameterInfo.ofParameter("baz".describeConstable(), info.flagsMask())); } - }; + a = MethodParametersAttribute.of(newParameterInfos); + methodBuilder.with(a); + } else { + methodBuilder.with(methodElement); + } + })); - // Flip the code and method attributes. This is for checking + // Flip the code and method attributes(). This is for checking // that order doesn't matter. if (flip) { - baz.methods[0].attributes.attrs[mpind] = cattr; - baz.methods[0].attributes.attrs[cind] = mpattr; + bazBytes = Classfile.of().transform(baz, ClassTransform.transformingMethods((methodBuilder, methodElement) -> { + if (methodElement instanceof MethodParametersAttribute) { + methodBuilder.with(cattr); + } else if (methodElement instanceof CodeAttribute){ + methodBuilder.with(mpattr); + } else { + methodBuilder.with(methodElement); + } + })); } - - new ClassWriter().write(baz, Baz_class); + Files.write(Baz_class.toPath(), bazBytes); } // Run a bunch of structural tests on foo to make sure it looks right. void checkFoo() throws Exception { final File Foo_class = new File(classesdir, Foo_name + ".class"); - final ClassFile foo = ClassFile.read(Foo_class); - for (int i = 0; i < foo.methods.length; i++) { - System.err.println("Examine method Foo." + foo.methods[i].getName(foo.constant_pool)); - if (foo.methods[i].getName(foo.constant_pool).equals("foo2")) { - for (int j = 0; j < foo.methods[i].attributes.attrs.length; j++) - if (foo.methods[i].attributes.attrs[j] instanceof - MethodParameters_attribute) { - MethodParameters_attribute mp = - (MethodParameters_attribute) - foo.methods[i].attributes.attrs[j]; + final ClassModel foo = Classfile.of().parse(Foo_class.toPath()); + for (int i = 0; i < foo.methods().size(); i++) { + System.err.println("Examine method Foo." + foo.methods().get(i).methodName()); + if (foo.methods().get(i).methodName().equalsString("foo2")) { + for (int j = 0; j < foo.methods().get(i).attributes().size(); j++) + if (foo.methods().get(i).attributes().get(j) instanceof MethodParametersAttribute mp) { System.err.println("Foo.foo2 should have 2 parameters: j and k"); - if (2 != mp.method_parameter_table_length) + if (2 != mp.parameters().size()) error("expected 2 method parameter entries in foo2, got " + - mp.method_parameter_table_length); - else if (!foo.constant_pool.getUTF8Value(mp.method_parameter_table[0].name_index).equals("j")) + mp.parameters().size()); + else if (!mp.parameters().get(0).name().orElseThrow().equalsString("j")) error("expected first parameter to foo2 to be \"j\", got \"" + - foo.constant_pool.getUTF8Value(mp.method_parameter_table[0].name_index) + + mp.parameters().get(0).name().orElseThrow().stringValue() + "\" instead"); - else if (!foo.constant_pool.getUTF8Value(mp.method_parameter_table[1].name_index).equals("k")) + else if (!mp.parameters().get(1).name().orElseThrow().equalsString("k")) error("expected first parameter to foo2 to be \"k\", got \"" + - foo.constant_pool.getUTF8Value(mp.method_parameter_table[1].name_index) + + mp.parameters().get(1).name().orElseThrow() + "\" instead"); } } - else if (foo.methods[i].getName(foo.constant_pool).equals("")) { - for (int j = 0; j < foo.methods[i].attributes.attrs.length; j++) { - if (foo.methods[i].attributes.attrs[j] instanceof - MethodParameters_attribute) + else if (foo.methods().get(i).methodName().equalsString("")) { + for (int j = 0; j < foo.methods().get(i).attributes().size(); j++) { + if (foo.methods().get(i).attributes().get(j) instanceof + MethodParametersAttribute) error("Zero-argument constructor shouldn't have MethodParameters"); } } - else if (foo.methods[i].getName(foo.constant_pool).equals("foo0")) { - for (int j = 0; j < foo.methods[i].attributes.attrs.length; j++) - if (foo.methods[i].attributes.attrs[j] instanceof - MethodParameters_attribute) + else if (foo.methods().get(i).methodName().equalsString("foo0")) { + for (int j = 0; j < foo.methods().get(i).attributes().size(); j++) + if (foo.methods().get(i).attributes().get(j) instanceof + MethodParametersAttribute) error("Zero-argument method shouldn't have MethodParameters"); } else - error("Unknown method " + foo.methods[i].getName(foo.constant_pool) + " showed up in class Foo"); + error("Unknown method " + foo.methods().get(i).methodName() + " showed up in class Foo"); } } // Run a bunch of structural tests on Bar to make sure it looks right. void checkBar() throws Exception { final File Bar_class = new File(classesdir, Bar_name + ".class"); - final ClassFile bar = ClassFile.read(Bar_class); - for (int i = 0; i < bar.methods.length; i++) { - System.err.println("Examine method Bar." + bar.methods[i].getName(bar.constant_pool)); - if (bar.methods[i].getName(bar.constant_pool).equals("")) { - for (int j = 0; j < bar.methods[i].attributes.attrs.length; j++) - if (bar.methods[i].attributes.attrs[j] instanceof - MethodParameters_attribute) { - MethodParameters_attribute mp = - (MethodParameters_attribute) - bar.methods[i].attributes.attrs[j]; + final ClassModel bar = Classfile.of().parse(Bar_class.toPath()); + for (int i = 0; i < bar.methods().size(); i++) { + System.err.println("Examine method Bar." + bar.methods().get(i).methodName()); + if (bar.methods().get(i).methodName().equalsString("")) { + for (int j = 0; j < bar.methods().get(i).attributes().size(); j++) + if (bar.methods().get(i).attributes().get(j) instanceof + MethodParametersAttribute mp) { System.err.println("Bar constructor should have 1 parameter: i"); - if (1 != mp.method_parameter_table_length) + if (1 != mp.parameters().size()) error("expected 1 method parameter entries in constructor, got " + - mp.method_parameter_table_length); - else if (!bar.constant_pool.getUTF8Value(mp.method_parameter_table[0].name_index).equals("i")) + mp.parameters().size()); + else if (!mp.parameters().get(0).name().orElseThrow().equalsString("i")) error("expected first parameter to foo2 to be \"i\", got \"" + - bar.constant_pool.getUTF8Value(mp.method_parameter_table[0].name_index) + + mp.parameters().get(0).name().orElseThrow() + "\" instead"); } } - else if (bar.methods[i].getName(bar.constant_pool).equals("foo")) { - for (int j = 0; j < bar.methods[i].attributes.attrs.length; j++) { - if (bar.methods[i].attributes.attrs[j] instanceof - MethodParameters_attribute) + else if (bar.methods().get(i).methodName().equalsString("foo")) { + for (int j = 0; j < bar.methods().get(i).attributes().size(); j++) { + if (bar.methods().get(i).attributes().get(j) instanceof + MethodParametersAttribute) error("Zero-argument constructor shouldn't have MethodParameters"); } } diff --git a/test/langtools/tools/javac/NoStringToLower.java b/test/langtools/tools/javac/NoStringToLower.java index 757881f9332..1caadb5849c 100644 --- a/test/langtools/tools/javac/NoStringToLower.java +++ b/test/langtools/tools/javac/NoStringToLower.java @@ -25,14 +25,19 @@ * @test * @bug 8029800 * @summary String.toLowerCase()/toUpperCase is generally dangerous, check it is not used in langtools - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl */ import java.io.*; import java.util.*; import javax.tools.*; -import com.sun.tools.classfile.*; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Methodref_info; +import jdk.internal.classfile.*; +import jdk.internal.classfile.constantpool.*; public class NoStringToLower { public static void main(String... args) throws Exception { @@ -62,7 +67,7 @@ public class NoStringToLower { "javax.lang.model", "javax.tools", "com.sun.source", - "com.sun.tools.classfile", + "jdk.internal.classfile", "com.sun.tools.doclint", "com.sun.tools.javac", "com.sun.tools.javah", @@ -103,11 +108,11 @@ public class NoStringToLower { */ void scan(JavaFileObject fo) throws IOException { try (InputStream in = fo.openInputStream()) { - ClassFile cf = ClassFile.read(in); - for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) { - if (cpinfo.getTag() == ConstantPool.CONSTANT_Methodref) { - CONSTANT_Methodref_info ref = (CONSTANT_Methodref_info) cpinfo; - String methodDesc = ref.getClassInfo().getName() + "." + ref.getNameAndTypeInfo().getName() + ":" + ref.getNameAndTypeInfo().getType(); + ClassModel cf = Classfile.of().parse(in.readAllBytes()); + ConstantPool cp = cf.constantPool(); + for (int i = 1; i < cp.entryCount(); i += cp.entryByIndex(i).width()) { + if (cp.entryByIndex(i) instanceof MethodRefEntry ref) { + String methodDesc = ref.owner().name().stringValue() + "." + ref.name().stringValue() + ":" + ref.type().stringValue(); if ("java/lang/String.toLowerCase:()Ljava/lang/String;".equals(methodDesc)) { error("found reference to String.toLowerCase() in: " + fo.getName()); diff --git a/test/langtools/tools/javac/RequiredParameterFlags/ImplicitParameters.java b/test/langtools/tools/javac/RequiredParameterFlags/ImplicitParameters.java index 3683ae42510..563a65089e1 100644 --- a/test/langtools/tools/javac/RequiredParameterFlags/ImplicitParameters.java +++ b/test/langtools/tools/javac/RequiredParameterFlags/ImplicitParameters.java @@ -29,13 +29,18 @@ * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.code - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @run main ImplicitParameters */ -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.MethodParameters_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.MethodParameterInfo; +import jdk.internal.classfile.attribute.MethodParametersAttribute; import com.sun.tools.javac.code.Flags; import toolbox.Assert; import toolbox.JavacTask; @@ -50,9 +55,10 @@ import java.lang.constant.ConstantDescs; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; public class ImplicitParameters extends TestRunner { - private static final int CHECKED_FLAGS = Flags.MANDATED | Flags.SYNTHETIC; + private static final int CHECKED_FLAGS = Classfile.ACC_MANDATED | Classfile.ACC_SYNTHETIC; private static final int NO_FLAGS = 0; public ImplicitParameters() { @@ -121,11 +127,11 @@ public class ImplicitParameters extends TestRunner { .writeAll(); } - private ClassFile readClassFile(Path classes, Method method) { + private ClassModel readClassFile(Path classes, Method method) { String className = method.getAnnotation(ClassName.class).value(); try { - return ClassFile.read(classes.resolve("Outer$" + className + ".class")); - } catch (IOException | ConstantPoolException e) { + return Classfile.of().parse(classes.resolve("Outer$" + className + ".class")); + } catch (IOException e) { throw new RuntimeException(e); } } @@ -137,16 +143,16 @@ public class ImplicitParameters extends TestRunner { @Test @ClassName("Inner") - public void testInnerClassConstructor(ClassFile classFile) { - checkParameters(classFile.methods[0], Flags.MANDATED, 0); + public void testInnerClassConstructor(ClassModel classFile) { + checkParameters(classFile.methods().get(0), Classfile.ACC_MANDATED, 0); } @Test @ClassName("1Task") - public void testLocalClassConstructor(ClassFile classFile) throws ConstantPoolException { - for (com.sun.tools.classfile.Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals(ConstantDescs.INIT_NAME)) { - checkParameters(method, Flags.MANDATED, NO_FLAGS, Flags.SYNTHETIC); + public void testLocalClassConstructor(ClassModel classFile) { + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString(ConstantDescs.INIT_NAME)) { + checkParameters(method, Classfile.ACC_MANDATED, NO_FLAGS, Classfile.ACC_SYNTHETIC); break; } } @@ -154,22 +160,22 @@ public class ImplicitParameters extends TestRunner { @Test @ClassName("1") - public void testAnonymousClassExtendingInnerClassConstructor(ClassFile classFile) { - checkParameters(classFile.methods[0], Flags.MANDATED, NO_FLAGS, NO_FLAGS); + public void testAnonymousClassExtendingInnerClassConstructor(ClassModel classFile) { + checkParameters(classFile.methods().get(0), Classfile.ACC_MANDATED, NO_FLAGS, NO_FLAGS); } @Test @ClassName("2") - public void testAnonymousClassConstructor(ClassFile classFile) { - checkParameters(classFile.methods[0], Flags.MANDATED); + public void testAnonymousClassConstructor(ClassModel classFile) { + checkParameters(classFile.methods().get(0), Classfile.ACC_MANDATED); } @Test @ClassName("MyEnum") - public void testValueOfInEnum(ClassFile classFile) throws ConstantPoolException { - for (com.sun.tools.classfile.Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals("valueOf")) { - checkParameters(method, Flags.MANDATED); + public void testValueOfInEnum(ClassModel classFile) { + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString("valueOf")) { + checkParameters(method, Classfile.ACC_MANDATED); break; } } @@ -177,10 +183,10 @@ public class ImplicitParameters extends TestRunner { @Test @ClassName("MyEnum") - public void testEnumClassConstructor(ClassFile classFile) throws ConstantPoolException { - for (com.sun.tools.classfile.Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals(ConstantDescs.INIT_NAME)) { - checkParameters(method, Flags.SYNTHETIC, Flags.SYNTHETIC, NO_FLAGS, NO_FLAGS); + public void testEnumClassConstructor(ClassModel classFile) { + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString(ConstantDescs.INIT_NAME)) { + checkParameters(method, Classfile.ACC_SYNTHETIC, Classfile.ACC_SYNTHETIC, NO_FLAGS, NO_FLAGS); break; } } @@ -188,18 +194,18 @@ public class ImplicitParameters extends TestRunner { @Test @ClassName("MyRecord") - public void testCompactConstructor(ClassFile classFile) { - checkParameters(classFile.methods[0], Flags.MANDATED, Flags.MANDATED); + public void testCompactConstructor(ClassModel classFile) { + checkParameters(classFile.methods().get(0), Classfile.ACC_MANDATED, Classfile.ACC_MANDATED); } - private void checkParameters(com.sun.tools.classfile.Method method, int... parametersFlags) { - MethodParameters_attribute methodParameters = (MethodParameters_attribute) method.attributes.get("MethodParameters"); + private void checkParameters(MethodModel method, int... parametersFlags) { + MethodParametersAttribute methodParameters = method.findAttribute(Attributes.METHOD_PARAMETERS).orElseThrow(); Assert.checkNonNull(methodParameters, "MethodParameters attribute must be present"); - MethodParameters_attribute.Entry[] table = methodParameters.method_parameter_table; - Assert.check(table.length == parametersFlags.length, () -> "Expected " + parametersFlags.length - + " MethodParameters entries, found " + table.length); - for (int i = 0; i < methodParameters.method_parameter_table_length; i++) { - int foundFlags = table[i].flags & CHECKED_FLAGS; + List table = methodParameters.parameters(); + Assert.check(table.size() == parametersFlags.length, () -> "Expected " + parametersFlags.length + + " MethodParameters entries, found " + table.size()); + for (int i = 0; i < methodParameters.parameters().size(); i++) { + int foundFlags = table.get(i).flagsMask() & CHECKED_FLAGS; int desiredFlags = parametersFlags[i] & CHECKED_FLAGS; Assert.check(foundFlags == desiredFlags, () -> "Expected mandated and synthethic flags to be " + convertFlags(desiredFlags) + ", found " + convertFlags(foundFlags)); @@ -207,6 +213,6 @@ public class ImplicitParameters extends TestRunner { } private static String convertFlags(int flags) { - return ((flags & Flags.MANDATED) == Flags.MANDATED) + " and " + ((flags & Flags.SYNTHETIC) == Flags.SYNTHETIC); + return ((flags & Classfile.ACC_MANDATED) == Classfile.ACC_MANDATED) + " and " + ((flags & Classfile.ACC_SYNTHETIC) == Classfile.ACC_SYNTHETIC); } } diff --git a/test/langtools/tools/javac/StringConcat/TestIndyStringConcat.java b/test/langtools/tools/javac/StringConcat/TestIndyStringConcat.java index fe70a2a9104..32aa103f52a 100644 --- a/test/langtools/tools/javac/StringConcat/TestIndyStringConcat.java +++ b/test/langtools/tools/javac/StringConcat/TestIndyStringConcat.java @@ -21,10 +21,11 @@ * questions. */ -import com.sun.tools.classfile.*; -import com.sun.tools.classfile.BootstrapMethods_attribute.BootstrapMethodSpecifier; -import com.sun.tools.classfile.ConstantPool.CONSTANT_InvokeDynamic_info; -import com.sun.tools.classfile.ConstantPool.CONSTANT_MethodHandle_info; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.InvokeDynamicEntry; +import jdk.internal.classfile.constantpool.MethodHandleEntry; +import jdk.internal.classfile.instruction.InvokeDynamicInstruction; import java.io.File; @@ -32,7 +33,12 @@ import java.io.File; * @test * @bug 8148483 8151516 8151223 * @summary Test that StringConcat is working for JDK >= 9 - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * * @clean * * @compile -source 8 -target 8 TestIndyStringConcat.java @@ -59,7 +65,7 @@ public class TestIndyStringConcat { } public static void main(String[] args) throws Exception { - boolean expected = Boolean.valueOf(args[0]); + boolean expected = Boolean.parseBoolean(args[0]); boolean actual = hasStringConcatFactoryCall("test"); if (expected != actual) { throw new AssertionError("expected = " + expected + ", actual = " + actual); @@ -67,30 +73,18 @@ public class TestIndyStringConcat { } public static boolean hasStringConcatFactoryCall(String methodName) throws Exception { - ClassFile classFile = ClassFile.read(new File(System.getProperty("test.classes", "."), - TestIndyStringConcat.class.getName() + ".class")); - ConstantPool constantPool = classFile.constant_pool; + ClassModel classFile = Classfile.of().parse(new File(System.getProperty("test.classes", "."), + TestIndyStringConcat.class.getName() + ".class").toPath()); - BootstrapMethods_attribute bsm_attr = - (BootstrapMethods_attribute)classFile - .getAttribute(Attribute.BootstrapMethods); - - for (Method method : classFile.methods) { - if (method.getName(constantPool).equals(methodName)) { - Code_attribute code = (Code_attribute) method.attributes - .get(Attribute.Code); - for (Instruction i : code.getInstructions()) { - if (i.getOpcode() == Opcode.INVOKEDYNAMIC) { - CONSTANT_InvokeDynamic_info indyInfo = - (CONSTANT_InvokeDynamic_info) constantPool.get(i.getUnsignedShort(1)); - - BootstrapMethodSpecifier bsmSpec = - bsm_attr.bootstrap_method_specifiers[indyInfo.bootstrap_method_attr_index]; - - CONSTANT_MethodHandle_info bsmInfo = - (CONSTANT_MethodHandle_info) constantPool.get(bsmSpec.bootstrap_method_ref); - - if (bsmInfo.getCPRefInfo().getClassName().equals("java/lang/invoke/StringConcatFactory")) { + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString(methodName)) { + CodeAttribute code = method.findAttribute(Attributes.CODE).orElseThrow(); + for (CodeElement i : code.elementList()) { + if (i instanceof InvokeDynamicInstruction) { + InvokeDynamicInstruction indy = (InvokeDynamicInstruction) i; + BootstrapMethodEntry bsmSpec = indy.invokedynamic().bootstrap(); + MethodHandleEntry bsmInfo = bsmSpec.bootstrapMethod(); + if (bsmInfo.reference().owner().asInternalName().equals("java/lang/invoke/StringConcatFactory")) { return true; } } diff --git a/test/langtools/tools/javac/StringConcat/WellKnownTypeSignatures.java b/test/langtools/tools/javac/StringConcat/WellKnownTypeSignatures.java index 07cdeef4956..7e14ae361c9 100644 --- a/test/langtools/tools/javac/StringConcat/WellKnownTypeSignatures.java +++ b/test/langtools/tools/javac/StringConcat/WellKnownTypeSignatures.java @@ -21,8 +21,10 @@ * questions. */ -import com.sun.tools.classfile.*; -import com.sun.tools.classfile.ConstantPool.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.NameAndTypeEntry; +import jdk.internal.classfile.instruction.InvokeDynamicInstruction; import java.io.File; import java.util.ArrayList; @@ -32,7 +34,12 @@ import java.util.List; * @test * @bug 8273914 * @summary Indy string concat changes order of operations - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * * @clean * * @compile -XDstringConcat=indy WellKnownTypeSignatures.java @@ -94,23 +101,19 @@ public class WellKnownTypeSignatures { public static void readIndyTypes() throws Exception { actualTypes = new ArrayList(); - ClassFile classFile = - ClassFile.read( + ClassModel classFile = Classfile.of().parse( new File( System.getProperty("test.classes", "."), - WellKnownTypeSignatures.class.getName() + ".class")); - ConstantPool constantPool = classFile.constant_pool; + WellKnownTypeSignatures.class.getName() + ".class").toPath()); - for (Method method : classFile.methods) { - if (method.getName(constantPool).equals("main")) { - Code_attribute code = (Code_attribute) method.attributes.get(Attribute.Code); - for (Instruction i : code.getInstructions()) { - if (i.getOpcode() == Opcode.INVOKEDYNAMIC) { - CONSTANT_InvokeDynamic_info indyInfo = - (CONSTANT_InvokeDynamic_info) - constantPool.get(i.getUnsignedShort(1)); - CONSTANT_NameAndType_info natInfo = indyInfo.getNameAndTypeInfo(); - actualTypes.add(natInfo.getType()); + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString("main")) { + CodeAttribute code = method.findAttribute(Attributes.CODE).orElseThrow(); + for (CodeElement i : code.elementList()) { + if (i instanceof InvokeDynamicInstruction) { + InvokeDynamicInstruction indy = (InvokeDynamicInstruction) i; + NameAndTypeEntry natInfo = indy.invokedynamic().nameAndType(); + actualTypes.add(natInfo.type().stringValue()); } } } diff --git a/test/langtools/tools/javac/StringConcat/access/Test.java b/test/langtools/tools/javac/StringConcat/access/Test.java index 578bbddb118..51313092e78 100644 --- a/test/langtools/tools/javac/StringConcat/access/Test.java +++ b/test/langtools/tools/javac/StringConcat/access/Test.java @@ -21,8 +21,10 @@ * questions. */ -import com.sun.tools.classfile.*; -import com.sun.tools.classfile.ConstantPool.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.*; +import jdk.internal.classfile.instruction.InvokeDynamicInstruction; import java.io.File; import java.util.ArrayList; @@ -32,7 +34,11 @@ import java.util.List; * @test * @bug 8151223 * @summary String concatenation fails with implicit toString() on package-private class - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components * * @clean * * @compile -XDstringConcat=indy Holder.java PublicClass.java PublicInterface.java Public_PublicClass.java Public_PublicInterface.java Public_PrivateInterface1.java Public_PrivateInterface2.java Test.java @@ -175,19 +181,17 @@ public class Test { public static void readIndyTypes() throws Exception { actualTypes = new ArrayList(); - ClassFile classFile = ClassFile.read(new File(System.getProperty("test.classes", "."), - Test.class.getName() + ".class")); - ConstantPool constantPool = classFile.constant_pool; + ClassModel classFile = Classfile.of().parse(new File(System.getProperty("test.classes", "."), + Test.class.getName() + ".class").toPath()); - for (Method method : classFile.methods) { - if (method.getName(constantPool).equals("main")) { - Code_attribute code = (Code_attribute) method.attributes - .get(Attribute.Code); - for (Instruction i : code.getInstructions()) { - if (i.getOpcode() == Opcode.INVOKEDYNAMIC) { - CONSTANT_InvokeDynamic_info indyInfo = (CONSTANT_InvokeDynamic_info) constantPool.get(i.getUnsignedShort(1)); - CONSTANT_NameAndType_info natInfo = indyInfo.getNameAndTypeInfo(); - actualTypes.add(natInfo.getType()); + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString("main")) { + CodeAttribute code = method.findAttribute(Attributes.CODE).orElseThrow(); + for (CodeElement i : code.elementList()) { + if (i instanceof InvokeDynamicInstruction) { + InvokeDynamicEntry indyInfo = ((InvokeDynamicInstruction) i).invokedynamic(); + NameAndTypeEntry natInfo = indyInfo.nameAndType(); + actualTypes.add(natInfo.type().stringValue()); } } } diff --git a/test/langtools/tools/javac/T6695379/AnnotationsAreNotCopiedToBridgeMethodsTest.java b/test/langtools/tools/javac/T6695379/AnnotationsAreNotCopiedToBridgeMethodsTest.java index 9d1a2c4fd62..16fef1b8242 100644 --- a/test/langtools/tools/javac/T6695379/AnnotationsAreNotCopiedToBridgeMethodsTest.java +++ b/test/langtools/tools/javac/T6695379/AnnotationsAreNotCopiedToBridgeMethodsTest.java @@ -26,7 +26,12 @@ * @bug 6695379 * @summary Copy method annotations and parameter annotations to synthetic * bridge methods - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.util * @run main AnnotationsAreNotCopiedToBridgeMethodsTest */ @@ -40,11 +45,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import com.sun.tools.classfile.AccessFlags; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Attributes; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import com.sun.tools.javac.util.Assert; public class AnnotationsAreNotCopiedToBridgeMethodsTest { @@ -61,25 +63,18 @@ public class AnnotationsAreNotCopiedToBridgeMethodsTest { "$CovariantReturnType$VisibilityChange.class")); } - void checkClassFile(final Path cfilePath) throws Exception { - ClassFile classFile = ClassFile.read( - new BufferedInputStream(Files.newInputStream(cfilePath))); - for (Method method : classFile.methods) { - if (method.access_flags.is(AccessFlags.ACC_BRIDGE)) { - checkForAttr(method.attributes, - "Annotations hasn't been copied to bridge method", - Attribute.RuntimeVisibleAnnotations, - Attribute.RuntimeVisibleParameterAnnotations); + > void checkClassFile(final Path cfilePath) throws Exception { + ClassModel classFile = Classfile.of().parse(cfilePath); + for (MethodModel method : classFile.methods()) { + if ((method.flags().flagsMask() & Classfile.ACC_BRIDGE) != 0) { + Assert.checkNonNull(method.findAttribute(Attributes.RUNTIME_VISIBLE_ANNOTATIONS), + "Annotations hasn't been copied to bridge method"); + Assert.checkNonNull(method.findAttribute(Attributes.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS), + "Annotations hasn't been copied to bridge method"); } } } - void checkForAttr(Attributes attrs, String errorMsg, String... attrNames) { - for (String attrName : attrNames) { - Assert.checkNonNull(attrs.get(attrName), errorMsg); - } - } - @Target(value = {ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @interface ParamAnnotation {} diff --git a/test/langtools/tools/javac/T6970173/DebugPointerAtBadPositionTest.java b/test/langtools/tools/javac/T6970173/DebugPointerAtBadPositionTest.java index 91ecab86755..2ef4c45d7ec 100644 --- a/test/langtools/tools/javac/T6970173/DebugPointerAtBadPositionTest.java +++ b/test/langtools/tools/javac/T6970173/DebugPointerAtBadPositionTest.java @@ -26,7 +26,12 @@ * @bug 6970173 * @summary Debug pointer at bad position * @library /tools/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util @@ -38,10 +43,8 @@ import java.io.File; import java.nio.file.Paths; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.LineNumberTable_attribute; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import com.sun.tools.javac.util.Assert; import toolbox.JavacTask; @@ -90,22 +93,21 @@ public class DebugPointerAtBadPositionTest { } void checkClassFile(final File cfile, String methodToFind) throws Exception { - ClassFile classFile = ClassFile.read(cfile); + ClassModel classFile = Classfile.of().parse(cfile.toPath()); boolean methodFound = false; - for (Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals(methodToFind)) { + for (MethodModel m : classFile.methods()) { + if (m.methodName().equalsString(methodToFind)) { methodFound = true; - Code_attribute code = (Code_attribute) method.attributes.get("Code"); - LineNumberTable_attribute lnt = - (LineNumberTable_attribute) code.attributes.get("LineNumberTable"); - Assert.check(lnt.line_number_table_length == expectedLNT.length, + CodeAttribute code = m.findAttribute(Attributes.CODE).orElseThrow(); + LineNumberTableAttribute lnt = code.findAttribute(Attributes.LINE_NUMBER_TABLE).orElseThrow(); + Assert.check(lnt.lineNumbers().size() == expectedLNT.length, foundLNTLengthDifferentThanExpMsg); int i = 0; - for (LineNumberTable_attribute.Entry entry: lnt.line_number_table) { - Assert.check(entry.line_number == expectedLNT[i][0] && - entry.start_pc == expectedLNT[i][1], + for (LineNumberInfo entry: lnt.lineNumbers()) { + Assert.check(entry.lineNumber() == expectedLNT[i][0] && + entry.startPc() == expectedLNT[i][1], "LNT entry at pos " + i + " differ from expected." + - "Found " + entry.line_number + ":" + entry.start_pc + + "Found " + entry.lineNumber() + ":" + entry.startPc() + ". Expected " + expectedLNT[i][0] + ":" + expectedLNT[i][1]); i++; } diff --git a/test/langtools/tools/javac/T7008643/InlinedFinallyConfuseDebuggersTest.java b/test/langtools/tools/javac/T7008643/InlinedFinallyConfuseDebuggersTest.java index 721e9f72002..99e370ecb3b 100644 --- a/test/langtools/tools/javac/T7008643/InlinedFinallyConfuseDebuggersTest.java +++ b/test/langtools/tools/javac/T7008643/InlinedFinallyConfuseDebuggersTest.java @@ -26,7 +26,12 @@ * @bug 7008643 * @summary inlined finally clauses confuse debuggers * @library /tools/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util @@ -38,10 +43,8 @@ import java.io.File; import java.nio.file.Paths; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.LineNumberTable_attribute; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import com.sun.tools.javac.util.Assert; import toolbox.JavacTask; @@ -97,22 +100,21 @@ public class InlinedFinallyConfuseDebuggersTest { } void checkClassFile(final File cfile, String methodToFind) throws Exception { - ClassFile classFile = ClassFile.read(cfile); + ClassModel classFile = Classfile.of().parse(cfile.toPath()); boolean methodFound = false; - for (Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals(methodToFind)) { + for (MethodModel m : classFile.methods()) { + if (m.methodName().equalsString(methodToFind)) { methodFound = true; - Code_attribute code = (Code_attribute) method.attributes.get("Code"); - LineNumberTable_attribute lnt = - (LineNumberTable_attribute) code.attributes.get("LineNumberTable"); - Assert.check(lnt.line_number_table_length == expectedLNT.length, + CodeAttribute code = m.findAttribute(Attributes.CODE).orElseThrow(); + LineNumberTableAttribute lnt = code.findAttribute(Attributes.LINE_NUMBER_TABLE).orElseThrow(); + Assert.check(lnt.lineNumbers().size() == expectedLNT.length, "The LineNumberTable found has a length different to the expected one"); int i = 0; - for (LineNumberTable_attribute.Entry entry: lnt.line_number_table) { - Assert.check(entry.line_number == expectedLNT[i][0] && - entry.start_pc == expectedLNT[i][1], + for (LineNumberInfo entry: lnt.lineNumbers()) { + Assert.check(entry.lineNumber() == expectedLNT[i][0] && + entry.startPc() == expectedLNT[i][1], "LNT entry at pos " + i + " differ from expected." + - "Found " + entry.line_number + ":" + entry.start_pc + + "Found " + entry.lineNumber() + ":" + entry.startPc() + ". Expected " + expectedLNT[i][0] + ":" + expectedLNT[i][1]); i++; } diff --git a/test/langtools/tools/javac/T7053059/DoubleCastTest.java b/test/langtools/tools/javac/T7053059/DoubleCastTest.java index d09ed423a9c..2cf472d3ce9 100644 --- a/test/langtools/tools/javac/T7053059/DoubleCastTest.java +++ b/test/langtools/tools/javac/T7053059/DoubleCastTest.java @@ -25,14 +25,23 @@ * @test * @bug 8015499 * @summary javac, Gen is generating extra checkcast instructions in some corner cases - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.util * @run main DoubleCastTest */ import java.util.List; import java.util.ArrayList; -import com.sun.tools.classfile.*; +import java.util.Objects; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.ClassEntry; +import jdk.internal.classfile.instruction.TypeCheckInstruction; import com.sun.tools.javac.util.Assert; public class DoubleCastTest { @@ -55,22 +64,23 @@ public class DoubleCastTest { public static void main(String... cmdline) throws Exception { - ClassFile cls = ClassFile.read(DoubleCastTest.class.getResourceAsStream("DoubleCastTest$C.class")); - for (Method m: cls.methods) + ClassModel cls = Classfile.of().parse(Objects.requireNonNull(DoubleCastTest.class.getResourceAsStream("DoubleCastTest$C.class")).readAllBytes()); + for (MethodModel m: cls.methods()) check(m); } - static void check(Method m) throws Exception { + static void check(MethodModel m) throws Exception { boolean last_is_cast = false; - int last_ref = 0; - Code_attribute ea = (Code_attribute)m.attributes.get(Attribute.Code); - for (Instruction i : ea.getInstructions()) { - if (i.getOpcode() == Opcode.CHECKCAST) { + ClassEntry last_ref = null; + CodeAttribute ea = m.findAttribute(Attributes.CODE).orElseThrow(); + for (int i = 0; i < ea.elementList().size(); ++i) { + CodeElement ce = ea.elementList().get(i); + if (ce instanceof TypeCheckInstruction ins && ins.opcode() == Opcode.CHECKCAST) { Assert.check - (!(last_is_cast && last_ref == i.getUnsignedShort(1)), + (!(last_is_cast && last_ref == ins.type()), "Double cast found - Test failed"); last_is_cast = true; - last_ref = i.getUnsignedShort(1); + last_ref = ins.type(); } else { last_is_cast = false; } diff --git a/test/langtools/tools/javac/T7093325.java b/test/langtools/tools/javac/T7093325.java index 6472d8f3b38..bd7434f6119 100644 --- a/test/langtools/tools/javac/T7093325.java +++ b/test/langtools/tools/javac/T7093325.java @@ -27,7 +27,12 @@ * @summary Redundant entry in bytecode exception table * temporarily workaround combo tests are causing time out in several platforms * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.file * jdk.compiler/com.sun.tools.javac.util @@ -38,11 +43,9 @@ import java.io.IOException; import java.io.InputStream; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.ClassEntry; import javax.tools.JavaFileObject; @@ -149,15 +152,15 @@ public class T7093325 extends ComboInstance { } try (InputStream is = result.get().iterator().next().openInputStream()) { - ClassFile cf = ClassFile.read(is); + ClassModel cf = Classfile.of().parse(is.readAllBytes()); if (cf == null) { fail("Classfile not found: " + result.compilationInfo()); return; } - Method test_method = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals("test")) { + MethodModel test_method = null; + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString("test")) { test_method = m; break; } @@ -168,13 +171,7 @@ public class T7093325 extends ComboInstance { return; } - Code_attribute code = null; - for (Attribute a : test_method.attributes) { - if (a.getName(cf.constant_pool).equals(Attribute.Code)) { - code = (Code_attribute)a; - break; - } - } + CodeAttribute code = test_method.findAttribute(Attributes.CODE).orElse(null); if (code == null) { fail("Code attribute not found in method test()"); @@ -182,9 +179,9 @@ public class T7093325 extends ComboInstance { } int actualGapsCount = 0; - for (int i = 0; i < code.exception_table_length ; i++) { - int catchType = code.exception_table[i].catch_type; - if (catchType == 0) { //any + for (int i = 0; i < code.exceptionHandlers().size() ; i++) { + ClassEntry catchType = code.exceptionHandlers().get(i).catchType().orElse(null); + if (catchType == null) { //any actualGapsCount++; } } @@ -194,9 +191,8 @@ public class T7093325 extends ComboInstance { "expected gaps: " + gapsCount + "\n" + "found gaps: " + actualGapsCount + "\n" + result.compilationInfo()); - return; } - } catch (IOException | ConstantPoolException e) { + } catch (IOException e) { e.printStackTrace(); fail("error reading classfile: " + e); } diff --git a/test/langtools/tools/javac/T8003967/DetectMutableStaticFields.java b/test/langtools/tools/javac/T8003967/DetectMutableStaticFields.java index f25c0099fe7..af4d3f99035 100644 --- a/test/langtools/tools/javac/T8003967/DetectMutableStaticFields.java +++ b/test/langtools/tools/javac/T8003967/DetectMutableStaticFields.java @@ -25,11 +25,17 @@ * @test * @bug 8003967 * @summary detect and remove all mutable implicit static enum fields in langtools - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.util * @run main DetectMutableStaticFields */ +import jdk.internal.classfile.*; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -50,17 +56,9 @@ import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Descriptor; -import com.sun.tools.classfile.Descriptor.InvalidDescriptor; -import com.sun.tools.classfile.Field; import static javax.tools.JavaFileObject.Kind.CLASS; -import static com.sun.tools.classfile.AccessFlags.ACC_ENUM; -import static com.sun.tools.classfile.AccessFlags.ACC_FINAL; -import static com.sun.tools.classfile.AccessFlags.ACC_STATIC; public class DetectMutableStaticFields { @@ -75,7 +73,12 @@ public class DetectMutableStaticFields { "javax.tools", "javax.lang.model", "com.sun.source", - "com.sun.tools.classfile", + "jdk.internal.classfile", + "jdk.internal.classfile.attribute", + "jdk.internal.classfile.constantpool", + "jdk.internal.classfile.instruction", + "jdk.internal.classfile.components", + "jdk.internal.classfile.impl", "com.sun.tools.javac", "com.sun.tools.javah", "com.sun.tools.javap", @@ -90,7 +93,6 @@ public class DetectMutableStaticFields { static { ignore("javax/tools/ToolProvider", "instance"); ignore("com/sun/tools/javah/JavahTask", "versionRB"); - ignore("com/sun/tools/classfile/Dependencies$DefaultFilter", "instance"); ignore("com/sun/tools/javap/JavapTask", "versionRB"); ignore("com/sun/tools/doclets/formats/html/HtmlDoclet", "docletToStart"); ignore("com/sun/tools/javac/util/JCDiagnostic", "fragmentFormatter"); @@ -132,12 +134,7 @@ public class DetectMutableStaticFields { } } - private void run() - throws - IOException, - ConstantPoolException, - InvalidDescriptor, - URISyntaxException { + private void run() throws IOException { JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) { @@ -164,11 +161,7 @@ public class DetectMutableStaticFields { return false; } - void analyzeModule(StandardJavaFileManager fm, String moduleName) - throws - IOException, - ConstantPoolException, - InvalidDescriptor { + void analyzeModule(StandardJavaFileManager fm, String moduleName) throws IOException { JavaFileManager.Location location = fm.getLocationForModule(StandardLocation.SYSTEM_MODULES, moduleName); if (location == null) @@ -179,9 +172,9 @@ public class DetectMutableStaticFields { int index = className.lastIndexOf('.'); String pckName = index == -1 ? "" : className.substring(0, index); if (shouldAnalyzePackage(pckName)) { - ClassFile classFile; + ClassModel classFile; try (InputStream input = file.openInputStream()) { - classFile = ClassFile.read(input); + classFile = Classfile.of().parse(input.readAllBytes()); } analyzeClassFile(classFile); } @@ -201,33 +194,29 @@ public class DetectMutableStaticFields { return false; } - void analyzeClassFile(ClassFile classFileToCheck) - throws - IOException, - ConstantPoolException, - Descriptor.InvalidDescriptor { + void analyzeClassFile(ClassModel classFileToCheck) { boolean enumClass = - (classFileToCheck.access_flags.flags & ACC_ENUM) != 0; + (classFileToCheck.flags().flagsMask() & Classfile.ACC_ENUM) != 0; boolean nonFinalStaticEnumField; boolean nonFinalStaticField; currentFieldsToIgnore = - classFieldsToIgnoreMap.get(classFileToCheck.getName()); + classFieldsToIgnoreMap.get(classFileToCheck.thisClass().asInternalName()); - for (Field field : classFileToCheck.fields) { - if (ignoreField(field.getName(classFileToCheck.constant_pool))) { + for (FieldModel field : classFileToCheck.fields()) { + if (ignoreField(field.fieldName().stringValue())) { continue; } nonFinalStaticEnumField = - (field.access_flags.flags & (ACC_ENUM | ACC_FINAL)) == 0; + (field.flags().flagsMask() & (Classfile.ACC_ENUM | Classfile.ACC_FINAL)) == 0; nonFinalStaticField = - (field.access_flags.flags & ACC_STATIC) != 0 && - (field.access_flags.flags & ACC_FINAL) == 0; + (field.flags().flagsMask() & Classfile.ACC_STATIC) != 0 && + (field.flags().flagsMask() & Classfile.ACC_FINAL) == 0; if (enumClass ? nonFinalStaticEnumField : nonFinalStaticField) { errors.add("There is a mutable field named " + - field.getName(classFileToCheck.constant_pool) + + field.fieldName().stringValue() + ", at class " + - classFileToCheck.getName()); + classFileToCheck.thisClass().asInternalName()); } } } diff --git a/test/langtools/tools/javac/T8010737/ParameterNamesAreNotCopiedToAnonymousInitTest.java b/test/langtools/tools/javac/T8010737/ParameterNamesAreNotCopiedToAnonymousInitTest.java index bacde6b9166..e435cf82b00 100644 --- a/test/langtools/tools/javac/T8010737/ParameterNamesAreNotCopiedToAnonymousInitTest.java +++ b/test/langtools/tools/javac/T8010737/ParameterNamesAreNotCopiedToAnonymousInitTest.java @@ -26,7 +26,12 @@ * @bug 8010737 * @summary javac, known parameter's names should be copied to automatically * generated constructors for inner classes - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.tree @@ -51,8 +56,6 @@ import com.sun.source.tree.Tree; import com.sun.source.util.JavacTask; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Method; import com.sun.tools.javac.api.BasicJavacTask; import com.sun.tools.javac.code.Attribute.Compound; import com.sun.tools.javac.code.Symbol.ClassSymbol; @@ -63,6 +66,7 @@ import com.sun.tools.javac.util.Assert; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Names; +import jdk.internal.classfile.*; public class ParameterNamesAreNotCopiedToAnonymousInitTest { @@ -112,10 +116,10 @@ public class ParameterNamesAreNotCopiedToAnonymousInitTest { } void checkClassFile(final File cfile, int numberOfParams) throws Exception { - ClassFile classFile = ClassFile.read(cfile); + ClassModel classFile = Classfile.of().parse(cfile.toPath()); boolean methodFound = false; - for (Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals("")) { + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString("")) { methodFound = true; } } @@ -143,8 +147,12 @@ public class ParameterNamesAreNotCopiedToAnonymousInitTest { Arrays.asList(new File(System.getProperty("test.src"), this.getClass().getName() + ".java"))); java.util.List options = Arrays.asList( - "--add-modules", "jdk.jdeps", - "--add-exports", "jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.classfile=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.classfile.attribute=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.classfile.constantpool=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.classfile.instruction=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.classfile.components=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.classfile.impl=ALL-UNNAMED", "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", "--add-exports", "jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", "--add-exports", "jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", diff --git a/test/langtools/tools/javac/T8019486/WrongLNTForLambdaTest.java b/test/langtools/tools/javac/T8019486/WrongLNTForLambdaTest.java index f278c0de5ff..b6ba6333b82 100644 --- a/test/langtools/tools/javac/T8019486/WrongLNTForLambdaTest.java +++ b/test/langtools/tools/javac/T8019486/WrongLNTForLambdaTest.java @@ -29,7 +29,12 @@ * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main WrongLNTForLambdaTest */ @@ -37,12 +42,10 @@ import java.io.File; import java.nio.file.Paths; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.LineNumberTable_attribute; -import com.sun.tools.classfile.Method; import com.sun.tools.javac.util.Assert; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import toolbox.JavacTask; import toolbox.ToolBox; @@ -159,22 +162,21 @@ public class WrongLNTForLambdaTest { } void checkClassFile(final File cfile, String methodToFind, int[][] expectedLNT) throws Exception { - ClassFile classFile = ClassFile.read(cfile); + ClassModel classFile = Classfile.of().parse(cfile.toPath()); boolean methodFound = false; - for (Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals(methodToFind)) { + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString(methodToFind)) { methodFound = true; - Code_attribute code = (Code_attribute) method.attributes.get("Code"); - LineNumberTable_attribute lnt = - (LineNumberTable_attribute) code.attributes.get("LineNumberTable"); - Assert.check(lnt.line_number_table_length == expectedLNT.length, + CodeAttribute code = method.findAttribute(Attributes.CODE).orElseThrow(); + LineNumberTableAttribute lnt = code.findAttribute(Attributes.LINE_NUMBER_TABLE).orElseThrow(); + Assert.check(lnt.lineNumbers().size() == expectedLNT.length, "The LineNumberTable found has a length different to the expected one"); int i = 0; - for (LineNumberTable_attribute.Entry entry: lnt.line_number_table) { - Assert.check(entry.line_number == expectedLNT[i][0] && - entry.start_pc == expectedLNT[i][1], + for (LineNumberInfo entry: lnt.lineNumbers()) { + Assert.check(entry.lineNumber() == expectedLNT[i][0] && + entry.startPc() == expectedLNT[i][1], "LNT entry at pos " + i + " differ from expected." + - "Found " + entry.line_number + ":" + entry.start_pc + + "Found " + entry.lineNumber() + ":" + entry.startPc() + ". Expected " + expectedLNT[i][0] + ":" + expectedLNT[i][1]); i++; } diff --git a/test/langtools/tools/javac/T8022186/DeadCodeGeneratedForEmptyTryTest.java b/test/langtools/tools/javac/T8022186/DeadCodeGeneratedForEmptyTryTest.java index a443b04c4e1..ff60d7b15c5 100644 --- a/test/langtools/tools/javac/T8022186/DeadCodeGeneratedForEmptyTryTest.java +++ b/test/langtools/tools/javac/T8022186/DeadCodeGeneratedForEmptyTryTest.java @@ -25,21 +25,19 @@ * @test * @bug 8022186 8271254 * @summary javac generates dead code if a try with an empty body has a finalizer - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.util */ -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPool.CONSTANT_String_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; -import com.sun.tools.classfile.ConstantPool.InvalidIndex; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Instruction.KindVisitor; -import com.sun.tools.classfile.Instruction.TypeKind; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.*; +import jdk.internal.classfile.instruction.InvokeInstruction; import com.sun.tools.javac.util.Assert; import java.io.BufferedInputStream; import java.nio.file.Files; @@ -65,97 +63,27 @@ public class DeadCodeGeneratedForEmptyTryTest { void checkClassFile(final Path path) throws Exception { numberOfRefToStr = 0; - ClassFile classFile = ClassFile.read( - new BufferedInputStream(Files.newInputStream(path))); - constantPool = classFile.constant_pool; - utf8Index = constantPool.getUTF8Index("STR_TO_LOOK_FOR"); - for (Method method: classFile.methods) { - if (method.getName(constantPool).equals("methodToLookFor")) { - Code_attribute codeAtt = (Code_attribute)method.attributes.get(Attribute.Code); - for (Instruction inst: codeAtt.getInstructions()) { - inst.accept(codeVisitor, null); - } + ClassModel classFile = Classfile.of().parse( + new BufferedInputStream(Files.newInputStream(path)).readAllBytes()); + constantPool = classFile.constantPool(); + for (MethodModel method: classFile.methods()) { + if (method.methodName().equalsString("methodToLookFor")) { + CodeAttribute codeAtt = method.findAttribute(Attributes.CODE).orElseThrow(); + codeAtt.elementList().stream() + .filter(ce -> ce instanceof Instruction) + .forEach(ins -> checkIndirectRefToString((Instruction) ins)); } } Assert.check(numberOfRefToStr == 1, "There should only be one reference to a CONSTANT_String_info structure in the generated code"); } - - CodeVisitor codeVisitor = new CodeVisitor(); - - class CodeVisitor implements KindVisitor { - - void checkIndirectRefToString(int cp_index) { - try { - CPInfo cInfo = constantPool.get(cp_index); - if (cInfo instanceof CONSTANT_String_info) { - CONSTANT_String_info strInfo = (CONSTANT_String_info)cInfo; - if (strInfo.string_index == utf8Index) { - numberOfRefToStr++; - } - } - } catch (InvalidIndex ex) { - throw new AssertionError("invalid constant pool index at " + cp_index); + void checkIndirectRefToString(Instruction instruction) { + if (instruction instanceof InvokeInstruction invokeInstruction) { + MemberRefEntry refEntry = invokeInstruction.method(); + if (constantPool.entryByIndex(refEntry.type().index()) instanceof Utf8Entry) { + numberOfRefToStr++; } } - - @Override - public Void visitNoOperands(Instruction instr, Void p) { - return null; - } - - @Override - public Void visitArrayType(Instruction instr, TypeKind kind, Void p) { - return null; - } - - @Override - public Void visitBranch(Instruction instr, int offset, Void p) { - return null; - } - - @Override - public Void visitConstantPoolRef(Instruction instr, int index, Void p) { - checkIndirectRefToString(index); - return null; - } - - @Override - public Void visitConstantPoolRefAndValue(Instruction instr, int index, int value, Void p) { - checkIndirectRefToString(index); - return null; - } - - @Override - public Void visitLocal(Instruction instr, int index, Void p) { - return null; - } - - @Override - public Void visitLocalAndValue(Instruction instr, int index, int value, Void p) { - return null; - } - - @Override - public Void visitLookupSwitch(Instruction instr, int default_, int npairs, int[] matches, int[] offsets, Void p) { - return null; - } - - @Override - public Void visitTableSwitch(Instruction instr, int default_, int low, int high, int[] offsets, Void p) { - return null; - } - - @Override - public Void visitValue(Instruction instr, int value, Void p) { - return null; - } - - @Override - public Void visitUnknown(Instruction instr, Void p) { - return null; - } - } public class Test1 { diff --git a/test/langtools/tools/javac/T8024039/NoDeadCodeGenerationOnTrySmtTest.java b/test/langtools/tools/javac/T8024039/NoDeadCodeGenerationOnTrySmtTest.java index e6d739fb3d8..15cd4ea8d70 100644 --- a/test/langtools/tools/javac/T8024039/NoDeadCodeGenerationOnTrySmtTest.java +++ b/test/langtools/tools/javac/T8024039/NoDeadCodeGenerationOnTrySmtTest.java @@ -29,7 +29,12 @@ * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main NoDeadCodeGenerationOnTrySmtTest */ @@ -37,12 +42,11 @@ import java.io.File; import java.nio.file.Paths; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.Code_attribute.Exception_data; -import com.sun.tools.classfile.Method; import com.sun.tools.javac.util.Assert; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.instruction.ExceptionCatch; import toolbox.JavacTask; import toolbox.ToolBox; @@ -100,21 +104,21 @@ public class NoDeadCodeGenerationOnTrySmtTest { } void checkClassFile(final File cfile, String[] methodsToFind) throws Exception { - ClassFile classFile = ClassFile.read(cfile); + ClassModel classFile = Classfile.of().parse(cfile.toPath()); int numberOfmethodsFound = 0; for (String methodToFind : methodsToFind) { - for (Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals(methodToFind)) { + for (MethodModel m : classFile.methods()) { + if (m.methodName().equalsString(methodToFind)) { numberOfmethodsFound++; - Code_attribute code = (Code_attribute) method.attributes.get("Code"); - Assert.check(code.exception_table_length == expectedExceptionTable.length, + CodeAttribute code = m.findAttribute(Attributes.CODE).orElseThrow(); + Assert.check(code.exceptionHandlers().size() == expectedExceptionTable.length, "The ExceptionTable found has a length different to the expected one"); int i = 0; - for (Exception_data entry: code.exception_table) { - Assert.check(entry.start_pc == expectedExceptionTable[i][0] && - entry.end_pc == expectedExceptionTable[i][1] && - entry.handler_pc == expectedExceptionTable[i][2] && - entry.catch_type == expectedExceptionTable[i][3], + for (ExceptionCatch entry: code.exceptionHandlers()) { + Assert.check(code.labelToBci(entry.tryStart()) == expectedExceptionTable[i][0] && + code.labelToBci(entry.tryEnd()) == expectedExceptionTable[i][1] && + code.labelToBci(entry.handler()) == expectedExceptionTable[i][2] && + (entry.catchType().isPresent()? entry.catchType().get().index(): 0)== expectedExceptionTable[i][3], "Exception table entry at pos " + i + " differ from expected."); i++; } diff --git a/test/langtools/tools/javac/T8180141/MissingLNTEntryForBreakContinueTest.java b/test/langtools/tools/javac/T8180141/MissingLNTEntryForBreakContinueTest.java index e032e93e8c2..645ed32de7a 100644 --- a/test/langtools/tools/javac/T8180141/MissingLNTEntryForBreakContinueTest.java +++ b/test/langtools/tools/javac/T8180141/MissingLNTEntryForBreakContinueTest.java @@ -25,7 +25,12 @@ * @test * @bug 8180141 * @summary Missing entry in LineNumberTable for break statement that jumps out of try-finally - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.comp * jdk.compiler/com.sun.tools.javac.file @@ -42,7 +47,6 @@ import java.net.URI; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; -import com.sun.tools.classfile.*; import com.sun.tools.javac.comp.Attr; import com.sun.tools.javac.comp.AttrContext; import com.sun.tools.javac.comp.Env; @@ -52,6 +56,8 @@ import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import static com.sun.tools.javac.util.List.of; import static com.sun.tools.javac.tree.JCTree.Tag.*; @@ -87,19 +93,19 @@ public class MissingLNTEntryForBreakContinueTest { } File testClasses = new File("."); File file = new File(testClasses, "Test" + id + ".class"); - ClassFile classFile = ClassFile.read(file); - for (Method m : classFile.methods) { - if (classFile.constant_pool.getUTF8Value(m.name_index).equals("foo")) { - Code_attribute code = (Code_attribute)m.attributes.get(Attribute.Code); - LineNumberTable_attribute lnt = (LineNumberTable_attribute)code.attributes.get(Attribute.LineNumberTable); + ClassModel classFile = Classfile.of().parse(file.toPath()); + for (MethodModel m : classFile.methods()) { + if (m.methodName().equalsString("foo")) { + CodeAttribute code = m.findAttribute(Attributes.CODE).orElseThrow(); + LineNumberTableAttribute lnt = code.findAttribute(Attributes.LINE_NUMBER_TABLE).orElseThrow(); checkLNT(lnt, MyAttr.lineNumber); } } } - void checkLNT(LineNumberTable_attribute lnt, int lineToCheckFor) { - for (LineNumberTable_attribute.Entry e: lnt.line_number_table) { - if (e.line_number == lineToCheckFor) { + void checkLNT(LineNumberTableAttribute lnt, int lineToCheckFor) { + for (LineNumberInfo e: lnt.lineNumbers()) { + if (e.lineNumber() == lineToCheckFor) { return; } } diff --git a/test/langtools/tools/javac/T8180660/MissingLNTEntryForFinalizerTest.java b/test/langtools/tools/javac/T8180660/MissingLNTEntryForFinalizerTest.java index 49e4026fd07..dfbba1e23a7 100644 --- a/test/langtools/tools/javac/T8180660/MissingLNTEntryForFinalizerTest.java +++ b/test/langtools/tools/javac/T8180660/MissingLNTEntryForFinalizerTest.java @@ -25,7 +25,12 @@ * @test * @bug 8180141 * @summary Missing entry in LineNumberTable for break statement that jumps out of try-finally - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.comp * jdk.compiler/com.sun.tools.javac.file @@ -42,7 +47,6 @@ import java.net.URI; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; -import com.sun.tools.classfile.*; import com.sun.tools.javac.comp.Attr; import com.sun.tools.javac.comp.AttrContext; import com.sun.tools.javac.comp.Env; @@ -53,6 +57,8 @@ import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.*; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import static com.sun.tools.javac.util.List.of; import static com.sun.tools.javac.tree.JCTree.Tag.*; @@ -83,19 +89,19 @@ public class MissingLNTEntryForFinalizerTest { } File testClasses = new File("."); File file = new File(testClasses, "Test1.class"); - ClassFile classFile = ClassFile.read(file); - for (Method m : classFile.methods) { - if (classFile.constant_pool.getUTF8Value(m.name_index).equals("foo")) { - Code_attribute code = (Code_attribute)m.attributes.get(Attribute.Code); - LineNumberTable_attribute lnt = (LineNumberTable_attribute)code.attributes.get(Attribute.LineNumberTable); + ClassModel classFile = Classfile.of().parse(file.toPath()); + for (MethodModel m : classFile.methods()) { + if (m.methodName().equalsString("foo")) { + CodeAttribute code = m.findAttribute(Attributes.CODE).orElseThrow(); + LineNumberTableAttribute lnt = code.findAttribute(Attributes.LINE_NUMBER_TABLE).orElseThrow(); checkLNT(lnt, MyAttr.lineNumber); } } } - void checkLNT(LineNumberTable_attribute lnt, int lineToCheckFor) { - for (LineNumberTable_attribute.Entry e: lnt.line_number_table) { - if (e.line_number == lineToCheckFor) { + void checkLNT(LineNumberTableAttribute lnt, int lineToCheckFor) { + for (LineNumberInfo e: lnt.lineNumbers()) { + if (e.lineNumber() == lineToCheckFor) { return; } } diff --git a/test/langtools/tools/javac/T8187805/BogusRTTAForUnusedVarTest.java b/test/langtools/tools/javac/T8187805/BogusRTTAForUnusedVarTest.java index bc45478ee0a..4bf259c609b 100644 --- a/test/langtools/tools/javac/T8187805/BogusRTTAForUnusedVarTest.java +++ b/test/langtools/tools/javac/T8187805/BogusRTTAForUnusedVarTest.java @@ -24,23 +24,25 @@ /* * @test 8187805 * @summary bogus RuntimeVisibleTypeAnnotations for unused local in a block - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.util * @run main BogusRTTAForUnusedVarTest */ -import com.sun.tools.classfile.*; - import java.io.File; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.RuntimeVisibleTypeAnnotations_attribute; -import com.sun.tools.classfile.TypeAnnotation; -import com.sun.tools.classfile.TypeAnnotation.Position; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.attribute.RuntimeVisibleTypeAnnotationsAttribute; import com.sun.tools.javac.util.Assert; public class BogusRTTAForUnusedVarTest { @@ -69,14 +71,13 @@ public class BogusRTTAForUnusedVarTest { File testClasses = new File(System.getProperty("test.classes")); File file = new File(testClasses, BogusRTTAForUnusedVarTest.class.getName() + "$Foo.class"); - ClassFile classFile = ClassFile.read(file); - for (Method m : classFile.methods) { - if (m.getName(classFile.constant_pool).equals("something")) { - for (Attribute a : m.attributes) { - if (a.getName(classFile.constant_pool).equals("Code")) { - Code_attribute code = (Code_attribute)a; - for (Attribute codeAttrs : code.attributes) { - if (codeAttrs.getName(classFile.constant_pool).equals("RuntimeVisibleTypeAnnotations")) { + ClassModel classFile = Classfile.of().parse(file.toPath()); + for (MethodModel m : classFile.methods()) { + if (m.methodName().equalsString("something")) { + for (Attribute a : m.attributes()) { + if (a instanceof CodeAttribute code) { + for (Attribute codeAttrs : code.attributes()) { + if (codeAttrs instanceof RuntimeVisibleTypeAnnotationsAttribute) { throw new AssertionError("no RuntimeVisibleTypeAnnotations attribute should have been generated in this case"); } } diff --git a/test/langtools/tools/javac/T8203892/CheckTargetIsNotAddedAsMarkerInterfaceTest.java b/test/langtools/tools/javac/T8203892/CheckTargetIsNotAddedAsMarkerInterfaceTest.java index 7315f61e34e..bcfde0766fa 100644 --- a/test/langtools/tools/javac/T8203892/CheckTargetIsNotAddedAsMarkerInterfaceTest.java +++ b/test/langtools/tools/javac/T8203892/CheckTargetIsNotAddedAsMarkerInterfaceTest.java @@ -25,7 +25,12 @@ * @test 8203892 * @summary Target interface added as marker interface in calls to altMetafactory * @library /tools/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util @@ -37,11 +42,9 @@ import java.io.File; import java.nio.file.Paths; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute.BootstrapMethodSpecifier; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.*; import com.sun.tools.javac.util.Assert; import toolbox.JavacTask; @@ -80,16 +83,15 @@ public class CheckTargetIsNotAddedAsMarkerInterfaceTest { } void checkClassFile(final File cfile) throws Exception { - ClassFile classFile = ClassFile.read(cfile); - for (Attribute attr : classFile.attributes) { - if (attr.getName(classFile.constant_pool).equals("BootstrapMethods")) { - BootstrapMethods_attribute bsmAttr = (BootstrapMethods_attribute)attr; - BootstrapMethodSpecifier bsmSpecifier = bsmAttr.bootstrap_method_specifiers[0]; - Assert.check(classFile.constant_pool.get(bsmSpecifier.bootstrap_arguments[0]) instanceof CONSTANT_MethodType_info); - Assert.check(classFile.constant_pool.get(bsmSpecifier.bootstrap_arguments[1]) instanceof CONSTANT_MethodHandle_info); - Assert.check(classFile.constant_pool.get(bsmSpecifier.bootstrap_arguments[2]) instanceof CONSTANT_MethodType_info); - Assert.check(classFile.constant_pool.get(bsmSpecifier.bootstrap_arguments[3]) instanceof CONSTANT_Integer_info); - Assert.check(classFile.constant_pool.get(bsmSpecifier.bootstrap_arguments[4]) instanceof CONSTANT_Integer_info); + ClassModel classFile = Classfile.of().parse(cfile.toPath()); + for (Attribute attr : classFile.attributes()) { + if (attr instanceof BootstrapMethodsAttribute bsmAttr) { + BootstrapMethodEntry bsmSpecifier = bsmAttr.bootstrapMethods().getFirst(); + Assert.check(bsmSpecifier.arguments().get(0) instanceof MethodTypeEntry); + Assert.check(bsmSpecifier.arguments().get(1) instanceof MethodHandleEntry); + Assert.check(bsmSpecifier.arguments().get(2) instanceof MethodTypeEntry); + Assert.check(bsmSpecifier.arguments().get(3) instanceof IntegerEntry); + Assert.check(bsmSpecifier.arguments().get(4) instanceof IntegerEntry); break; } } diff --git a/test/langtools/tools/javac/T8209173/CodeCompletionExceptTest.java b/test/langtools/tools/javac/T8209173/CodeCompletionExceptTest.java index ea2f1ddac2a..3106c765a44 100644 --- a/test/langtools/tools/javac/T8209173/CodeCompletionExceptTest.java +++ b/test/langtools/tools/javac/T8209173/CodeCompletionExceptTest.java @@ -26,7 +26,12 @@ * @bug 8209173 * @summary javac fails with completion exception while reporting an error * @library /tools/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util diff --git a/test/langtools/tools/javac/T8222949/TestConstantDynamic.java b/test/langtools/tools/javac/T8222949/TestConstantDynamic.java index 6772c24275c..dc34716e544 100644 --- a/test/langtools/tools/javac/T8222949/TestConstantDynamic.java +++ b/test/langtools/tools/javac/T8222949/TestConstantDynamic.java @@ -26,7 +26,12 @@ * @bug 8222949 * @summary add condy support to javac's pool API * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.file @@ -40,6 +45,7 @@ import java.io.IOException; import java.io.InputStream; +import javax.lang.model.type.TypeKind; import javax.tools.JavaFileObject; import com.sun.source.tree.*; @@ -47,14 +53,10 @@ import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; import com.sun.source.util.TreeScanner; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.LineNumberTable_attribute; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.*; +import jdk.internal.classfile.instruction.ConstantInstruction; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.*; @@ -74,6 +76,8 @@ import combo.ComboTestHelper; import combo.ComboInstance; import combo.ComboTask.Result; +import static java.lang.invoke.MethodHandleInfo.REF_invokeStatic; + public class TestConstantDynamic extends ComboInstance { enum ConstantType implements ComboParameter { @@ -172,10 +176,10 @@ public class TestConstantDynamic extends ComboInstance { return; } try (InputStream is = res.get().iterator().next().openInputStream()){ - ClassFile cf = ClassFile.read(is); - Method testMethod = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals("test")) { + ClassModel cf = Classfile.of().parse(is.readAllBytes()); + MethodModel testMethod = null; + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString("test")) { testMethod = m; break; } @@ -184,90 +188,79 @@ public class TestConstantDynamic extends ComboInstance { fail("Test method not found"); return; } - Code_attribute ea = - (Code_attribute)testMethod.attributes.get(Attribute.Code); - if (testMethod == null) { + CodeAttribute ea = testMethod.findAttribute(Attributes.CODE).orElse(null); + if (ea == null) { fail("Code attribute for test() method not found"); return; } - int bsmIdx = -1; + BootstrapMethodEntry bootstrapMethodEntry = null; - for (Instruction i : ea.getInstructions()) { - if (i.getMnemonic().equals("ldc")) { - CONSTANT_Dynamic_info condyInfo = (CONSTANT_Dynamic_info)cf.constant_pool.get(i.getByte(1)); - bsmIdx = condyInfo.bootstrap_method_attr_index; - System.out.println("condyInfo.getNameAndTypeInfo().getType() " + condyInfo.getNameAndTypeInfo().getType()); - if (!condyInfo.getNameAndTypeInfo().getType().equals(type.bytecodeTypeStr)) { - fail("type mismatch for CONSTANT_Dynamic_info"); + for (CodeElement i : ea.elementList()) { + if (i instanceof ConstantInstruction.LoadConstantInstruction lci) { + ConstantDynamicEntry condyInfo = (ConstantDynamicEntry)lci.constantEntry(); + bootstrapMethodEntry = condyInfo.bootstrap(); + System.out.println("condyInfo.getNameAndTypeInfo().getType() " + condyInfo.type().stringValue()); + if (!condyInfo.type().equalsString(type.bytecodeTypeStr)) { + fail("type mismatch for ConstantDynamicEntry"); return; } } } - if (bsmIdx == -1) { + if (bootstrapMethodEntry == null) { fail("Missing constantdynamic in generated code"); return; } - BootstrapMethods_attribute bsm_attr = - (BootstrapMethods_attribute)cf - .getAttribute(Attribute.BootstrapMethods); - if (bsm_attr.bootstrap_method_specifiers.length != 1) { + BootstrapMethodsAttribute bsm_attr = cf.findAttribute(Attributes.BOOTSTRAP_METHODS).orElseThrow(); + if (bsm_attr.bootstrapMethods().size() != 1) { fail("Bad number of method specifiers " + "in BootstrapMethods attribute"); return; } - BootstrapMethods_attribute.BootstrapMethodSpecifier bsm_spec = - bsm_attr.bootstrap_method_specifiers[0]; + BootstrapMethodEntry bsm_spec = + bsm_attr.bootstrapMethods().getFirst(); - CONSTANT_MethodHandle_info bsm_handle = - (CONSTANT_MethodHandle_info)cf.constant_pool - .get(bsm_spec.bootstrap_method_ref); + MethodHandleEntry bsm_handle = bsm_spec.bootstrapMethod(); - if (bsm_handle.reference_kind != RefKind.REF_invokeStatic) { + if (bsm_handle.kind() != REF_invokeStatic) { fail("Bad kind on boostrap method handle"); return; } - CONSTANT_Methodref_info bsm_ref = - (CONSTANT_Methodref_info)cf.constant_pool - .get(bsm_handle.reference_index); + MemberRefEntry bsm_ref = bsm_handle.reference(); - if (!bsm_ref.getClassInfo().getName().equals("Test")) { + if (!bsm_ref.owner().name().equalsString("Test")) { fail("Bad owner of boostrap method"); return; } - if (!bsm_ref.getNameAndTypeInfo().getName().equals("bsm")) { + if (!bsm_ref.name().equalsString("bsm")) { fail("Bad boostrap method name"); return; } - if (!bsm_ref.getNameAndTypeInfo() - .getType().equals(asBSMSignatureString())) { + if (!bsm_ref.type().equalsString(asBSMSignatureString())) { fail("Bad boostrap method type" + - bsm_ref.getNameAndTypeInfo().getType() + " " + + bsm_ref.type() + " " + asBSMSignatureString()); return; } - LineNumberTable_attribute lnt = - (LineNumberTable_attribute)ea.attributes.get(Attribute.LineNumberTable); + LineNumberTableAttribute lnt = ea.findAttribute(Attributes.LINE_NUMBER_TABLE).orElse(null); if (lnt == null) { fail("No LineNumberTable attribute"); return; } - if (lnt.line_number_table_length != 2) { + if (lnt.lineNumbers().size() != 2) { fail("Wrong number of entries in LineNumberTable"); - return; } } catch (Exception e) { e.printStackTrace(); fail("error reading classfile: " + res.compilationInfo()); - return; } } diff --git a/test/langtools/tools/javac/TryWithResources/TwrSimpleClose.java b/test/langtools/tools/javac/TryWithResources/TwrSimpleClose.java index c0e440f62d6..d2911d72e3a 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrSimpleClose.java +++ b/test/langtools/tools/javac/TryWithResources/TwrSimpleClose.java @@ -26,7 +26,12 @@ * @bug 8194978 * @summary Verify than an appropriate number of close method invocations is generated. * @library /tools/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox TwrSimpleClose * @run main TwrSimpleClose */ @@ -52,14 +57,10 @@ import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Methodref_info; -import com.sun.tools.classfile.ConstantPool.CONSTANT_NameAndType_info; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Opcode; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.MemberRefEntry; +import jdk.internal.classfile.instruction.InvokeInstruction; import toolbox.ToolBox; @@ -101,17 +102,14 @@ public class TwrSimpleClose { } byte[] data = fm.classBytes.values().iterator().next(); - ClassFile cf = ClassFile.read(new ByteArrayInputStream(data)); + ClassModel cf = Classfile.of().parse(new ByteArrayInputStream(data).readAllBytes()); - for (Method m : cf.methods) { - Code_attribute codeAttr = (Code_attribute) m.attributes.map.get(Attribute.Code); - for (Instruction i : codeAttr.getInstructions()) { - if (i.getOpcode() == Opcode.INVOKEVIRTUAL) { - CONSTANT_Methodref_info method = - (CONSTANT_Methodref_info) cf.constant_pool.get(i.getShort(1)); - CONSTANT_NameAndType_info nameAndType = - cf.constant_pool.getNameAndTypeInfo(method.name_and_type_index); - if ("close".equals(nameAndType.getName())) { + for (MethodModel m : cf.methods()) { + CodeAttribute codeAttr = m.findAttribute(Attributes.CODE).orElseThrow(); + for (CodeElement ce : codeAttr.elementList()) { + if (ce instanceof InvokeInstruction ins && ins.opcode() == Opcode.INVOKEVIRTUAL) { + MemberRefEntry method = ins.method(); + if (method.name().equalsString("close")) { closeCount++; } } diff --git a/test/langtools/tools/javac/annotations/ApplicableAnnotationsOnRecords.java b/test/langtools/tools/javac/annotations/ApplicableAnnotationsOnRecords.java index da5c6746047..fcca8563ae0 100644 --- a/test/langtools/tools/javac/annotations/ApplicableAnnotationsOnRecords.java +++ b/test/langtools/tools/javac/annotations/ApplicableAnnotationsOnRecords.java @@ -27,13 +27,19 @@ * @bug 8241312 8246774 * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.util - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @run main ApplicableAnnotationsOnRecords */ -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; import com.sun.tools.javac.util.Assert; import java.lang.annotation.*; import java.io.InputStream; +import java.util.Objects; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) @@ -54,30 +60,30 @@ public record ApplicableAnnotationsOnRecords(@FieldAnnotation @MethodAnnotation public static void main(String... args) throws Exception { try ( InputStream in = ApplicableAnnotationsOnRecords.class.getResourceAsStream("ApplicableAnnotationsOnRecords.class")) { - ClassFile cf = ClassFile.read(in); - Assert.check(cf.methods.length > 5); - for (Method m : cf.methods) { - String methodName = m.getName(cf.constant_pool); + ClassModel cm = Classfile.of().parse(Objects.requireNonNull(in).readAllBytes()); + Assert.check(cm.methods().size() > 5); + for (MethodModel mm : cm.methods()) { + String methodName = mm.methodName().stringValue(); if (methodName.equals("toString") || methodName.equals("hashCode") || methodName.equals("equals") || methodName.equals("main")) { // ignore } else if (methodName.equals("")) { - var paAnnos = ((RuntimeVisibleParameterAnnotations_attribute) m.attributes.get(Attribute.RuntimeVisibleParameterAnnotations)).parameter_annotations; - Assert.check(paAnnos.length > 0); + var paAnnos = mm.findAttribute(Attributes.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS).orElseThrow().parameterAnnotations(); + Assert.check(paAnnos.size() > 0); for (var pa : paAnnos) { - Assert.check(pa.length == 1); - Assert.check(cf.constant_pool.getUTF8Value(pa[0].type_index).equals("LParameterAnnotation;")); + Assert.check(pa.size() == 1); + Assert.check(Objects.equals(pa.get(0).classSymbol().descriptorString(), "LParameterAnnotation;")); } } else { - var annos = ((RuntimeAnnotations_attribute) m.attributes.get(Attribute.RuntimeVisibleAnnotations)).annotations; - Assert.check(annos.length == 1); - Assert.check(cf.constant_pool.getUTF8Value(annos[0].type_index).equals("LMethodAnnotation;")); + var annos = mm.findAttribute(Attributes.RUNTIME_VISIBLE_ANNOTATIONS).orElseThrow().annotations(); + Assert.check(annos.size() == 1); + Assert.check(Objects.equals(annos.get(0).classSymbol().descriptorString(), "LMethodAnnotation;")); } } - Assert.check(cf.fields.length > 0); - for (Field field : cf.fields) { - var annos = ((RuntimeAnnotations_attribute) field.attributes.get(Attribute.RuntimeVisibleAnnotations)).annotations; - Assert.check(annos.length == 1); - Assert.check(cf.constant_pool.getUTF8Value(annos[0].type_index).equals("LFieldAnnotation;")); + Assert.check(cm.fields().size() > 0); + for (FieldModel fm : cm.fields()) { + var annos = fm.findAttribute(Attributes.RUNTIME_VISIBLE_ANNOTATIONS).orElseThrow().annotations(); + Assert.check(annos.size() == 1); + Assert.check(Objects.equals(annos.getFirst().classSymbol().descriptorString(), "LFieldAnnotation;")); } } } diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java b/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java index 551bd981c21..a0257ef1e17 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/TypeAnnotationsPositionsOnRecords.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, 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 @@ -27,7 +27,12 @@ * @summary Verify location of type annotations on records * @library /tools/lib * @modules - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.code @@ -45,7 +50,8 @@ import java.nio.file.Paths; import java.lang.annotation.*; import java.util.Arrays; -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import com.sun.tools.javac.util.Assert; import toolbox.JavacTask; @@ -109,11 +115,11 @@ public class TypeAnnotationsPositionsOnRecords { } void checkClassFile(final File cfile, int... taPositions) throws Exception { - ClassFile classFile = ClassFile.read(cfile); + ClassModel classFile = Classfile.of().parse(cfile.toPath()); int accessorPos = 0; int checkedAccessors = 0; - for (Method method : classFile.methods) { - String methodName = method.getName(classFile.constant_pool); + for (MethodModel method : classFile.methods()) { + String methodName = method.methodName().stringValue(); if (methodName.equals("toString") || methodName.equals("hashCode") || methodName.equals("equals")) { // ignore continue; @@ -138,15 +144,16 @@ public class TypeAnnotationsPositionsOnRecords { * there can be several parameters annotated we have to check that the ones annotated are the * expected ones */ - void checkConstructor(ClassFile classFile, Method method, int... positions) throws Exception { + void checkConstructor(ClassModel classFile, MethodModel method, int... positions) throws Exception { List annos = new ArrayList<>(); findAnnotations(classFile, method, annos); Assert.check(annos.size() == positions.length); int i = 0; for (int pos : positions) { TypeAnnotation ta = annos.get(i); - Assert.check(ta.position.type.toString().equals("METHOD_FORMAL_PARAMETER")); - Assert.check(ta.position.parameter_index == pos); + Assert.check(ta.targetInfo().targetType().name().equals("METHOD_FORMAL_PARAMETER")); + assert ta.targetInfo() instanceof TypeAnnotation.FormalParameterTarget; + Assert.check(((TypeAnnotation.FormalParameterTarget)ta.targetInfo()).formalParameterIndex() == pos); i++; } } @@ -155,25 +162,25 @@ public class TypeAnnotationsPositionsOnRecords { * this case is simpler as there can only be one annotation at the accessor and it has to be applied * at the return type */ - void checkAccessor(ClassFile classFile, Method method) { + void checkAccessor(ClassModel classFile, MethodModel method) { List annos = new ArrayList<>(); findAnnotations(classFile, method, annos); Assert.check(annos.size() == 1); TypeAnnotation ta = annos.get(0); - Assert.check(ta.position.type.toString().equals("METHOD_RETURN")); + Assert.check(ta.targetInfo().targetType().name().equals("METHOD_RETURN")); } /* * here we have to check that only the fields for which its position matches with the one of the * original annotated record component are annotated */ - void checkFields(ClassFile classFile, int... positions) { + void checkFields(ClassModel classFile, int... positions) { if (positions != null && positions.length > 0) { int fieldPos = 0; int annotationPos = 0; int currentAnnoPosition = positions[annotationPos]; int annotatedFields = 0; - for (Field field : classFile.fields) { + for (FieldModel field : classFile.fields()) { List annos = new ArrayList<>(); findAnnotations(classFile, field, annos); if (fieldPos != currentAnnoPosition) { @@ -181,7 +188,7 @@ public class TypeAnnotationsPositionsOnRecords { } else { Assert.check(annos.size() == 1); TypeAnnotation ta = annos.get(0); - Assert.check(ta.position.type.toString().equals("FIELD")); + Assert.check(ta.targetInfo().targetType().name().equals("FIELD")); annotationPos++; currentAnnoPosition = annotationPos < positions.length ? positions[annotationPos] : -1; annotatedFields++; @@ -193,47 +200,36 @@ public class TypeAnnotationsPositionsOnRecords { } // utility methods - void findAnnotations(ClassFile cf, Method m, List annos) { - findAnnotations(cf, m, Attribute.RuntimeVisibleTypeAnnotations, annos); - findAnnotations(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, annos); + void findAnnotations(ClassModel cm, AttributedElement m, List annos) { + findAnnotations(cm, m, Attributes.RUNTIME_VISIBLE_TYPE_ANNOTATIONS, annos); + findAnnotations(cm, m, Attributes.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS, annos); } - void findAnnotations(ClassFile cf, Field m, List annos) { - findAnnotations(cf, m, Attribute.RuntimeVisibleTypeAnnotations, annos); - findAnnotations(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, annos); - } - - void findAnnotations(ClassFile cf, Method m, String name, List annos) { - int index = m.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = m.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); - } - - int cindex = m.attributes.getIndex(cf.constant_pool, Attribute.Code); - if (cindex != -1) { - Attribute cattr = m.attributes.get(cindex); - assert cattr instanceof Code_attribute; - Code_attribute cAttr = (Code_attribute)cattr; - index = cAttr.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = cAttr.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); + > void findAnnotations(ClassModel cf, AttributedElement m, AttributeMapper attrName, List annos) { + Attribute attr = m.findAttribute(attrName).orElse(null); + addAnnos(annos, attr); + if (m instanceof MethodModel) { + CodeAttribute cattr = m.findAttribute(Attributes.CODE).orElse(null); + if (cattr != null) { + attr = cattr.findAttribute(attrName).orElse(null); + addAnnos(annos, attr); } } } - void findAnnotations(ClassFile cf, Field m, String name, List annos) { - int index = m.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = m.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); + private > void addAnnos(List annos, Attribute attr) { + if (attr != null) { + switch (attr) { + case RuntimeVisibleTypeAnnotationsAttribute vanno -> { + annos.addAll(vanno.annotations()); + } + case RuntimeInvisibleTypeAnnotationsAttribute ivanno -> { + annos.addAll(ivanno.annotations()); + } + default -> { + throw new AssertionError(); + } + } } } } diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/VariablesDeclaredWithVarTest.java b/test/langtools/tools/javac/annotations/typeAnnotations/VariablesDeclaredWithVarTest.java index 071b3fbeeed..f49304de688 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/VariablesDeclaredWithVarTest.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/VariablesDeclaredWithVarTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, 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 @@ -27,7 +27,12 @@ * @summary check that potentially applicable type annotations are skip if the variable or parameter was declared with var * @library /tools/lib * @modules - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.code @@ -45,7 +50,8 @@ import java.nio.file.Paths; import java.lang.annotation.*; import java.util.Arrays; -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import com.sun.tools.javac.util.Assert; import toolbox.JavacTask; @@ -97,41 +103,45 @@ public class VariablesDeclaredWithVarTest { } void checkClassFile(final File cfile, int... taPositions) throws Exception { - ClassFile classFile = ClassFile.read(cfile); + ClassModel classFile = Classfile.of().parse(cfile.toPath()); List annos = new ArrayList<>(); - for (Method method : classFile.methods) { + for (MethodModel method : classFile.methods()) { findAnnotations(classFile, method, annos); - String methodName = method.getName(classFile.constant_pool); + String methodName = method.methodName().stringValue(); Assert.check(annos.size() == 0, "there shouldn't be any type annotations in any method, found " + annos.size() + " type annotations at method " + methodName); } } - void findAnnotations(ClassFile cf, Method m, List annos) { - findAnnotations(cf, m, Attribute.RuntimeVisibleTypeAnnotations, annos); - findAnnotations(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, annos); + void findAnnotations(ClassModel cf, MethodModel m, List annos) { + findAnnotations(cf, m, Attributes.RUNTIME_VISIBLE_TYPE_ANNOTATIONS, annos); + findAnnotations(cf, m, Attributes.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS, annos); } - void findAnnotations(ClassFile cf, Method m, String name, List annos) { - int index = m.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = m.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); + > void findAnnotations(ClassModel cf, AttributedElement m, AttributeMapper attrName, List annos) { + Attribute attr = m.findAttribute(attrName).orElse(null); + addAnnos(annos, attr); + if (m instanceof MethodModel) { + CodeAttribute cattr = m.findAttribute(Attributes.CODE).orElse(null); + if (cattr != null) { + attr = cattr.findAttribute(attrName).orElse(null); + addAnnos(annos, attr); + } } + } - int cindex = m.attributes.getIndex(cf.constant_pool, Attribute.Code); - if (cindex != -1) { - Attribute cattr = m.attributes.get(cindex); - assert cattr instanceof Code_attribute; - Code_attribute cAttr = (Code_attribute)cattr; - index = cAttr.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = cAttr.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); + private > void addAnnos(List annos, Attribute attr) { + if (attr != null) { + switch (attr) { + case RuntimeVisibleTypeAnnotationsAttribute vanno -> { + annos.addAll(vanno.annotations()); + } + case RuntimeInvisibleTypeAnnotationsAttribute ivanno -> { + annos.addAll(ivanno.annotations()); + } + default -> { + throw new AssertionError(); + } } } } diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ClassExtends.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ClassExtends.java index 091d45c9196..d99f66e4e69 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ClassExtends.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ClassExtends.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 8164519 * @summary Test population of reference info for class extends clauses - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java ClassExtends.java * @run main Driver ClassExtends */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ClassTypeParam.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ClassTypeParam.java index 8894e210222..4b9524fc621 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ClassTypeParam.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ClassTypeParam.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test population of reference info for class type parameters - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java ClassTypeParam.java * @run main Driver ClassTypeParam */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ConstructorInvocationTypeArgument.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ConstructorInvocationTypeArgument.java index 2d83f123d32..2522164a798 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ConstructorInvocationTypeArgument.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ConstructorInvocationTypeArgument.java @@ -25,12 +25,17 @@ * @test * @bug 8042451 * @summary Test population of reference info for constructor invocation type argument - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java ConstructorInvocationTypeArgument.java * @run main Driver ConstructorInvocationTypeArgument */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT; +import static jdk.internal.classfile.TypeAnnotation.TargetType.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT; public class ConstructorInvocationTypeArgument { diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Constructors.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Constructors.java index 4044b2a816a..9e76c3c0503 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Constructors.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Constructors.java @@ -25,12 +25,17 @@ * @test * @bug 8026791 8042451 * @summary Test population of reference info for constructor results - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java Constructors.java * @run main Driver Constructors */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; public class Constructors { diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Driver.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Driver.java index af4b15ba536..16559d03a48 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Driver.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Driver.java @@ -21,6 +21,7 @@ * questions. */ +import jdk.internal.classfile.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -29,16 +30,8 @@ import java.io.PrintStream; import java.io.PrintWriter; import java.lang.annotation.*; import java.lang.reflect.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.TypeAnnotation; -import com.sun.tools.classfile.TypeAnnotation.TargetType; +import java.util.*; +import java.util.stream.Collectors; import static java.lang.String.format; @@ -53,7 +46,7 @@ public class Driver { } public static void main(String[] args) throws Exception { - if (args.length == 0 || args.length > 1) + if (args.length != 1) throw new IllegalArgumentException("Usage: java Driver "); String name = args[0]; new Driver(Class.forName(name)).runDriver(); @@ -74,7 +67,7 @@ public class Driver { // Find methods for (Method method : clazz.getMethods()) { try { - Map expected = expectedOf(method); + Map expected = expectedOf(method); if (expected == null) continue; if (method.getReturnType() != String.class) @@ -84,15 +77,15 @@ public class Driver { for (String retentionPolicy : retentionPolicies) { String testClassName = getTestClassName(method, retentionPolicy); String testClass = testClassOf(method, testClassName); - String fullFile = wrap(compact, new HashMap() {{ + String fullFile = wrap(compact, new HashMap<>() {{ put("%RETENTION_POLICY%", retentionPolicy); put("%TEST_CLASS_NAME%", testClassName); }}); for (String[] extraParams : extraParamsCombinations) { try { - ClassFile cf = compileAndReturn(fullFile, testClass, extraParams); - List actual = ReferenceInfoUtil.extendedAnnotationsOf(cf); - ReferenceInfoUtil.compare(expected, actual, cf); + ClassModel cm = compileAndReturn(fullFile, testClass, extraParams); + List actual = ReferenceInfoUtil.extendedAnnotationsOf(cm); + ReferenceInfoUtil.compare(expected, actual); out.format("PASSED: %s %s%n", testClassName, Arrays.toString(extraParams)); ++passed; } catch (Throwable e) { @@ -106,7 +99,7 @@ public class Driver { } } catch (IllegalAccessException | InvocationTargetException e) { out.println("FAILED: " + method.getName()); - out.println(" " + e.toString()); + out.println(" " + e); e.printStackTrace(out); ++failed; } @@ -122,61 +115,35 @@ public class Driver { throw new RuntimeException(failed + " tests failed"); } - private Map expectedOf(Method m) { + private Map expectedOf(Method m) { TADescription ta = m.getAnnotation(TADescription.class); TADescriptions tas = m.getAnnotation(TADescriptions.class); if (ta == null && tas == null) return null; - Map result = + Map result = new HashMap<>(); if (ta != null) - result.putAll(expectedOf(ta)); + result.put(ta.annotation(), wrapTADescription(ta)); if (tas != null) { for (TADescription a : tas.value()) { - result.putAll(expectedOf(a)); + result.put(a.annotation(), wrapTADescription(a)); } } return result; } - - private Map expectedOf(TADescription d) { - String annoName = d.annotation(); - - TypeAnnotation.Position p = new TypeAnnotation.Position(); - p.type = d.type(); - if (d.offset() != NOT_SET) - p.offset = d.offset(); - if (d.lvarOffset().length != 0) - p.lvarOffset = d.lvarOffset(); - if (d.lvarLength().length != 0) - p.lvarLength = d.lvarLength(); - if (d.lvarIndex().length != 0) - p.lvarIndex = d.lvarIndex(); - if (d.boundIndex() != NOT_SET) - p.bound_index = d.boundIndex(); - if (d.paramIndex() != NOT_SET) - p.parameter_index = d.paramIndex(); - if (d.typeIndex() != NOT_SET) - p.type_index = d.typeIndex(); - if (d.exceptionIndex() != NOT_SET) - p.exception_index = d.exceptionIndex(); - if (d.genericLocation().length != 0) { - p.location = TypeAnnotation.Position.getTypePathFromBinary(wrapIntArray(d.genericLocation())); - } - - return Collections.singletonMap(annoName, p); - } - - private List wrapIntArray(int[] ints) { - List list = new ArrayList<>(ints.length); - for (int i : ints) - list.add(i); - return list; + private ReferenceInfoUtil.TAD wrapTADescription(TADescription taD) { + List genericLocation = Arrays.stream(taD.genericLocation()).boxed().collect(Collectors.toList()); + List lvarIndex = Arrays.stream(taD.lvarIndex()).boxed().collect(Collectors.toList()); + List lvarLength = Arrays.stream(taD.lvarLength()).boxed().collect(Collectors.toList()); + List lvarOffset = Arrays.stream(taD.lvarOffset()).boxed().collect(Collectors.toList()); + return new ReferenceInfoUtil.TAD(taD.annotation(), taD.type(), taD.typeIndex(), + taD.paramIndex(), taD.boundIndex(), taD.exceptionIndex(), taD.offset(), + lvarOffset, lvarLength, lvarIndex, genericLocation); } private String getTestClassName(Method m, String retentionPolicy) { @@ -193,10 +160,10 @@ public class Driver { } } - private ClassFile compileAndReturn(String fullFile, String testClass, String... extraParams) throws Exception { + private ClassModel compileAndReturn(String fullFile, String testClass, String... extraParams) throws Exception { File source = writeTestFile(fullFile, testClass); File clazzFile = compileTestFile(source, testClass, extraParams); - return ClassFile.read(clazzFile); + return Classfile.of().parse(clazzFile.toPath()); } protected File writeTestFile(String fullFile, String testClass) throws IOException { @@ -208,14 +175,13 @@ public class Driver { } private String getClassDir() { - return System.getProperty("test.classes", Driver.class.getResource(".").getPath()); + return System.getProperty("test.classes", Objects.requireNonNull(Driver.class.getResource(".")).getPath()); } protected File compileTestFile(File f, String testClass, String... extraParams) { - List options = new ArrayList<>(); - options.addAll(Arrays.asList(extraParams)); + List options = new ArrayList<>(Arrays.asList(extraParams)); options.add(f.getPath()); - int rc = com.sun.tools.javac.Main.compile(options.toArray(new String[options.size()])); + int rc = com.sun.tools.javac.Main.compile(options.toArray(new String[0])); if (rc != 0) throw new Error("compilation failed. rc=" + rc); String path = f.getParent() != null ? f.getParent() : ""; @@ -352,7 +318,7 @@ public class Driver { return src; } - public static final int NOT_SET = -888; + public static final int NOT_SET = Integer.MIN_VALUE; } @@ -362,7 +328,7 @@ public class Driver { @interface TADescription { String annotation(); - TargetType type(); + TypeAnnotation.TargetType type(); int offset() default Driver.NOT_SET; int[] lvarOffset() default { }; int[] lvarLength() default { }; diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ExceptionParameters.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ExceptionParameters.java index 1a18c7ff4f5..3fa4551d1b0 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ExceptionParameters.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ExceptionParameters.java @@ -21,14 +21,19 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8028576 8042451 * @summary Test population of reference info for exception parameters * @author Werner Dietl - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java ExceptionParameters.java * @run main Driver ExceptionParameters */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Fields.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Fields.java index 1eb3cd2d04e..8e7815c2bf2 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Fields.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Fields.java @@ -25,12 +25,17 @@ * @test * @bug 8042451 8208470 * @summary Test population of reference info for field - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java Fields.java * @run main Driver Fields */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; public class Fields { // field types diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/FromSpecification.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/FromSpecification.java index 6f15a723ea1..249b723328b 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/FromSpecification.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/FromSpecification.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test that the examples from the manual are stored as expected - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java FromSpecification.java * @run main Driver FromSpecification */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Initializers.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Initializers.java index 6595692f939..c5de40c0690 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Initializers.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Initializers.java @@ -21,14 +21,19 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8013852 8042451 * @summary Test population of reference info for instance and class initializers * @author Werner Dietl - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java Initializers.java * @run main Driver Initializers */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Lambda.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Lambda.java index 00871c58cab..ccdffbae746 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Lambda.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/Lambda.java @@ -26,14 +26,19 @@ * @bug 8008077 8029721 8042451 8043974 * @summary Test population of reference info for lambda expressions * javac crash for annotated parameter type of lambda in a field - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @ignore 8057687 emit correct byte code an attributes for type annotations * @compile -g Driver.java ReferenceInfoUtil.java Lambda.java * @run main Driver Lambda * @author Werner Dietl */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; public class Lambda { diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodInvocationTypeArgument.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodInvocationTypeArgument.java index 66756f91961..5be36df634e 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodInvocationTypeArgument.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodInvocationTypeArgument.java @@ -25,12 +25,17 @@ * @test * @bug 8042451 * @summary Test population of reference info for method invocation type arguments - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java MethodInvocationTypeArgument.java * @run main Driver MethodInvocationTypeArgument */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.METHOD_INVOCATION_TYPE_ARGUMENT; +import static jdk.internal.classfile.TypeAnnotation.TargetType.METHOD_INVOCATION_TYPE_ARGUMENT; import static java.lang.System.lineSeparator; public class MethodInvocationTypeArgument { diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodParameters.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodParameters.java index 2aa84c0e605..b06ad3cec96 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodParameters.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodParameters.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test population of reference info for method parameters - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java MethodParameters.java * @run main Driver MethodParameters */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodReceivers.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodReceivers.java index 515c2f14605..f6c15b5a0d0 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodReceivers.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodReceivers.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test population of reference info for method receivers - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java MethodReceivers.java * @run main Driver MethodReceivers */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodReturns.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodReturns.java index f69f8386964..ebc9217946c 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodReturns.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodReturns.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test population of reference info for method return - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java MethodReturns.java * @run main Driver MethodReturns */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodThrows.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodThrows.java index ef2c1bf51a4..83b0d2e95e2 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodThrows.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodThrows.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test population of reference info for method exception clauses - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java MethodThrows.java * @run main Driver MethodThrows */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodTypeParam.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodTypeParam.java index 573222855d9..a4a267b83f6 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodTypeParam.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MethodTypeParam.java @@ -21,14 +21,19 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; import static java.lang.System.lineSeparator; /* * @test * @bug 8042451 * @summary Test population of reference info for method type parameters - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java MethodTypeParam.java * @run main Driver MethodTypeParam */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MultiCatch.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MultiCatch.java index 67c5d405c0a..b1a395aa81c 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MultiCatch.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/MultiCatch.java @@ -21,14 +21,19 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8006732 8006775 8042451 * @summary Test population of reference info for multicatch exception parameters * @author Werner Dietl - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java MultiCatch.java * @run main Driver MultiCatch */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/NestedTypes.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/NestedTypes.java index 3d630b3fb5c..5ba71a33ab9 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/NestedTypes.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/NestedTypes.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 8044009 8044010 * @summary Test population of reference info for nested types - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @ignore 8057687 emit correct byte code an attributes for type annotations * @compile -g Driver.java ReferenceInfoUtil.java NestedTypes.java * @run main Driver NestedTypes diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/NewObjects.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/NewObjects.java index d66f8164549..ba7581df340 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/NewObjects.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/NewObjects.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test population of reference info for new object creations - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java NewObjects.java * @run main Driver NewObjects */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ReferenceInfoUtil.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ReferenceInfoUtil.java index 8ed09252894..51772f2e460 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ReferenceInfoUtil.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ReferenceInfoUtil.java @@ -21,102 +21,126 @@ * questions. */ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.TypeAnnotation; -import com.sun.tools.classfile.Field; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.RuntimeTypeAnnotations_attribute; -import com.sun.tools.classfile.ConstantPool.InvalidIndex; -import com.sun.tools.classfile.ConstantPool.UnexpectedEntry; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import java.util.*; public class ReferenceInfoUtil { - public static final int IGNORE_VALUE = -321; + public static final int IGNORE_VALUE = Integer.MIN_VALUE; - public static List extendedAnnotationsOf(ClassFile cf) { - List annos = new ArrayList<>(); - findAnnotations(cf, annos); + public static List extendedAnnotationsOf(ClassModel cm) { + List annos = new ArrayList<>(); + findAnnotations(cm, annos); return annos; } /////////////////// Extract type annotations ////////////////// - private static void findAnnotations(ClassFile cf, List annos) { - findAnnotations(cf, Attribute.RuntimeVisibleTypeAnnotations, annos); - findAnnotations(cf, Attribute.RuntimeInvisibleTypeAnnotations, annos); + private static void findAnnotations(ClassModel cm, List annos) { + findAnnotations(cm, Attributes.RUNTIME_VISIBLE_TYPE_ANNOTATIONS, annos); + findAnnotations(cm, Attributes.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS, annos); - for (Field f : cf.fields) { - findAnnotations(cf, f, annos); + for (FieldModel f : cm.fields()) { + findAnnotations(f, annos); } - for (Method m: cf.methods) { - findAnnotations(cf, m, annos); + for (MethodModel m: cm.methods()) { + findAnnotations(m, annos); } } - private static void findAnnotations(ClassFile cf, Method m, List annos) { - findAnnotations(cf, m, Attribute.RuntimeVisibleTypeAnnotations, annos); - findAnnotations(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, annos); - } - - private static void findAnnotations(ClassFile cf, Field m, List annos) { - findAnnotations(cf, m, Attribute.RuntimeVisibleTypeAnnotations, annos); - findAnnotations(cf, m, Attribute.RuntimeInvisibleTypeAnnotations, annos); + private static void findAnnotations(AttributedElement ae, List annos) { + findAnnotations(ae, Attributes.RUNTIME_VISIBLE_TYPE_ANNOTATIONS, annos); + findAnnotations(ae, Attributes.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS, annos); } // test the result of Attributes.getIndex according to expectations // encoded in the method's name - private static void findAnnotations(ClassFile cf, String name, List annos) { - int index = cf.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = cf.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); + private static > void findAnnotations(ClassModel cm, AttributeMapper attrName, List annos) { + Attribute attr = cm.findAttribute(attrName).orElse(null); + if (attr != null) { + if (attr instanceof RuntimeVisibleTypeAnnotationsAttribute tAttr) { + annos.addAll(Objects.requireNonNull(generateTADList(tAttr.annotations(), null))); + } else if (attr instanceof RuntimeInvisibleTypeAnnotationsAttribute tAttr) { + annos.addAll(Objects.requireNonNull(generateTADList(tAttr.annotations(), null))); + } else throw new AssertionError(); } } // test the result of Attributes.getIndex according to expectations // encoded in the method's name - private static void findAnnotations(ClassFile cf, Method m, String name, List annos) { - int index = m.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = m.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); + private static > void findAnnotations(AttributedElement m, AttributeMapper attrName, List annos) { + Attribute attr = m.findAttribute(attrName).orElse(null); + if (attr != null) { + if (attr instanceof RuntimeVisibleTypeAnnotationsAttribute tAttr) { + annos.addAll(Objects.requireNonNull(generateTADList(tAttr.annotations(), null))); + } else if (attr instanceof RuntimeInvisibleTypeAnnotationsAttribute tAttr) { + annos.addAll(Objects.requireNonNull(generateTADList(tAttr.annotations(), null))); + } else throw new AssertionError(); } - - int cindex = m.attributes.getIndex(cf.constant_pool, Attribute.Code); - if (cindex != -1) { - Attribute cattr = m.attributes.get(cindex); - assert cattr instanceof Code_attribute; - Code_attribute cAttr = (Code_attribute)cattr; - index = cAttr.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = cAttr.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); + if (m instanceof MethodModel mm) { + CodeAttribute cAttr = mm.findAttribute(Attributes.CODE).orElse(null); + if (cAttr != null) { + Attribute attr2 = cAttr.findAttribute(attrName).orElse(null);; + if (attr2 != null) { + if (attr2 instanceof RuntimeVisibleTypeAnnotationsAttribute tAttr2) { + annos.addAll(Objects.requireNonNull(generateTADList(tAttr2.annotations(), cAttr))); + } else if (attr2 instanceof RuntimeInvisibleTypeAnnotationsAttribute tAttr2) { + annos.addAll(Objects.requireNonNull(generateTADList(tAttr2.annotations(), cAttr))); + } else throw new AssertionError(); + } } } } - // test the result of Attributes.getIndex according to expectations - // encoded in the method's name - private static void findAnnotations(ClassFile cf, Field m, String name, List annos) { - int index = m.attributes.getIndex(cf.constant_pool, name); - if (index != -1) { - Attribute attr = m.attributes.get(index); - assert attr instanceof RuntimeTypeAnnotations_attribute; - RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr; - annos.addAll(Arrays.asList(tAttr.annotations)); + // get each target information and wrap with TAD (corresponding with TADescription in driver class) + private static List generateTADList(List annos, CodeAttribute cAttr) { + List result = new ArrayList<>(); + for (TypeAnnotation anno: annos) { + TAD tad = new TAD(); + tad.annotation = anno.className().stringValue(); + tad.type = anno.targetInfo().targetType(); + switch (anno.targetInfo().targetType()) { + case CAST, CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT, METHOD_INVOCATION_TYPE_ARGUMENT -> { + if (cAttr == null) throw new AssertionError("Invalid Annotation"); + tad.typeIndex = ((TypeAnnotation.TypeArgumentTarget) anno.targetInfo()).typeArgumentIndex(); + tad.offset = cAttr.labelToBci(((TypeAnnotation.TypeArgumentTarget) anno.targetInfo()).target()); + } + case CLASS_EXTENDS -> tad.typeIndex = ((TypeAnnotation.SupertypeTarget) anno.targetInfo()).supertypeIndex(); + case CLASS_TYPE_PARAMETER, METHOD_TYPE_PARAMETER -> tad.paramIndex = ((TypeAnnotation.TypeParameterTarget) anno.targetInfo()).typeParameterIndex(); + case CLASS_TYPE_PARAMETER_BOUND, METHOD_TYPE_PARAMETER_BOUND -> { + tad.paramIndex = ((TypeAnnotation.TypeParameterBoundTarget) anno.targetInfo()).typeParameterIndex(); + tad.boundIndex = ((TypeAnnotation.TypeParameterBoundTarget) anno.targetInfo()).boundIndex(); + } + case EXCEPTION_PARAMETER -> tad.exceptionIndex = ((TypeAnnotation.CatchTarget) anno.targetInfo()).exceptionTableIndex(); + case INSTANCEOF, NEW -> { + if (cAttr == null) throw new AssertionError("Invalid Annotation"); + tad.offset = cAttr.labelToBci(((TypeAnnotation.OffsetTarget) anno.targetInfo()).target()); + } + case LOCAL_VARIABLE, RESOURCE_VARIABLE -> { + if (cAttr == null) throw new AssertionError("Invalid Annotation"); + TypeAnnotation.LocalVarTarget localTarget = (TypeAnnotation.LocalVarTarget) anno.targetInfo(); + for (TypeAnnotation.LocalVarTargetInfo localInfo : localTarget.table()) { + tad.lvarIndex.add(localInfo.index()); + tad.lvarOffset.add(cAttr.labelToBci(localInfo.startLabel())); + tad.lvarLength.add(cAttr.labelToBci(localInfo.endLabel()) - cAttr.labelToBci(localInfo.startLabel())); + } + } + case METHOD_FORMAL_PARAMETER -> tad.paramIndex = ((TypeAnnotation.FormalParameterTarget) anno.targetInfo()).formalParameterIndex(); + case THROWS -> tad.typeIndex = ((TypeAnnotation.ThrowsTarget) anno.targetInfo()).throwsTargetIndex(); + default -> {} + } + for (TypeAnnotation.TypePathComponent pathComponent : anno.targetPath()) { + switch (pathComponent.typePathKind()) { + case ARRAY -> tad.genericLocation.add(0); + case INNER_TYPE -> tad.genericLocation.add(1); + case WILDCARD -> tad.genericLocation.add(2); + case TYPE_ARGUMENT -> tad.genericLocation.add(3); + } + tad.genericLocation.add(pathComponent.typeArgumentIndex()); + } + result.add(tad); } + return result; } /////////////////////// Equality testing ///////////////////// @@ -124,84 +148,98 @@ public class ReferenceInfoUtil { return a == b || a == IGNORE_VALUE || b == IGNORE_VALUE; } - private static boolean areEquals(int[] a, int[] a2) { + private static boolean areEquals(List a, List a2) { if (a==a2) return true; if (a==null || a2==null) return false; - int length = a.length; - if (a2.length != length) + int length = a.size(); + if (a2.size() != length) return false; for (int i=0; i annotations, ClassFile cf) throws InvalidIndex, UnexpectedEntry { + private static TAD findAnnotation(String name, List annotations) { String properName = "L" + name + ";"; - for (TypeAnnotation anno : annotations) { - String actualName = cf.constant_pool.getUTF8Value(anno.annotation.type_index); + for (TAD anno : annotations) { + String actualName = anno.annotation; if (properName.equals(actualName)) return anno; } return null; } - public static boolean compare(Map expectedAnnos, - List actualAnnos, ClassFile cf) throws InvalidIndex, UnexpectedEntry { + public static boolean compare(Map expectedAnnos, + List actualAnnos) { if (actualAnnos.size() != expectedAnnos.size()) { throw new ComparisionException("Wrong number of annotations", expectedAnnos, actualAnnos); } - for (Map.Entry e : expectedAnnos.entrySet()) { - String aName = e.getKey(); - TypeAnnotation.Position expected = e.getValue(); - TypeAnnotation actual = findAnnotation(aName, actualAnnos, cf); - if (actual == null) + for (Map.Entry expectedAno : expectedAnnos.entrySet()) { + String aName = expectedAno.getKey(); + TAD expectedTAD = expectedAno.getValue(); + TAD actualTAD = findAnnotation(aName, actualAnnos); + if (actualTAD == null) throw new ComparisionException("Expected annotation not found: " + aName); - if (!areEquals(expected, actual.position)) { + if (!areEquals(expectedTAD, actualTAD)) { throw new ComparisionException("Unexpected position for annotation : " + aName + - "\n Expected: " + expected.toString() + - "\n Found: " + actual.position.toString()); + "\n Expected: " + expectedTAD + + "\n Found: " + actualTAD); } } return true; } + public static class TAD { + String annotation; + TypeAnnotation.TargetType type; + int typeIndex = IGNORE_VALUE, paramIndex = IGNORE_VALUE, boundIndex = IGNORE_VALUE, exceptionIndex = IGNORE_VALUE, offset = IGNORE_VALUE; + List lvarOffset = new ArrayList<>(), lvarLength = new ArrayList<>(), lvarIndex = new ArrayList<>(), genericLocation = new ArrayList<>(); + public TAD(String a, TypeAnnotation.TargetType t, int tIdx, int pIndx, int bIdx, int eIdx, + int ofs, List lvarOfs, List lvarLen, List lvarIdx, List genericLoc) { + annotation = a; type = t; typeIndex = tIdx; + paramIndex = pIndx; boundIndex = bIdx; exceptionIndex = eIdx; + offset = ofs; lvarOffset = lvarOfs; lvarLength = lvarLen; lvarIndex = lvarIdx; + genericLocation = genericLoc; + } + public TAD() {} + } } class ComparisionException extends RuntimeException { private static final long serialVersionUID = -3930499712333815821L; - public final Map expected; - public final List found; + public final Map expected; + public final List found; public ComparisionException(String message) { this(message, null, null); } - public ComparisionException(String message, Map expected, List found) { + public ComparisionException(String message, Map expected, List found) { super(message); this.expected = expected; this.found = found; diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/RepeatingTypeAnnotations.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/RepeatingTypeAnnotations.java index c16a6be37fd..8d6b8b15ef8 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/RepeatingTypeAnnotations.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/RepeatingTypeAnnotations.java @@ -21,12 +21,17 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @summary Test population of reference info for repeating type annotations - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java RepeatingTypeAnnotations.java * @run main Driver RepeatingTypeAnnotations * @author Werner Dietl diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ResourceVariable.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ResourceVariable.java index 38a41b2ce3e..84fbed87e21 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ResourceVariable.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/ResourceVariable.java @@ -25,12 +25,17 @@ * @test * @bug 8042451 * @summary Test population of reference info for resource variable - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java ResourceVariable.java * @run main Driver ResourceVariable */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.RESOURCE_VARIABLE; +import static jdk.internal.classfile.TypeAnnotation.TargetType.RESOURCE_VARIABLE; import static java.lang.System.lineSeparator; public class ResourceVariable { diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/TypeCasts.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/TypeCasts.java index af86f15df51..acf044af92e 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/TypeCasts.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/TypeCasts.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test population of reference info for type casts - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java TypeCasts.java * @run main Driver TypeCasts */ diff --git a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/TypeTests.java b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/TypeTests.java index 6c068081d34..a1cd7fedccf 100644 --- a/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/TypeTests.java +++ b/test/langtools/tools/javac/annotations/typeAnnotations/referenceinfos/TypeTests.java @@ -21,13 +21,18 @@ * questions. */ -import static com.sun.tools.classfile.TypeAnnotation.TargetType.*; +import static jdk.internal.classfile.TypeAnnotation.TargetType.*; /* * @test * @bug 8042451 * @summary Test population of reference info for class literals - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g Driver.java ReferenceInfoUtil.java TypeTests.java * @run main Driver TypeTests */ diff --git a/test/langtools/tools/javac/cast/intersection/DuplicatedCheckcastTest.java b/test/langtools/tools/javac/cast/intersection/DuplicatedCheckcastTest.java index 166f2377030..affb5a0bc0b 100644 --- a/test/langtools/tools/javac/cast/intersection/DuplicatedCheckcastTest.java +++ b/test/langtools/tools/javac/cast/intersection/DuplicatedCheckcastTest.java @@ -29,7 +29,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main DuplicatedCheckcastTest */ @@ -37,12 +42,10 @@ import java.nio.file.Path; import java.util.ArrayList; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.ClassEntry; +import jdk.internal.classfile.instruction.*; import toolbox.JavacTask; import toolbox.TestRunner; @@ -50,7 +53,7 @@ import toolbox.ToolBox; public class DuplicatedCheckcastTest extends TestRunner { ToolBox tb; - ClassFile cf; + ClassModel cf; public DuplicatedCheckcastTest() { super(System.err); @@ -97,13 +100,13 @@ public class DuplicatedCheckcastTest extends TestRunner { .sources(source) .outdir(curPath) .run(); - cf = ClassFile.read(curPath.resolve("IntersectionTypeTest.class")); + cf = Classfile.of().parse(curPath.resolve("IntersectionTypeTest.class")); ArrayList checkCastList = new ArrayList<>(); - for (Method method : cf.methods) { - if ("test".equals(method.getName(cf.constant_pool))) { - Code_attribute code_attribute = (Code_attribute) method.attributes.get(Attribute.Code); - for (Instruction instruction : code_attribute.getInstructions()) { - if ("checkcast".equals(instruction.getMnemonic())) { + for (MethodModel method : cf.methods()) { + if (method.methodName().equalsString("test")) { + CodeAttribute code_attribute = method.findAttribute(Attributes.CODE).orElseThrow(); + for (CodeElement ce : code_attribute.elementList()) { + if (ce instanceof Instruction instruction && Opcode.CHECKCAST == instruction.opcode()) { checkCastList.add(instruction); } } @@ -117,10 +120,12 @@ public class DuplicatedCheckcastTest extends TestRunner { checkClassName(checkCastList.get(1), expected2); } - public void checkClassName(Instruction ins, String expected) throws Exception { - int classIndex = ins.getUnsignedShort(1); - CONSTANT_Class_info classInfo = cf.constant_pool.getClassInfo(classIndex); - String className = classInfo.getName(); + public void checkClassName(Instruction ins, String expected) { + String className = ""; + if (ins instanceof TypeCheckInstruction typeCheckInstruction) { + ClassEntry classInfo = typeCheckInstruction.type(); + className = classInfo.asInternalName(); + } if (!expected.equals(className)) { throw new AssertionError("The type of the 'checkcast' is not right. Expected: " + expected + ", actual: " + className); diff --git a/test/langtools/tools/javac/classfiles/InnerClasses/SyntheticClasses.java b/test/langtools/tools/javac/classfiles/InnerClasses/SyntheticClasses.java index d08982cd075..d1cdd1985d5 100644 --- a/test/langtools/tools/javac/classfiles/InnerClasses/SyntheticClasses.java +++ b/test/langtools/tools/javac/classfiles/InnerClasses/SyntheticClasses.java @@ -25,45 +25,48 @@ * @bug 8034854 * @summary Verify that the InnerClasses attribute has outer_class_info_index zero if it has * inner_name_index zero (for synthetic classes) - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile SyntheticClasses.java * @run main SyntheticClasses */ import java.io.*; import java.util.*; -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; public class SyntheticClasses { - public static void main(String[] args) throws IOException, ConstantPoolException { + public static void main(String[] args) throws IOException { new SyntheticClasses().run(); } - private void run() throws IOException, ConstantPoolException { + private void run() throws IOException { File testClasses = new File(System.getProperty("test.classes")); - for (File classFile : testClasses.listFiles(f -> f.getName().endsWith(".class"))) { - ClassFile cf = ClassFile.read(classFile); - if (cf.getName().matches(".*\\$[0-9]+")) { - EnclosingMethod_attribute encl = - (EnclosingMethod_attribute) cf.getAttribute(Attribute.EnclosingMethod); + for (File classFile : Objects.requireNonNull(testClasses.listFiles(f -> f.getName().endsWith(".class")))) { + ClassModel cf = Classfile.of().parse(classFile.toPath()); + if (cf.thisClass().asInternalName().matches(".*\\$[0-9]+")) { + EnclosingMethodAttribute encl = cf.findAttribute(Attributes.ENCLOSING_METHOD).orElse(null); if (encl != null) { - if (encl.method_index != 0) - throw new IllegalStateException("Invalid EnclosingMethod.method_index: " + - encl.method_index + "."); + if (encl.enclosingMethodName().isPresent()) + throw new IllegalStateException("Invalid EnclosingMethod.method: " + + encl.enclosingMethodName().get().stringValue() + "."); } } - InnerClasses_attribute attr = - (InnerClasses_attribute) cf.getAttribute(Attribute.InnerClasses); + InnerClassesAttribute attr = cf.findAttribute(Attributes.INNER_CLASSES).orElse(null); if (attr != null) { - for (InnerClasses_attribute.Info info : attr.classes) { - if (cf.major_version < 51) + for (InnerClassInfo info : attr.classes()) { + if (cf.majorVersion() < 51) throw new IllegalStateException(); - if (info.inner_name_index == 0 && info.outer_class_info_index != 0) - throw new IllegalStateException("Invalid outer_class_info_index=" + - info.outer_class_info_index + - "; inner_name_index=" + - info.inner_name_index + "."); + if (info.innerName().isEmpty() && info.outerClass().isPresent() ) + throw new IllegalStateException("Invalid outer_class_info: " + + info.outerClass().get().asInternalName() + + "; inner_name is empty"); } } } diff --git a/test/langtools/tools/javac/classfiles/T8255757/T8255757.java b/test/langtools/tools/javac/classfiles/T8255757/T8255757.java index 4b1b740b94c..411ecca010d 100644 --- a/test/langtools/tools/javac/classfiles/T8255757/T8255757.java +++ b/test/langtools/tools/javac/classfiles/T8255757/T8255757.java @@ -28,16 +28,20 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main T8255757 */ import java.nio.file.Path; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPool.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.constantpool.*; import toolbox.JavacTask; import toolbox.ToolBox; @@ -75,22 +79,17 @@ public class T8255757 extends TestRunner { .outdir(curPath) .run(); - ClassFile cf = ClassFile.read(curPath.resolve("Test.class")); - ConstantPool cp = cf.constant_pool; + ClassModel cf = Classfile.of().parse(curPath.resolve("Test.class")); + ConstantPool cp = cf.constantPool(); int num = 0; - for (CPInfo cpInfo : cp.entries()) { - if (cpInfo instanceof CONSTANT_Methodref_info) { - int class_index = ((CONSTANT_Methodref_info) cpInfo).class_index; - int name_and_type_index = ((CONSTANT_Methodref_info) cpInfo).name_and_type_index; - int class_name_index = ((CONSTANT_Class_info) - cp.getClassInfo(class_index)).name_index; - int method_name_index = ((CONSTANT_NameAndType_info) - cp.getNameAndTypeInfo(name_and_type_index)).name_index; - int method_type_name_index = ((CONSTANT_NameAndType_info) - cp.getNameAndTypeInfo(name_and_type_index)).type_index; - if ("[Ljava/lang/Object;".equals(cp.getUTF8Value(class_name_index)) && - "clone".equals(cp.getUTF8Value(method_name_index)) && - "()Ljava/lang/Object;".equals(cp.getUTF8Value(method_type_name_index))) { + for (int i = 1; i < cp.entryCount(); i += cp.entryByIndex(i).width()) { + if (cp.entryByIndex(i) instanceof MethodRefEntry methodRefEntry) { + String class_name = methodRefEntry.owner().asInternalName(); + String method_name = methodRefEntry.name().stringValue(); + String method_type = methodRefEntry.type().stringValue(); + if ("[Ljava/lang/Object;".equals(class_name) && + "clone".equals(method_name) && + "()Ljava/lang/Object;".equals(method_type)) { ++num; } } diff --git a/test/langtools/tools/javac/classreader/8171132/BadConstantValue.java b/test/langtools/tools/javac/classreader/8171132/BadConstantValue.java index 97985834c67..9fbe9ef4990 100644 --- a/test/langtools/tools/javac/classreader/8171132/BadConstantValue.java +++ b/test/langtools/tools/javac/classreader/8171132/BadConstantValue.java @@ -25,7 +25,12 @@ * @test * @bug 8171132 * @summary Improve class reading of invalid or out-of-range ConstantValue attributes - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.jvm @@ -35,9 +40,7 @@ * @run main BadConstantValue */ -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ClassWriter; -import com.sun.tools.classfile.Field; +import jdk.internal.classfile.*; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.code.ClassFinder.BadClassFile; import com.sun.tools.javac.code.Symtab; @@ -45,11 +48,8 @@ import com.sun.tools.javac.jvm.Target; import com.sun.tools.javac.util.Assert; import com.sun.tools.javac.util.JCDiagnostic; import com.sun.tools.javac.util.Names; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; +import java.io.*; +import java.nio.file.Files; import java.util.Arrays; import java.util.Objects; import javax.tools.JavaCompiler; @@ -185,16 +185,17 @@ public class BadConstantValue { * B's type and A's ConstantValue attribute. */ private static void swapConstantValues(File file) throws Exception { - ClassFile cf = ClassFile.read(file); - Field a = cf.fields[0]; - Field b = cf.fields[1]; - Field[] fields = { - new Field(b.access_flags, b.name_index, b.descriptor, a.attributes), - }; - cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion, Target.JDK1_7.majorVersion, - cf.constant_pool, cf.access_flags, cf.this_class, cf.super_class, cf.interfaces, - fields, cf.methods, cf.attributes); - new ClassWriter().write(cf, file); + ClassModel cf = Classfile.of().parse(file.toPath()); + FieldModel a = cf.fields().getFirst(); + FieldModel b = cf.fields().get(1); + byte[] Bytes = Classfile.of().transform(cf, ClassTransform + .dropping(ce -> ce instanceof ClassfileVersion || ce instanceof FieldModel) + .andThen(ClassTransform.endHandler(classBuilder -> classBuilder + .withField(b.fieldName(), b.fieldType(), fieldBuilder -> { + fieldBuilder.withFlags(b.flags().flagsMask()); + a.attributes().forEach(e -> fieldBuilder.with((FieldElement) e));}) + .withVersion(Target.JDK1_7.majorVersion, Target.JDK1_7.minorVersion)))); + Files.write(file.toPath(), Bytes); } static String compile(String... args) throws Exception { diff --git a/test/langtools/tools/javac/classwriter/IndyCorrectInvocationName.java b/test/langtools/tools/javac/classwriter/IndyCorrectInvocationName.java index 36d7b8c2759..db1c9fd649e 100644 --- a/test/langtools/tools/javac/classwriter/IndyCorrectInvocationName.java +++ b/test/langtools/tools/javac/classwriter/IndyCorrectInvocationName.java @@ -34,7 +34,12 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.tree * jdk.compiler/com.sun.tools.javac.util - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.jdeps/com.sun.tools.javap * @build toolbox.JarTask toolbox.JavacTask toolbox.JavapTask toolbox.ToolBox * @run main IndyCorrectInvocationName @@ -54,13 +59,10 @@ import com.sun.source.util.Plugin; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.CONSTANT_InvokeDynamic_info; -import com.sun.tools.classfile.ConstantPool.CONSTANT_NameAndType_info; -import com.sun.tools.classfile.Instruction; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.*; +import jdk.internal.classfile.instruction.*; import com.sun.tools.javac.api.BasicJavacTask; import com.sun.tools.javac.code.Symbol; @@ -166,34 +168,32 @@ public class IndyCorrectInvocationName implements Plugin { } Path testClass = classes.resolve("Test.class"); - ClassFile cf = ClassFile.read(testClass); - BootstrapMethods_attribute bootAttr = - (BootstrapMethods_attribute) cf.attributes.get(Attribute.BootstrapMethods); - if (bootAttr.bootstrap_method_specifiers.length != 1) { + ClassModel cf = Classfile.of().parse(testClass); + BootstrapMethodsAttribute bootAttr = cf.findAttribute(Attributes.BOOTSTRAP_METHODS).orElseThrow(); + if (bootAttr.bootstrapMethodsSize() != 1) { throw new AssertionError("Incorrect number of bootstrap methods: " + - bootAttr.bootstrap_method_specifiers.length); + bootAttr.bootstrapMethodsSize()); } - Code_attribute codeAttr = - (Code_attribute) cf.methods[1].attributes.get(Attribute.Code); - Set seenBootstraps = new HashSet<>(); - Set seenNameAndTypes = new HashSet<>(); + CodeAttribute codeAttr = cf.methods().get(1).findAttribute(Attributes.CODE).orElseThrow(); + Set seenBootstraps = new HashSet<>(); + Set seenNameAndTypes = new HashSet<>(); Set seenNames = new HashSet<>(); - for (Instruction i : codeAttr.getInstructions()) { - switch (i.getOpcode()) { - case INVOKEDYNAMIC -> { - int idx = i.getUnsignedShort(1); - CONSTANT_InvokeDynamic_info dynamicInfo = - (CONSTANT_InvokeDynamic_info) cf.constant_pool.get(idx); - seenBootstraps.add(dynamicInfo.bootstrap_method_attr_index); - seenNameAndTypes.add(dynamicInfo.name_and_type_index); - CONSTANT_NameAndType_info nameAndTypeInfo = - cf.constant_pool.getNameAndTypeInfo(dynamicInfo.name_and_type_index); - seenNames.add(nameAndTypeInfo.getName()); + for (CodeElement i : codeAttr.elementList()) { + if (i instanceof Instruction instruction) { + switch (instruction ) { + case InvokeDynamicInstruction indy -> { + InvokeDynamicEntry dynamicInfo = indy.invokedynamic(); + seenBootstraps.add(dynamicInfo.bootstrap()); + seenNameAndTypes.add(dynamicInfo.nameAndType()); + NameAndTypeEntry nameAndTypeInfo = dynamicInfo.nameAndType(); + seenNames.add(nameAndTypeInfo.name().stringValue()); + } + case ReturnInstruction returnInstruction -> { + } + default -> throw new AssertionError("Unexpected instruction: " + instruction.opcode()); } - case RETURN -> {} - default -> throw new AssertionError("Unexpected instruction: " + i.getOpcode()); - } } + } if (seenBootstraps.size() != 1) { throw new AssertionError("Unexpected bootstraps: " + seenBootstraps); } diff --git a/test/langtools/tools/javac/code/CharImmediateValue.java b/test/langtools/tools/javac/code/CharImmediateValue.java index 38745358be0..891883f77b4 100644 --- a/test/langtools/tools/javac/code/CharImmediateValue.java +++ b/test/langtools/tools/javac/code/CharImmediateValue.java @@ -34,7 +34,12 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.tree * jdk.compiler/com.sun.tools.javac.util - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.jdeps/com.sun.tools.javap * @build toolbox.JarTask toolbox.JavacTask toolbox.JavapTask toolbox.ToolBox * @compile CharImmediateValue.java @@ -53,11 +58,8 @@ import com.sun.source.util.Plugin; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Opcode; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCIdent; @@ -134,12 +136,11 @@ public class CharImmediateValue implements Plugin { } Path testClass = classes.resolve("Test.class"); - ClassFile cf = ClassFile.read(testClass); - Code_attribute codeAttr = - (Code_attribute) cf.methods[1].attributes.get(Attribute.Code); + ClassModel cf = Classfile.of().parse(testClass); + CodeAttribute codeAttr = cf.methods().get(1).findAttribute(Attributes.CODE).orElseThrow(); boolean seenCast = false; - for (Instruction i : codeAttr.getInstructions()) { - if (i.getOpcode() == Opcode.I2C) { + for (CodeElement i : codeAttr.elementList()) { + if (i instanceof Instruction ins && ins.opcode() == Opcode.I2C) { seenCast = true; } } diff --git a/test/langtools/tools/javac/defaultMethods/BadClassfile.java b/test/langtools/tools/javac/defaultMethods/BadClassfile.java index 0c12913dadd..bdfdbf9647a 100644 --- a/test/langtools/tools/javac/defaultMethods/BadClassfile.java +++ b/test/langtools/tools/javac/defaultMethods/BadClassfile.java @@ -26,7 +26,12 @@ * @bug 8025087 * @summary Verify that pre-JDK8 classfiles with default and/or static methods * are refused correctly. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.comp @@ -37,7 +42,7 @@ * @run main BadClassfile */ -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.code.ClassFinder.BadClassFile; import com.sun.tools.javac.code.Symbol; @@ -59,15 +64,9 @@ public class BadClassfile { private static void test(String classname, String expected) throws Exception { File classfile = new File(System.getProperty("test.classes", "."), classname + ".class"); - ClassFile cf = ClassFile.read(classfile); - - cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion, - Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags, - cf.this_class, cf.super_class, cf.interfaces, cf.fields, - cf.methods, cf.attributes); - - new ClassWriter().write(cf, classfile); - + ClassModel cf = Classfile.of().parse(classfile.toPath()); + Classfile.of().transform(cf, ClassTransform.dropping(ce -> ce instanceof ClassfileVersion) + .andThen(ClassTransform.endHandler(classBuilder -> classBuilder.withVersion(Target.JDK1_7.majorVersion, Target.JDK1_7.minorVersion)))); JavaCompiler c = ToolProvider.getSystemJavaCompiler(); JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null); Symtab syms = Symtab.instance(task.getContext()); diff --git a/test/langtools/tools/javac/defaultMethods/CheckACC_STRICTFlagOnDefaultMethodTest.java b/test/langtools/tools/javac/defaultMethods/CheckACC_STRICTFlagOnDefaultMethodTest.java index b177a12a505..f1cb54b41ac 100644 --- a/test/langtools/tools/javac/defaultMethods/CheckACC_STRICTFlagOnDefaultMethodTest.java +++ b/test/langtools/tools/javac/defaultMethods/CheckACC_STRICTFlagOnDefaultMethodTest.java @@ -25,23 +25,21 @@ * @test * @bug 8012723 * @summary strictfp interface misses strictfp modifer on default method - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -source 16 -target 16 CheckACC_STRICTFlagOnDefaultMethodTest.java * @run main CheckACC_STRICTFlagOnDefaultMethodTest */ -import java.util.ArrayList; -import java.util.List; +import jdk.internal.classfile.*; import java.io.File; import java.io.IOException; - -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Descriptor; -import com.sun.tools.classfile.Descriptor.InvalidDescriptor; -import com.sun.tools.classfile.Method; - -import static com.sun.tools.classfile.AccessFlags.ACC_STRICT; +import java.util.ArrayList; +import java.util.List; public class CheckACC_STRICTFlagOnDefaultMethodTest { private static final String AssertionErrorMessage = @@ -52,13 +50,11 @@ public class CheckACC_STRICTFlagOnDefaultMethodTest { private List errors = new ArrayList<>(); - public static void main(String[] args) - throws IOException, ConstantPoolException, InvalidDescriptor { + public static void main(String[] args) throws IOException { new CheckACC_STRICTFlagOnDefaultMethodTest().run(); } - private void run() - throws IOException, ConstantPoolException, InvalidDescriptor { + private void run() throws IOException { String testClasses = System.getProperty("test.classes"); check(testClasses, "CheckACC_STRICTFlagOnDefaultMethodTest$StrictfpInterface.class"); @@ -70,19 +66,15 @@ public class CheckACC_STRICTFlagOnDefaultMethodTest { } } - void check(String dir, String... fileNames) - throws - IOException, - ConstantPoolException, - Descriptor.InvalidDescriptor { + void check(String dir, String... fileNames) throws IOException { for (String fileName : fileNames) { - ClassFile classFileToCheck = ClassFile.read(new File(dir, fileName)); + ClassModel classFileToCheck = Classfile.of().parse(new File(dir, fileName).toPath()); - for (Method method : classFileToCheck.methods) { - if ((method.access_flags.flags & ACC_STRICT) == 0) { + for (MethodModel method : classFileToCheck.methods()) { + if ((method.flags().flagsMask() & Classfile.ACC_STRICT) == 0) { errors.add(String.format(offendingMethodErrorMessage, - method.getName(classFileToCheck.constant_pool), - classFileToCheck.getName())); + method.methodName().stringValue(), + classFileToCheck.thisClass().asInternalName())); } } } diff --git a/test/langtools/tools/javac/defaultMethods/TestDefaultBody.java b/test/langtools/tools/javac/defaultMethods/TestDefaultBody.java index adefc901397..e44c819e615 100644 --- a/test/langtools/tools/javac/defaultMethods/TestDefaultBody.java +++ b/test/langtools/tools/javac/defaultMethods/TestDefaultBody.java @@ -25,18 +25,18 @@ * @test * @bug 7192246 * @summary check that code attributed for default methods is correctly generated - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl */ -import com.sun.tools.classfile.AccessFlags; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; - -import com.sun.tools.classfile.Opcode; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.MemberRefEntry; +import jdk.internal.classfile.instruction.InvokeInstruction; import java.io.*; public class TestDefaultBody { @@ -67,12 +67,12 @@ public class TestDefaultBody { void verifyDefaultBody(File f) { System.err.println("verify: " + f); try { - ClassFile cf = ClassFile.read(f); - Method testMethod = null; - Code_attribute codeAttr = null; - for (Method m : cf.methods) { - codeAttr = (Code_attribute)m.attributes.get(Attribute.Code); - String mname = m.getName(cf.constant_pool); + ClassModel cf = Classfile.of().parse(f.toPath()); + MethodModel testMethod = null; + CodeAttribute codeAttr = null; + for (MethodModel m : cf.methods()) { + codeAttr = m.findAttribute(Attributes.CODE).orElse(null); + String mname = m.methodName().stringValue(); if (mname.equals(TEST_METHOD_NAME)) { testMethod = m; break; @@ -83,7 +83,7 @@ public class TestDefaultBody { if (testMethod == null) { throw new Error("Test method not found"); } - if (testMethod.access_flags.is(AccessFlags.ACC_ABSTRACT)) { + if ((testMethod.flags().flagsMask() & Classfile.ACC_ABSTRACT) != 0) { throw new Error("Test method is abstract"); } if (codeAttr == null) { @@ -91,14 +91,13 @@ public class TestDefaultBody { } boolean found = false; - for (Instruction instr : codeAttr.getInstructions()) { - if (instr.getOpcode() == Opcode.INVOKESTATIC) { + for (CodeElement instr : codeAttr.elementList()) { + if (instr instanceof InvokeInstruction ins && ins.opcode() == Opcode.INVOKESTATIC) { found = true; - int pc_index = instr.getShort(1); - CONSTANT_Methodref_info mref = (CONSTANT_Methodref_info)cf.constant_pool.get(pc_index); - String className = mref.getClassName(); - String targetName = mref.getNameAndTypeInfo().getName(); - String targetType = mref.getNameAndTypeInfo().getType(); + MemberRefEntry mref = ins.method(); + String className = mref.owner().asInternalName(); + String targetName = mref.name().stringValue(); + String targetType = mref.type().stringValue(); if (!className.equals(TARGET_CLASS_NAME)) { throw new Error("unexpected class in default method body " + className); diff --git a/test/langtools/tools/javac/defaultMethods/TestNoBridgeOnDefaults.java b/test/langtools/tools/javac/defaultMethods/TestNoBridgeOnDefaults.java index 3372049b49b..bdf88fb341d 100644 --- a/test/langtools/tools/javac/defaultMethods/TestNoBridgeOnDefaults.java +++ b/test/langtools/tools/javac/defaultMethods/TestNoBridgeOnDefaults.java @@ -25,12 +25,15 @@ * @test * @bug 7192246 * @summary check that javac does not generate bridge methods for defaults - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl */ -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; import java.io.*; @@ -71,9 +74,9 @@ public class TestNoBridgeOnDefaults { void checkNoBridgeOnDefaults(File f) { System.err.println("check: " + f); try { - ClassFile cf = ClassFile.read(f); - for (Method m : cf.methods) { - String mname = m.getName(cf.constant_pool); + ClassModel cf = Classfile.of().parse(f.toPath()); + for (MethodModel m : cf.methods()) { + String mname = m.methodName().stringValue(); if (mname.equals(TEST_METHOD_NAME)) { throw new Error("unexpected bridge method found " + m); } diff --git a/test/langtools/tools/javac/defaultMethods/super/TestDirectSuperInterfaceInvoke.java b/test/langtools/tools/javac/defaultMethods/super/TestDirectSuperInterfaceInvoke.java index b9c0d4aff96..6886107e5ab 100644 --- a/test/langtools/tools/javac/defaultMethods/super/TestDirectSuperInterfaceInvoke.java +++ b/test/langtools/tools/javac/defaultMethods/super/TestDirectSuperInterfaceInvoke.java @@ -25,19 +25,21 @@ * @test * @bug 8027281 * @summary As per JVMS 4.9.2, invokespecial can only refer to direct superinterfaces - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile TestDirectSuperInterfaceInvoke.java * @run main TestDirectSuperInterfaceInvoke */ import java.io.File; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.CPRefInfo; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Opcode; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.MemberRefEntry; +import jdk.internal.classfile.instruction.InvokeInstruction; interface BaseInterface { public default int testedMethod(){ return 1; } @@ -86,14 +88,13 @@ public class TestDirectSuperInterfaceInvoke { String workDir = System.getProperty("test.classes"); File file = new File(workDir, classFile); try { - final ClassFile cf = ClassFile.read(file); - for (Method m : cf.methods) { - Code_attribute codeAttr = (Code_attribute)m.attributes.get(Attribute.Code); - for (Instruction instr : codeAttr.getInstructions()) { - if (instr.getOpcode() == Opcode.INVOKESPECIAL) { - int pc_index = instr.getShort(1); - CPRefInfo ref = (CPRefInfo)cf.constant_pool.get(pc_index); - String className = ref.getClassName(); + final ClassModel cf = Classfile.of().parse(file.toPath()); + for (MethodModel m : cf.methods()) { + CodeAttribute codeAttr = m.findAttribute(Attributes.CODE).orElseThrow(); + for (CodeElement ce : codeAttr.elementList()) { + if (ce instanceof InvokeInstruction instr && instr.opcode() == Opcode.INVOKESPECIAL) { + MemberRefEntry ref = instr.method(); + String className = ref.owner().asInternalName(); if (className.equals("BaseInterface")) throw new IllegalStateException("Must not directly refer to TestedInterface"); } diff --git a/test/langtools/tools/javac/diags/CheckResourceKeys.java b/test/langtools/tools/javac/diags/CheckResourceKeys.java index b404d568fc3..b3bb06ba3e4 100644 --- a/test/langtools/tools/javac/diags/CheckResourceKeys.java +++ b/test/langtools/tools/javac/diags/CheckResourceKeys.java @@ -27,14 +27,20 @@ * @summary need test program to validate javac resource bundles * @modules jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.resources:open - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl */ import java.io.*; import java.util.*; import java.util.regex.*; import javax.tools.*; -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.constantpool.*; import com.sun.tools.javac.code.Lint.LintCategory; /** @@ -490,10 +496,10 @@ public class CheckResourceKeys { */ void scan(JavaFileObject fo, Set results) throws IOException { try (InputStream in = fo.openInputStream()) { - ClassFile cf = ClassFile.read(in); - for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) { - if (cpinfo.getTag() == ConstantPool.CONSTANT_Utf8) { - String v = ((ConstantPool.CONSTANT_Utf8_info) cpinfo).value; + ClassModel cm = Classfile.of().parse(in.readAllBytes()); + for (int i = 1; i < cm.constantPool().entryCount(); ++i) { + if (cm.constantPool().entryByIndex(i) instanceof Utf8Entry entry) { + String v = entry.stringValue(); if (v.matches("[A-Za-z0-9-_.]+")) results.add(v); } diff --git a/test/langtools/tools/javac/diags/Example.java b/test/langtools/tools/javac/diags/Example.java index dbba0318136..6b6013b61ca 100644 --- a/test/langtools/tools/javac/diags/Example.java +++ b/test/langtools/tools/javac/diags/Example.java @@ -297,8 +297,12 @@ class Example implements Comparable { // source for import statements or a magic comment for (File pf: procFiles) { if (pf.getName().equals("CreateBadClassFile.java")) { - pOpts.add("--add-modules=jdk.jdeps"); - pOpts.add("--add-exports=jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED"); + pOpts.add("--add-exports=java.base/jdk.internal.classfile=ALL-UNNAMED"); + pOpts.add("--add-exports=java.base/jdk.internal.classfile.attribute=ALL-UNNAMED"); + pOpts.add("--add-exports=java.base/jdk.internal.classfile.constantpool=ALL-UNNAMED"); + pOpts.add("--add-exports=java.base/jdk.internal.classfile.instruction=ALL-UNNAMED"); + pOpts.add("--add-exports=java.base/jdk.internal.classfile.components=ALL-UNNAMED"); + pOpts.add("--add-exports=java.base/jdk.internal.classfile.impl=ALL-UNNAMED"); } } diff --git a/test/langtools/tools/javac/diags/examples/BadConstantValueType/BadConstantValueType.java b/test/langtools/tools/javac/diags/examples/BadConstantValueType/BadConstantValueType.java index 602b95d30e0..b57f2e62d86 100644 --- a/test/langtools/tools/javac/diags/examples/BadConstantValueType/BadConstantValueType.java +++ b/test/langtools/tools/javac/diags/examples/BadConstantValueType/BadConstantValueType.java @@ -25,7 +25,7 @@ // key: compiler.misc.bad.class.file.header // key: compiler.err.cant.access // options: -processor CreateBadClassFile -// run: exec --add-exports jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED +// run: exec --add-exports java.base/jdk.internal.classfile=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.attribute=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.constantpool=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.instruction=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.components=ALL-UNNAMED /* The annotation processor will create an invalid classfile with a static * final field of type java.lang.Object having ConstantValue attribute with diff --git a/test/langtools/tools/javac/diags/examples/BadConstantValueType/processors/CreateBadClassFile.java b/test/langtools/tools/javac/diags/examples/BadConstantValueType/processors/CreateBadClassFile.java index d6f6e4519e6..24935e6207e 100644 --- a/test/langtools/tools/javac/diags/examples/BadConstantValueType/processors/CreateBadClassFile.java +++ b/test/langtools/tools/javac/diags/examples/BadConstantValueType/processors/CreateBadClassFile.java @@ -22,16 +22,19 @@ */ import java.io.*; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDesc; +import java.lang.constant.ConstantDescs; +import java.lang.constant.MethodTypeDesc; import java.util.*; import javax.annotation.processing.*; import javax.lang.model.*; import javax.lang.model.element.*; import javax.tools.*; +import java.lang.reflect.AccessFlag; -import com.sun.tools.classfile.*; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Utf8_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; +import jdk.internal.classfile.Classfile; +import jdk.internal.classfile.attribute.ConstantValueAttribute; /* Create an invalid classfile with a static final field of type object with * ConstantValue of type String. @@ -40,42 +43,21 @@ import com.sun.tools.classfile.ConstantPool.CPInfo; public class CreateBadClassFile extends AbstractProcessor { public boolean process(Set elems, RoundEnvironment renv) { if (++round == 1) { - ConstantPool cp = new ConstantPool(new CPInfo[] { - new CONSTANT_Utf8_info(""), //0 - new CONSTANT_Utf8_info("Test"), //1 - new CONSTANT_Class_info(null, 1), //2 - new CONSTANT_Utf8_info("java/lang/Object"), //3 - new CONSTANT_Class_info(null, 3), //4 - new CONSTANT_Utf8_info("test"), //5 - new CONSTANT_Utf8_info("Ljava/lang/Object;"), //6 - new CONSTANT_Utf8_info("ConstantValue"), //7 + byte[] bytes = Classfile.of().build(ClassDesc.of("Test"), cb -> { + cb.withSuperclass(ConstantDescs.CD_Object); + cb.withVersion(51, 0); + cb.withFlags(AccessFlag.ABSTRACT , + AccessFlag.INTERFACE , + AccessFlag.PUBLIC); + cb.withField("test", ConstantDescs.CD_Object, fieldBuilder -> { + fieldBuilder.withFlags(AccessFlag.PUBLIC, AccessFlag.STATIC, AccessFlag.FINAL); + fieldBuilder.with(ConstantValueAttribute.of("ConstantValue")); + }); }); - ClassFile cf = new ClassFile(0xCAFEBABE, - 0, - 51, - cp, - new AccessFlags(AccessFlags.ACC_ABSTRACT | - AccessFlags.ACC_INTERFACE | - AccessFlags.ACC_PUBLIC), - 2, - 4, - new int[0], - new Field[] { - new Field(new AccessFlags(AccessFlags.ACC_PUBLIC | - AccessFlags.ACC_STATIC | - AccessFlags.ACC_FINAL), - 5, - new Descriptor(6), - new Attributes(cp, new Attribute[] { - new ConstantValue_attribute(7, 6) - })) - }, - new Method[0], - new Attributes(cp, new Attribute[0])); try { JavaFileObject clazz = processingEnv.getFiler().createClassFile("Test"); try (OutputStream out = clazz.openOutputStream()) { - new ClassWriter().write(cf, out); + out.write(bytes); } } catch (IOException ex) { ex.printStackTrace(); diff --git a/test/langtools/tools/javac/diags/examples/InvalidDefaultInterface/InvalidDefaultInterface.java b/test/langtools/tools/javac/diags/examples/InvalidDefaultInterface/InvalidDefaultInterface.java index 9159e0f5bed..0b1899e151c 100644 --- a/test/langtools/tools/javac/diags/examples/InvalidDefaultInterface/InvalidDefaultInterface.java +++ b/test/langtools/tools/javac/diags/examples/InvalidDefaultInterface/InvalidDefaultInterface.java @@ -25,7 +25,7 @@ // key: compiler.misc.bad.class.file.header // key: compiler.err.cant.access // options: -processor CreateBadClassFile -// run: exec --add-exports jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED +// run: exec --add-exports java.base/jdk.internal.classfile=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.attribute=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.constantpool=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.instruction=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.components=ALL-UNNAMED /* The annotation processor will create an invalid classfile with version 51.0 * and a non-abstract method in an interface. Loading the classfile will produce diff --git a/test/langtools/tools/javac/diags/examples/InvalidDefaultInterface/processors/CreateBadClassFile.java b/test/langtools/tools/javac/diags/examples/InvalidDefaultInterface/processors/CreateBadClassFile.java index 202f6fe1f74..fd3c8046b44 100644 --- a/test/langtools/tools/javac/diags/examples/InvalidDefaultInterface/processors/CreateBadClassFile.java +++ b/test/langtools/tools/javac/diags/examples/InvalidDefaultInterface/processors/CreateBadClassFile.java @@ -22,54 +22,35 @@ */ import java.io.*; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDescs; +import java.lang.constant.MethodTypeDesc; import java.util.*; import javax.annotation.processing.*; import javax.lang.model.*; import javax.lang.model.element.*; import javax.tools.*; +import java.lang.reflect.AccessFlag; -import com.sun.tools.classfile.*; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Utf8_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; +import jdk.internal.classfile.Classfile; /* Create an invalid classfile with version 51.0 and a non-abstract method in an interface.*/ @SupportedAnnotationTypes("*") public class CreateBadClassFile extends AbstractProcessor { public boolean process(Set elems, RoundEnvironment renv) { if (++round == 1) { - ConstantPool cp = new ConstantPool(new CPInfo[] { - new CONSTANT_Utf8_info(""), //0 - new CONSTANT_Utf8_info("Test"), //1 - new CONSTANT_Class_info(null, 1), //2 - new CONSTANT_Utf8_info("java/lang/Object"), //3 - new CONSTANT_Class_info(null, 3), //4 - new CONSTANT_Utf8_info("test"), //5 - new CONSTANT_Utf8_info("()V"), //6 - }); - ClassFile cf = new ClassFile(0xCAFEBABE, - 0, - 51, - cp, - new AccessFlags(AccessFlags.ACC_ABSTRACT | - AccessFlags.ACC_INTERFACE | - AccessFlags.ACC_PUBLIC), - 2, - 4, - new int[0], - new Field[0], - new Method[] { - //creating non-abstract method in 51.0 classfile: - new Method(new AccessFlags(AccessFlags.ACC_PUBLIC), - 5, - new Descriptor(6), - new Attributes(cp, new Attribute[0])) - }, - new Attributes(cp, new Attribute[0])); + byte[] bytes = Classfile.of().build(ClassDesc.of("Test"), classBuilder -> { + classBuilder.withVersion(51, 0); + classBuilder.withFlags(AccessFlag.ABSTRACT , + AccessFlag.INTERFACE , + AccessFlag.PUBLIC); + classBuilder.withMethod("test", MethodTypeDesc.of(ConstantDescs.CD_void), Classfile.ACC_PUBLIC, methodBuilder -> { + methodBuilder.withFlags(AccessFlag.PUBLIC);}); + }); try { JavaFileObject clazz = processingEnv.getFiler().createClassFile("Test"); try (OutputStream out = clazz.openOutputStream()) { - new ClassWriter().write(cf, out); + out.write(bytes); } } catch (IOException ex) { ex.printStackTrace(); diff --git a/test/langtools/tools/javac/diags/examples/InvalidStaticInterface/InvalidStaticInterface.java b/test/langtools/tools/javac/diags/examples/InvalidStaticInterface/InvalidStaticInterface.java index e637d6a37ec..084b6698503 100644 --- a/test/langtools/tools/javac/diags/examples/InvalidStaticInterface/InvalidStaticInterface.java +++ b/test/langtools/tools/javac/diags/examples/InvalidStaticInterface/InvalidStaticInterface.java @@ -25,7 +25,7 @@ // key: compiler.misc.bad.class.file.header // key: compiler.err.cant.access // options: -processor CreateBadClassFile -// run: exec --add-exports jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED +// run: exec --add-exports java.base/jdk.internal.classfile=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.attribute=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.constantpool=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.instruction=ALL-UNNAMED --add-exports java.base/jdk.internal.classfile.components=ALL-UNNAMED /* The annotation processor will create an invalid classfile with version 51.0 * and a static method in an interface. Loading the classfile will produce diff --git a/test/langtools/tools/javac/diags/examples/InvalidStaticInterface/processors/CreateBadClassFile.java b/test/langtools/tools/javac/diags/examples/InvalidStaticInterface/processors/CreateBadClassFile.java index 3d9675661c9..d1b3e29f521 100644 --- a/test/langtools/tools/javac/diags/examples/InvalidStaticInterface/processors/CreateBadClassFile.java +++ b/test/langtools/tools/javac/diags/examples/InvalidStaticInterface/processors/CreateBadClassFile.java @@ -22,55 +22,40 @@ */ import java.io.*; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDescs; +import java.lang.constant.MethodTypeDesc; import java.util.*; import javax.annotation.processing.*; import javax.lang.model.*; import javax.lang.model.element.*; import javax.tools.*; -import com.sun.tools.classfile.*; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Utf8_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; +import java.lang.reflect.AccessFlag; +import jdk.internal.classfile.Classfile; /* Create an invalid classfile with version 51.0 and a static method in an interface.*/ @SupportedAnnotationTypes("*") public class CreateBadClassFile extends AbstractProcessor { public boolean process(Set elems, RoundEnvironment renv) { if (++round == 1) { - ConstantPool cp = new ConstantPool(new CPInfo[] { - new CONSTANT_Utf8_info(""), //0 - new CONSTANT_Utf8_info("Test"), //1 - new CONSTANT_Class_info(null, 1), //2 - new CONSTANT_Utf8_info("java/lang/Object"), //3 - new CONSTANT_Class_info(null, 3), //4 - new CONSTANT_Utf8_info("test"), //5 - new CONSTANT_Utf8_info("()V"), //6 + byte[] bytes = Classfile.of().build(ClassDesc.of("Test"), classBuilder -> { + classBuilder.withVersion(51, 0); + classBuilder.withFlags(AccessFlag.ABSTRACT, + AccessFlag.INTERFACE, + AccessFlag.PUBLIC); + classBuilder.withSuperclass(ConstantDescs.CD_Object); + classBuilder.withMethod("test", ConstantDescs.MTD_void, + Classfile.ACC_PUBLIC | Classfile.ACC_STATIC, methodBuilder -> { + methodBuilder.withCode(xb -> { + xb.return_(); + }); + }); }); - ClassFile cf = new ClassFile(0xCAFEBABE, - 0, - 51, - cp, - new AccessFlags(AccessFlags.ACC_ABSTRACT | - AccessFlags.ACC_INTERFACE | - AccessFlags.ACC_PUBLIC), - 2, - 4, - new int[0], - new Field[0], - new Method[] { - //creating static method in 51.0 classfile: - new Method(new AccessFlags(AccessFlags.ACC_PUBLIC | - AccessFlags.ACC_STATIC), - 5, - new Descriptor(6), - new Attributes(cp, new Attribute[0])) - }, - new Attributes(cp, new Attribute[0])); try { JavaFileObject clazz = processingEnv.getFiler().createClassFile("Test"); try (OutputStream out = clazz.openOutputStream()) { - new ClassWriter().write(cf, out); + out.write(bytes); } } catch (IOException ex) { ex.printStackTrace(); diff --git a/test/langtools/tools/javac/expression/_super/NonDirectSuper/NonDirectSuper.java b/test/langtools/tools/javac/expression/_super/NonDirectSuper/NonDirectSuper.java index bcb1f16926d..d19be79c6e4 100644 --- a/test/langtools/tools/javac/expression/_super/NonDirectSuper/NonDirectSuper.java +++ b/test/langtools/tools/javac/expression/_super/NonDirectSuper/NonDirectSuper.java @@ -26,7 +26,12 @@ * @bug 8027789 * @summary check that the direct superclass is used as the site when calling * a superclass' method - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile Base.java NonDirectSuper.java * @run main test.NonDirectSuper */ @@ -35,13 +40,11 @@ package test; import java.io.File; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.CPRefInfo; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Opcode; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.MemberRefEntry; +import jdk.internal.classfile.instruction.FieldInstruction; +import jdk.internal.classfile.instruction.InvokeInstruction; public class NonDirectSuper { public static void main(String... args) { @@ -60,16 +63,15 @@ public class NonDirectSuper { void verifyInvokeSpecialRefToObject(File clazz) { try { - final ClassFile cf = ClassFile.read(clazz); - for (Method m : cf.methods) { - Code_attribute codeAttr = (Code_attribute)m.attributes.get(Attribute.Code); - for (Instruction instr : codeAttr.getInstructions()) { - if (instr.getOpcode() == Opcode.INVOKESPECIAL || - instr.getOpcode() == Opcode.INVOKEVIRTUAL) { - int pc_index = instr.getShort(1); - CPRefInfo ref = (CPRefInfo)cf.constant_pool.get(pc_index); - String className = ref.getClassName(); - String methodName = ref.getNameAndTypeInfo().getName(); + final ClassModel cf = Classfile.of().parse(clazz.toPath()); + for (MethodModel m : cf.methods()) { + CodeAttribute codeAttr = m.findAttribute(Attributes.CODE).orElseThrow(); + for (CodeElement ce : codeAttr.elementList()) { + if (ce instanceof InvokeInstruction instr && (instr.opcode() == Opcode.INVOKESPECIAL || + instr.opcode() == Opcode.INVOKEVIRTUAL)) { + MemberRefEntry ref = instr.method(); + String className = ref.owner().asInternalName(); + String methodName = ref.name().stringValue(); if (methodName.equals("toString")) { if (!className.equals("java/lang/Object")) throw new IllegalStateException("Must directly refer to j.l.Object"); @@ -81,12 +83,10 @@ public class NonDirectSuper { } } } - if (instr.getOpcode() == Opcode.GETFIELD || - instr.getOpcode() == Opcode.PUTFIELD) { - int pc_index = instr.getShort(1); - CPRefInfo ref = (CPRefInfo)cf.constant_pool.get(pc_index); - String className = ref.getClassName(); - String fieldName = ref.getNameAndTypeInfo().getName(); + if (ce instanceof FieldInstruction instr && (instr.opcode() == Opcode.GETFIELD || + instr.opcode() == Opcode.PUTFIELD)) { + String className = instr.owner().asInternalName(); + String fieldName = instr.field().name().stringValue(); if (fieldName.startsWith("refTo")) { String expectedClass = fieldName.substring("refTo".length()); if (!className.replace("/", "").equals(expectedClass)) { diff --git a/test/langtools/tools/javac/file/SymLinkArchiveTest.java b/test/langtools/tools/javac/file/SymLinkArchiveTest.java index 2cd8d0381a4..adce7b9cc97 100644 --- a/test/langtools/tools/javac/file/SymLinkArchiveTest.java +++ b/test/langtools/tools/javac/file/SymLinkArchiveTest.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox * @run main SymLinkArchiveTest */ diff --git a/test/langtools/tools/javac/file/SymLinkShortNameTest.java b/test/langtools/tools/javac/file/SymLinkShortNameTest.java index 9aa9b562d51..991e6824795 100644 --- a/test/langtools/tools/javac/file/SymLinkShortNameTest.java +++ b/test/langtools/tools/javac/file/SymLinkShortNameTest.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox * @run main SymLinkShortNameTest */ diff --git a/test/langtools/tools/javac/file/SymLinkTest.java b/test/langtools/tools/javac/file/SymLinkTest.java index 176b03e20b0..c0afdd6da01 100644 --- a/test/langtools/tools/javac/file/SymLinkTest.java +++ b/test/langtools/tools/javac/file/SymLinkTest.java @@ -30,7 +30,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox * @run main SymLinkTest */ @@ -40,9 +45,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.SourceFile_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.SourceFileAttribute; import toolbox.JavacTask; import toolbox.TestRunner; import toolbox.TestRunner.Test; @@ -94,9 +98,9 @@ public class SymLinkTest extends TestRunner { .run() .writeAll(); - ClassFile cf = ClassFile.read(classes.resolve("HelloWorld.class")); - SourceFile_attribute sf = (SourceFile_attribute) cf.attributes.get(Attribute.SourceFile); - String sourceFile = sf.getSourceFile(cf.constant_pool); + ClassModel cf = Classfile.of().parse(classes.resolve("HelloWorld.class")); + SourceFileAttribute sf = cf.findAttribute(Attributes.SOURCE_FILE).orElseThrow(); + String sourceFile = sf.sourceFile().stringValue(); if (!"HelloWorld.java".equals(sourceFile)) { throw new AssertionError("Unexpected SourceFile attribute value: " + sourceFile); diff --git a/test/langtools/tools/javac/flow/LVTHarness.java b/test/langtools/tools/javac/flow/LVTHarness.java index aa4cf2706d8..9ca53642641 100644 --- a/test/langtools/tools/javac/flow/LVTHarness.java +++ b/test/langtools/tools/javac/flow/LVTHarness.java @@ -28,7 +28,12 @@ * javac crash while creating LVT entry for a local variable defined in * an inner block * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build JavacTestingAbstractProcessor LVTHarness * @run main LVTHarness */ @@ -54,19 +59,10 @@ import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.InvalidIndex; -import com.sun.tools.classfile.ConstantPool.UnexpectedEntry; -import com.sun.tools.classfile.Descriptor.InvalidDescriptor; -import com.sun.tools.classfile.LocalVariableTable_attribute; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import static javax.tools.StandardLocation.*; -import static com.sun.tools.classfile.LocalVariableTable_attribute.Entry; import static javax.tools.JavaFileObject.Kind.SOURCE; public class LVTHarness { @@ -79,10 +75,10 @@ public class LVTHarness { public static void main(String[] args) throws Exception { try { String testDir = System.getProperty("test.src"); - fm.setLocation(SOURCE_PATH, Arrays.asList(new File(testDir, "tests"))); + fm.setLocation(SOURCE_PATH, List.of(new File(testDir, "tests"))); // Make sure classes are written to scratch dir. - fm.setLocation(CLASS_OUTPUT, Arrays.asList(new File("."))); + fm.setLocation(CLASS_OUTPUT, List.of(new File("."))); for (JavaFileObject jfo : fm.list(SOURCE_PATH, "", Collections.singleton(SOURCE), true)) { new LVTHarness(jfo).check(); @@ -129,31 +125,27 @@ public class LVTHarness { } } - void checkClassFile(File file) - throws IOException, ConstantPoolException, InvalidDescriptor { - ClassFile classFile = ClassFile.read(file); - ConstantPool constantPool = classFile.constant_pool; + void checkClassFile(File file) throws IOException { + ClassModel classFile = Classfile.of().parse(file.toPath()); //lets get all the methods in the class file. - for (Method method : classFile.methods) { + for (MethodModel method : classFile.methods()) { for (ElementKey elementKey: aliveRangeMap.keySet()) { - String methodDesc = method.getName(constantPool) + - method.descriptor.getParameterTypes(constantPool).replace(" ", ""); + String methodDesc = method.methodName().stringValue() + + parse(method.methodTypeSymbol().descriptorString()).replace(" ", ""); if (methodDesc.equals(elementKey.elem.toString())) { - checkMethod(constantPool, method, aliveRangeMap.get(elementKey)); + checkMethod(method, aliveRangeMap.get(elementKey)); seenAliveRanges.add(elementKey); } } } } - void checkMethod(ConstantPool constantPool, Method method, AliveRanges ranges) - throws InvalidIndex, UnexpectedEntry, ConstantPoolException { - Code_attribute code = (Code_attribute) method.attributes.get(Attribute.Code); - LocalVariableTable_attribute lvt = - (LocalVariableTable_attribute) (code.attributes.get(Attribute.LocalVariableTable)); + void checkMethod(MethodModel method, AliveRanges ranges) { + CodeAttribute code = method.findAttribute(Attributes.CODE).orElseThrow(); + LocalVariableTableAttribute lvt = code.findAttribute(Attributes.LOCAL_VARIABLE_TABLE).orElseThrow(); List infoFromRanges = convertToStringList(ranges); - List infoFromLVT = convertToStringList(constantPool, lvt); + List infoFromLVT = convertToStringList(lvt); // infoFromRanges most be contained in infoFromLVT int i = 0; @@ -170,7 +162,7 @@ public class LVTHarness { } if (i < infoFromRanges.size()) { - error(infoFromLVT, infoFromRanges, method.getName(constantPool).toString()); + error(infoFromLVT, infoFromRanges, method.methodName().stringValue()); } } @@ -186,12 +178,11 @@ public class LVTHarness { return result; } - List convertToStringList(ConstantPool constantPool, - LocalVariableTable_attribute lvt) throws InvalidIndex, UnexpectedEntry { + List convertToStringList(LocalVariableTableAttribute lvt) { List result = new ArrayList<>(); - for (Entry entry : lvt.local_variable_table) { - String str = formatLocalVariableData(constantPool.getUTF8Value(entry.name_index), - entry.start_pc, entry.length); + for (LocalVariableInfo entry : lvt.localVariables()) { + String str = formatLocalVariableData(entry.name().stringValue(), + entry.startPc(), entry.length()); result.add(str); } Collections.sort(result); @@ -292,4 +283,56 @@ public class LVTHarness { } } + private String parse(String desc) { + int end = desc.indexOf(")"); + if (end == -1) + throw new AssertionError(); + end ++; + int p = 0; + StringBuilder sb = new StringBuilder(); + int dims = 0; + + while (p < end) { + String type; + switch (desc.charAt(p++)) { + case '(' -> { + sb.append('('); + continue; + } + case ')' -> { + sb.append(')'); + continue; + } + case '[' -> { + dims++; + continue; + } + case 'B' -> type = "byte"; + case 'C' -> type = "char"; + case 'D' -> type = "double"; + case 'F' -> type = "float"; + case 'I' -> type = "int"; + case 'J' -> type = "long"; + case 'L' -> { + int sep = desc.indexOf(';', p); + if (sep == -1) + throw new AssertionError(); + type = desc.substring(p, sep).replace('/', '.'); + p = sep + 1; + } + case 'S' -> type = "short"; + case 'Z' -> type = "boolean"; + case 'V' -> type = "void"; + default -> throw new AssertionError(); + } + + if (sb.length() > 1 && sb.charAt(0) == '(') + sb.append(", "); + sb.append(type); + for ( ; dims > 0; dims-- ) + sb.append("[]"); + } + return sb.toString(); + } + } diff --git a/test/langtools/tools/javac/generics/bridges/BridgeHarness.java b/test/langtools/tools/javac/generics/bridges/BridgeHarness.java index 73988d0ac9d..480d5d703ba 100644 --- a/test/langtools/tools/javac/generics/bridges/BridgeHarness.java +++ b/test/langtools/tools/javac/generics/bridges/BridgeHarness.java @@ -26,7 +26,12 @@ * @bug 8013789 * @summary Compiler should emit bridges in interfaces * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.util * @build JavacTestingAbstractProcessor BridgeHarness @@ -34,11 +39,7 @@ */ import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.AccessFlags; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.util.List; @@ -111,8 +112,8 @@ public class BridgeHarness { /** * return a string representation of a bytecode method */ - static String descriptor(Method m, ConstantPool cp) throws ConstantPoolException { - return m.getName(cp) + m.descriptor.getValue(cp); + static String descriptor(MethodModel m) { + return m.methodName() + m.methodTypeSymbol().descriptorString(); } /* test harness */ @@ -146,27 +147,27 @@ public class BridgeHarness { */ protected void checkBridges(JavaFileObject jfo) { try (InputStream is = jfo.openInputStream()) { - ClassFile cf = ClassFile.read(is); - System.err.println("checking: " + cf.getName()); + ClassModel cf = Classfile.of().parse(is.readAllBytes()); + System.err.println("checking: " + cf.thisClass().asInternalName()); - List bridgeList = bridgesMap.get(cf.getName()); + List bridgeList = bridgesMap.get(cf.thisClass().asInternalName()); if (bridgeList == null) { //no bridges - nothing to check; bridgeList = List.nil(); } - for (Method m : cf.methods) { - if (m.access_flags.is(AccessFlags.ACC_SYNTHETIC | AccessFlags.ACC_BRIDGE)) { + for (MethodModel m : cf.methods()) { + if ((m.flags().flagsMask() & (Classfile.ACC_SYNTHETIC | Classfile.ACC_BRIDGE)) != 0) { //this is a bridge - see if there's a match in the bridge list Bridge match = null; for (Bridge b : bridgeList) { - if (b.value().equals(descriptor(m, cf.constant_pool))) { + if (b.value().equals(descriptor(m))) { match = b; break; } } if (match == null) { - error("No annotation for bridge method: " + descriptor(m, cf.constant_pool)); + error("No annotation for bridge method: " + descriptor(m)); } else { bridgeList = drop(bridgeList, match); } diff --git a/test/langtools/tools/javac/importscope/T8193717.java b/test/langtools/tools/javac/importscope/T8193717.java index 34aa9c9b02d..4c88c57974d 100644 --- a/test/langtools/tools/javac/importscope/T8193717.java +++ b/test/langtools/tools/javac/importscope/T8193717.java @@ -26,7 +26,12 @@ * @bug 8193717 * @summary Check that code with a lot named imports can compile. * @library /tools/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.jdeps/com.sun.tools.javap @@ -38,6 +43,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.lang.constant.ClassDesc; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Paths; @@ -55,17 +61,7 @@ import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; -import com.sun.tools.classfile.AccessFlags; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Attributes; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ClassWriter; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Utf8_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; -import com.sun.tools.classfile.Field; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; import toolbox.JavacTask; import toolbox.ToolBox; @@ -106,28 +102,13 @@ public class T8193717 { } private byte[] generateClassFile(String name) throws IOException { - ConstantPool cp = new ConstantPool(new CPInfo[] { - new CONSTANT_Utf8_info(""), //0 - new CONSTANT_Utf8_info(name.replace(".", "/")), //1 - new CONSTANT_Class_info(null, 1), //2 - new CONSTANT_Utf8_info("java/lang/Object"), //3 - new CONSTANT_Class_info(null, 3), //4 + byte[] bytes = Classfile.of().build(ClassDesc.of(name), classBuilder -> { + classBuilder.withSuperclass(ClassDesc.ofInternalName("java/lang/Object")) + .withVersion(51, 0) + .withFlags(Classfile.ACC_ABSTRACT | Classfile.ACC_INTERFACE | Classfile.ACC_PUBLIC); }); - ClassFile cf = new ClassFile(0xCAFEBABE, - 0, - 51, - cp, - new AccessFlags(AccessFlags.ACC_ABSTRACT | - AccessFlags.ACC_INTERFACE | - AccessFlags.ACC_PUBLIC), - 2, - 4, - new int[0], - new Field[0], - new Method[0], - new Attributes(cp, new Attribute[0])); ByteArrayOutputStream baos = new ByteArrayOutputStream(); - new ClassWriter().write(cf, baos); + baos.write(bytes); return baos.toByteArray(); } diff --git a/test/langtools/tools/javac/jvm/ClassRefDupInConstantPoolTest.java b/test/langtools/tools/javac/jvm/ClassRefDupInConstantPoolTest.java index a84c87245af..a0a0c687fa2 100644 --- a/test/langtools/tools/javac/jvm/ClassRefDupInConstantPoolTest.java +++ b/test/langtools/tools/javac/jvm/ClassRefDupInConstantPoolTest.java @@ -25,30 +25,33 @@ * @test * @bug 8015927 * @summary Class reference duplicates in constant pool - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components * @clean ClassRefDupInConstantPoolTest$Duplicates * @run main ClassRefDupInConstantPoolTest */ import java.util.TreeSet; -import com.sun.tools.classfile.*; -import com.sun.tools.classfile.ConstantPool.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.constantpool.*; public class ClassRefDupInConstantPoolTest { public static void main(String[] args) throws Exception { - ClassFile cls = ClassFile.read(ClassRefDupInConstantPoolTest.class. - getResourceAsStream("ClassRefDupInConstantPoolTest$Duplicates.class")); - ConstantPool pool = cls.constant_pool; + ClassModel cls = Classfile.of().parse(ClassRefDupInConstantPoolTest.class. + getResourceAsStream("ClassRefDupInConstantPoolTest$Duplicates.class").readAllBytes()); + ConstantPool pool = cls.constantPool(); int duplicates = 0; - TreeSet set = new TreeSet<>(); - for (CPInfo i : pool.entries()) { - if (i.getTag() == ConstantPool.CONSTANT_Class) { - CONSTANT_Class_info ci = (CONSTANT_Class_info)i; - if (!set.add(ci.name_index)) { + TreeSet set = new TreeSet<>(); + for (int i = 1; i < pool.entryCount(); i += pool.entryByIndex(i).width()) { + if (pool.entryByIndex(i) instanceof ClassEntry ce) { + if (!set.add(ce.asInternalName())) { duplicates++; - System.out.println("DUPLICATE CLASS REF " + ci.getName()); + System.out.println("DUPLICATE CLASS REF " + ce.asInternalName()); } } } diff --git a/test/langtools/tools/javac/lambda/ByteCodeTest.java b/test/langtools/tools/javac/lambda/ByteCodeTest.java index 2e42d4472ba..42c0be83439 100644 --- a/test/langtools/tools/javac/lambda/ByteCodeTest.java +++ b/test/langtools/tools/javac/lambda/ByteCodeTest.java @@ -26,22 +26,25 @@ * @bug 8011738 * @author sogoel * @summary Code translation test for Lambda expressions, method references - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @run main ByteCodeTest */ -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.ConstantPool.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.BootstrapMethodsAttribute; +import jdk.internal.classfile.constantpool.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; +import java.lang.invoke.MethodHandleInfo; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -73,13 +76,14 @@ public class ByteCodeTest { } private static boolean verifyClassFileAttributes(File classFile, TestCases tc) { - ClassFile c = null; + ClassModel c = null; try { - c = ClassFile.read(classFile); - } catch (IOException | ConstantPoolException e) { + c = Classfile.of().parse(classFile.toPath()); + } catch (IOException e) { e.printStackTrace(); } - ConstantPoolVisitor cpv = new ConstantPoolVisitor(c, c.constant_pool.size()); + assert c != null; + ConstantPoolVisitor cpv = new ConstantPoolVisitor(c, c.constantPool().entryCount()); Map hm = cpv.getBSMMap(); List expectedValList = tc.getExpectedArgValues(); @@ -378,20 +382,20 @@ public class ByteCodeTest { } } - static class ConstantPoolVisitor implements ConstantPool.Visitor { + static class ConstantPoolVisitor { final List slist; - final ClassFile cf; + final ClassModel cf; final ConstantPool cfpool; final Map bsmMap; - public ConstantPoolVisitor(ClassFile cf, int size) { + public ConstantPoolVisitor(ClassModel cf, int size) { slist = new ArrayList<>(size); for (int i = 0 ; i < size; i++) { slist.add(null); } this.cf = cf; - this.cfpool = cf.constant_pool; + this.cfpool = cf.constantPool(); bsmMap = readBSM(); } @@ -399,39 +403,57 @@ public class ByteCodeTest { return Collections.unmodifiableMap(bsmMap); } - public String visit(CPInfo c, int index) { - return c.accept(this, index); + public String visit(PoolEntry c, int index) { + return switch (c) { + case ClassEntry entry -> visitClass(entry, index); + case DoubleEntry entry -> visitDouble(entry, index); + case FieldRefEntry entry -> visitFieldref(entry, index); + case FloatEntry entry -> visitFloat(entry, index); + case IntegerEntry entry -> visitInteger(entry, index); + case InterfaceMethodRefEntry entry -> visitInterfaceMethodref(entry, index); + case InvokeDynamicEntry entry -> visitInvokeDynamic(entry, index); + case ConstantDynamicEntry entry -> visitDynamicConstant(entry, index); + case LongEntry entry -> visitLong(entry, index); + case NameAndTypeEntry entry -> visitNameAndType(entry, index); + case MethodRefEntry entry -> visitMethodref(entry, index); + case MethodHandleEntry entry -> visitMethodHandle(entry, index); + case MethodTypeEntry entry -> visitMethodType(entry, index); + case ModuleEntry entry -> visitModule(entry, index); + case PackageEntry entry -> visitPackage(entry, index); + case StringEntry entry -> visitString(entry, index); + case Utf8Entry entry -> visitUtf8(entry, index); + default -> throw new AssertionError(); + }; } private Map readBSM() { - BootstrapMethods_attribute bsmAttr = - (BootstrapMethods_attribute) cf.getAttribute(Attribute.BootstrapMethods); + BootstrapMethodsAttribute bsmAttr = cf.findAttribute(Attributes.BOOTSTRAP_METHODS).orElse(null); if (bsmAttr != null) { Map out = - new HashMap<>(bsmAttr.bootstrap_method_specifiers.length); - for (BootstrapMethods_attribute.BootstrapMethodSpecifier bsms : - bsmAttr.bootstrap_method_specifiers) { - int index = bsms.bootstrap_method_ref; + new HashMap<>(bsmAttr.bootstrapMethodsSize()); + for (BootstrapMethodEntry bsms : bsmAttr.bootstrapMethods()) { + int index = bsms.bootstrapMethod().index(); try { String value = slist.get(index); if (value == null) { - value = visit(cfpool.get(index), index); + value = visit(cfpool.entryByIndex(index), index); debugln("[SG]: index " + index); debugln("[SG]: value " + value); slist.set(index, value); out.put(index, value); } - for (int idx : bsms.bootstrap_arguments) { + for (LoadableConstantEntry ce : bsms.arguments()) { + int idx = ce.index(); value = slist.get(idx); if (value == null) { - value = visit(cfpool.get(idx), idx); + value = visit(cfpool.entryByIndex(idx), idx); debugln("[SG]: idx " + idx); debugln("[SG]: value " + value); slist.set(idx, value); out.put(idx, value); } } - } catch (InvalidIndex ex) { + } catch (ConstantPoolException ex) { ex.printStackTrace(); } } @@ -440,13 +462,12 @@ public class ByteCodeTest { return new HashMap<>(0); } - @Override - public String visitClass(CONSTANT_Class_info c, Integer p) { + public String visitClass(ClassEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = visit(cfpool.get(c.name_index), c.name_index); + value = visit(cfpool.entryByIndex(c.name().index()), c.index()); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -455,26 +476,24 @@ public class ByteCodeTest { return value; } - @Override - public String visitDouble(CONSTANT_Double_info c, Integer p) { + public String visitDouble(DoubleEntry c, Integer p) { String value = slist.get(p); if (value == null) { - value = Double.toString(c.value); + value = Double.toString(c.doubleValue()); slist.set(p, value); } return value; } - @Override - public String visitFieldref(CONSTANT_Fieldref_info c, Integer p) { + public String visitFieldref(FieldRefEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = visit(cfpool.get(c.class_index), c.class_index); - value = value.concat(" " + visit(cfpool.get(c.name_and_type_index), - c.name_and_type_index)); + value = visit(cfpool.entryByIndex(c.owner().index()), c.owner().index()); + value = value.concat(" " + visit(cfpool.entryByIndex(c.nameAndType().index()), + c.nameAndType().index())); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -483,39 +502,36 @@ public class ByteCodeTest { return value; } - @Override - public String visitFloat(CONSTANT_Float_info c, Integer p) { + public String visitFloat(FloatEntry c, Integer p) { String value = slist.get(p); if (value == null) { - value = Float.toString(c.value); + value = Float.toString(c.floatValue()); slist.set(p, value); } return value; } - @Override - public String visitInteger(CONSTANT_Integer_info cnstnt, Integer p) { + public String visitInteger(IntegerEntry cnstnt, Integer p) { String value = slist.get(p); if (value == null) { - value = Integer.toString(cnstnt.value); + value = Integer.toString(cnstnt.intValue()); slist.set(p, value); } return value; } - @Override - public String visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info c, + public String visitInterfaceMethodref(InterfaceMethodRefEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = visit(cfpool.get(c.class_index), c.class_index); + value = visit(cfpool.entryByIndex(c.owner().index()), c.owner().index()); value = value.concat(" " + - visit(cfpool.get(c.name_and_type_index), - c.name_and_type_index)); + visit(cfpool.entryByIndex(c.nameAndType().index()), + c.nameAndType().index())); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -524,14 +540,13 @@ public class ByteCodeTest { return value; } - @Override - public String visitInvokeDynamic(CONSTANT_InvokeDynamic_info c, Integer p) { + public String visitInvokeDynamic(InvokeDynamicEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = bsmMap.get(c.bootstrap_method_attr_index) + " " - + visit(cfpool.get(c.name_and_type_index), c.name_and_type_index); + value = bsmMap.get(c.bootstrap().bsmIndex()) + " " + + visit(cfpool.entryByIndex(c.nameAndType().index()), c.nameAndType().index()); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -540,14 +555,13 @@ public class ByteCodeTest { return value; } - @Override - public String visitDynamicConstant(CONSTANT_Dynamic_info c, Integer p) { + public String visitDynamicConstant(ConstantDynamicEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = bsmMap.get(c.bootstrap_method_attr_index) + " " - + visit(cfpool.get(c.name_and_type_index), c.name_and_type_index); + value = bsmMap.get(c.bootstrap().bsmIndex()) + " " + + visit(cfpool.entryByIndex(c.nameAndType().index()), c.nameAndType().index()); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -556,44 +570,24 @@ public class ByteCodeTest { return value; } - @Override - public String visitLong(CONSTANT_Long_info c, Integer p) { + public String visitLong(LongEntry c, Integer p) { String value = slist.get(p); if (value == null) { - value = Long.toString(c.value); + value = Long.toString(c.longValue()); slist.set(p, value); } return value; } - @Override - public String visitNameAndType(CONSTANT_NameAndType_info c, Integer p) { + public String visitNameAndType(NameAndTypeEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = visit(cfpool.get(c.name_index), c.name_index); + value = visit(cfpool.entryByIndex(c.name().index()), c.name().index()); value = value.concat(" " + - visit(cfpool.get(c.type_index), c.type_index)); - slist.set(p, value); - } catch (InvalidIndex ex) { - ex.printStackTrace(); - } - } - return value; - } - - @Override - public String visitMethodref(CONSTANT_Methodref_info c, Integer p) { - - String value = slist.get(p); - if (value == null) { - try { - value = visit(cfpool.get(c.class_index), c.class_index); - value = value.concat(" " + - visit(cfpool.get(c.name_and_type_index), - c.name_and_type_index)); + visit(cfpool.entryByIndex(c.type().index()), c.type().index())); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -602,15 +596,31 @@ public class ByteCodeTest { return value; } - @Override - public String visitMethodHandle(CONSTANT_MethodHandle_info c, Integer p) { + public String visitMethodref(MethodRefEntry c, Integer p) { + + String value = slist.get(p); + if (value == null) { + try { + value = visit(cfpool.entryByIndex(c.owner().index()), c.owner().index()); + value = value.concat(" " + + visit(cfpool.entryByIndex(c.nameAndType().index()), + c.nameAndType().index())); + slist.set(p, value); + } catch (ConstantPoolException ex) { + ex.printStackTrace(); + } + } + return value; + } + + public String visitMethodHandle(MethodHandleEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = c.reference_kind.name(); + value = MethodHandleInfo.referenceKindToString(c.kind()); value = value.concat(" " - + visit(cfpool.get(c.reference_index), c.reference_index)); + + visit(cfpool.entryByIndex(c.reference().index()), c.reference().index())); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -619,13 +629,12 @@ public class ByteCodeTest { return value; } - @Override - public String visitMethodType(CONSTANT_MethodType_info c, Integer p) { + public String visitMethodType(MethodTypeEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = visit(cfpool.get(c.descriptor_index), c.descriptor_index); + value = visit(cfpool.entryByIndex(c.descriptor().index()), c.descriptor().index()); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -634,13 +643,12 @@ public class ByteCodeTest { return value; } - @Override - public String visitModule(CONSTANT_Module_info c, Integer p) { + public String visitModule(ModuleEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = visit(cfpool.get(c.name_index), c.name_index); + value = visit(cfpool.entryByIndex(c.name().index()), c.name().index()); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -649,13 +657,12 @@ public class ByteCodeTest { return value; } - @Override - public String visitPackage(CONSTANT_Package_info c, Integer p) { + public String visitPackage(PackageEntry c, Integer p) { String value = slist.get(p); if (value == null) { try { - value = visit(cfpool.get(c.name_index), c.name_index); + value = visit(cfpool.entryByIndex(c.name().index()), c.name().index()); slist.set(p, value); } catch (ConstantPoolException ex) { ex.printStackTrace(); @@ -664,13 +671,12 @@ public class ByteCodeTest { return value; } - @Override - public String visitString(CONSTANT_String_info c, Integer p) { + public String visitString(StringEntry c, Integer p) { try { String value = slist.get(p); if (value == null) { - value = c.getString(); + value = c.stringValue(); slist.set(p, value); } return value; @@ -679,12 +685,11 @@ public class ByteCodeTest { } } - @Override - public String visitUtf8(CONSTANT_Utf8_info cnstnt, Integer p) { + public String visitUtf8(Utf8Entry cnstnt, Integer p) { String value = slist.get(p); if (value == null) { - value = cnstnt.value; + value = cnstnt.stringValue(); slist.set(p, value); } return value; diff --git a/test/langtools/tools/javac/lambda/LocalVariableTable.java b/test/langtools/tools/javac/lambda/LocalVariableTable.java index 22bd426bee6..3b94f1972e5 100644 --- a/test/langtools/tools/javac/lambda/LocalVariableTable.java +++ b/test/langtools/tools/javac/lambda/LocalVariableTable.java @@ -25,7 +25,12 @@ * @test * @bug 8025998 8026749 8054220 8058227 * @summary Missing LV table in lambda bodies - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g LocalVariableTable.java * @run main LocalVariableTable */ @@ -33,7 +38,8 @@ import java.io.*; import java.lang.annotation.*; import java.util.*; -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; /* * The test checks that a LocalVariableTable attribute is generated for the @@ -42,12 +48,12 @@ import com.sun.tools.classfile.*; * * Since the bug was about missing entries in the LVT, not malformed entries, * the test is not intended to be a detailed test of the contents of each - * LocalVariableTable entry: it is assumed that if a entry is present, it + * LocalVariableTable entry: it is assumed that if an entry is present, it * will have the correct contents. * * The test looks for test cases represented by nested classes whose * name begins with "Lambda". Each such class contains a lambda expression - * that will mapped into a lambda method, and because the test is compiled + * that will map into a lambda method, and because the test is compiled * with -g, these methods should have a LocalVariableTable. The set of * expected names in the LVT is provided in an annotation on the class for * the test case. @@ -81,29 +87,28 @@ public class LocalVariableTable { return; } - ClassFile cf = ClassFile.read(getClass().getResource(c.getName() + ".class").openStream()); - Method m = getLambdaMethod(cf); + ClassModel cm = Classfile.of().parse(Objects.requireNonNull(getClass().getResource(c.getName() + ".class")).openStream().readAllBytes()); + MethodModel m = getLambdaMethod(cm); if (m == null) { error("lambda method not found"); return; } - Code_attribute code = (Code_attribute) m.attributes.get(Attribute.Code); + CodeAttribute code = m.findAttribute(Attributes.CODE).orElse(null); if (code == null) { error("Code attribute not found"); return; } - LocalVariableTable_attribute lvt = - (LocalVariableTable_attribute) code.attributes.get(Attribute.LocalVariableTable); + LocalVariableTableAttribute lvt = code.findAttribute(Attributes.LOCAL_VARIABLE_TABLE).orElse(null); if (lvt == null) { error("LocalVariableTable attribute not found"); return; } Set foundNames = new LinkedHashSet<>(); - for (LocalVariableTable_attribute.Entry e: lvt.local_variable_table) { - foundNames.add(cf.constant_pool.getUTF8Value(e.name_index)); + for (LocalVariableInfo e: lvt.localVariables()) { + foundNames.add(e.name().stringValue()); } Set expectNames = new LinkedHashSet<>(Arrays.asList(expect.value())); @@ -120,9 +125,9 @@ public class LocalVariableTable { } /** Get a method whose name begins "lambda$...". */ - Method getLambdaMethod(ClassFile cf) throws ConstantPoolException { - for (Method m: cf.methods) { - if (m.getName(cf.constant_pool).startsWith("lambda$")) + MethodModel getLambdaMethod(ClassModel cf) { + for (MethodModel m: cf.methods()) { + if (m.methodName().stringValue().startsWith("lambda$")) return m; } return null; diff --git a/test/langtools/tools/javac/lambda/TestBootstrapMethodsCount.java b/test/langtools/tools/javac/lambda/TestBootstrapMethodsCount.java index a3d71d52420..99d55c9e0ed 100644 --- a/test/langtools/tools/javac/lambda/TestBootstrapMethodsCount.java +++ b/test/langtools/tools/javac/lambda/TestBootstrapMethodsCount.java @@ -26,7 +26,12 @@ * @bug 8129547 * @summary Excess entries in BootstrapMethods with the same (bsm, bsmKind, bsmStaticArgs), but different dynamicArgs * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.jvm @@ -52,9 +57,8 @@ import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; import com.sun.source.util.TreeScanner; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.ClassFile; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.BootstrapMethodsAttribute; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.code.Symbol; @@ -111,11 +115,9 @@ public class TestBootstrapMethodsCount { void verifyBytecode() { File compiledTest = new File("Test.class"); try { - ClassFile cf = ClassFile.read(compiledTest); - BootstrapMethods_attribute bsm_attr = - (BootstrapMethods_attribute)cf - .getAttribute(Attribute.BootstrapMethods); - int length = bsm_attr.bootstrap_method_specifiers.length; + ClassModel cf = Classfile.of().parse(compiledTest.toPath()); + BootstrapMethodsAttribute bsm_attr = cf.findAttribute(Attributes.BOOTSTRAP_METHODS).orElseThrow(); + int length = bsm_attr.bootstrapMethodsSize(); if (length != 1) { throw new Error("Bad number of method specifiers " + "in BootstrapMethods attribute: " + length); diff --git a/test/langtools/tools/javac/lambda/TestInvokeDynamic.java b/test/langtools/tools/javac/lambda/TestInvokeDynamic.java index ecdd0842bb4..006588146b5 100644 --- a/test/langtools/tools/javac/lambda/TestInvokeDynamic.java +++ b/test/langtools/tools/javac/lambda/TestInvokeDynamic.java @@ -28,7 +28,12 @@ * Add back-end support for invokedynamic * temporarily workaround combo tests are causing time out in several platforms * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.file @@ -41,6 +46,7 @@ import java.io.IOException; import java.io.InputStream; +import java.lang.invoke.MethodHandleInfo; import javax.tools.JavaFileObject; @@ -50,14 +56,10 @@ import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; import com.sun.source.util.TreeScanner; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.LineNumberTable_attribute; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.*; +import jdk.internal.classfile.instruction.InvokeDynamicInstruction; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodHandleSymbol; @@ -81,73 +83,68 @@ public class TestInvokeDynamic extends ComboInstance { enum StaticArgumentKind implements ComboParameter { STRING("Hello!", "String", "Ljava/lang/String;") { @Override - boolean check(CPInfo cpInfo) throws Exception { - return (cpInfo instanceof CONSTANT_String_info) && - ((CONSTANT_String_info)cpInfo).getString() + boolean check(PoolEntry poolEntry) throws Exception { + return (poolEntry instanceof StringEntry) && + ((StringEntry)poolEntry).stringValue() .equals(value); } }, CLASS(null, "Class", "Ljava/lang/Class;") { @Override - boolean check(CPInfo cpInfo) throws Exception { - return (cpInfo instanceof CONSTANT_Class_info) && - ((CONSTANT_Class_info)cpInfo).getName() - .equals("java/lang/String"); + boolean check(PoolEntry poolEntry) throws Exception { + return (poolEntry instanceof ClassEntry) && + ((ClassEntry)poolEntry).name() + .equalsString("java/lang/String"); } }, INTEGER(1, "int", "I") { @Override - boolean check(CPInfo cpInfo) throws Exception { - return (cpInfo instanceof CONSTANT_Integer_info) && - ((CONSTANT_Integer_info)cpInfo).value == - ((Integer)value).intValue(); + boolean check( PoolEntry poolEntry) throws Exception { + return (poolEntry instanceof IntegerEntry) && + ((IntegerEntry)poolEntry).intValue() == + (Integer) value; } }, LONG(1L, "long", "J") { @Override - boolean check(CPInfo cpInfo) throws Exception { - return (cpInfo instanceof CONSTANT_Long_info) && - ((CONSTANT_Long_info)cpInfo).value == - ((Long)value).longValue(); + boolean check( PoolEntry poolEntry) throws Exception { + return (poolEntry instanceof LongEntry) && + ((LongEntry)poolEntry).longValue() == + (Long) value; } }, FLOAT(1.0f, "float", "F") { @Override - boolean check(CPInfo cpInfo) throws Exception { - return (cpInfo instanceof CONSTANT_Float_info) && - ((CONSTANT_Float_info)cpInfo).value == - ((Float)value).floatValue(); + boolean check( PoolEntry poolEntry) throws Exception { + return (poolEntry instanceof FloatEntry) && + ((FloatEntry)poolEntry).floatValue() == + (Float) value; } }, DOUBLE(1.0, "double","D") { @Override - boolean check(CPInfo cpInfo) throws Exception { - return (cpInfo instanceof CONSTANT_Double_info) && - ((CONSTANT_Double_info)cpInfo).value == - ((Double)value).doubleValue(); + boolean check( PoolEntry poolEntry) throws Exception { + return (poolEntry instanceof DoubleEntry) && + ((DoubleEntry)poolEntry).doubleValue() == + (Double) value; } }, METHOD_HANDLE(null, "MethodHandle", "Ljava/lang/invoke/MethodHandle;") { @Override - boolean check(CPInfo cpInfo) throws Exception { - if (!(cpInfo instanceof CONSTANT_MethodHandle_info)) + boolean check( PoolEntry poolEntry) throws Exception { + if (!(poolEntry instanceof MethodHandleEntry handleInfo)) return false; - CONSTANT_MethodHandle_info handleInfo = - (CONSTANT_MethodHandle_info)cpInfo; - return handleInfo.getCPRefInfo().getClassName().equals("Array") && - handleInfo.reference_kind == RefKind.REF_invokeVirtual && - handleInfo.getCPRefInfo() - .getNameAndTypeInfo().getName().equals("clone") && - handleInfo.getCPRefInfo() - .getNameAndTypeInfo().getType().equals("()Ljava/lang/Object;"); + return handleInfo.reference().owner().name().equalsString("Array") && + handleInfo.kind() == MethodHandleInfo.REF_invokeVirtual && + handleInfo.reference().name().equalsString("clone") && + handleInfo.reference().type().equalsString("()Ljava/lang/Object;"); } }, METHOD_TYPE(null, "MethodType", "Ljava/lang/invoke/MethodType;") { @Override - boolean check(CPInfo cpInfo) throws Exception { - return (cpInfo instanceof CONSTANT_MethodType_info) && - ((CONSTANT_MethodType_info)cpInfo).getType() - .equals("()Ljava/lang/Object;"); + boolean check( PoolEntry poolEntry) throws Exception { + return (poolEntry instanceof MethodTypeEntry methodTypeEntry) && + methodTypeEntry.asSymbol().descriptorString().equals("()Ljava/lang/Object;"); } }; @@ -162,29 +159,20 @@ public class TestInvokeDynamic extends ComboInstance { this.bytecodeTypeStr = bytecodeTypeStr; } - abstract boolean check(CPInfo cpInfo) throws Exception; + abstract boolean check( PoolEntry poolEntry) throws Exception; LoadableConstant getValue(Symtab syms) { - switch (this) { - case STRING: - return LoadableConstant.String((String)value); - case INTEGER: - return LoadableConstant.Int((Integer)value); - case LONG: - return LoadableConstant.Long((Long)value); - case FLOAT: - return LoadableConstant.Float((Float)value); - case DOUBLE: - return LoadableConstant.Double((Double)value); - case CLASS: - return (ClassType)syms.stringType; - case METHOD_HANDLE: - return syms.arrayCloneMethod.asHandle(); - case METHOD_TYPE: - return ((MethodType)syms.arrayCloneMethod.type); - default: - throw new AssertionError(); - } + return switch (this) { + case STRING -> LoadableConstant.String((String) value); + case INTEGER -> LoadableConstant.Int((Integer) value); + case LONG -> LoadableConstant.Long((Long) value); + case FLOAT -> LoadableConstant.Float((Float) value); + case DOUBLE -> LoadableConstant.Double((Double) value); + case CLASS -> (ClassType) syms.stringType; + case METHOD_HANDLE -> syms.arrayCloneMethod.asHandle(); + case METHOD_TYPE -> ((MethodType) syms.arrayCloneMethod.type); + default -> throw new AssertionError(); + }; } @Override @@ -269,10 +257,10 @@ public class TestInvokeDynamic extends ComboInstance { return; } try (InputStream is = res.get().iterator().next().openInputStream()){ - ClassFile cf = ClassFile.read(is); - Method testMethod = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals("test")) { + ClassModel cm = Classfile.of().parse(is.readAllBytes()); + MethodModel testMethod = null; + for (MethodModel m : cm.methods()) { + if (m.methodName().equalsString("test")) { testMethod = m; break; } @@ -281,22 +269,19 @@ public class TestInvokeDynamic extends ComboInstance { fail("Test method not found"); return; } - Code_attribute ea = - (Code_attribute)testMethod.attributes.get(Attribute.Code); - if (testMethod == null) { + CodeAttribute ea = testMethod.findAttribute(Attributes.CODE).orElse(null); + if (ea == null) { fail("Code attribute for test() method not found"); return; } int bsmIdx = -1; - for (Instruction i : ea.getInstructions()) { - if (i.getMnemonic().equals("invokedynamic")) { - CONSTANT_InvokeDynamic_info indyInfo = - (CONSTANT_InvokeDynamic_info)cf - .constant_pool.get(i.getShort(1)); - bsmIdx = indyInfo.bootstrap_method_attr_index; - if (!indyInfo.getNameAndTypeInfo().getType().equals("()V")) { + for (CodeElement ce : ea.elementList()) { + if (ce instanceof InvokeDynamicInstruction indy) { + InvokeDynamicEntry indyEntry = indy.invokedynamic(); + bsmIdx = indyEntry.bootstrap().bsmIndex(); + if (!indyEntry.type().equalsString("()V")) { fail("type mismatch for CONSTANT_InvokeDynamic_info"); return; } @@ -307,70 +292,62 @@ public class TestInvokeDynamic extends ComboInstance { return; } - BootstrapMethods_attribute bsm_attr = - (BootstrapMethods_attribute)cf - .getAttribute(Attribute.BootstrapMethods); - if (bsm_attr.bootstrap_method_specifiers.length != 1) { + BootstrapMethodsAttribute bsm_attr = cm + .findAttribute(Attributes.BOOTSTRAP_METHODS).orElseThrow(); + if (bsm_attr.bootstrapMethodsSize() != 1) { fail("Bad number of method specifiers " + "in BootstrapMethods attribute"); return; } - BootstrapMethods_attribute.BootstrapMethodSpecifier bsm_spec = - bsm_attr.bootstrap_method_specifiers[0]; + BootstrapMethodEntry bsm_spec = + bsm_attr.bootstrapMethods().getFirst(); - if (bsm_spec.bootstrap_arguments.length != arity.arity) { + if (bsm_spec.arguments().size() != arity.arity) { fail("Bad number of static invokedynamic args " + "in BootstrapMethod attribute"); return; } for (int i = 0 ; i < arity.arity ; i++) { - if (!saks[i].check(cf.constant_pool - .get(bsm_spec.bootstrap_arguments[i]))) { + if (!saks[i].check(bsm_spec.arguments().get(i))) { fail("Bad static argument value " + saks[i]); return; } } - CONSTANT_MethodHandle_info bsm_handle = - (CONSTANT_MethodHandle_info)cf.constant_pool - .get(bsm_spec.bootstrap_method_ref); + MethodHandleEntry bsm_handle = bsm_spec.bootstrapMethod(); - if (bsm_handle.reference_kind != RefKind.REF_invokeStatic) { + if (bsm_handle.kind() != MethodHandleInfo.REF_invokeStatic) { fail("Bad kind on boostrap method handle"); return; } - CONSTANT_Methodref_info bsm_ref = - (CONSTANT_Methodref_info)cf.constant_pool - .get(bsm_handle.reference_index); + MemberRefEntry bsm_ref =bsm_handle.reference(); - if (!bsm_ref.getClassInfo().getName().equals("Bootstrap")) { + if (!bsm_ref.owner().name().equalsString("Bootstrap")) { fail("Bad owner of boostrap method"); return; } - if (!bsm_ref.getNameAndTypeInfo().getName().equals("bsm")) { + if (!bsm_ref.name().equalsString("bsm")) { fail("Bad boostrap method name"); return; } - if (!bsm_ref.getNameAndTypeInfo() - .getType().equals(asBSMSignatureString())) { + if (!bsm_ref.type().equalsString(asBSMSignatureString())) { fail("Bad boostrap method type" + - bsm_ref.getNameAndTypeInfo().getType() + " " + + bsm_ref.type().stringValue() + " " + asBSMSignatureString()); return; } - LineNumberTable_attribute lnt = - (LineNumberTable_attribute)ea.attributes.get(Attribute.LineNumberTable); + LineNumberTableAttribute lnt = ea.findAttribute(Attributes.LINE_NUMBER_TABLE).orElse(null); if (lnt == null) { fail("No LineNumberTable attribute"); return; } - if (lnt.line_number_table_length != 3) { + if (lnt.lineNumbers().size() != 3) { fail("Wrong number of entries in LineNumberTable"); return; } diff --git a/test/langtools/tools/javac/lambda/bytecode/TestLambdaBytecode.java b/test/langtools/tools/javac/lambda/bytecode/TestLambdaBytecode.java index 825ea98aa76..bc5a673dc95 100644 --- a/test/langtools/tools/javac/lambda/bytecode/TestLambdaBytecode.java +++ b/test/langtools/tools/javac/lambda/bytecode/TestLambdaBytecode.java @@ -27,7 +27,12 @@ * @summary Lambda back-end should generate invokevirtual for method handles referring to * private instance methods as lambda proxy is a nestmate of the target clsas * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.file * jdk.compiler/com.sun.tools.javac.util @@ -35,16 +40,14 @@ * @run main TestLambdaBytecode */ -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.*; +import jdk.internal.classfile.instruction.InvokeDynamicInstruction; import java.io.IOException; import java.io.InputStream; +import java.lang.invoke.MethodHandleInfo; import combo.ComboInstance; import combo.ComboParameter; @@ -207,10 +210,10 @@ public class TestLambdaBytecode extends ComboInstance { return; } try (InputStream is = res.get().iterator().next().openInputStream()) { - ClassFile cf = ClassFile.read(is); - Method testMethod = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals("test")) { + ClassModel cf = Classfile.of().parse(is.readAllBytes()); + MethodModel testMethod = null; + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString("test")) { testMethod = m; break; } @@ -219,24 +222,21 @@ public class TestLambdaBytecode extends ComboInstance { fail("Test method not found"); return; } - Code_attribute ea = - (Code_attribute)testMethod.attributes.get(Attribute.Code); - if (testMethod == null) { + CodeAttribute ea = testMethod.findAttribute(Attributes.CODE).orElse(null); + if (ea == null) { fail("Code attribute for test() method not found"); return; } int bsmIdx = -1; - for (Instruction i : ea.getInstructions()) { - if (i.getMnemonic().equals("invokedynamic")) { - CONSTANT_InvokeDynamic_info indyInfo = - (CONSTANT_InvokeDynamic_info)cf - .constant_pool.get(i.getShort(1)); - bsmIdx = indyInfo.bootstrap_method_attr_index; - if (!indyInfo.getNameAndTypeInfo().getType().equals(makeIndyType())) { + for (CodeElement ce : ea.elementList()) { + if (ce instanceof InvokeDynamicInstruction indy) { + InvokeDynamicEntry indyInfo = indy.invokedynamic(); + bsmIdx = indyInfo.bootstrap().bsmIndex(); + if (!indyInfo.type().equalsString(makeIndyType())) { fail("type mismatch for CONSTANT_InvokeDynamic_info " + - res.compilationInfo() + "\n" + indyInfo.getNameAndTypeInfo().getType() + + res.compilationInfo() + "\n" + indyInfo.type().stringValue() + "\n" + makeIndyType()); return; } @@ -247,41 +247,35 @@ public class TestLambdaBytecode extends ComboInstance { return; } - BootstrapMethods_attribute bsm_attr = - (BootstrapMethods_attribute)cf - .getAttribute(Attribute.BootstrapMethods); - if (bsm_attr.bootstrap_method_specifiers.length != 1) { + BootstrapMethodsAttribute bsm_attr = cf.findAttribute(Attributes.BOOTSTRAP_METHODS).orElseThrow(); + if (bsm_attr.bootstrapMethodsSize() != 1) { fail("Bad number of method specifiers " + "in BootstrapMethods attribute"); return; } - BootstrapMethods_attribute.BootstrapMethodSpecifier bsm_spec = - bsm_attr.bootstrap_method_specifiers[0]; + BootstrapMethodEntry bsm_spec = bsm_attr.bootstrapMethods().get(0); - if (bsm_spec.bootstrap_arguments.length != MF_ARITY) { + if (bsm_spec.arguments().size() != MF_ARITY) { fail("Bad number of static invokedynamic args " + "in BootstrapMethod attribute"); return; } - CONSTANT_MethodHandle_info mh = - (CONSTANT_MethodHandle_info)cf.constant_pool.get(bsm_spec.bootstrap_arguments[1]); + MethodHandleEntry mh = (MethodHandleEntry) bsm_spec.arguments().get(1); - boolean kindOK; - switch (mh.reference_kind) { - case REF_invokeStatic: kindOK = mk2.isStatic(); break; - case REF_invokeVirtual: kindOK = !mk2.isStatic() && !mk2.inInterface(); break; - case REF_invokeInterface: kindOK = mk2.inInterface(); break; - default: - kindOK = false; - } + boolean kindOK = switch (mh.kind()) { + case MethodHandleInfo.REF_invokeStatic -> mk2.isStatic(); + case MethodHandleInfo.REF_invokeVirtual -> !mk2.isStatic() && !mk2.inInterface(); + case MethodHandleInfo.REF_invokeInterface -> mk2.inInterface(); + default -> false; + }; if (!kindOK) { - fail("Bad invoke kind in implementation method handle: " + mh.reference_kind); + fail("Bad invoke kind in implementation method handle: " + mh.kind()); return; } - if (!mh.getCPRefInfo().getNameAndTypeInfo().getType().toString().equals(MH_SIG)) { + if (!mh.reference().type().equalsString(MH_SIG)) { fail("Type mismatch in implementation method handle"); return; } diff --git a/test/langtools/tools/javac/lambda/bytecode/TestLambdaBytecodeTargetRelease14.java b/test/langtools/tools/javac/lambda/bytecode/TestLambdaBytecodeTargetRelease14.java index 1a3b5d41f33..6a566c1edb8 100644 --- a/test/langtools/tools/javac/lambda/bytecode/TestLambdaBytecodeTargetRelease14.java +++ b/test/langtools/tools/javac/lambda/bytecode/TestLambdaBytecodeTargetRelease14.java @@ -27,7 +27,12 @@ * @summary Lambda back-end should generate invokespecial for method handles referring to * private instance methods when compiling with --release 14 * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.file * jdk.compiler/com.sun.tools.javac.util @@ -35,13 +40,11 @@ * @run main TestLambdaBytecodeTargetRelease14 */ -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.constantpool.InvokeDynamicEntry; +import jdk.internal.classfile.constantpool.MethodHandleEntry; +import jdk.internal.classfile.instruction.InvokeDynamicInstruction; import java.io.IOException; import java.io.InputStream; @@ -51,6 +54,7 @@ import combo.ComboParameter; import combo.ComboTask.Result; import combo.ComboTestHelper; +import java.lang.invoke.MethodHandleInfo; import javax.tools.JavaFileObject; public class TestLambdaBytecodeTargetRelease14 extends ComboInstance { @@ -208,10 +212,10 @@ public class TestLambdaBytecodeTargetRelease14 extends ComboInstance mk2.isStatic(); + case MethodHandleInfo.REF_invokeSpecial -> !mk2.isStatic(); + case MethodHandleInfo.REF_invokeInterface -> mk2.inInterface(); + default -> false; + }; if (!kindOK) { fail("Bad invoke kind in implementation method handle"); return; } - if (!mh.getCPRefInfo().getNameAndTypeInfo().getType().toString().equals(MH_SIG)) { + if (!mh.reference().type().equalsString(MH_SIG)) { fail("Type mismatch in implementation method handle"); - return; } } catch (Exception e) { e.printStackTrace(); diff --git a/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java b/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java index a98348adb1e..32ea7a6d8ca 100644 --- a/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java +++ b/test/langtools/tools/javac/lambda/deduplication/DeduplicationTest.java @@ -24,7 +24,13 @@ /** * @test 8200301 8201194 * @summary deduplicate lambda methods with the same body, target type, and captured state - * @modules jdk.jdeps/com.sun.tools.classfile jdk.compiler/com.sun.tools.javac.api + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl + * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code jdk.compiler/com.sun.tools.javac.comp * jdk.compiler/com.sun.tools.javac.file jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.tree jdk.compiler/com.sun.tools.javac.util @@ -40,11 +46,10 @@ import com.sun.source.util.JavacTask; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskEvent.Kind; import com.sun.source.util.TaskListener; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute; -import com.sun.tools.classfile.BootstrapMethods_attribute.BootstrapMethodSpecifier; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool.CONSTANT_MethodHandle_info; +import jdk.internal.classfile.BootstrapMethodEntry; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.BootstrapMethodsAttribute; +import jdk.internal.classfile.constantpool.MethodHandleEntry; import com.sun.tools.javac.api.ClientCodeWrapper.Trusted; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.code.Symbol; @@ -136,22 +141,19 @@ public class DeduplicationTest { // lambdas. Set bootstrapMethodNames = new TreeSet<>(); for (JavaFileObject output : generated) { - ClassFile cf; + ClassModel cm; try (InputStream input = output.openInputStream()) { - cf = ClassFile.read(input); + cm = Classfile.of().parse(input.readAllBytes()); } - if (cf.getName().equals("com/sun/tools/javac/comp/Deduplication$R")) { + if (cm.thisClass().asInternalName().equals("com/sun/tools/javac/comp/Deduplication$R")) { continue; } - BootstrapMethods_attribute bsm = - (BootstrapMethods_attribute) cf.getAttribute(Attribute.BootstrapMethods); - for (BootstrapMethodSpecifier b : bsm.bootstrap_method_specifiers) { + BootstrapMethodsAttribute bsm = cm.findAttribute(Attributes.BOOTSTRAP_METHODS).orElseThrow(); + for (BootstrapMethodEntry b : bsm.bootstrapMethods()) { bootstrapMethodNames.add( - ((CONSTANT_MethodHandle_info) - cf.constant_pool.get(b.bootstrap_arguments[1])) - .getCPRefInfo() - .getNameAndTypeInfo() - .getName()); + ((MethodHandleEntry)b.arguments().get(1)) + .reference() + .name().stringValue()); } } Set deduplicatedNames = diff --git a/test/langtools/tools/javac/lambda/lambdaNaming/TestNonSerializableLambdaNameStability.java b/test/langtools/tools/javac/lambda/lambdaNaming/TestNonSerializableLambdaNameStability.java index 70b35d7956e..4a5ff01aaa9 100644 --- a/test/langtools/tools/javac/lambda/lambdaNaming/TestNonSerializableLambdaNameStability.java +++ b/test/langtools/tools/javac/lambda/lambdaNaming/TestNonSerializableLambdaNameStability.java @@ -26,7 +26,12 @@ * @bug 8067422 * @summary Check that the lambda names are not unnecessarily unstable * @library /tools/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.jdeps/com.sun.tools.javap @@ -40,8 +45,7 @@ import java.util.ArrayList; import java.util.List; import javax.tools.StandardLocation; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; import toolbox.JavacTask; import toolbox.ToolBox; @@ -83,11 +87,11 @@ public class TestNonSerializableLambdaNameStability { byte[] fileBytes = fm.getFileBytes(StandardLocation.CLASS_OUTPUT, file); try (InputStream in = new ByteArrayInputStream(fileBytes)) { boolean foundLambdaMethod = false; - ClassFile cf = ClassFile.read(in); + ClassModel cf = Classfile.of().parse(in.readAllBytes()); StringBuilder seenMethods = new StringBuilder(); String sep = ""; - for (Method m : cf.methods) { - String methodName = m.getName(cf.constant_pool); + for (MethodModel m : cf.methods()) { + String methodName = m.methodName().stringValue(); if (expectedLambdaMethodName.equals(methodName)) { foundLambdaMethod = true; break; diff --git a/test/langtools/tools/javac/launcher/GetResourceTest.java b/test/langtools/tools/javac/launcher/GetResourceTest.java index 2190da81595..9433ec657b2 100644 --- a/test/langtools/tools/javac/launcher/GetResourceTest.java +++ b/test/langtools/tools/javac/launcher/GetResourceTest.java @@ -25,7 +25,7 @@ * @test * @bug 8210009 * @summary Source Launcher classloader should support getResource and getResourceAsStream - * @modules jdk.compiler jdk.jdeps + * @modules jdk.compiler * @library /tools/lib * @build toolbox.JavaTask toolbox.ToolBox * @run main GetResourceTest @@ -53,8 +53,8 @@ public class GetResourceTest { ToolBox tb = new ToolBox(); Path file = Paths.get(tb.testSrc).resolve("src").resolve("CLTest.java"); new JavaTask(tb) - .vmOptions("--add-modules", "jdk.jdeps", - "--add-exports", "jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED") + .vmOptions("--add-exports", "java.base/jdk.internal.classfile=ALL-UNNAMED", + "--add-exports", "java.base/jdk.internal.classfile.constantpool=ALL-UNNAMED") .className(file.toString()) // implies source file mode .run(Task.Expect.SUCCESS) .writeAll(); diff --git a/test/langtools/tools/javac/launcher/SourceLauncherTest.java b/test/langtools/tools/javac/launcher/SourceLauncherTest.java index 87b691be396..06190546d49 100644 --- a/test/langtools/tools/javac/launcher/SourceLauncherTest.java +++ b/test/langtools/tools/javac/launcher/SourceLauncherTest.java @@ -29,18 +29,19 @@ * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.launcher * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl + * java.base/jdk.internal.module * @build toolbox.JavaTask toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox * @run main SourceLauncherTest */ -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Attributes; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ClassWriter; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPool.CPInfo; -import com.sun.tools.classfile.ModuleResolution_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.ModuleResolutionAttribute; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -70,6 +71,8 @@ import toolbox.TestRunner; import toolbox.TestRunner.Test; import toolbox.ToolBox; +import static jdk.internal.module.ClassFileConstants.WARN_INCUBATING; + public class SourceLauncherTest extends TestRunner { public static void main(String... args) throws Exception { SourceLauncherTest t = new SourceLauncherTest(); @@ -717,29 +720,12 @@ public class SourceLauncherTest extends TestRunner { } //where: private static void markModuleAsIncubator(Path moduleInfoFile) throws Exception { - ClassFile cf = ClassFile.read(moduleInfoFile); - List newPool = new ArrayList<>(); - newPool.add(null); - cf.constant_pool.entries().forEach(newPool::add); - int moduleResolutionIndex = newPool.size(); - newPool.add(new ConstantPool.CONSTANT_Utf8_info(Attribute.ModuleResolution)); - Map newAttributes = new HashMap<>(cf.attributes.map); - newAttributes.put(Attribute.ModuleResolution, - new ModuleResolution_attribute(moduleResolutionIndex, - ModuleResolution_attribute.WARN_INCUBATING)); - ClassFile newClassFile = new ClassFile(cf.magic, - cf.minor_version, - cf.major_version, - new ConstantPool(newPool.toArray(new CPInfo[0])), - cf.access_flags, - cf.this_class, - cf.super_class, - cf.interfaces, - cf.fields, - cf.methods, - new Attributes(newAttributes)); + ClassModel cf = Classfile.of().parse(moduleInfoFile); + ModuleResolutionAttribute newAttr = ModuleResolutionAttribute.of(WARN_INCUBATING); + byte[] newBytes = Classfile.of().transform(cf, ClassTransform.dropping(ce -> ce instanceof Attributes) + .andThen(ClassTransform.endHandler(classBuilder -> classBuilder.with(newAttr)))); try (OutputStream out = Files.newOutputStream(moduleInfoFile)) { - new ClassWriter().write(newClassFile, out); + out.write(newBytes); } } diff --git a/test/langtools/tools/javac/launcher/src/CLTest.java b/test/langtools/tools/javac/launcher/src/CLTest.java index b6a71e8b351..3e04aab0e6a 100644 --- a/test/langtools/tools/javac/launcher/src/CLTest.java +++ b/test/langtools/tools/javac/launcher/src/CLTest.java @@ -31,8 +31,7 @@ * the URLs and streams returned by the methods being tested. * * $ java \ - * --add-modules jdk.jdeps \ - * --add-exports jdk.jdeps/com.sun.tools.classfile=ALL-UNNAMED + * --add-exports java.base/jdk.internal.classfile=ALL-UNNAMED * /path/to/CLTest.java */ package p.q; @@ -40,7 +39,8 @@ package p.q; import java.io.*; import java.net.*; import java.util.*; -import com.sun.tools.classfile.ClassFile; +import jdk.internal.classfile.ClassModel; +import jdk.internal.classfile.Classfile; public class CLTest { public static void main(String... args) throws Exception { @@ -152,10 +152,10 @@ public class CLTest { } void checkClass(String name, InputStream in) throws Exception { - ClassFile cf = ClassFile.read(in); - System.err.println(" class " + cf.getName()); - if (!name.equals(cf.getName() + ".class")) { - error("unexpected class found: " + cf.getName()); + ClassModel cf = Classfile.of().parse(in.readAllBytes()); + System.err.println(" class " + cf.thisClass().asInternalName()); + if (!name.equals(cf.thisClass().asInternalName() + ".class")) { + error("unexpected class found: " + cf.thisClass().asInternalName()); } } diff --git a/test/langtools/tools/javac/linenumbers/FinallyLineNumberTest.java b/test/langtools/tools/javac/linenumbers/FinallyLineNumberTest.java index 51946f63884..2e4aaa131f0 100644 --- a/test/langtools/tools/javac/linenumbers/FinallyLineNumberTest.java +++ b/test/langtools/tools/javac/linenumbers/FinallyLineNumberTest.java @@ -25,72 +25,72 @@ * @test * @bug 8134759 * @summary Add LineNumberTable attribute for return bytecodes split around finally code - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components */ -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.LineNumberTable_attribute; -import com.sun.tools.classfile.LineNumberTable_attribute.Entry; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import java.io.IOException; +import java.util.List; public class FinallyLineNumberTest { public static void main(String[] args) throws Exception { // check that we have 5 consecutive entries for method() - Entry[] lines = findEntries(); + List lines = findEntries(); if (lines == null) { throw new Exception("finally line number table could not be loaded"); } - if (lines.length != 5) { + if (lines.size() != 5) { // Help debug System.err.println("LineTable error, got lines:"); - for (Entry e : lines) { - System.err.println(e.line_number); + for (LineNumberInfo e : lines) { + System.err.println(e.lineNumber()); } - throw new Exception("finally line number table incorrect: length=" + lines.length + " expected length=5"); + throw new Exception("finally line number table incorrect: length=" + lines.size() + " expected length=5"); } // return null line, for the load null operation - int current = lines[0].line_number; + int current = lines.get(0).lineNumber(); int first = current; // finally line - current = lines[1].line_number; + current = lines.get(1).lineNumber(); if (current != first + 2) { throw new Exception("finally line number table incorrect: got=" + current + " expected=" + (first + 2)); } // return null line, for the return operation - current = lines[2].line_number; + current = lines.get(2).lineNumber(); if (current != first) { throw new Exception("finally line number table incorrect: got=" + current + " expected=" + first); } // for when exception is thrown - current = lines[3].line_number; + current = lines.get(3).lineNumber(); if (current != first + 2) { throw new Exception("finally line number table incorrect: got=" + current + " expected=" + (first + 2)); } // the '}' closing the finally block - current = lines[4].line_number; + current = lines.get(4).lineNumber(); if (current != first + 3) { throw new Exception("finally line number table incorrect: got=" + current + " expected=" + (first + 3)); } } - static Entry[] findEntries() throws IOException, ConstantPoolException { - ClassFile self = ClassFile.read(FinallyLineNumberTest.class.getResourceAsStream("FinallyLineNumberTest.class")); - for (Method m : self.methods) { - if ("method".equals(m.getName(self.constant_pool))) { - Code_attribute code_attribute = (Code_attribute)m.attributes.get(Attribute.Code); - for (Attribute at : code_attribute.attributes) { - if (Attribute.LineNumberTable.equals(at.getName(self.constant_pool))) { - return ((LineNumberTable_attribute)at).line_number_table; + static List findEntries() throws IOException { + ClassModel self = Classfile.of().parse(FinallyLineNumberTest.class.getResourceAsStream("FinallyLineNumberTest.class").readAllBytes()); + for (MethodModel m : self.methods()) { + if (m.methodName().equalsString("method")) { + CodeAttribute code_attribute = m.findAttribute(Attributes.CODE).orElseThrow(); + for (Attribute at : code_attribute.attributes()) { + if (at instanceof LineNumberTableAttribute lineAt) { + return lineAt.lineNumbers(); } } } diff --git a/test/langtools/tools/javac/linenumbers/NestedLineNumberTest.java b/test/langtools/tools/javac/linenumbers/NestedLineNumberTest.java index 9f9d83c6ed2..9b042c7f8ab 100644 --- a/test/langtools/tools/javac/linenumbers/NestedLineNumberTest.java +++ b/test/langtools/tools/javac/linenumbers/NestedLineNumberTest.java @@ -2,42 +2,42 @@ * @test /nodynamiccopyright/ * @bug 8061778 * @summary Wrong LineNumberTable for default constructors - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components */ -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.LineNumberTable_attribute; -import com.sun.tools.classfile.LineNumberTable_attribute.Entry; +import java.util.List; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import java.io.IOException; public class NestedLineNumberTest { public static void main(String[] args) throws Exception { - Entry[] lines = findEntries(); - if (lines == null || lines.length != 1) { - int found = lines == null ? 0 : lines.length; + List lines = findEntries(); + if (lines == null || lines.size() != 1) { + int found = lines == null ? 0 : lines.size(); error(String.format("LineNumberTable contains wrong number of entries - expected %d, found %d", 1, found)); } - int line = lines[0].line_number; + int line = lines.get(0).lineNumber(); if (line != 54) { error(String.format("LineNumberTable contains wrong line number - expected %d, found %d", 54, line)); } } - static Entry[] findEntries() throws IOException, ConstantPoolException { - ClassFile self = ClassFile.read(NestedLineNumberTest.Test.class.getResourceAsStream("NestedLineNumberTest$Test.class")); - for (Method m : self.methods) { - if ("".equals(m.getName(self.constant_pool))) { - Code_attribute code_attribute = (Code_attribute)m.attributes.get(Attribute.Code); - for (Attribute at : code_attribute.attributes) { - if (Attribute.LineNumberTable.equals(at.getName(self.constant_pool))) { - return ((LineNumberTable_attribute)at).line_number_table; + static List findEntries() throws IOException { + ClassModel self = Classfile.of().parse(NestedLineNumberTest.Test.class.getResourceAsStream("NestedLineNumberTest$Test.class").readAllBytes()); + for (MethodModel m : self.methods()) { + if ("".equals(m.methodName().stringValue())) { + CodeAttribute code_attribute = m.findAttribute(Attributes.CODE).orElseThrow(); + for (Attribute at : code_attribute.attributes()) { + if (at instanceof LineNumberTableAttribute lineAt) { + return lineAt.lineNumbers(); } } } diff --git a/test/langtools/tools/javac/linenumbers/NullCheckLineNumberTest.java b/test/langtools/tools/javac/linenumbers/NullCheckLineNumberTest.java index 30c1a1c6b0e..018641747fd 100644 --- a/test/langtools/tools/javac/linenumbers/NullCheckLineNumberTest.java +++ b/test/langtools/tools/javac/linenumbers/NullCheckLineNumberTest.java @@ -2,15 +2,15 @@ * @test /nodynamiccopyright/ * @bug 8172880 * @summary Wrong LineNumberTable for synthetic null checks - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components */ -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.LineNumberTable_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import java.io.IOException; import java.util.AbstractMap.SimpleEntry; @@ -63,15 +63,15 @@ public class NullCheckLineNumberTest { } } - static List findEntries() throws IOException, ConstantPoolException { - ClassFile self = ClassFile.read(NullCheckLineNumberTest.Test.class.getResourceAsStream("NullCheckLineNumberTest$Test.class")); - for (Method m : self.methods) { - if ("".equals(m.getName(self.constant_pool))) { - Code_attribute code_attribute = (Code_attribute)m.attributes.get(Attribute.Code); - for (Attribute at : code_attribute.attributes) { - if (Attribute.LineNumberTable.equals(at.getName(self.constant_pool))) { - return Arrays.stream(((LineNumberTable_attribute)at).line_number_table) - .map(e -> new SimpleEntry<> (e.line_number, e.start_pc)) + static List findEntries() throws IOException { + ClassModel self = Classfile.of().parse(Objects.requireNonNull(Test.class.getResourceAsStream("NullCheckLineNumberTest$Test.class")).readAllBytes()); + for (MethodModel m : self.methods()) { + if ("".equals(m.methodName().stringValue())) { + CodeAttribute code_attribute = m.findAttribute(Attributes.CODE).orElseThrow(); + for (Attribute at : code_attribute.attributes()) { + if (at instanceof LineNumberTableAttribute lineAt) { + return lineAt.lineNumbers().stream() + .map(e -> new SimpleEntry<> (e.lineNumber(), e.startPc())) .collect(Collectors.toList()); } } diff --git a/test/langtools/tools/javac/meth/TestCP.java b/test/langtools/tools/javac/meth/TestCP.java index 4b2b277dfb2..3f942f5b42d 100644 --- a/test/langtools/tools/javac/meth/TestCP.java +++ b/test/langtools/tools/javac/meth/TestCP.java @@ -25,16 +25,19 @@ * @test * @bug 6991980 * @summary polymorphic signature calls don't share the same CP entries - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @run main TestCP */ -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.MemberRefEntry; +import jdk.internal.classfile.instruction.InvokeInstruction; import java.lang.invoke.*; import java.io.*; @@ -125,10 +128,10 @@ public class TestCP { System.err.println("verify: " + f); try { int count = 0; - ClassFile cf = ClassFile.read(f); - Method testMethod = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals(TEST_METHOD_NAME)) { + ClassModel cf = Classfile.of().parse(f.toPath()); + MethodModel testMethod = null; + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString(TEST_METHOD_NAME)) { testMethod = m; break; } @@ -136,24 +139,22 @@ public class TestCP { if (testMethod == null) { throw new Error("Test method not found"); } - Code_attribute ea = (Code_attribute)testMethod.attributes.get(Attribute.Code); - if (testMethod == null) { + CodeAttribute ea = testMethod.findAttribute(Attributes.CODE).orElse(null); + if (ea == null) { throw new Error("Code attribute for test() method not found"); } int instr_count = 0; - int cp_entry = -1; + MemberRefEntry methRef = null; - for (Instruction i : ea.getInstructions()) { - if (i.getMnemonic().equals("invokevirtual")) { + for (CodeElement ce : ea.elementList()) { + if (ce instanceof InvokeInstruction ins && ins.opcode() == Opcode.INVOKEVIRTUAL) { instr_count++; - if (cp_entry == -1) { - cp_entry = i.getUnsignedShort(1); - } else if (cp_entry != i.getUnsignedShort(1)) { + if (methRef == null) { + methRef = ins.method(); + } else if (methRef != ins.method()) { throw new Error("Unexpected CP entry in polymorphic signature call"); } - CONSTANT_Methodref_info methRef = - (CONSTANT_Methodref_info)cf.constant_pool.get(cp_entry); - String type = methRef.getNameAndTypeInfo().getType(); + String type = methRef.type().stringValue(); if (!type.equals(psType)) { throw new Error("Unexpected type in polymorphic signature call: " + type); } diff --git a/test/langtools/tools/javac/modules/AnnotationsOnModules.java b/test/langtools/tools/javac/modules/AnnotationsOnModules.java index 46541a90ed9..a797ae8d44e 100644 --- a/test/langtools/tools/javac/modules/AnnotationsOnModules.java +++ b/test/langtools/tools/javac/modules/AnnotationsOnModules.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask ModuleTestBase * @run main AnnotationsOnModules */ @@ -51,11 +56,9 @@ import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ModuleElement; import javax.lang.model.element.TypeElement; -import com.sun.tools.classfile.Annotation; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.RuntimeInvisibleAnnotations_attribute; -import com.sun.tools.classfile.RuntimeVisibleAnnotations_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.Classfile; +import jdk.internal.classfile.attribute.*; import toolbox.JavacTask; import toolbox.Task; import toolbox.Task.OutputKind; @@ -86,10 +89,10 @@ public class AnnotationsOnModules extends ModuleTestBase { .run() .writeAll(); - ClassFile cf = ClassFile.read(modulePath.resolve("m1x").resolve("module-info.class")); - RuntimeVisibleAnnotations_attribute annotations = (RuntimeVisibleAnnotations_attribute) cf.attributes.map.get(Attribute.RuntimeVisibleAnnotations); + ClassModel cf = Classfile.of().parse(modulePath.resolve("m1x").resolve("module-info.class")); + RuntimeVisibleAnnotationsAttribute annotations = cf.findAttribute(Attributes.RUNTIME_VISIBLE_ANNOTATIONS).orElse(null); - if (annotations == null || annotations.annotations.length != 1) { + if (annotations == null || annotations.annotations().size() != 1) { throw new AssertionError("Annotations not correct!"); } } @@ -140,14 +143,14 @@ public class AnnotationsOnModules extends ModuleTestBase { throw new AssertionError("Output is not empty. Expected no output and no warnings."); } - ClassFile cf = ClassFile.read(modulePath.resolve("A").resolve("module-info.class")); - RuntimeVisibleAnnotations_attribute annotations = (RuntimeVisibleAnnotations_attribute) cf.attributes.map.get(Attribute.RuntimeVisibleAnnotations); + ClassModel cf = Classfile.of().parse(modulePath.resolve("A").resolve("module-info.class")); + RuntimeVisibleAnnotationsAttribute annotations = cf.findAttribute(Attributes.RUNTIME_VISIBLE_ANNOTATIONS).orElse(null); - if (annotations != null && annotations.annotations.length > 0) { + if (annotations != null && annotations.annotations().size() > 0) { throw new AssertionError("Found annotation attributes. Expected no annotations for javadoc @deprecated tag."); } - if (cf.attributes.map.get(Attribute.Deprecated) != null) { + if (cf.findAttribute(Attributes.DEPRECATED).isPresent()) { throw new AssertionError("Found Deprecated attribute. Expected no Deprecated attribute for javadoc @deprecated tag."); } } @@ -191,17 +194,17 @@ public class AnnotationsOnModules extends ModuleTestBase { throw new AssertionError("Expected output not found. Expected: " + expected); } - ClassFile cf = ClassFile.read(modulePath.resolve("A").resolve("module-info.class")); - RuntimeVisibleAnnotations_attribute annotations = (RuntimeVisibleAnnotations_attribute) cf.attributes.map.get(Attribute.RuntimeVisibleAnnotations); + ClassModel cf = Classfile.of().parse(modulePath.resolve("A").resolve("module-info.class")); + RuntimeVisibleAnnotationsAttribute annotations = cf.findAttribute(Attributes.RUNTIME_VISIBLE_ANNOTATIONS).orElse(null); if (annotations == null ) { throw new AssertionError("Annotations not found!"); } - int length = annotations.annotations.length; + int length = annotations.annotations().size(); if (length != 1 ) { throw new AssertionError("Incorrect number of annotations: " + length); } - int pairsCount = annotations.annotations[0].num_element_value_pairs; + int pairsCount = annotations.annotations().get(0).elements().size(); if (pairsCount != 2) { throw new AssertionError("Incorrect number of key-value pairs in annotation: " + pairsCount + " Expected two: forRemoval and since."); } @@ -314,10 +317,10 @@ public class AnnotationsOnModules extends ModuleTestBase { .run() .writeAll(); - ClassFile cf = ClassFile.read(modulePath.resolve("m1x").resolve("module-info.class")); - RuntimeInvisibleAnnotations_attribute annotations = (RuntimeInvisibleAnnotations_attribute) cf.attributes.map.get(Attribute.RuntimeInvisibleAnnotations); + ClassModel cf = Classfile.of().parse(modulePath.resolve("m1x").resolve("module-info.class")); + RuntimeInvisibleAnnotationsAttribute annotations = cf.findAttribute(Attributes.RUNTIME_INVISIBLE_ANNOTATIONS).orElse(null); - if (annotations == null || annotations.annotations.length != 1) { + if (annotations == null || annotations.annotations().size() != 1) { throw new AssertionError("Annotations not correct!"); } } @@ -356,13 +359,13 @@ public class AnnotationsOnModules extends ModuleTestBase { .run() .writeAll(); - ClassFile cf = ClassFile.read(modulePath.resolve("B").resolve("module-info.class")); - RuntimeInvisibleAnnotations_attribute annotations = (RuntimeInvisibleAnnotations_attribute) cf.attributes.map.get(Attribute.RuntimeInvisibleAnnotations); + ClassModel cf = Classfile.of().parse(modulePath.resolve("B").resolve("module-info.class")); + RuntimeInvisibleAnnotationsAttribute annotations = cf.findAttribute(Attributes.RUNTIME_INVISIBLE_ANNOTATIONS).orElse(null); if (annotations == null ) { throw new AssertionError("Annotations not found!"); } - int length = annotations.annotations.length; + int length = annotations.annotations().size(); if (length != 2 ) { throw new AssertionError("Incorrect number of annotations: " + length); } @@ -431,18 +434,18 @@ public class AnnotationsOnModules extends ModuleTestBase { .run() .writeAll(); - ClassFile cf = ClassFile.read(classes.resolve("m1x").resolve("module-info.class")); - var invisibleAnnotations = (RuntimeInvisibleAnnotations_attribute) cf.attributes.map.get(Attribute.RuntimeInvisibleAnnotations); + ClassModel cf = Classfile.of().parse(classes.resolve("m1x").resolve("module-info.class")); + RuntimeInvisibleAnnotationsAttribute invisibleAnnotations = cf.findAttribute(Attributes.RUNTIME_INVISIBLE_ANNOTATIONS).orElse(null); if (invisibleAnnotations == null) { throw new AssertionError("Annotations not found!"); } - int length = invisibleAnnotations.annotations.length; + int length = invisibleAnnotations.annotations().size(); if (length != 1) { throw new AssertionError("Incorrect number of annotations: " + length); } - Annotation annotation = invisibleAnnotations.annotations[0]; - String annotationName = cf.constant_pool.getUTF8Value(annotation.type_index).toString(); + Annotation annotation = invisibleAnnotations.annotations().get(0); + String annotationName = annotation.classSymbol().descriptorString(); if (!"Ltest/A;".equals(annotationName)) { throw new AssertionError("Incorrect annotation name: " + annotationName); } diff --git a/test/langtools/tools/javac/modules/IncubatingTest.java b/test/langtools/tools/javac/modules/IncubatingTest.java index 796d8df343f..23112d4200e 100644 --- a/test/langtools/tools/javac/modules/IncubatingTest.java +++ b/test/langtools/tools/javac/modules/IncubatingTest.java @@ -28,7 +28,13 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl + * java.base/jdk.internal.module * jdk.jdeps/com.sun.tools.javap * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask toolbox.JavapTask ModuleTestBase * @run main IncubatingTest @@ -47,17 +53,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Attributes; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ClassWriter; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Utf8_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; -import com.sun.tools.classfile.ModuleResolution_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.ModuleResolutionAttribute; +import jdk.internal.classfile.constantpool.*; import toolbox.JavacTask; import toolbox.Task; import toolbox.Task.Expect; +import static jdk.internal.module.ClassFileConstants.DO_NOT_RESOLVE_BY_DEFAULT; +import static jdk.internal.module.ClassFileConstants.WARN_INCUBATING; public class IncubatingTest extends ModuleTestBase { @@ -85,7 +88,7 @@ public class IncubatingTest extends ModuleTestBase { copyJavaBase(classes); Path jdkIModuleInfo = iClasses.resolve("module-info.class"); - addModuleResolutionAttribute(jdkIModuleInfo, ModuleResolution_attribute.DO_NOT_RESOLVE_BY_DEFAULT); + addModuleResolutionAttribute(jdkIModuleInfo, DO_NOT_RESOLVE_BY_DEFAULT); Path testSrc = base.resolve("test-src"); tb.writeJavaFiles(testSrc, @@ -175,7 +178,7 @@ public class IncubatingTest extends ModuleTestBase { .writeAll(); Path jdkIModuleInfo = iClasses.resolve("module-info.class"); - addModuleResolutionAttribute(jdkIModuleInfo, ModuleResolution_attribute.WARN_INCUBATING); + addModuleResolutionAttribute(jdkIModuleInfo, WARN_INCUBATING); Path testSrc = base.resolve("test-src"); tb.writeJavaFiles(testSrc, @@ -255,34 +258,12 @@ public class IncubatingTest extends ModuleTestBase { } private void addModuleResolutionAttribute(Path classfile, int resolution_flags) throws Exception { - ClassFile cf = ClassFile.read(classfile); - Attributes attrs = cf.attributes; - List cpData = new ArrayList<>(); - cpData.add(null); - for (CPInfo info : cf.constant_pool.entries()) { - cpData.add(info); - if (info.size() == 2) - cpData.add(null); - } - cpData.add(new CONSTANT_Utf8_info(Attribute.ModuleResolution)); - ConstantPool newCP = new ConstantPool(cpData.toArray(new CPInfo[0])); - ModuleResolution_attribute res = new ModuleResolution_attribute(newCP, resolution_flags); - Map newAttributeMap = new HashMap<>(attrs.map); - newAttributeMap.put(Attribute.ModuleResolution, res); - Attributes newAttrs = new Attributes(newAttributeMap); - ClassFile newCF = new ClassFile(cf.magic, - cf.minor_version, - cf.major_version, - newCP, - cf.access_flags, - cf.this_class, - cf.super_class, - cf.interfaces, - cf.fields, - cf.methods, - newAttrs); + ClassModel cm = Classfile.of().parse(classfile); + ModuleResolutionAttribute modRAttr = ModuleResolutionAttribute.of(resolution_flags); + byte[] newBytes = Classfile.of().transform(cm, ClassTransform.dropping(ce -> ce instanceof ModuleResolutionAttribute). + andThen(ClassTransform.endHandler(classBuilder -> classBuilder.with(modRAttr)))); try (OutputStream out = Files.newOutputStream(classfile)) { - new ClassWriter().write(newCF, out); + out.write(newBytes); } } } diff --git a/test/langtools/tools/javac/modules/JavaBaseTest.java b/test/langtools/tools/javac/modules/JavaBaseTest.java index 0f9ebb78ec4..110c796525b 100644 --- a/test/langtools/tools/javac/modules/JavaBaseTest.java +++ b/test/langtools/tools/javac/modules/JavaBaseTest.java @@ -31,26 +31,25 @@ * jdk.compiler/com.sun.tools.javac.jvm * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.platform - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main JavaBaseTest */ +import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.stream.StreamSupport; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Attributes; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ClassWriter; -import com.sun.tools.classfile.Module_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import com.sun.tools.javac.jvm.Target; import com.sun.tools.javac.platform.JDKPlatformProvider; @@ -109,12 +108,8 @@ public class JavaBaseTest { .resolve(target).resolve(mode.name().toLowerCase()); Files.createDirectories(base); switch (mode) { - case SOURCE: - testSource(base, mods, target); - break; - case CLASS: - testClass(base, mods, target); - break; + case SOURCE -> testSource(base, mods, target); + case CLASS -> testClass(base, mods, target); } } catch (Exception e) { error("Exception: " + e); @@ -213,57 +208,44 @@ public class JavaBaseTest { jct.files(tb.findJavaFiles(src1)) .run(Task.Expect.SUCCESS); - ClassFile cf1 = ClassFile.read(modules1.resolve("module-info.class")); + ClassModel cm1 = Classfile.of().parse(modules1.resolve("module-info.class")); - Map attrMap = new LinkedHashMap<>(cf1.attributes.map); - Module_attribute modAttr1 = (Module_attribute) attrMap.get("Module"); - Module_attribute.RequiresEntry[] requires = - new Module_attribute.RequiresEntry[modAttr1.requires_count]; - for (int i = 0; i < modAttr1.requires_count; i++) { - Module_attribute.RequiresEntry e1 = modAttr1.requires[i]; - int flags = e1.requires_flags; - Module_attribute.RequiresEntry e2; - if (e1.getRequires(cf1.constant_pool).equals("java.base")) { + ModuleAttribute modAttr1 = cm1.findAttribute(Attributes.MODULE).orElseThrow(); + List requires = Arrays.asList(new ModuleRequireInfo[modAttr1.requires().size()]); + for (int i = 0; i < modAttr1.requires().size(); ++i) { + ModuleRequireInfo e1 = modAttr1.requires().get(i); + int flags = e1.requiresFlagsMask(); + ModuleRequireInfo e2; + if (e1.requires().name().equalsString("java.base")) { for (String mod : mods) { switch (mod) { - case "static": - flags |= Module_attribute.ACC_STATIC_PHASE; - break; - case "transitive": - flags |= Module_attribute.ACC_TRANSITIVE; - break; + case "static" -> flags |= Classfile.ACC_STATIC_PHASE; + case "transitive" -> flags |= Classfile.ACC_TRANSITIVE; } } - e2 = new Module_attribute.RequiresEntry( - e1.requires_index, - flags, - e1.requires_version_index); + e2 = ModuleRequireInfo.of(e1.requires(), flags, e1.requiresVersion().orElse(null)); } else { e2 = e1; } - requires[i] = e2; + requires.set(i, e2); } - Module_attribute modAttr2 = new Module_attribute( - modAttr1.attribute_name_index, - modAttr1.module_name, - modAttr1.module_flags, - modAttr1.module_version_index, - requires, - modAttr1.exports, - modAttr1.opens, - modAttr1.uses_index, - modAttr1.provides); - attrMap.put("Module", modAttr2); - Attributes attributes = new Attributes(attrMap); - ClassFile cf2 = new ClassFile( - cf1.magic, cf1.minor_version, cf1.major_version, - cf1.constant_pool, cf1.access_flags, - cf1.this_class, cf1.super_class, cf1.interfaces, - cf1.fields, cf1.methods, attributes); + ModuleAttribute modAttr2 = ModuleAttribute.of( + modAttr1.moduleName(), + modAttr1.moduleFlagsMask(), + modAttr1.moduleVersion().orElse(null), + requires, + modAttr1.exports(), + modAttr1.opens(), + modAttr1.uses(), + modAttr1.provides()); Path modInfo = base.resolve("test-modules").resolve("module-info.class"); Files.createDirectories(modInfo.getParent()); - new ClassWriter().write(cf2, modInfo.toFile()); + byte[] newBytes = Classfile.of().transform(cm1, ClassTransform.dropping(ce -> ce instanceof ModuleAttribute). + andThen(ClassTransform.endHandler(classBuilder -> classBuilder.with(modAttr2)))); + try (OutputStream out = Files.newOutputStream(modInfo)) { + out.write(newBytes); + } } private void error(String message) { diff --git a/test/langtools/tools/javac/modules/ModuleVersion.java b/test/langtools/tools/javac/modules/ModuleVersion.java index 5ae6757475b..6c6d04b15fc 100644 --- a/test/langtools/tools/javac/modules/ModuleVersion.java +++ b/test/langtools/tools/javac/modules/ModuleVersion.java @@ -27,7 +27,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask toolbox.ModuleBuilder ModuleTestBase * @run main ModuleVersion */ @@ -36,10 +41,8 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Module_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.ModuleAttribute; import toolbox.JavacTask; import toolbox.Task.Expect; import toolbox.Task.OutputKind; @@ -112,16 +115,16 @@ public class ModuleVersion extends ModuleTestBase { } } - private void checkModuleVersion(Path classfile, String version) throws IOException, ConstantPoolException { - ClassFile cf = ClassFile.read(classfile); + private void checkModuleVersion(Path classfile, String version) throws IOException { + ClassModel cm = Classfile.of().parse(classfile); - Module_attribute moduleAttribute = (Module_attribute) cf.attributes.get(Attribute.Module); + ModuleAttribute moduleAttribute = cm.findAttribute(Attributes.MODULE).orElse(null); if (moduleAttribute == null) { throw new AssertionError("Version attribute missing!"); } - String actualVersion = cf.constant_pool.getUTF8Value(moduleAttribute.module_version_index); + String actualVersion = moduleAttribute.moduleVersion().orElseThrow().stringValue(); if (!version.equals(actualVersion)) { throw new AssertionError("Incorrect version in the classfile: " + actualVersion); diff --git a/test/langtools/tools/javac/modules/OpenModulesTest.java b/test/langtools/tools/javac/modules/OpenModulesTest.java index 3b531d576d4..319aa24f387 100644 --- a/test/langtools/tools/javac/modules/OpenModulesTest.java +++ b/test/langtools/tools/javac/modules/OpenModulesTest.java @@ -27,7 +27,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.jdeps/com.sun.tools.javap * @build toolbox.ToolBox toolbox.JavacTask toolbox.ModuleBuilder ModuleTestBase * @run main OpenModulesTest @@ -42,11 +47,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Attributes; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ClassWriter; -import com.sun.tools.classfile.Module_attribute; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.ModuleAttribute; import toolbox.JavacTask; import toolbox.JavapTask; import toolbox.Task; @@ -234,36 +236,21 @@ public class OpenModulesTest extends ModuleTestBase { .writeAll(); Path miClass = m1Classes.resolve("module-info.class"); - ClassFile cf = ClassFile.read(miClass); - Module_attribute module = (Module_attribute) cf.attributes.map.get(Attribute.Module); - Module_attribute newModule = new Module_attribute(module.attribute_name_index, - module.module_name, - module.module_flags | Module_attribute.ACC_OPEN, - module.module_version_index, - module.requires, - module.exports, - module.opens, - module.uses_index, - module.provides); - Map attrs = new HashMap<>(cf.attributes.map); - - attrs.put(Attribute.Module, newModule); - - Attributes newAttributes = new Attributes(attrs); - ClassFile newClassFile = new ClassFile(cf.magic, - cf.minor_version, - cf.major_version, - cf.constant_pool, - cf.access_flags, - cf.this_class, - cf.super_class, - cf.interfaces, - cf.fields, - cf.methods, - newAttributes); + ClassModel cm = Classfile.of().parse(miClass); + ModuleAttribute module = cm.findAttribute(Attributes.MODULE).orElseThrow(); + ModuleAttribute newModule = ModuleAttribute.of(module.moduleName(), + module.moduleFlagsMask() | Classfile.ACC_OPEN, + module.moduleVersion().orElse(null), + module.requires(), + module.exports(), + module.opens(), + module.uses(), + module.provides()); + byte[] newBytes = Classfile.of().transform(cm, ClassTransform.dropping(ce -> ce instanceof ModuleAttribute). + andThen(ClassTransform.endHandler(classBuilder -> classBuilder.with(newModule)))); try (OutputStream out = Files.newOutputStream(miClass)) { - new ClassWriter().write(newClassFile, out); + out.write(newBytes); } Path test = base.resolve("test"); diff --git a/test/langtools/tools/javac/multicatch/7005371/T7005371.java b/test/langtools/tools/javac/multicatch/7005371/T7005371.java index bf300b83a55..9a4cb55a46e 100644 --- a/test/langtools/tools/javac/multicatch/7005371/T7005371.java +++ b/test/langtools/tools/javac/multicatch/7005371/T7005371.java @@ -25,16 +25,19 @@ * @test * @bug 7005371 * @summary Multicatch: assertion error while generating LocalVariableTypeTable attribute - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g SubTest.java * @run main T7005371 */ -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.LocalVariableTypeTable_attribute; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.attribute.LocalVariableTypeTableAttribute; import java.io.*; @@ -60,10 +63,10 @@ public class T7005371 { void verifyLocalVariableTypeTableAttr(File f) { System.err.println("verify: " + f); try { - ClassFile cf = ClassFile.read(f); - Method testMethod = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals(TEST_METHOD_NAME)) { + ClassModel cf = Classfile.of().parse(f.toPath()); + MethodModel testMethod = null; + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString(TEST_METHOD_NAME)) { testMethod = m; break; } @@ -71,22 +74,20 @@ public class T7005371 { if (testMethod == null) { throw new Error("Missing method: " + TEST_METHOD_NAME); } - Code_attribute code = (Code_attribute)testMethod.attributes.get(Attribute.Code); + CodeAttribute code = testMethod.findAttribute(Attributes.CODE).orElse(null); if (code == null) { throw new Error("Missing Code attribute for method: " + TEST_METHOD_NAME); } - LocalVariableTypeTable_attribute lvt_table = - (LocalVariableTypeTable_attribute)code.attributes.get(Attribute.LocalVariableTypeTable); + LocalVariableTypeTableAttribute lvt_table = code.findAttribute(Attributes.LOCAL_VARIABLE_TYPE_TABLE).orElse(null); if (lvt_table == null) { throw new Error("Missing LocalVariableTypeTable attribute for method: " + TEST_METHOD_NAME); } - if (lvt_table.local_variable_table_length != LVT_LENGTH) { + if (lvt_table.localVariableTypes().size() != LVT_LENGTH) { throw new Error("LocalVariableTypeTable has wrong size" + - "\nfound: " + lvt_table.local_variable_table_length + + "\nfound: " + lvt_table.localVariableTypes().size() + "\nrequired: " + LVT_LENGTH); } - String sig = - cf.constant_pool.getUTF8Value(lvt_table.local_variable_table[0].signature_index); + String sig = lvt_table.localVariableTypes().get(0).signature().stringValue(); if (sig == null || !sig.equals(LVT_SIG_TYPE)) { throw new Error("LocalVariableTypeTable has wrong signature" + diff --git a/test/langtools/tools/javac/multicatch/Pos05.java b/test/langtools/tools/javac/multicatch/Pos05.java index f4c4d01f75f..baeb17918bb 100644 --- a/test/langtools/tools/javac/multicatch/Pos05.java +++ b/test/langtools/tools/javac/multicatch/Pos05.java @@ -25,15 +25,18 @@ * @test * @bug 6943289 * @summary Project Coin: Improved Exception Handling for Java (aka 'multicatch') - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @run main Pos05 */ -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.Code_attribute.Exception_data; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.instruction.ExceptionCatch; import java.io.*; public class Pos05 { @@ -80,10 +83,10 @@ public class Pos05 { System.err.println("verify: " + f); try { int count = 0; - ClassFile cf = ClassFile.read(f); - Method testMethod = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals(TEST_METHOD_NAME)) { + ClassModel cf = Classfile.of().parse(f.toPath()); + MethodModel testMethod = null; + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString(TEST_METHOD_NAME)) { testMethod = m; break; } @@ -91,18 +94,18 @@ public class Pos05 { if (testMethod == null) { throw new Error("Test method not found"); } - Code_attribute ea = (Code_attribute)testMethod.attributes.get(Attribute.Code); - if (testMethod == null) { + CodeAttribute ea = testMethod.findAttribute(Attributes.CODE).orElse(null); + if (ea == null) { throw new Error("Code attribute for test() method not found"); } - Exception_data firstExceptionTable = null; - for (int i = 0 ; i < ea.exception_table_length; i++) { + ExceptionCatch firstExceptionTable = null; + for (int i = 0 ; i < ea.exceptionHandlers().size(); i++) { if (firstExceptionTable == null) { - firstExceptionTable = ea.exception_table[i]; + firstExceptionTable = ea.exceptionHandlers().get(i); } - if (ea.exception_table[i].handler_pc != firstExceptionTable.handler_pc || - ea.exception_table[i].start_pc != firstExceptionTable.start_pc || - ea.exception_table[i].end_pc != firstExceptionTable.end_pc) { + if (ea.exceptionHandlers().get(i).handler() != firstExceptionTable.handler() || + ea.exceptionHandlers().get(i).tryStart() != firstExceptionTable.tryStart() || + ea.exceptionHandlers().get(i).tryEnd() != firstExceptionTable.tryEnd()) { throw new Error("Multiple overlapping catch clause found in generated code"); } count++; diff --git a/test/langtools/tools/javac/options/release/ReleaseOption9.java b/test/langtools/tools/javac/options/release/ReleaseOption9.java index 5649a182dbb..a7c188c951a 100644 --- a/test/langtools/tools/javac/options/release/ReleaseOption9.java +++ b/test/langtools/tools/javac/options/release/ReleaseOption9.java @@ -29,7 +29,6 @@ * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.jvm - * jdk.jdeps/com.sun.tools.classfile * jdk.jdeps/com.sun.tools.javap * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask toolbox.JavapTask toolbox.TestRunner * @run main ReleaseOption9 diff --git a/test/langtools/tools/javac/options/release/ReleaseOptionUnsupported.java b/test/langtools/tools/javac/options/release/ReleaseOptionUnsupported.java index 4997740eea5..0ff370c456f 100644 --- a/test/langtools/tools/javac/options/release/ReleaseOptionUnsupported.java +++ b/test/langtools/tools/javac/options/release/ReleaseOptionUnsupported.java @@ -29,7 +29,6 @@ * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.jvm - * jdk.jdeps/com.sun.tools.classfile * jdk.jdeps/com.sun.tools.javap * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask toolbox.JavapTask toolbox.TestRunner * @run main ReleaseOptionUnsupported diff --git a/test/langtools/tools/javac/patterns/Annotations.java b/test/langtools/tools/javac/patterns/Annotations.java index 324f07945dd..d9ae2b18247 100644 --- a/test/langtools/tools/javac/patterns/Annotations.java +++ b/test/langtools/tools/javac/patterns/Annotations.java @@ -28,7 +28,12 @@ * @library /tools/javac/lib * @modules java.compiler * jdk.compiler - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build JavacTestingAbstractProcessor * @compile Annotations.java * @compile -processor Annotations -proc:only Annotations.java @@ -49,9 +54,10 @@ import com.sun.source.tree.BindingPatternTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePathScanner; import com.sun.source.util.Trees; -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.attribute.RuntimeInvisibleTypeAnnotationsAttribute; import java.io.InputStream; -import java.util.Arrays; public class Annotations extends JavacTestingAbstractProcessor { public static void main(String... args) throws Exception { @@ -61,19 +67,22 @@ public class Annotations extends JavacTestingAbstractProcessor { void run() throws Exception { InputStream annotationsClass = Annotations.class.getResourceAsStream("Annotations.class"); - ClassFile cf = ClassFile.read(annotationsClass); - for (Method m : cf.methods) { - if ("test".equals(cf.constant_pool.getUTF8Value(m.name_index))) { - Code_attribute codeAttr = - (Code_attribute) m.attributes.map.get(Attribute.Code); - Attribute annoAttr = - codeAttr.attributes.map.get(Attribute.RuntimeInvisibleTypeAnnotations); - RuntimeInvisibleTypeAnnotations_attribute annotations = - (RuntimeInvisibleTypeAnnotations_attribute) annoAttr; - String expected = "[@Annotations$DTA; pos: [LOCAL_VARIABLE, {start_pc = 31, length = 7, index = 1}, pos = -1], " + - "@Annotations$TA; pos: [LOCAL_VARIABLE, {start_pc = 50, length = 7, index = 1}, pos = -1]]"; - String actual = Arrays.toString(annotations.annotations); - if (!expected.equals(actual)) { + assert annotationsClass != null; + ClassModel cf = Classfile.of().parse(annotationsClass.readAllBytes()); + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString("test")) { + CodeAttribute codeAttr = m.findAttribute(Attributes.CODE).orElseThrow(); + RuntimeInvisibleTypeAnnotationsAttribute annotations = codeAttr.findAttribute(Attributes.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS).orElseThrow(); + String expected = "LAnnotations$DTA; pos: [LOCAL_VARIABLE, {start_pc=31, end_pc=38, index=1}], " + + "LAnnotations$TA; pos: [LOCAL_VARIABLE, {start_pc=50, end_pc=57, index=1}], "; + StringBuilder actual = new StringBuilder(); + for (TypeAnnotation ta: annotations.annotations()) { + TypeAnnotation.LocalVarTargetInfo info = ((TypeAnnotation.LocalVarTarget) ta.targetInfo()).table().getFirst(); + actual.append(ta.className().stringValue() + " pos: [" + ta.targetInfo().targetType()); + actual.append(", {start_pc=" + codeAttr.labelToBci(info.startLabel()) + ", end_pc=" + codeAttr.labelToBci(info.endLabel())); + actual.append(", index=" + info.index()+ "}], "); + } + if (!expected.contentEquals(actual)) { throw new AssertionError("Unexpected type annotations: " + actual); } diff --git a/test/langtools/tools/javac/patterns/LocalVariableTable.java b/test/langtools/tools/javac/patterns/LocalVariableTable.java index ee03b16b927..af1a2baa1f7 100644 --- a/test/langtools/tools/javac/patterns/LocalVariableTable.java +++ b/test/langtools/tools/javac/patterns/LocalVariableTable.java @@ -25,15 +25,21 @@ * @test * @bug 8231827 * @summary Ensure the LV table entries are generated for bindings - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile -g LocalVariableTable.java * @run main LocalVariableTable */ +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import java.io.*; import java.lang.annotation.*; import java.util.*; -import com.sun.tools.classfile.*; /* * The test checks that a LocalVariableTable attribute is generated for the @@ -77,29 +83,29 @@ public class LocalVariableTable { return; } - ClassFile cf = ClassFile.read(getClass().getResource(c.getName() + ".class").openStream()); - Method m = getMethodByName(cf, c.getSimpleName().contains("Lambda") ? "lambda$" : "test"); + ClassModel cf = Classfile.of().parse(Objects.requireNonNull(getClass().getResource(c.getName() + ".class")) + .openStream().readAllBytes()); + MethodModel m = getMethodByName(cf, c.getSimpleName().contains("Lambda") ? "lambda$" : "test"); if (m == null) { error("test method not found"); return; } - Code_attribute code = (Code_attribute) m.attributes.get(Attribute.Code); + CodeAttribute code = m.findAttribute(Attributes.CODE).orElse(null); if (code == null) { error("Code attribute not found"); return; } - LocalVariableTable_attribute lvt = - (LocalVariableTable_attribute) code.attributes.get(Attribute.LocalVariableTable); + LocalVariableTableAttribute lvt = code.findAttribute(Attributes.LOCAL_VARIABLE_TABLE).orElse(null); if (lvt == null) { error("LocalVariableTable attribute not found"); return; } Set foundNames = new LinkedHashSet<>(); - for (LocalVariableTable_attribute.Entry e: lvt.local_variable_table) { - foundNames.add(cf.constant_pool.getUTF8Value(e.name_index)); + for (LocalVariableInfo e: lvt.localVariables()) { + foundNames.add(e.name().stringValue()); } Set expectNames = new LinkedHashSet<>(Arrays.asList(expect.value())); @@ -115,9 +121,9 @@ public class LocalVariableTable { } } - Method getMethodByName(ClassFile cf, String name) throws ConstantPoolException { - for (Method m: cf.methods) { - if (m.getName(cf.constant_pool).startsWith(name)) + MethodModel getMethodByName(ClassModel cf, String name) { + for (MethodModel m: cf.methods()) { + if (m.methodName().stringValue().startsWith(name)) return m; } return null; diff --git a/test/langtools/tools/javac/patterns/MatchExceptionTest.java b/test/langtools/tools/javac/patterns/MatchExceptionTest.java index 397e30862c0..abc21cd880d 100644 --- a/test/langtools/tools/javac/patterns/MatchExceptionTest.java +++ b/test/langtools/tools/javac/patterns/MatchExceptionTest.java @@ -28,17 +28,21 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main MatchExceptionTest */ import java.nio.file.Path; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Class_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; +import jdk.internal.classfile.*; +import jdk.internal.classfile.constantpool.ClassEntry; +import jdk.internal.classfile.constantpool.ConstantPool; import java.util.Arrays; import toolbox.JavacTask; @@ -50,7 +54,7 @@ public class MatchExceptionTest extends TestRunner { private static final String TEST_METHOD = "test"; ToolBox tb; - ClassFile cf; + ClassModel cf; public MatchExceptionTest() { super(System.err); @@ -111,15 +115,15 @@ public class MatchExceptionTest extends TestRunner { .outdir(curPath) .run(); - cf = ClassFile.read(curPath.resolve("Test.class")); + cf = Classfile.of().parse(curPath.resolve("Test.class")); boolean incompatibleClassChangeErrror = false; boolean matchException = false; - for (CPInfo entry : cf.constant_pool.entries()) { - if (entry.getTag() == ConstantPool.CONSTANT_Class) { - CONSTANT_Class_info clazz = (CONSTANT_Class_info) entry; - incompatibleClassChangeErrror |= - "java/lang/IncompatibleClassChangeError".equals(clazz.getName()); - matchException |= "java/lang/MatchException".equals(clazz.getName()); + ConstantPool cp = cf.constantPool(); + for (int i = 1; i < cp.entryCount(); i += cp.entryByIndex(i).width()) { + if (cp.entryByIndex(i) instanceof ClassEntry clazz) { + incompatibleClassChangeErrror |= clazz.name().equalsString( + "java/lang/IncompatibleClassChangeError"); + matchException |= clazz.name().equalsString("java/lang/MatchException"); } } if (variant.hasMatchException) { diff --git a/test/langtools/tools/javac/patterns/NestedPatternVariablesBytecode.java b/test/langtools/tools/javac/patterns/NestedPatternVariablesBytecode.java index 6ceca9d95a6..05a417ad335 100644 --- a/test/langtools/tools/javac/patterns/NestedPatternVariablesBytecode.java +++ b/test/langtools/tools/javac/patterns/NestedPatternVariablesBytecode.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main NestedPatternVariablesBytecode */ @@ -38,12 +43,8 @@ import java.util.Arrays; import java.util.List; import java.util.stream.StreamSupport; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.Instruction; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; import toolbox.JavacTask; import toolbox.TestRunner; @@ -54,7 +55,7 @@ public class NestedPatternVariablesBytecode extends TestRunner { private static final String TEST_METHOD = "test"; ToolBox tb; - ClassFile cf; + ClassModel cf; public NestedPatternVariablesBytecode() { super(System.err); @@ -83,31 +84,28 @@ public class NestedPatternVariablesBytecode extends TestRunner { .outdir(curPath) .run(); - cf = ClassFile.read(curPath.resolve("NestedPatterVariablesTest.class")); - Method testMethod = Arrays.stream(cf.methods) - .filter(m -> isTestMethod(m)) + cf = Classfile.of().parse(curPath.resolve("NestedPatterVariablesTest.class")); + MethodModel testMethod = cf.methods().stream() + .filter(this::isTestMethod) .findAny() - .get(); - Code_attribute code_attribute = (Code_attribute) testMethod.attributes.get(Attribute.Code); + .orElseThrow(); + CodeAttribute code_attribute = testMethod.findAttribute(Attributes.CODE).orElseThrow(); List actualCode = getCodeInstructions(code_attribute); List expectedCode = Arrays.asList( - "aload_1", "instanceof", "ifeq", "aload_1", "checkcast", "astore_2", "aload_2", "instanceof", - "ifeq", "aload_2", "checkcast", "astore_3", "aload_3", "areturn", "aconst_null", "areturn"); + "ALOAD_1", "INSTANCEOF", "IFEQ", "ALOAD_1", "CHECKCAST", "ASTORE_2", "ALOAD_2", "INSTANCEOF", + "IFEQ", "ALOAD_2", "CHECKCAST", "ASTORE_3", "ALOAD_3", "ARETURN", "ACONST_NULL", "ARETURN"); tb.checkEqual(expectedCode, actualCode); } - boolean isTestMethod(Method m) { - try { - return TEST_METHOD.equals(m.getName(cf.constant_pool)); - } catch (ConstantPoolException e) { - throw new IllegalStateException(e); - } + boolean isTestMethod(MethodModel m) { + return m.methodName().equalsString(TEST_METHOD); } - List getCodeInstructions(Code_attribute code) { - return StreamSupport.stream(code.getInstructions().spliterator(), false) - .map(Instruction::getMnemonic) + List getCodeInstructions(CodeAttribute code) { + return code.elementList().stream() + .filter(ce -> ce instanceof Instruction) + .map(ins -> ((Instruction) ins).opcode().name()) .toList(); } } diff --git a/test/langtools/tools/javac/patterns/NoUnnecessaryCast.java b/test/langtools/tools/javac/patterns/NoUnnecessaryCast.java index 0d3c217f2e9..1b058e03db1 100644 --- a/test/langtools/tools/javac/patterns/NoUnnecessaryCast.java +++ b/test/langtools/tools/javac/patterns/NoUnnecessaryCast.java @@ -26,62 +26,56 @@ * @bug 8237528 * @summary Verify there are no unnecessary checkcasts and conditions generated * for the pattern matching in instanceof. - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile NoUnnecessaryCast.java * @run main NoUnnecessaryCast */ +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.ConstantPool; import java.io.File; import java.io.IOException; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.Code_attribute.InvalidIndex; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPoolException; -import com.sun.tools.classfile.Descriptor.InvalidDescriptor; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class NoUnnecessaryCast { - public static void main(String[] args) - throws IOException, ConstantPoolException, InvalidDescriptor, InvalidIndex { + public static void main(String[] args) throws IOException { new NoUnnecessaryCast() .checkClassFile(new File(System.getProperty("test.classes", "."), NoUnnecessaryCast.class.getName() + ".class")); } - void checkClassFile(File file) - throws IOException, ConstantPoolException, InvalidDescriptor, InvalidIndex { - ClassFile classFile = ClassFile.read(file); - ConstantPool constantPool = classFile.constant_pool; + void checkClassFile(File file) throws IOException { + ClassModel classFile = Classfile.of().parse(file.toPath()); - Method method = Arrays.stream(classFile.methods) - .filter(m -> getName(m, constantPool) - .equals("test")) + MethodModel method = classFile.methods().stream() + .filter(m -> getName(m).equals("test")) .findAny() .get(); String expectedInstructions = """ - aload_1 - instanceof - ifeq - aload_1 - checkcast - astore_2 - aload_2 - invokevirtual - ifeq - iconst_1 - goto - iconst_0 - ireturn + ALOAD_1 + INSTANCEOF + IFEQ + ALOAD_1 + CHECKCAST + ASTORE_2 + ALOAD_2 + INVOKEVIRTUAL + IFEQ + ICONST_1 + GOTO + ICONST_0 + IRETURN """; - Code_attribute code = (Code_attribute) method.attributes - .get(Attribute.Code); + CodeAttribute code = method.findAttribute(Attributes.CODE).orElseThrow(); String actualInstructions = printCode(code); if (!expectedInstructions.equals(actualInstructions)) { throw new AssertionError("Unexpected instructions found:\n" + @@ -89,18 +83,15 @@ public class NoUnnecessaryCast { } } - String printCode(Code_attribute code) { - return StreamSupport.stream(code.getInstructions().spliterator(), false) - .map(Instruction::getMnemonic) + String printCode(CodeAttribute code) { + return code.elementList().stream() + .filter(e -> e instanceof Instruction) + .map(ins -> ((Instruction) ins).opcode().name()) .collect(Collectors.joining("\n", "", "\n")); } - String getName(Method m, ConstantPool constantPool) { - try { - return m.getName(constantPool); - } catch (ConstantPoolException ex) { - throw new IllegalStateException(ex); - } + String getName(MethodModel m) { + return m.methodName().stringValue(); } boolean test(Object o) { diff --git a/test/langtools/tools/javac/preview/PreviewAutoSuppress.java b/test/langtools/tools/javac/preview/PreviewAutoSuppress.java index 2ae98cb349d..3a053f9b334 100644 --- a/test/langtools/tools/javac/preview/PreviewAutoSuppress.java +++ b/test/langtools/tools/javac/preview/PreviewAutoSuppress.java @@ -28,11 +28,16 @@ * @modules * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main PreviewAutoSuppress */ -import com.sun.tools.classfile.ClassFile; +import jdk.internal.classfile.*; import java.io.InputStream; import java.nio.file.Files; import toolbox.JavacTask; @@ -206,11 +211,11 @@ public class PreviewAutoSuppress extends TestRunner { private void checkPreviewClassfile(Path p, boolean preview) throws Exception { try (InputStream in = Files.newInputStream(p)) { - ClassFile cf = ClassFile.read(in); - if (preview && cf.minor_version != 65535) { - throw new IllegalStateException("Expected preview class, but got: " + cf.minor_version); - } else if (!preview && cf.minor_version != 0) { - throw new IllegalStateException("Expected minor version == 0 but got: " + cf.minor_version); + ClassModel cf = Classfile.of().parse(in.readAllBytes()); + if (preview && cf.minorVersion() != 65535) { + throw new IllegalStateException("Expected preview class, but got: " + cf.minorVersion()); + } else if (!preview && cf.minorVersion() != 0) { + throw new IllegalStateException("Expected minor version == 0 but got: " + cf.minorVersion()); } } } diff --git a/test/langtools/tools/javac/preview/PreviewErrors.java b/test/langtools/tools/javac/preview/PreviewErrors.java index 87fb242ffa3..2dd84cacdf3 100644 --- a/test/langtools/tools/javac/preview/PreviewErrors.java +++ b/test/langtools/tools/javac/preview/PreviewErrors.java @@ -32,7 +32,12 @@ * jdk.compiler/com.sun.tools.javac.file * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @build combo.ComboTestHelper * @run main PreviewErrors @@ -55,8 +60,8 @@ import java.util.TreeMap; import java.util.stream.Collectors; import javax.tools.Diagnostic; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; +import jdk.internal.classfile.ClassModel; +import jdk.internal.classfile.Classfile; import java.io.FileWriter; import java.io.UncheckedIOException; import java.io.Writer; @@ -394,7 +399,7 @@ public class PreviewErrors extends ComboInstance { if (!result.get().iterator().hasNext()) { throw new IllegalStateException("Did not succeed as expected for preview=" + preview + ", lint=" + lint + ", suppress=" + suppress + ", elementType=" + elementType + ": actual:\"" + actual + "\""); } - ClassFile cf; + ClassModel cf; try { JavaFileObject testClass = null; for (JavaFileObject classfile : result.get()) { @@ -406,15 +411,15 @@ public class PreviewErrors extends ComboInstance { throw new IllegalStateException("Cannot find Test.class"); } try (InputStream input = testClass.openInputStream()) { - cf = ClassFile.read(input); + cf = Classfile.of().parse(input.readAllBytes()); } - } catch (IOException | ConstantPoolException ex) { + } catch (IOException ex) { throw new IllegalStateException(ex); } - if (previewClass && cf.minor_version != 65535) { - throw new IllegalStateException("Expected preview class, but got: " + cf.minor_version); - } else if (!previewClass && cf.minor_version != 0) { - throw new IllegalStateException("Expected minor version == 0 but got: " + cf.minor_version); + if (previewClass && cf.minorVersion() != 65535) { + throw new IllegalStateException("Expected preview class, but got: " + cf.minorVersion()); + } else if (!previewClass && cf.minorVersion() != 0) { + throw new IllegalStateException("Expected minor version == 0 but got: " + cf.minorVersion()); } } else { if (result.get().iterator().hasNext()) { diff --git a/test/langtools/tools/javac/preview/PreviewTest.java b/test/langtools/tools/javac/preview/PreviewTest.java index f8a8ffe6e08..7bf15c41c0b 100644 --- a/test/langtools/tools/javac/preview/PreviewTest.java +++ b/test/langtools/tools/javac/preview/PreviewTest.java @@ -28,11 +28,17 @@ * @modules * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main PreviewTest */ -import com.sun.tools.classfile.ClassFile; +import jdk.internal.classfile.ClassModel; +import jdk.internal.classfile.Classfile; import java.io.InputStream; import java.nio.file.Files; import toolbox.JavacTask; @@ -475,11 +481,11 @@ public class PreviewTest extends TestRunner { private void checkPreviewClassfile(Path p, boolean preview) throws Exception { try (InputStream in = Files.newInputStream(p)) { - ClassFile cf = ClassFile.read(in); - if (preview && cf.minor_version != 65535) { - throw new IllegalStateException("Expected preview class, but got: " + cf.minor_version + " for: " + p.toString()); - } else if (!preview && cf.minor_version != 0) { - throw new IllegalStateException("Expected minor version == 0 but got: " + cf.minor_version + " for: " + p.toString()); + ClassModel cf = Classfile.of().parse(in.readAllBytes()); + if (preview && cf.minorVersion() != 65535) { + throw new IllegalStateException("Expected preview class, but got: " + cf.minorVersion() + " for: " + p.toString()); + } else if (!preview && cf.minorVersion() != 0) { + throw new IllegalStateException("Expected minor version == 0 but got: " + cf.minorVersion() + " for: " + p.toString()); } } } diff --git a/test/langtools/tools/javac/processing/model/element/TestFileObjectOf.java b/test/langtools/tools/javac/processing/model/element/TestFileObjectOf.java index 1957d00ea4a..a9e22804f9a 100644 --- a/test/langtools/tools/javac/processing/model/element/TestFileObjectOf.java +++ b/test/langtools/tools/javac/processing/model/element/TestFileObjectOf.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask toolbox.TestRunner * @build TestFileObjectOf * @run main TestFileObjectOf diff --git a/test/langtools/tools/javac/processing/model/element/TestOrigin.java b/test/langtools/tools/javac/processing/model/element/TestOrigin.java index c2cc6e31628..d1a1d247953 100644 --- a/test/langtools/tools/javac/processing/model/element/TestOrigin.java +++ b/test/langtools/tools/javac/processing/model/element/TestOrigin.java @@ -28,13 +28,19 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask toolbox.TestRunner * @build TestOrigin * @run main TestOrigin */ import java.io.OutputStream; +import java.lang.instrument.ClassFileTransformer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -55,14 +61,8 @@ import javax.lang.model.element.ModuleElement.OpensDirective; import javax.lang.model.element.ModuleElement.RequiresDirective; import javax.lang.model.util.Elements; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Attributes; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ClassWriter; -import com.sun.tools.classfile.Module_attribute; -import com.sun.tools.classfile.Module_attribute.ExportsEntry; -import com.sun.tools.classfile.Module_attribute.OpensEntry; -import com.sun.tools.classfile.Module_attribute.RequiresEntry; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; import toolbox.JavacTask; import toolbox.Task; import toolbox.TestRunner; @@ -140,8 +140,7 @@ public class TestOrigin extends TestRunner { TypeElement test = elements.getTypeElement("test.Test"); List members = new ArrayList<>(test.getEnclosedElements()); - Collections.sort(members, - (e1, e2) -> e1.getSimpleName().toString().compareTo(e2.getSimpleName().toString())); + members.sort((e1, e2) -> e1.getSimpleName().toString().compareTo(e2.getSimpleName().toString())); for (Element el : members) { System.out.println(el.getSimpleName() + ":" + elements.getOrigin(el)); @@ -184,7 +183,7 @@ public class TestOrigin extends TestRunner { .writeAll() .getOutputLines(Task.OutputKind.STDOUT); - expected = Arrays.asList("test.Container:MANDATED"); + expected = List.of("test.Container:MANDATED"); if (!expected.equals(log)) throw new AssertionError("expected output not found: " + log); @@ -200,7 +199,7 @@ public class TestOrigin extends TestRunner { .writeAll() .getOutputLines(Task.OutputKind.STDOUT); - expected = Arrays.asList("test.Container:EXPLICIT"); + expected = List.of("test.Container:EXPLICIT"); if (!expected.equals(log)) throw new AssertionError("expected output not found: " + log); @@ -255,7 +254,7 @@ public class TestOrigin extends TestRunner { .writeAll() .getOutputLines(Task.OutputKind.STDOUT); - expected = Arrays.asList("REQUIRES:java.base:MANDATED"); + expected = List.of("REQUIRES:java.base:MANDATED"); if (!expected.equals(log)) throw new AssertionError("expected output not found: " + log); @@ -280,64 +279,37 @@ public class TestOrigin extends TestRunner { .writeAll(); Path moduleInfo = classes.resolve("module-info.class"); - ClassFile cf = ClassFile.read(moduleInfo); - Module_attribute module = (Module_attribute) cf.getAttribute(Attribute.Module); + ClassModel cf = Classfile.of().parse(moduleInfo); + ModuleAttribute module = cf.findAttribute(Attributes.MODULE).orElseThrow(); - RequiresEntry[] newRequires = new RequiresEntry[3]; - newRequires[0] = new RequiresEntry(module.requires[0].requires_index, - Module_attribute.ACC_MANDATED, - module.requires[0].requires_version_index); - newRequires[1] = new RequiresEntry(module.requires[1].requires_index, - Module_attribute.ACC_SYNTHETIC, - module.requires[1].requires_version_index); - newRequires[2] = module.requires[2]; + List newRequires = new ArrayList<>(3); + newRequires.add(ModuleRequireInfo.of(module.requires().get(0).requires(), Classfile.ACC_MANDATED, module.requires().get(0).requiresVersion().orElse(null))); + newRequires.add(ModuleRequireInfo.of(module.requires().get(1).requires(), Classfile.ACC_SYNTHETIC, module.requires().get(1).requiresVersion().orElse(null))); + newRequires.add(module.requires().get(2)); - ExportsEntry[] newExports = new ExportsEntry[3]; - newExports[0] = new ExportsEntry(module.exports[0].exports_index, - Module_attribute.ACC_MANDATED, - module.exports[0].exports_to_index); - newExports[1] = new ExportsEntry(module.exports[1].exports_index, - Module_attribute.ACC_SYNTHETIC, - module.exports[1].exports_to_index); - newExports[2] = module.exports[2]; + List newExports = new ArrayList<>(3); + newExports.add(ModuleExportInfo.of(module.exports().get(0).exportedPackage(), Classfile.ACC_MANDATED, module.exports().get(0).exportsTo())); + newExports.add(ModuleExportInfo.of(module.exports().get(1).exportedPackage(), Classfile.ACC_SYNTHETIC, module.exports().get(1).exportsTo())); + newExports.add(module.exports().get(2)); - OpensEntry[] newOpens = new OpensEntry[3]; - newOpens[0] = new OpensEntry(module.opens[0].opens_index, - Module_attribute.ACC_MANDATED, - module.opens[0].opens_to_index); - newOpens[1] = new OpensEntry(module.opens[1].opens_index, - Module_attribute.ACC_SYNTHETIC, - module.opens[1].opens_to_index); - newOpens[2] = module.opens[2]; + List newOpens = new ArrayList<>(3); + newOpens.add(ModuleOpenInfo.of(module.opens().get(0).openedPackage(), Classfile.ACC_MANDATED, module.opens().get(0).opensTo())); + newOpens.add(ModuleOpenInfo.of(module.opens().get(1).openedPackage(), Classfile.ACC_SYNTHETIC, module.opens().get(1).opensTo())); + newOpens.add(module.opens().get(2)); - Module_attribute newModule = new Module_attribute(module.attribute_name_index, - module.module_name, - module.module_flags, - module.module_version_index, + + ModuleAttribute newModule = ModuleAttribute.of(module.moduleName(), + module.moduleFlagsMask(), + module.moduleVersion().orElse(null), newRequires, newExports, newOpens, - module.uses_index, - module.provides); - Map newAttributesMap = new HashMap<>(cf.attributes.map); - - newAttributesMap.put(Attribute.Module, newModule); - - Attributes newAttributes = new Attributes(newAttributesMap); - ClassFile newClassFile = new ClassFile(cf.magic, - cf.minor_version, - cf.major_version, - cf.constant_pool, - cf.access_flags, - cf.this_class, - cf.super_class, - cf.interfaces, - cf.fields, - cf.methods, - newAttributes); - + module.uses(), + module.provides()); + byte[] newClassFileBytes = Classfile.of().transform(cf, ClassTransform.dropping(ce -> ce instanceof ModuleAttribute) + .andThen(ClassTransform.endHandler(classBuilder -> classBuilder.with(newModule)))); try (OutputStream out = Files.newOutputStream(moduleInfo)) { - new ClassWriter().write(newClassFile, out); + out.write(newClassFileBytes); } //from class: @@ -377,24 +349,24 @@ public class TestOrigin extends TestRunner { for (Directive d : m.getDirectives()) { switch (d.getKind()) { - case REQUIRES: + case REQUIRES -> { RequiresDirective rd = (RequiresDirective) d; System.out.println(rd.getKind() + ":" + - rd.getDependency().getQualifiedName() + ":" + - elements.getOrigin(m, rd)); - break; - case EXPORTS: + rd.getDependency().getQualifiedName() + ":" + + elements.getOrigin(m, rd)); + } + case EXPORTS -> { ExportsDirective ed = (ExportsDirective) d; System.out.println(ed.getKind() + ":" + - ed.getPackage() + ":" + - elements.getOrigin(m, ed)); - break; - case OPENS: + ed.getPackage() + ":" + + elements.getOrigin(m, ed)); + } + case OPENS -> { OpensDirective od = (OpensDirective) d; System.out.println(od.getKind() + ":" + - od.getPackage() + ":" + - elements.getOrigin(m, od)); - break; + od.getPackage() + ":" + + elements.getOrigin(m, od)); + } } } diff --git a/test/langtools/tools/javac/records/RecordCompilationTests.java b/test/langtools/tools/javac/records/RecordCompilationTests.java index 15f5eacf8dc..e2d6679dd80 100644 --- a/test/langtools/tools/javac/records/RecordCompilationTests.java +++ b/test/langtools/tools/javac/records/RecordCompilationTests.java @@ -32,7 +32,12 @@ * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.code * jdk.compiler/com.sun.tools.javac.util - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build JavacTestingAbstractProcessor * @run testng/othervm -DuseAP=false RecordCompilationTests * @run testng/othervm -DuseAP=true RecordCompilationTests @@ -41,13 +46,7 @@ import java.io.File; import java.lang.annotation.ElementType; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -70,26 +69,11 @@ import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.TypeMirror; -import com.sun.tools.classfile.AccessFlags; -import com.sun.tools.classfile.Annotation; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.Attributes; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool; -import com.sun.tools.classfile.ConstantPool.CONSTANT_Fieldref_info; -import com.sun.tools.classfile.ConstantPool.CPInfo; -import com.sun.tools.classfile.Field; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Method; -import com.sun.tools.classfile.Record_attribute; -import com.sun.tools.classfile.Record_attribute.ComponentInfo; -import com.sun.tools.classfile.RuntimeAnnotations_attribute; -import com.sun.tools.classfile.RuntimeTypeAnnotations_attribute; -import com.sun.tools.classfile.RuntimeVisibleAnnotations_attribute; -import com.sun.tools.classfile.RuntimeVisibleParameterAnnotations_attribute; -import com.sun.tools.classfile.RuntimeVisibleTypeAnnotations_attribute; -import com.sun.tools.classfile.TypeAnnotation; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.*; +import jdk.internal.classfile.Opcode; +import jdk.internal.classfile.constantpool.*; +import jdk.internal.classfile.instruction.FieldInstruction; import com.sun.tools.javac.api.ClientCodeWrapper.DiagnosticSourceUnwrapper; import com.sun.tools.javac.code.Attribute.TypeCompound; @@ -1289,16 +1273,15 @@ public class RecordCompilationTests extends CompilationTestCase { )) { File dir = assertOK(true, source); int numberOfFieldRefs = 0; - for (final File fileEntry : dir.listFiles()) { + for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) { if (fileEntry.getName().endsWith("R.class")) { - ClassFile classFile = ClassFile.read(fileEntry); - for (CPInfo cpInfo : classFile.constant_pool.entries()) { - if (cpInfo instanceof ConstantPool.CONSTANT_Fieldref_info) { + ClassModel classFile = Classfile.of().parse(fileEntry.toPath()); + for (int i = 1; i < classFile.constantPool().entryCount(); ++i) { + if (classFile.constantPool().entryByIndex(i) instanceof FieldRefEntry fieldRefEntry) { numberOfFieldRefs++; - ConstantPool.CONSTANT_NameAndType_info nameAndType = - (ConstantPool.CONSTANT_NameAndType_info)classFile.constant_pool - .get(((ConstantPool.CONSTANT_Fieldref_info)cpInfo).name_and_type_index); - Assert.check(nameAndType.getName().equals("recordComponent")); + NameAndTypeEntry nameAndType = (NameAndTypeEntry) classFile.constantPool() + .entryByIndex(fieldRefEntry.nameAndType().index()); + Assert.check(nameAndType.name().equalsString("recordComponent")); } } Assert.check(numberOfFieldRefs == 1); @@ -1310,35 +1293,36 @@ public class RecordCompilationTests extends CompilationTestCase { // check that fields are initialized in a canonical constructor in the same declaration order as the corresponding // record component public void testCheckInitializationOrderInCompactConstructor() throws Exception { - int putField1 = -1; - int putField2 = -1; + FieldInstruction putField1 = null; + FieldInstruction putField2 = null; File dir = assertOK(true, "record R(int i, String s) { R {} }"); - for (final File fileEntry : dir.listFiles()) { + for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) { if (fileEntry.getName().equals("R.class")) { - ClassFile classFile = ClassFile.read(fileEntry); - for (Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals("")) { - Code_attribute code_attribute = (Code_attribute) method.attributes.get("Code"); - for (Instruction instruction : code_attribute.getInstructions()) { - if (instruction.getMnemonic().equals("putfield")) { - if (putField1 != -1 && putField2 != -1) { + ClassModel classFile = Classfile.of().parse(fileEntry.toPath()); + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString("")) { + CodeAttribute code_attribute = method.findAttribute(Attributes.CODE).orElseThrow(); + for (CodeElement ce : code_attribute.elementList()) { + if (ce instanceof Instruction instruction && instruction.opcode() == Opcode.PUTFIELD) { + if (putField1 != null && putField2 != null) { throw new AssertionError("was expecting only two putfield instructions in this method"); } - if (putField1 == -1) { - putField1 = instruction.getShort(1); - } else if (putField2 == -1) { - putField2 = instruction.getShort(1); + if (putField1 == null) { + putField1 = (FieldInstruction) instruction; + } else { + putField2 = (FieldInstruction) instruction; } } } // now we need to check that we are assigning to `i` first and to `s` afterwards - CONSTANT_Fieldref_info fieldref_info1 = (CONSTANT_Fieldref_info)classFile.constant_pool.get(putField1); - if (!fieldref_info1.getNameAndTypeInfo().getName().equals("i")) { + assert putField1 != null; + FieldRefEntry fieldref_info1 = putField1.field(); + if (!fieldref_info1.name().equalsString("i")) { throw new AssertionError("was expecting variable name 'i'"); } - - CONSTANT_Fieldref_info fieldref_info2 = (CONSTANT_Fieldref_info)classFile.constant_pool.get(putField2); - if (!fieldref_info2.getNameAndTypeInfo().getName().equals("s")) { + assert putField2 != null; + FieldRefEntry fieldref_info2 = putField2.field(); + if (!fieldref_info2.name().equalsString("s")) { throw new AssertionError("was expecting variable name 's'"); } } @@ -1459,104 +1443,84 @@ public class RecordCompilationTests extends CompilationTestCase { File dir = assertOK(true, code); - ClassFile classFile = ClassFile.read(findClassFileOrFail(dir, "R.class")); + ClassModel classFile = Classfile.of().parse(findClassFileOrFail(dir, "R.class").toPath()); // field first - Assert.check(classFile.fields.length == 1); - Field field = classFile.fields[0]; + Assert.check(classFile.fields().size() == 1); + FieldModel field = classFile.fields().get(0); // if FIELD is one of the targets then there must be a declaration annotation applied to the field, apart from // the type annotation if (target.contains("ElementType.FIELD")) { - checkAnno(classFile, - (RuntimeAnnotations_attribute) findAttributeOrFail( - field.attributes, - RuntimeVisibleAnnotations_attribute.class), + checkAnno(findAttributeOrFail(field.attributes(), RuntimeVisibleAnnotationsAttribute.class), "Anno"); } else { - assertAttributeNotPresent(field.attributes, RuntimeVisibleAnnotations_attribute.class); + assertAttributeNotPresent(field.attributes(), RuntimeVisibleAnnotationsAttribute.class); } // lets check now for the type annotation if (target.contains("ElementType.TYPE_USE")) { - checkTypeAnno( - classFile, - (RuntimeVisibleTypeAnnotations_attribute) findAttributeOrFail(field.attributes, RuntimeVisibleTypeAnnotations_attribute.class), - "FIELD", - "Anno"); + checkTypeAnno(findAttributeOrFail(field.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class), + "FIELD", "Anno"); } else { - assertAttributeNotPresent(field.attributes, RuntimeVisibleTypeAnnotations_attribute.class); + assertAttributeNotPresent(field.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class); } // checking for the annotation on the corresponding parameter of the canonical constructor - Method init = findMethodOrFail(classFile, ""); + MethodModel init = findMethodOrFail(classFile, ""); // if PARAMETER is one of the targets then there must be a declaration annotation applied to the parameter, apart from // the type annotation if (target.contains("ElementType.PARAMETER")) { - checkParameterAnno(classFile, - (RuntimeVisibleParameterAnnotations_attribute) findAttributeOrFail( - init.attributes, - RuntimeVisibleParameterAnnotations_attribute.class), + checkParameterAnno( + (RuntimeVisibleParameterAnnotationsAttribute) findAttributeOrFail( + init.attributes(), + RuntimeVisibleParameterAnnotationsAttribute.class), "Anno"); } else { - assertAttributeNotPresent(init.attributes, RuntimeVisibleAnnotations_attribute.class); + assertAttributeNotPresent(init.attributes(), RuntimeVisibleAnnotationsAttribute.class); } // let's check now for the type annotation if (target.contains("ElementType.TYPE_USE")) { - checkTypeAnno( - classFile, - (RuntimeVisibleTypeAnnotations_attribute) findAttributeOrFail(init.attributes, RuntimeVisibleTypeAnnotations_attribute.class), + checkTypeAnno(findAttributeOrFail(init.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class), "METHOD_FORMAL_PARAMETER", "Anno"); } else { - assertAttributeNotPresent(init.attributes, RuntimeVisibleTypeAnnotations_attribute.class); + assertAttributeNotPresent(init.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class); } // checking for the annotation in the accessor - Method accessor = findMethodOrFail(classFile, "s"); + MethodModel accessor = findMethodOrFail(classFile, "s"); // if METHOD is one of the targets then there must be a declaration annotation applied to the accessor, apart from // the type annotation if (target.contains("ElementType.METHOD")) { - checkAnno(classFile, - (RuntimeAnnotations_attribute) findAttributeOrFail( - accessor.attributes, - RuntimeVisibleAnnotations_attribute.class), + checkAnno(findAttributeOrFail(accessor.attributes(), RuntimeVisibleAnnotationsAttribute.class), "Anno"); } else { - assertAttributeNotPresent(accessor.attributes, RuntimeVisibleAnnotations_attribute.class); + assertAttributeNotPresent(accessor.attributes(), RuntimeVisibleAnnotationsAttribute.class); } // let's check now for the type annotation if (target.contains("ElementType.TYPE_USE")) { - checkTypeAnno( - classFile, - (RuntimeVisibleTypeAnnotations_attribute) findAttributeOrFail(accessor.attributes, RuntimeVisibleTypeAnnotations_attribute.class), + checkTypeAnno(findAttributeOrFail(accessor.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class), "METHOD_RETURN", "Anno"); } else { - assertAttributeNotPresent(accessor.attributes, RuntimeVisibleTypeAnnotations_attribute.class); + assertAttributeNotPresent(accessor.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class); } // checking for the annotation in the Record attribute - Record_attribute record = (Record_attribute) findAttributeOrFail(classFile.attributes, Record_attribute.class); - Assert.check(record.component_count == 1); + RecordAttribute record = (RecordAttribute) findAttributeOrFail(classFile.attributes(), RecordAttribute.class); + Assert.check(record.components().size() == 1); // if RECORD_COMPONENT is one of the targets then there must be a declaration annotation applied to the // field, apart from the type annotation if (target.contains("ElementType.RECORD_COMPONENT")) { - checkAnno(classFile, - (RuntimeAnnotations_attribute) findAttributeOrFail( - record.component_info_arr[0].attributes, - RuntimeVisibleAnnotations_attribute.class), + checkAnno(findAttributeOrFail(record.components().get(0).attributes(), RuntimeVisibleAnnotationsAttribute.class), "Anno"); } else { - assertAttributeNotPresent(record.component_info_arr[0].attributes, RuntimeVisibleAnnotations_attribute.class); + assertAttributeNotPresent(record.components().get(0).attributes(), RuntimeVisibleAnnotationsAttribute.class); } // lets check now for the type annotation if (target.contains("ElementType.TYPE_USE")) { - checkTypeAnno( - classFile, - (RuntimeVisibleTypeAnnotations_attribute) findAttributeOrFail( - record.component_info_arr[0].attributes, - RuntimeVisibleTypeAnnotations_attribute.class), + checkTypeAnno(findAttributeOrFail(record.components().get(0).attributes(), RuntimeVisibleTypeAnnotationsAttribute.class), "FIELD", "Anno"); } else { - assertAttributeNotPresent(record.component_info_arr[0].attributes, RuntimeVisibleTypeAnnotations_attribute.class); + assertAttributeNotPresent(record.components().get(0).attributes(), RuntimeVisibleTypeAnnotationsAttribute.class); } } @@ -1581,105 +1545,114 @@ public class RecordCompilationTests extends CompilationTestCase { File dir = assertOK(true, code); - ClassFile classFile = ClassFile.read(findClassFileOrFail(dir, "R.class")); + ClassModel classFile = Classfile.of().parse(findClassFileOrFail(dir, "R.class").toPath()); // field first - Assert.check(classFile.fields.length == 1); - Field field = classFile.fields[0]; - checkTypeAnno( - classFile, - (RuntimeVisibleTypeAnnotations_attribute) findAttributeOrFail(field.attributes, RuntimeVisibleTypeAnnotations_attribute.class), + Assert.check(classFile.fields().size() == 1); + FieldModel field = classFile.fields().get(0); + checkTypeAnno(findAttributeOrFail(field.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class), "FIELD", "Anno"); // checking for the annotation on the corresponding parameter of the canonical constructor - Method init = findMethodOrFail(classFile, ""); - checkTypeAnno( - classFile, - (RuntimeVisibleTypeAnnotations_attribute) findAttributeOrFail(init.attributes, RuntimeVisibleTypeAnnotations_attribute.class), + MethodModel init = findMethodOrFail(classFile, ""); + checkTypeAnno(findAttributeOrFail(init.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class), "METHOD_FORMAL_PARAMETER", "Anno"); // checking for the annotation in the accessor - Method accessor = findMethodOrFail(classFile, "s"); - checkTypeAnno( - classFile, - (RuntimeVisibleTypeAnnotations_attribute) findAttributeOrFail(accessor.attributes, RuntimeVisibleTypeAnnotations_attribute.class), + MethodModel accessor = findMethodOrFail(classFile, "s"); + checkTypeAnno(findAttributeOrFail(accessor.attributes(), RuntimeVisibleTypeAnnotationsAttribute.class), "METHOD_RETURN", "Anno"); // checking for the annotation in the Record attribute - Record_attribute record = (Record_attribute) findAttributeOrFail(classFile.attributes, Record_attribute.class); - Assert.check(record.component_count == 1); - checkTypeAnno( - classFile, - (RuntimeVisibleTypeAnnotations_attribute) findAttributeOrFail( - record.component_info_arr[0].attributes, - RuntimeVisibleTypeAnnotations_attribute.class), + RecordAttribute record = (RecordAttribute) findAttributeOrFail(classFile.attributes(), RecordAttribute.class); + Assert.check(record.components().size() == 1); + checkTypeAnno(findAttributeOrFail(record.components().get(0).attributes(), + RuntimeVisibleTypeAnnotationsAttribute.class), "FIELD", "Anno"); } - private void checkTypeAnno(ClassFile classFile, - RuntimeTypeAnnotations_attribute rtAnnos, + private void checkTypeAnno(Attribute rtAnnos, String positionType, - String annoName) throws Exception { + String annoName) { // containing only one type annotation - Assert.check(rtAnnos.annotations.length == 1); - TypeAnnotation tAnno = (TypeAnnotation)rtAnnos.annotations[0]; - Assert.check(tAnno.position.type.toString().equals(positionType)); - String annotationName = classFile.constant_pool.getUTF8Value(tAnno.annotation.type_index).toString().substring(1); + TypeAnnotation tAnno; + switch (rtAnnos) { + case RuntimeVisibleTypeAnnotationsAttribute rtVAnnos -> { + Assert.check(rtVAnnos.annotations().size() == 1); + tAnno = rtVAnnos.annotations().get(0); + } + case RuntimeInvisibleTypeAnnotationsAttribute rtIAnnos -> { + Assert.check(rtIAnnos.annotations().size() == 1); + tAnno = rtIAnnos.annotations().get(0); + } + default -> throw new AssertionError(); + } + assert tAnno != null; + Assert.check(tAnno.targetInfo().targetType().name().equals(positionType)); + String annotationName = tAnno.classSymbol().displayName(); Assert.check(annotationName.startsWith(annoName)); } - - private void checkAnno(ClassFile classFile, - RuntimeAnnotations_attribute rAnnos, - String annoName) throws Exception { + private void checkAnno(Attribute rAnnos, + String annoName) { // containing only one type annotation - Assert.check(rAnnos.annotations.length == 1); - Annotation anno = (Annotation)rAnnos.annotations[0]; - String annotationName = classFile.constant_pool.getUTF8Value(anno.type_index).toString().substring(1); + Annotation anno; + switch (rAnnos) { + case RuntimeVisibleAnnotationsAttribute rVAnnos -> { + Assert.check(rVAnnos.annotations().size() == 1); + anno = rVAnnos.annotations().get(0); + } + case RuntimeInvisibleAnnotationsAttribute rIAnnos -> { + Assert.check(rIAnnos.annotations().size() == 1); + anno = rIAnnos.annotations().get(0); + } + default -> throw new AssertionError(); + } + assert anno != null; + String annotationName = anno.classSymbol().displayName(); Assert.check(annotationName.startsWith(annoName)); } // special case for parameter annotations - private void checkParameterAnno(ClassFile classFile, - RuntimeVisibleParameterAnnotations_attribute rAnnos, - String annoName) throws Exception { + private void checkParameterAnno(RuntimeVisibleParameterAnnotationsAttribute rAnnos, + String annoName) { // containing only one type annotation - Assert.check(rAnnos.parameter_annotations.length == 1); - Assert.check(rAnnos.parameter_annotations[0].length == 1); - Annotation anno = (Annotation)rAnnos.parameter_annotations[0][0]; - String annotationName = classFile.constant_pool.getUTF8Value(anno.type_index).toString().substring(1); + Assert.check(rAnnos.parameterAnnotations().size() == 1); + Assert.check(rAnnos.parameterAnnotations().get(0).size() == 1); + Annotation anno = rAnnos.parameterAnnotations().get(0).get(0); + String annotationName = anno.classSymbol().displayName(); Assert.check(annotationName.startsWith(annoName)); } private File findClassFileOrFail(File dir, String name) { for (final File fileEntry : dir.listFiles()) { - if (fileEntry.getName().equals("R.class")) { + if (fileEntry.getName().equals(name)) { return fileEntry; } } throw new AssertionError("file not found"); } - private Method findMethodOrFail(ClassFile classFile, String name) throws Exception { - for (Method method : classFile.methods) { - if (method.getName(classFile.constant_pool).equals(name)) { + private MethodModel findMethodOrFail(ClassModel classFile, String name) { + for (MethodModel method : classFile.methods()) { + if (method.methodName().equalsString(name)) { return method; } } throw new AssertionError("method not found"); } - private Attribute findAttributeOrFail(Attributes attributes, Class attrClass) { - for (Attribute attribute : attributes) { - if (attribute.getClass() == attrClass) { + private Attribute findAttributeOrFail(List> attributes, Class> attrClass) { + for (Attribute attribute : attributes) { + if (attrClass.isAssignableFrom(attribute.getClass())) { return attribute; } } - throw new AssertionError("attribute not found"); + throw new AssertionError("attribute not found" + attrClass.toString() + "!!!!" + attributes.getFirst().getClass().toString()); } - private void assertAttributeNotPresent(Attributes attributes, Class attrClass) { - for (Attribute attribute : attributes) { + private void assertAttributeNotPresent(List> attributes, Class> attrClass) { + for (Attribute attribute : attributes) { if (attribute.getClass() == attrClass) { throw new AssertionError("attribute not expected"); } @@ -1717,24 +1690,23 @@ public class RecordCompilationTests extends CompilationTestCase { for (Element e : annoElements) { Symbol s = (Symbol) e; switch (s.getKind()) { - case FIELD: + case FIELD -> { Assert.check(targetSet.contains("ElementType.FIELD")); targetSet.remove("ElementType.FIELD"); - break; - case METHOD: + } + case METHOD -> { Assert.check(targetSet.contains("ElementType.METHOD")); targetSet.remove("ElementType.METHOD"); - break; - case PARAMETER: + } + case PARAMETER -> { Assert.check(targetSet.contains("ElementType.PARAMETER")); targetSet.remove("ElementType.PARAMETER"); - break; - case RECORD_COMPONENT: + } + case RECORD_COMPONENT -> { Assert.check(targetSet.contains("ElementType.RECORD_COMPONENT")); targetSet.remove("ElementType.RECORD_COMPONENT"); - break; - default: - throw new AssertionError("unexpected element kind"); + } + default -> throw new AssertionError("unexpected element kind"); } } } @@ -1786,13 +1758,13 @@ public class RecordCompilationTests extends CompilationTestCase { public void testMethodsInheritedFromRecordArePublicAndFinal() throws Exception { int numberOfFieldRefs = 0; File dir = assertOK(true, "record R() {}"); - for (final File fileEntry : dir.listFiles()) { + for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) { if (fileEntry.getName().equals("R.class")) { - ClassFile classFile = ClassFile.read(fileEntry); - for (Method method : classFile.methods) - switch (method.getName(classFile.constant_pool)) { + ClassModel classFile = Classfile.of().parse(fileEntry.toPath()); + for (MethodModel method : classFile.methods()) + switch (method.methodName().stringValue()) { case "toString", "equals", "hashCode" -> - Assert.check(method.access_flags.is(AccessFlags.ACC_PUBLIC) && method.access_flags.is(AccessFlags.ACC_FINAL)); + Assert.check(((method.flags().flagsMask() & Classfile.ACC_PUBLIC) != 0) && ((method.flags().flagsMask() & Classfile.ACC_FINAL) != 0)); default -> {} } } @@ -1818,13 +1790,13 @@ public class RecordCompilationTests extends CompilationTestCase { // as the record type for (String a : ACCESSIBILITY) { File dir = assertOK(true, "class R {# record RR() {} }", a); - for (final File fileEntry : dir.listFiles()) { + for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) { if (fileEntry.getName().equals("R$RR.class")) { - ClassFile classFile = ClassFile.read(fileEntry); - for (Method method : classFile.methods) - if (method.getName(classFile.constant_pool).equals("")) { - Assert.check(method.access_flags.flags == accessFlag(a), - "was expecting access flag " + accessFlag(a) + " but found " + method.access_flags.flags); + ClassModel classFile = Classfile.of().parse(fileEntry.toPath()); + for (MethodModel method : classFile.methods()) + if (method.methodName().equalsString("")) { + Assert.check(method.flags().flagsMask() == accessFlag(a), + "was expecting access flag " + accessFlag(a) + " but found " + method.flags().flagsMask()); } } } @@ -1832,25 +1804,23 @@ public class RecordCompilationTests extends CompilationTestCase { } private int protection(String access) { - switch (access) { - case "private": return 3; - case "protected": return 1; - case "public": return 0; - case "": return 2; - default: - throw new AssertionError(); - } + return switch (access) { + case "private" -> 3; + case "protected" -> 1; + case "public" -> 0; + case "" -> 2; + default -> throw new AssertionError(); + }; } private int accessFlag(String access) { - switch (access) { - case "private": return AccessFlags.ACC_PRIVATE; - case "protected": return AccessFlags.ACC_PROTECTED; - case "public": return AccessFlags.ACC_PUBLIC; - case "": return 0; - default: - throw new AssertionError(); - } + return switch (access) { + case "private" -> Classfile.ACC_PRIVATE; + case "protected" -> Classfile.ACC_PROTECTED; + case "public" -> Classfile.ACC_PUBLIC; + case "" -> 0; + default -> throw new AssertionError(); + }; } public void testSameArity() { @@ -2101,7 +2071,7 @@ public class RecordCompilationTests extends CompilationTestCase { public void testNoWarningForSerializableRecords() { if (!useAP) { - // dont execute this test when the default annotation processor is on as it will fail due to + // don't execute this test when the default annotation processor is on as it will fail due to // spurious warnings appendCompileOptions("-Werror", "-Xlint:serial"); assertOK( diff --git a/test/langtools/tools/javac/records/RecordsBinaryCompatibilityTests.java b/test/langtools/tools/javac/records/RecordsBinaryCompatibilityTests.java index d526dbc4ef2..1c258ac9d25 100644 --- a/test/langtools/tools/javac/records/RecordsBinaryCompatibilityTests.java +++ b/test/langtools/tools/javac/records/RecordsBinaryCompatibilityTests.java @@ -29,7 +29,12 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util * jdk.compiler/com.sun.tools.javac.code - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main RecordsBinaryCompatibilityTests */ @@ -42,7 +47,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.IntStream; -import com.sun.tools.classfile.*; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.util.Assert; import toolbox.TestRunner; diff --git a/test/langtools/tools/javac/records/recordComponent/RecordComponentTypeTest.java b/test/langtools/tools/javac/records/recordComponent/RecordComponentTypeTest.java index 46418a66d83..e4fcdc6c07a 100644 --- a/test/langtools/tools/javac/records/recordComponent/RecordComponentTypeTest.java +++ b/test/langtools/tools/javac/records/recordComponent/RecordComponentTypeTest.java @@ -28,12 +28,18 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @compile GenerateTypeProcessor.java * @run main RecordComponentTypeTest */ -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.RuntimeVisibleAnnotationsAttribute; import java.nio.file.Path; import java.util.Arrays; @@ -47,7 +53,7 @@ import toolbox.Task; public class RecordComponentTypeTest extends TestRunner { ToolBox tb; - ClassFile cf; + ClassModel cf; public RecordComponentTypeTest() { super(System.err); @@ -137,27 +143,26 @@ public class RecordComponentTypeTest extends TestRunner { .options("-processor", "GenerateTypeProcessor") .outdir(curPath) .run(); - cf = ClassFile.read(curPath.resolve("RecordComponentUsingGeneratedTypeWithAnnotation.class")); + cf = Classfile.of().parse(curPath.resolve("RecordComponentUsingGeneratedTypeWithAnnotation.class")); - for (Field field : cf.fields) { - if ("generatedType".equals(field.getName(cf.constant_pool))) { - checkRuntimeVisibleAnnotation(field.attributes); + for (FieldModel field : cf.fields()) { + if (field.fieldName().equalsString("generatedType")){ + checkRuntimeVisibleAnnotation(field); } } - for (Method method : cf.methods) { - if ("generatedType".equals(method.getName(cf.constant_pool))) { - checkRuntimeVisibleAnnotation(method.attributes); + for (MethodModel method : cf.methods()) { + if (method.methodName().equalsString("generatedType")) { + checkRuntimeVisibleAnnotation(method); } } } - private void checkRuntimeVisibleAnnotation(Attributes attributes) throws Exception { - RuntimeVisibleAnnotations_attribute annotations = - (RuntimeVisibleAnnotations_attribute) attributes.get(Attribute.RuntimeVisibleAnnotations); + private void checkRuntimeVisibleAnnotation(AttributedElement attributedElement) throws Exception { + RuntimeVisibleAnnotationsAttribute annotations = attributedElement.findAttribute(Attributes.RUNTIME_VISIBLE_ANNOTATIONS).orElseThrow(); boolean hasAnnotation = false; - for (Annotation annotation : annotations.annotations) { - if ("LTestAnnotation;".equals(cf.constant_pool.getUTF8Value(annotation.type_index))) { + for (Annotation annotation : annotations.annotations()) { + if (annotation.classSymbol().descriptorString().equals("LTestAnnotation;")) { hasAnnotation = true; } } diff --git a/test/langtools/tools/javac/recovery/AnnotationRecovery.java b/test/langtools/tools/javac/recovery/AnnotationRecovery.java index cdcb4f4b256..30f1fb3c182 100644 --- a/test/langtools/tools/javac/recovery/AnnotationRecovery.java +++ b/test/langtools/tools/javac/recovery/AnnotationRecovery.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main AnnotationRecovery */ diff --git a/test/langtools/tools/javac/recovery/AttrRecovery.java b/test/langtools/tools/javac/recovery/AttrRecovery.java index e0dd57d23b9..67df9f84567 100644 --- a/test/langtools/tools/javac/recovery/AttrRecovery.java +++ b/test/langtools/tools/javac/recovery/AttrRecovery.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main AttrRecovery */ diff --git a/test/langtools/tools/javac/recovery/LambdaRecovery.java b/test/langtools/tools/javac/recovery/LambdaRecovery.java index 74d796d0b02..38151ac70e5 100644 --- a/test/langtools/tools/javac/recovery/LambdaRecovery.java +++ b/test/langtools/tools/javac/recovery/LambdaRecovery.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main LambdaRecovery */ diff --git a/test/langtools/tools/javac/recovery/MethodModifiers.java b/test/langtools/tools/javac/recovery/MethodModifiers.java index 3212d20f47c..ea12a4a5c3f 100644 --- a/test/langtools/tools/javac/recovery/MethodModifiers.java +++ b/test/langtools/tools/javac/recovery/MethodModifiers.java @@ -28,7 +28,12 @@ * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main MethodModifiers */ diff --git a/test/langtools/tools/javac/sealed/BinaryCompatibilityTests.java b/test/langtools/tools/javac/sealed/BinaryCompatibilityTests.java index 793dba41d17..f828a548c07 100644 --- a/test/langtools/tools/javac/sealed/BinaryCompatibilityTests.java +++ b/test/langtools/tools/javac/sealed/BinaryCompatibilityTests.java @@ -29,7 +29,12 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util * jdk.compiler/com.sun.tools.javac.code - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main BinaryCompatibilityTests */ @@ -42,7 +47,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.IntStream; -import com.sun.tools.classfile.*; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.util.Assert; import toolbox.TestRunner; @@ -52,8 +56,6 @@ import toolbox.JavacTask; import toolbox.Task; import toolbox.Task.OutputKind; -import static com.sun.tools.classfile.ConstantPool.*; - public class BinaryCompatibilityTests extends TestRunner { ToolBox tb; diff --git a/test/langtools/tools/javac/sealed/SealedDiffConfigurationsTest.java b/test/langtools/tools/javac/sealed/SealedDiffConfigurationsTest.java index 0e7e37e6547..de6d8276703 100644 --- a/test/langtools/tools/javac/sealed/SealedDiffConfigurationsTest.java +++ b/test/langtools/tools/javac/sealed/SealedDiffConfigurationsTest.java @@ -29,7 +29,12 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.util * jdk.compiler/com.sun.tools.javac.code - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * @build toolbox.ToolBox toolbox.JavacTask * @run main SealedDiffConfigurationsTest */ @@ -42,7 +47,10 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.IntStream; -import com.sun.tools.classfile.*; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.PermittedSubclassesAttribute; +import jdk.internal.classfile.constantpool.ClassEntry; +import jdk.internal.classfile.constantpool.ConstantPoolException; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.util.Assert; import toolbox.TestRunner; @@ -51,8 +59,6 @@ import toolbox.JavacTask; import toolbox.Task; import toolbox.Task.OutputKind; -import static com.sun.tools.classfile.ConstantPool.*; - public class SealedDiffConfigurationsTest extends TestRunner { ToolBox tb; @@ -129,14 +135,14 @@ public class SealedDiffConfigurationsTest extends TestRunner { } private void checkSealedClassFile(Path out, String cfName, List expectedSubTypeNames) throws ConstantPoolException, Exception { - ClassFile sealedCF = ClassFile.read(out.resolve(cfName)); - Assert.check((sealedCF.access_flags.flags & Flags.FINAL) == 0, String.format("class at file %s must not be final", cfName)); - PermittedSubclasses_attribute permittedSubclasses = (PermittedSubclasses_attribute)sealedCF.attributes.get("PermittedSubclasses"); - Assert.check(permittedSubclasses.subtypes.length == expectedSubTypeNames.size()); + ClassModel sealedCF = Classfile.of().parse(out.resolve(cfName)); + Assert.check((sealedCF.flags().flagsMask() & Classfile.ACC_FINAL) == 0, String.format("class at file %s must not be final", cfName)); + PermittedSubclassesAttribute permittedSubclasses = sealedCF.findAttribute(Attributes.PERMITTED_SUBCLASSES).orElseThrow(); + Assert.check(permittedSubclasses.permittedSubclasses().size() == expectedSubTypeNames.size()); List subtypeNames = new ArrayList<>(); - IntStream.of(permittedSubclasses.subtypes).forEach(i -> { + permittedSubclasses.permittedSubclasses().forEach(i -> { try { - subtypeNames.add(((CONSTANT_Class_info)sealedCF.constant_pool.get(i)).getName()); + subtypeNames.add(i.name().stringValue()); } catch (ConstantPoolException ex) { } }); @@ -147,12 +153,12 @@ public class SealedDiffConfigurationsTest extends TestRunner { } private void checkSubtypeClassFile(Path out, String cfName, String superClassName, boolean shouldBeFinal) throws Exception { - ClassFile subCF1 = ClassFile.read(out.resolve(cfName)); + ClassModel subCF1 = Classfile.of().parse(out.resolve(cfName)); if (shouldBeFinal) { - Assert.check((subCF1.access_flags.flags & Flags.FINAL) != 0, String.format("class at file %s must be final", cfName)); + Assert.check((subCF1.flags().flagsMask() & Classfile.ACC_FINAL) != 0, String.format("class at file %s must be final", cfName)); } - Assert.checkNull((PermittedSubclasses_attribute)subCF1.attributes.get("PermittedSubclasses")); - Assert.check(((CONSTANT_Class_info)subCF1.constant_pool.get(subCF1.super_class)).getName().equals(superClassName)); + Assert.checkNull(subCF1.findAttribute(Attributes.PERMITTED_SUBCLASSES).orElse(null)); + Assert.check(subCF1.superclass().orElseThrow().name().equalsString(superClassName)); } @Test diff --git a/test/langtools/tools/javac/sym/ElementStructureTest.java b/test/langtools/tools/javac/sym/ElementStructureTest.java index 3760ef95107..3513a6347ac 100644 --- a/test/langtools/tools/javac/sym/ElementStructureTest.java +++ b/test/langtools/tools/javac/sym/ElementStructureTest.java @@ -31,7 +31,12 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.compiler/com.sun.tools.javac.platform * jdk.compiler/com.sun.tools.javac.util - * jdk.jdeps/com.sun.tools.classfile + * java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.jdeps/com.sun.tools.javap * @build toolbox.ToolBox ElementStructureTest * @run main ElementStructureTest @@ -93,8 +98,7 @@ import javax.tools.StandardLocation; import javax.tools.ToolProvider; import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.ConstantPoolException; +import jdk.internal.classfile.Classfile; import com.sun.tools.javac.api.JavacTaskImpl; import com.sun.tools.javac.code.Symbol.CompletionFailure; import com.sun.tools.javac.platform.PlatformProvider; @@ -213,14 +217,11 @@ public class ElementStructureTest { return; StringBuilder targetPattern; switch (line.charAt(0)) { - case '+': - targetPattern = acceptPattern; - break; - case '-': - targetPattern = rejectPattern; - break; - default: - return ; + case '+' -> targetPattern = acceptPattern; + case '-' -> targetPattern = rejectPattern; + default -> { + return; + } } line = line.substring(1); if (line.endsWith("/")) { @@ -256,7 +257,7 @@ public class ElementStructureTest { void run(Writer output, String version) throws Exception { List options = Arrays.asList("--release", version, "-classpath", ""); - List files = Arrays.asList(new ToolBox.JavaSource("Test", "")); + List files = List.of(new ToolBox.JavaSource("Test", "")); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, null, null, options, null, files); @@ -288,10 +289,10 @@ public class ElementStructureTest { } JavaFileObject file = new ByteArrayJavaFileObject(data.toByteArray()); try (InputStream in = new ByteArrayInputStream(data.toByteArray())) { - String name = ClassFile.read(in).getName().replace("/", "."); + String name = Classfile.of().parse(in.readAllBytes()).thisClass().name().stringValue(); className2File.put(name, file); file2ClassName.put(file, name); - } catch (IOException | ConstantPoolException ex) { + } catch (IOException ex) { throw new IllegalStateException(ex); } } diff --git a/test/langtools/tools/javac/varargs/6199075/T6199075.java b/test/langtools/tools/javac/varargs/6199075/T6199075.java index 7800d5afb07..19fe33284eb 100644 --- a/test/langtools/tools/javac/varargs/6199075/T6199075.java +++ b/test/langtools/tools/javac/varargs/6199075/T6199075.java @@ -28,19 +28,22 @@ * @summary Unambiguous varargs method calls flagged as ambiguous * @author mcimadamore * - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.file * jdk.compiler/com.sun.tools.javac.util */ import com.sun.source.util.JavacTask; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.MemberRefEntry; +import jdk.internal.classfile.instruction.InvokeInstruction; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.util.List; @@ -216,10 +219,10 @@ public class T6199075 { bytecodeCheckCount++; File compiledTest = new File("Test.class"); try { - ClassFile cf = ClassFile.read(compiledTest); - Method testMethod = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals("test")) { + ClassModel cf = Classfile.of().parse(compiledTest.toPath()); + MethodModel testMethod = null; + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString("test")) { testMethod = m; break; } @@ -227,17 +230,15 @@ public class T6199075 { if (testMethod == null) { throw new Error("Test method not found"); } - Code_attribute ea = (Code_attribute)testMethod.attributes.get(Attribute.Code); - if (testMethod == null) { + CodeAttribute ea = testMethod.findAttribute(Attributes.CODE).orElse(null); + if (ea == null) { throw new Error("Code attribute for test() method not found"); } - for (Instruction i : ea.getInstructions()) { - if (i.getMnemonic().equals("invokevirtual")) { - int cp_entry = i.getUnsignedShort(1); - CONSTANT_Methodref_info methRef = - (CONSTANT_Methodref_info)cf.constant_pool.get(cp_entry); - String type = methRef.getNameAndTypeInfo().getType(); + for (CodeElement i : ea.elementList()) { + if (i instanceof InvokeInstruction ins && ins.opcode() == Opcode.INVOKEVIRTUAL) { + MemberRefEntry methRef = ins.method(); + String type = methRef.type().stringValue(); if (!type.contains(selected.varargsElement.bytecodeString)) { throw new Error("Unexpected type method call: " + type); } diff --git a/test/langtools/tools/javac/varargs/7042566/T7042566.java b/test/langtools/tools/javac/varargs/7042566/T7042566.java index e6633629e86..6126c180f19 100644 --- a/test/langtools/tools/javac/varargs/7042566/T7042566.java +++ b/test/langtools/tools/javac/varargs/7042566/T7042566.java @@ -27,7 +27,12 @@ * @summary Unambiguous varargs method calls flagged as ambiguous * temporarily workaround combo tests are causing time out in several platforms * @library /tools/javac/lib - * @modules jdk.jdeps/com.sun.tools.classfile + * @modules java.base/jdk.internal.classfile + * java.base/jdk.internal.classfile.attribute + * java.base/jdk.internal.classfile.constantpool + * java.base/jdk.internal.classfile.instruction + * java.base/jdk.internal.classfile.components + * java.base/jdk.internal.classfile.impl * jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.file * jdk.compiler/com.sun.tools.javac.util @@ -39,12 +44,11 @@ import java.io.IOException; import java.io.InputStream; import javax.tools.JavaFileObject; -import com.sun.tools.classfile.Instruction; -import com.sun.tools.classfile.Attribute; -import com.sun.tools.classfile.ClassFile; -import com.sun.tools.classfile.Code_attribute; -import com.sun.tools.classfile.ConstantPool.*; -import com.sun.tools.classfile.Method; +import jdk.internal.classfile.*; +import jdk.internal.classfile.attribute.CodeAttribute; +import jdk.internal.classfile.constantpool.MemberRefEntry; +import jdk.internal.classfile.constantpool.MethodRefEntry; +import jdk.internal.classfile.instruction.InvokeInstruction; import com.sun.tools.javac.util.List; import combo.ComboInstance; @@ -270,10 +274,10 @@ public class T7042566 extends ComboInstance { void verifyBytecode(Result> res, VarargsMethod selected) { try (InputStream is = res.get().iterator().next().openInputStream()) { - ClassFile cf = ClassFile.read(is); - Method testMethod = null; - for (Method m : cf.methods) { - if (m.getName(cf.constant_pool).equals("test")) { + ClassModel cf = Classfile.of().parse(is.readAllBytes()); + MethodModel testMethod = null; + for (MethodModel m : cf.methods()) { + if (m.methodName().equalsString("test")) { testMethod = m; break; } @@ -282,19 +286,15 @@ public class T7042566 extends ComboInstance { fail("Test method not found"); return; } - Code_attribute ea = - (Code_attribute)testMethod.attributes.get(Attribute.Code); - if (testMethod == null) { + CodeAttribute ea = testMethod.findAttribute(Attributes.CODE).orElse(null); + if (ea == null) { fail("Code attribute for test() method not found"); return; } - - for (Instruction i : ea.getInstructions()) { - if (i.getMnemonic().equals("invokevirtual")) { - int cp_entry = i.getUnsignedShort(1); - CONSTANT_Methodref_info methRef = - (CONSTANT_Methodref_info)cf.constant_pool.get(cp_entry); - String type = methRef.getNameAndTypeInfo().getType(); + for (CodeElement i : ea.elementList()) { + if (i instanceof InvokeInstruction ins && ins.opcode() == Opcode.INVOKEVIRTUAL) { + MemberRefEntry methRef = ins.method(); + String type = methRef.type().stringValue(); String sig = selected.parameterTypes.bytecodeSigStr; if (!type.contains(sig)) { fail("Unexpected type method call: " +