VerifyErroneousAnnotationsAttributed.java revision 2244:c1c20e618930
1/*
2 * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/*
25 * @test
26 * @bug 8029161 8029376
27 */
28
29import com.sun.source.tree.CompilationUnitTree;
30import com.sun.source.tree.IdentifierTree;
31import com.sun.source.tree.MemberSelectTree;
32import com.sun.source.util.JavacTask;
33import com.sun.source.util.TreePathScanner;
34import com.sun.source.util.Trees;
35import com.sun.tools.javac.api.JavacTool;
36import java.io.IOException;
37import java.net.URI;
38import java.net.URISyntaxException;
39import java.util.ArrayList;
40import java.util.Arrays;
41import java.util.List;
42import javax.lang.model.element.Element;
43import javax.lang.model.element.ElementKind;
44import javax.lang.model.type.TypeKind;
45import javax.tools.Diagnostic;
46import javax.tools.DiagnosticListener;
47import javax.tools.JavaFileObject;
48import javax.tools.SimpleJavaFileObject;
49
50public class VerifyErroneousAnnotationsAttributed {
51    public static void main(String... args) throws IOException, URISyntaxException {
52        new VerifyErroneousAnnotationsAttributed().run();
53    }
54
55    void run() {
56        int failCount = 0;
57        for (String ann : generateAnnotations()) {
58            String code = PATTERN.replace("PLACEHOLDER", ann);
59            try {
60                validate(code);
61            } catch (Throwable t) {
62                System.out.println("Failed for: ");
63                System.out.println(code);
64                t.printStackTrace(System.out);
65                failCount++;
66            }
67        }
68
69        if (failCount > 0) {
70            throw new IllegalStateException("failed sub-tests: " + failCount);
71        }
72    }
73
74    List<String> generateAnnotations() {
75        List<String> result = new ArrayList<>();
76
77        result.addAll(Kind.ANNOTATION.generateValue(2, true));
78        result.addAll(Kind.ANNOTATION.generateValue(2, false));
79
80        return result;
81    }
82
83    enum Kind {
84        INT("i", "ValueInt") {
85            @Override public List<String> generateValue(int depth, boolean valid) {
86                if (valid) {
87                    return Arrays.asList("INT_VALUE");
88                } else {
89                    return Arrays.asList("BROKEN_INT_VALUE");
90                }
91            }
92        },
93        ANNOTATION("a", "ValueAnnotation") {
94            @Override public List<String> generateValue(int depth, boolean valid) {
95                String ad = "@Annotation" + depth + (valid ? "" : "Unknown");
96
97                if (depth <= 0) {
98                    return Arrays.asList(ad);
99                }
100
101                List<String> result = new ArrayList<>();
102                final Kind[][] generateKindCombinations = new Kind[][] {
103                    new Kind[] {Kind.INT},
104                    new Kind[] {Kind.ANNOTATION},
105                    new Kind[] {Kind.INT, Kind.ANNOTATION}
106                };
107
108                for (boolean generateAssignment : new boolean[] {false, true}) {
109                    for (boolean generateValid : new boolean[] {false, true}) {
110                        for (Kind[] generateKinds : generateKindCombinations) {
111                            if (generateKinds.length > 1 && generateValid && !generateAssignment) {
112                                //skip: the same code is generated for generateValid == false.
113                                continue;
114                            }
115                            List<String> attributes = generateAttributes(generateAssignment,
116                                    generateValid, depth, generateKinds);
117                            String annotation;
118                            if (generateAssignment) {
119                                annotation = ad;
120                            } else {
121                                annotation = ad + generateKinds[0].annotationWithValueSuffix;
122                            }
123                            for (String attr : attributes) {
124                                result.add(annotation + "(" + attr + ")");
125                            }
126                        }
127                    }
128                }
129
130                return result;
131            }
132
133            List<String> generateAttributes(boolean generateAssignment, boolean valid, int depth,
134                                            Kind... kinds) {
135                List<List<String>> combinations = new ArrayList<>();
136
137                for (boolean subValid : new boolean[] {false, true}) {
138                    for (Kind k : kinds) {
139                        String prefix;
140
141                        if (generateAssignment) {
142                            if (valid) {
143                                prefix = k.validAttributeName + "=";
144                            } else {
145                                prefix = "invalid" + k.validAttributeName + "=";
146                            }
147                        } else {
148                            prefix = "";
149                        }
150
151                        List<String> combination = new ArrayList<>();
152
153                        combinations.add(combination);
154
155                        for (String val : k.generateValue(depth - 1, subValid)) {
156                            combination.add(prefix + val);
157                        }
158                    }
159                }
160
161                List<String> result = new ArrayList<>();
162
163                combine(combinations, new StringBuilder(), result);
164
165                return result;
166            }
167
168            void combine(List<List<String>> combinations, StringBuilder current, List<String> to) {
169                if (combinations.isEmpty()) {
170                    to.add(current.toString());
171                    return ;
172                }
173
174                int currLen = current.length();
175
176                for (String str : combinations.get(0)) {
177                    if (current.length() > 0) current.append(", ");
178                    current.append(str);
179
180                    combine(combinations.subList(1, combinations.size()), current, to);
181
182                    current.delete(currLen, current.length());
183                }
184            }
185        };
186        String validAttributeName;
187        String annotationWithValueSuffix;
188
189        private Kind(String validAttributeName, String annotationWithValueSuffix) {
190            this.validAttributeName = validAttributeName;
191            this.annotationWithValueSuffix = annotationWithValueSuffix;
192        }
193
194        public abstract List<String> generateValue(int depth, boolean valid);
195
196    }
197
198    private static final String PATTERN =
199            "public class Test {\n" +
200            "    public static final int INT_VALUE = 1;\n" +
201            "    @interface Annotation0 {}\n" +
202            "    @interface Annotation1 {int i() default 0; Annotation0 a() default @Annotation0; }\n" +
203            "    @interface Annotation2 {int i() default 0; Annotation1 a() default @Annotation1; }\n" +
204            "    @interface Annotation1ValueInt {int value() default 0; }\n" +
205            "    @interface Annotation2ValueInt {int value() default 0; }\n" +
206            "    @interface Annotation1ValueAnnotation {Annotation0 a() default @Annotation0; }\n" +
207            "    @interface Annotation2ValueAnnotation {Annotation1 a() default @Annotation1; }\n" +
208            "    PLACEHOLDER\n" +
209            "    private void test() { }\n" +
210            "}";
211
212    static final class TestCase {
213        final String code;
214        final boolean valid;
215
216        public TestCase(String code, boolean valid) {
217            this.code = code;
218            this.valid = valid;
219        }
220
221    }
222
223    final JavacTool tool = JavacTool.create();
224    final DiagnosticListener<JavaFileObject> devNull = new DiagnosticListener<JavaFileObject>() {
225        @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) {}
226    };
227
228    void validate(String code) throws IOException, URISyntaxException {
229        JavacTask task = tool.getTask(null,
230                                      null,
231                                      devNull,
232                                      Arrays.asList("-XDshouldStopPolicy=FLOW"),
233                                      null,
234                                      Arrays.asList(new MyFileObject(code)));
235
236        final Trees trees = Trees.instance(task);
237        final CompilationUnitTree cut = task.parse().iterator().next();
238        task.analyze();
239
240        //ensure all the annotation attributes are annotated meaningfully
241        //all the attributes in the test file should contain either an identifier
242        //or a select, so only checking those for a reasonable Element/Symbol.
243        new TreePathScanner<Void, Void>() {
244            @Override
245            public Void visitIdentifier(IdentifierTree node, Void p) {
246                verifyAttributedMeaningfully();
247                return super.visitIdentifier(node, p);
248            }
249            @Override
250            public Void visitMemberSelect(MemberSelectTree node, Void p) {
251                verifyAttributedMeaningfully();
252                return super.visitMemberSelect(node, p);
253            }
254            private void verifyAttributedMeaningfully() {
255                Element el = trees.getElement(getCurrentPath());
256
257                if (el == null || el.getKind() == ElementKind.OTHER ||
258                        el.asType().getKind() == TypeKind.OTHER) {
259                    throw new IllegalStateException("Not attributed properly: " +
260                            getCurrentPath().getParentPath().getLeaf());
261                }
262            }
263        }.scan(cut, null);
264    }
265    static class MyFileObject extends SimpleJavaFileObject {
266        private final String text;
267        public MyFileObject(String text) {
268            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
269            this.text = text;
270        }
271        @Override
272        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
273            return text;
274        }
275    }
276}
277