File: NegativeCyclicDependencyTest.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 (339 lines) | stat: -rw-r--r-- 12,992 bytes parent folder | download | duplicates (18)
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
 * Copyright (c) 2014, 2016, 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 8064794
 * @summary The negative test against cyclic dependencies.
 * @library /tools/lib
 * @modules jdk.compiler/com.sun.tools.javac.api
 *          jdk.compiler/com.sun.tools.javac.main
 * @build toolbox.ToolBox NegativeCyclicDependencyTest
 * @run main NegativeCyclicDependencyTest
 */

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import toolbox.ToolBox;

/**
 * The test generates the following code:
 *
 * package pkg;
 * import pkg.B.InnerB;
 * class A extends InnerB {
 *    static class InnerA {}
 * }
 *
 * package pkg;
 * import pkg.A.InnerA;
 * class B extends InnerA {
 *     static class InnerB {}
 * }
 *
 * compiles and checks whether compilation fails with the correct message.
 * The test generates all possible combination of inheritance:
 *     1. A extends InnerB, B extends InnerA;
 *     2. InnerA extends InnerB, InnerB extends InnerA;
 *     3. A extends InnerB, InnerB extends InnerA;
 *     4. B extends InnerA, InnerA extends InnerB;
 *     5. A extends InnerA.
 * The test checks class, enum and interface as parent class, and checks all
 * possible import statements.
 */
public class NegativeCyclicDependencyTest {
    private final static String expectedErrorMessage =
            "\\w+:\\d+:\\d+: compiler.err.cyclic.inheritance: [\\w.]+\n1 error\n";

    private final static String[] sourceTemplatesA = {
            "package pkg;\n" +
            "#IMPORT_TYPE\n" +
            "#OUTER_CLASS A #INHERIT InnerB {#ENUM_SEMI\n" +
            "    static #INNER_CLASS InnerA {}\n" +
            "}",
            "package pkg;\n" +
            "#IMPORT_TYPE\n" +
            "#OUTER_CLASS A {#ENUM_SEMI\n" +
            "    static #INNER_CLASS InnerA #INHERIT InnerB {}\n" +
            "}"
    };

    private final static String[] sourceTemplatesB = {
            "package pkg;\n" +
            "#IMPORT_TYPE\n" +
            "#OUTER_CLASS B #INHERIT InnerA {#ENUM_SEMI\n" +
            "    static #INNER_CLASS InnerB {}\n" +
            "}",
            "package pkg;\n" +
            "#IMPORT_TYPE\n" +
            "#OUTER_CLASS B {#ENUM_SEMI\n" +
            "    static #INNER_CLASS InnerB #INHERIT InnerA {}\n" +
            "}"
    };

    private final static String sourceTemplate =
            "package pkg;\n" +
            "#IMPORT_TYPE\n" +
            "#OUTER_CLASS A #INHERIT InnerA {#ENUM_SEMI\n" +
            "    static #INNER_CLASS InnerA {}\n" +
            "}";

    public static void main(String[] args) {
        new NegativeCyclicDependencyTest().test();
    }

    public void test() {
        int passed = 0;
        List<TestCase> testCases = generateTestCases();
        for (TestCase testCase : testCases) {
            try {
                String output = compile(testCase.sources);
                if (!output.matches(testCase.expectedMessage)) {
                    reportFailure(testCase);
                    printf(String.format("Message: %s, does not match regexp: %s\n",
                            output, testCase.expectedMessage));
                } else {
                    ++passed;
                }
            } catch (RuntimeException e) {
                reportFailure(testCase);
                e.printStackTrace();
            }
        }
        String message = String.format(
                "Total test cases run: %d, passed: %d, failed: %d.",
                testCases.size(), passed, testCases.size() - passed);
        if (passed != testCases.size()) {
            throw new RuntimeException(message);
        }
        echo(message);
    }

    private void reportFailure(TestCase testCase) {
        echo("Test case failed.");
        for (ToolBox.JavaSource source : testCase.sources) {
            echo(source.getCharContent(true));
            echo();
        }
    }

    public List<TestCase> generateTestCases() {
        List<TestCase> testCases = generateTestCasesWithTwoClasses();
        testCases.addAll(generateTestCasesWithOneClass());
        return testCases;
    }

    private List<TestCase> generateTestCasesWithOneClass() {
        String importedClassName = "pkg.A.InnerA";
        List<TestCase> testCases = new ArrayList<>();
        for (ClassType outerClass : ClassType.values()) {
            for (ClassType innerClass : ClassType.values()) {
                if (!outerClass.canInherit(innerClass)) {
                    continue;
                }
                for (ImportType importType : ImportType.values()) {
                    String source = generateSource(
                            sourceTemplate,
                            outerClass,
                            innerClass,
                            outerClass.inheritedString(innerClass),
                            importType,
                            importedClassName);
                    testCases.add(new TestCase(expectedErrorMessage,
                            new ToolBox.JavaSource("A", source)));
                }
            }
        }
        return testCases;
    }

