File: MethodParametersTest.java

package info (click to toggle)
openjdk-25 25.0.1%2B8-1~deb13u1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 825,408 kB
  • sloc: java: 5,585,680; cpp: 1,333,948; xml: 1,321,242; ansic: 488,034; asm: 404,003; objc: 21,088; sh: 15,106; javascript: 13,265; python: 8,319; makefile: 2,518; perl: 357; awk: 351; pascal: 103; exp: 83; sed: 72; jsp: 24
file content (314 lines) | stat: -rw-r--r-- 14,618 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 8004727
 * @summary javac should generate method parameters correctly.
 * @modules 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.model
 *          jdk.compiler/com.sun.tools.javac.util
 */
// key: opt.arg.parameters
import java.lang.classfile.*;
import java.lang.classfile.attribute.*;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.main.Main;
import com.sun.tools.javac.util.Context;
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 {

    static final String Foo_name = "Foo";
    static final String Foo_contents =
        "public class Foo {\n" +
        "  Foo() {}\n" +
        "  void foo0() {}\n" +
        "  void foo2(int j, int k) {}\n" +
        "}";
    static final String Bar_name = "Bar";
    static final String Bar_contents =
        "public class Bar {\n" +
        "  Bar(int i) {}" +
        "  Foo foo() { return new Foo(); }\n" +
        "}";
    static final String Baz_name = "Baz";
    static final String Baz_contents =
        "public class Baz {\n" +
        "  int baz;" +
        "  Baz(int i) {}" +
        "}";
    static final String Qux_name = "Qux";
    static final String Qux_contents =
        "public class Qux extends Baz {\n" +
        "  Qux(int i) { super(i); }" +
        "}";
    static final File classesdir = new File("methodparameters");

    public static void main(String... args) throws Exception {
        new MethodParametersTest().run();
    }

    void run() throws Exception {
        classesdir.mkdir();
        final File Foo_java =
            writeFile(classesdir, Foo_name + ".java", Foo_contents);
        final File Bar_java =
            writeFile(classesdir, Bar_name + ".java", Bar_contents);
        final File Baz_java =
            writeFile(classesdir, Baz_name + ".java", Baz_contents);
        System.err.println("Test compile with -parameter");
        compile("-parameters", "-d", classesdir.getPath(), Foo_java.getPath());
        // First test: make sure javac doesn't choke to death on
        // MethodParameter attributes
        System.err.println("Test compile with classfile containing MethodParameter attributes");
        compile("-parameters", "-d", classesdir.getPath(),
                "-cp", classesdir.getPath(), Bar_java.getPath());
        System.err.println("Examine class foo");
        checkFoo();
        checkBar();
        System.err.println("Test debug information conflict");
        compile("-g", "-parameters", "-d", classesdir.getPath(),
                "-cp", classesdir.getPath(), Baz_java.getPath());
        System.err.println("Introducing debug information conflict");
        Baz_java.delete();
        modifyBaz(false);
        System.err.println("Checking language model");
        inspectBaz();
        System.err.println("Permuting attributes");
        modifyBaz(true);
        System.err.println("Checking language model");
        inspectBaz();

        if(0 != errors)
            throw new Exception("MethodParameters test failed with " +
                                errors + " errors");
    }

    void inspectBaz() throws Exception {
        final File Qux_java =
            writeFile(classesdir, Qux_name + ".java", Qux_contents);
        final String[] args = { "-parameters", "-d",
                                classesdir.getPath(),
                                "-cp", classesdir.getPath(),
                                Qux_java.getPath() };
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);

        // We need to be able to crack open javac and look at its data
        // structures.  We'll rig up a compiler instance, but keep its
        // Context, thus allowing us to get at the ClassReader.
        Context context = new Context();
        Main comp =  new Main("javac", pw);
        JavacFileManager.preRegister(context);

        // Compile Qux, which uses Baz.
        comp.compile(args, context);
        pw.close();
        final String out = sw.toString();
        if (out.length() > 0)
            System.err.println(out);

        // Now get the class finder, construct a name for Baz, and load it.
        com.sun.tools.javac.code.ClassFinder cf =
            com.sun.tools.javac.code.ClassFinder.instance(context);
        Name name = Names.instance(context).fromString(Baz_name);
        Symtab syms = Symtab.instance(context);

        // Now walk down the language model and check the name of the
        // parameter.
        final Element baz = cf.loadClass(syms.unnamedModule, name);
        for (Element e : baz.getEnclosedElements()) {
            if (e instanceof ExecutableElement ee) {
                final List<? extends VariableElement> params =
                    ee.getParameters();
                if (1 != params.size())
                    throw new Exception("Classfile Baz badly formed: wrong number of methods");
                final VariableElement param = params.get(0);
                if (!param.getSimpleName().contentEquals("baz")) {
                    errors++;
                    System.err.println("javac did not correctly resolve the metadata conflict, parameter's name reads as " + param.getSimpleName());
                } else
                    System.err.println("javac did correctly resolve the metadata conflict");
            }
        }
    }

    void modifyBaz(boolean flip) throws Exception {
        final File Baz_class = new File(classesdir, Baz_name + ".class");
        final ClassModel baz = ClassFile.of().parse(Baz_class.toPath());

        // 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().get(0).methodName().equalsString("<init>"))
            throw new Exception("Classfile Baz badly formed: method has name " +
                                baz.methods().get(0).methodName().stringValue());
        MethodParametersAttribute mpattr = baz.methods().get(0).findAttribute(Attributes.methodParameters()).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");

        // Alter the MethodParameters attribute, changing the name of
        // the parameter from i to baz.
        byte[] bazBytes = ClassFile.of().transformClass(baz, ClassTransform.transformingMethods((methodBuilder, methodElement) -> {
            if (methodElement instanceof MethodParametersAttribute a) {
                List<MethodParameterInfo> 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
        // that order doesn't matter.
        if (flip) {
            bazBytes = ClassFile.of().transformClass(baz, ClassTransform.transformingMethods((methodBuilder, methodElement) -> {
                if (methodElement instanceof MethodParametersAttribute) {
                    methodBuilder.with(cattr);
                } else if (methodElement instanceof CodeAttribute){
                    methodBuilder.with(mpattr);
                } else {
                    methodBuilder.with(methodElement);
                }
            }));
        }
        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 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.parameters().size())
                            error("expected 2 method parameter entries in foo2, got " +
                                  mp.parameters().size());
                        else if (!mp.parameters().get(0).name().orElseThrow().equalsString("j"))
                            error("expected first parameter to foo2 to be \"j\", got \"" +
                                  mp.parameters().get(0).name().orElseThrow().stringValue() +
                                  "\" instead");
                        else if  (!mp.parameters().get(1).name().orElseThrow().equalsString("k"))
                            error("expected first parameter to foo2 to be \"k\", got \"" +
                                 mp.parameters().get(1).name().orElseThrow() +
                                  "\" instead");
                    }
            }
            else if (foo.methods().get(i).methodName().equalsString("<init>")) {
                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().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().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 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("<init>")) {
                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.parameters().size())
                            error("expected 1 method parameter entries in constructor, got " +
                                  mp.parameters().size());
                        else if (!mp.parameters().get(0).name().orElseThrow().equalsString("i"))
                            error("expected first parameter to foo2 to be \"i\", got \"" +
                                  mp.parameters().get(0).name().orElseThrow() +
                                  "\" instead");
                    }
            }
            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");
                }
            }
        }
    }

    String compile(String... args) throws Exception {
        System.err.println("compile: " + Arrays.asList(args));
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        int rc = com.sun.tools.javac.Main.compile(args, pw);
        pw.close();
        String out = sw.toString();
        if (out.length() > 0)
            System.err.println(out);
        if (rc != 0)
            error("compilation failed, rc=" + rc);
        return out;
    }

    File writeFile(File dir, String path, String body) throws IOException {
        File f = new File(dir, path);
        f.getParentFile().mkdirs();
        FileWriter out = new FileWriter(f);
        out.write(body);
        out.close();
        return f;
    }

    void error(String msg) {
        System.err.println("Error: " + msg);
        errors++;
    }

    int errors;
}