    private List<TestCase> generateTestCasesWithTwoClasses() {
        String importedClassName1 = "pkg.A.InnerA";
        String importedClassName2 = "pkg.B.InnerB";
        List<TestCase> testCases = new ArrayList<>();
        for (int i = 0; i < sourceTemplatesA.length; ++i) {
            for (int j = 0; j < sourceTemplatesB.length; ++j) {
                for (ClassType outerClass1 : ClassType.values()) {
                    for (ClassType outerClass2 : ClassType.values()) {
                        for (ClassType innerClass1 : ClassType.values()) {
                            for (ClassType innerClass2 : ClassType.values()) {
                                ClassType childClass1 = i == 0 ? outerClass1 : innerClass1;
                                ClassType childClass2 = j == 0 ? outerClass2 : innerClass2;
                                if (!childClass1.canInherit(innerClass2) ||
                                        !childClass2.canInherit(innerClass1)) {
                                    continue;
                                }
                                for (ImportType importType1 : ImportType.values()) {
                                    for (ImportType importType2 : ImportType.values()) {
                                        String sourceA = generateSource(
                                                sourceTemplatesA[i],
                                                outerClass1,
                                                innerClass1,
                                                childClass1.inheritedString(innerClass2),
                                                importType1,
                                                importedClassName2);
                                        String sourceB = generateSource(
                                                sourceTemplatesB[j],
                                                outerClass2,
                                                innerClass2,
                                                childClass2.inheritedString(innerClass1),
                                                importType2,
                                                importedClassName1);
                                        testCases.add(new TestCase(expectedErrorMessage,
                                                new ToolBox.JavaSource("A", sourceA),
                                                new ToolBox.JavaSource("B", sourceB)));
                                        testCases.add(new TestCase(expectedErrorMessage,
                                                new ToolBox.JavaSource("B", sourceB),
                                                new ToolBox.JavaSource("A", sourceA)));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return testCases;
    }

    public String generateSource(String template,
                                 ClassType outerClass,
                                 ClassType innerClass,
                                 String inheritString,
                                 ImportType importType,
                                 String innerClassName) {
        return template
                .replace("#OUTER_CLASS", outerClass.getType())
                .replace("#INNER_CLASS", innerClass.getType())
                .replace("#INHERIT", inheritString)
                .replace("#IMPORT_TYPE", importType.getImport(innerClassName))
                .replace("#ENUM_SEMI", outerClass == ClassType.ENUM ? ";" : "");
    }

    /**
     * Compiles sources with -XDrawDiagnostics flag and
     * returns the output of compilation.
     *
     * @param sources sources
     * @return the result of compilation
     */
    private String compile(ToolBox.JavaSource...sources) {
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
        StringWriter writer = new StringWriter();
        JavaCompiler.CompilationTask ct = jc.getTask(writer, null, null,
                Arrays.asList("-XDrawDiagnostics"),
                null, Arrays.asList(sources));
        if (ct.call()) {
            throw new RuntimeException("Expected compilation failure.");
        }
        return writer.toString().replace(ToolBox.lineSeparator, "\n");
    }

    public void echo() {
        echo("");
    }

    public void echo(CharSequence message) {
        echo(message.toString());
    }

    public void echo(String message) {
        printf(message + "\n");
    }

    public void printf(String template, Object...args) {
        System.err.print(String.format(template, args).replace("\n", ToolBox.lineSeparator));
    }

    /**
     * The class represents a test case.
     */
    public static class TestCase {
        public final ToolBox.JavaSource[] sources;
        public final String expectedMessage;

        public TestCase(String expectedMessage, ToolBox.JavaSource...sources) {
            this.sources = sources;
            this.expectedMessage = expectedMessage;
        }
    }

    /**
     * The enum represents all possible imports.
     */
    public enum ImportType {
        SINGLE_IMPORT("import %s;"),
        IMPORT_ON_DEMAND("import %s.*;"),
        SINGLE_STATIC_IMPORT("import static %s;"),
        STATIC_IMPORT_ON_DEMAND("import static %s.*;");

        private final String type;

        private ImportType(String type) {
            this.type = type;
        }

        public String getImport(String className) {
            if (this == ImportType.IMPORT_ON_DEMAND || this == ImportType.STATIC_IMPORT_ON_DEMAND) {
                int lastDot = className.lastIndexOf('.');
                className = className.substring(0, lastDot);
            }
            return String.format(type, className);
        }
    }

    /**
     * The enum represents all possible class types that can be used in
     * inheritance.
     */
    public enum ClassType {
        CLASS("class"), INTERFACE("interface"), ENUM("enum");

        public boolean canInherit(ClassType innerClass) {
            return innerClass != ENUM && !(this == ENUM && innerClass == ClassType.CLASS
                    || this == INTERFACE && innerClass == ClassType.CLASS);
        }

        public String inheritedString(ClassType innerClass) {
            if (!canInherit(innerClass)) {
                throw new IllegalArgumentException(String.format("%s cannot inherit %s", this, innerClass));
            }
            return this == innerClass ? "extends" : "implements";
        }

        private final String type;

        private ClassType(String type) {
            this.type = type;
        }

        public String getType() {
            return type;
        }
    }
}