TestContainTypes.java revision 2702:b9daa6475f12
1/*
2 * Copyright (c) 2010, 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 6981185
27 * @summary  com.sun.tools.model.JavacTypes.contains() calls Type.contains instead of Types.containsType
28 * @run main TestContainTypes
29 */
30
31import java.net.URI;
32import java.util.Arrays;
33import java.util.HashSet;
34import java.util.Set;
35import javax.annotation.processing.AbstractProcessor;
36import javax.annotation.processing.RoundEnvironment;
37import javax.annotation.processing.SupportedSourceVersion;
38import javax.lang.model.SourceVersion;
39import javax.lang.model.element.Element;
40import javax.lang.model.element.TypeElement;
41import javax.lang.model.element.ExecutableElement;
42import javax.lang.model.type.TypeMirror;
43import javax.lang.model.type.DeclaredType;
44import javax.tools.JavaCompiler;
45import javax.tools.JavaFileManager;
46import javax.tools.JavaFileObject;
47import javax.tools.SimpleJavaFileObject;
48import javax.tools.ToolProvider;
49
50import com.sun.source.util.JavacTask;
51
52public class TestContainTypes {
53
54    enum ClassType {
55        OBJECT("Object"),
56        NUMBER("Number"),
57        INTEGER("Integer"),
58        STRING("String");
59
60        String classStub;
61
62        ClassType(String classStub) {
63            this.classStub = classStub;
64        }
65
66        boolean subtypeOf(ClassType that) {
67            switch (that) {
68                case OBJECT: return true;
69                case NUMBER: return this == NUMBER || this == INTEGER;
70                case INTEGER: return this == INTEGER;
71                case STRING: return this == STRING;
72                default: throw new AssertionError("Bad type kind in subtyping test");
73            }
74        }
75    }
76
77    enum ParameterType {
78        INVARIANT("List<#1>"),
79        COVARIANT("List<? extends #1>"),
80        CONTRAVARIANT("List<? super #1>"),
81        BIVARIANT("List<?>");
82
83        String paramTypeStub;
84
85        ParameterType(String paramTypeStub) {
86            this.paramTypeStub = paramTypeStub;
87        }
88
89        String instantiate(ClassType ct) {
90            return paramTypeStub.replace("#1", ct.classStub);
91        }
92
93        static boolean contains(ParameterType pt1, ClassType ct1,
94                ParameterType pt2, ClassType ct2) {
95            switch (pt1) {
96                case INVARIANT: return (pt2 == INVARIANT && ct1 == ct2) ||
97                                           (pt2 == CONTRAVARIANT && ct1 == ct2 && ct1 == ClassType.OBJECT);
98                case COVARIANT: return ((pt2 == INVARIANT || pt2 == COVARIANT) &&
99                                            ct2.subtypeOf(ct1)) ||
100                                            (ct1 == ClassType.OBJECT);
101                case CONTRAVARIANT: return (pt2 == INVARIANT || pt2 == CONTRAVARIANT) &&
102                                            ct1.subtypeOf(ct2);
103                case BIVARIANT: return true;
104                default: throw new AssertionError("Bad type kind in containment test");
105            }
106        }
107    }
108
109    static class JavaSource extends SimpleJavaFileObject {
110
111        final static String sourceStub =
112                        "import java.util.List;\n" +
113                        "@interface ToCheck {}\n" +
114                        "class Test {\n" +
115                        "   @ToCheck void test(#A a, #B b) {}\n" +
116                        "}\n";
117
118        String source;
119
120        public JavaSource(String typeA, String typeB) {
121            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
122            source = sourceStub.replace("#A", typeA).replace("#B", typeB);
123        }
124
125        @Override
126        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
127            return source;
128        }
129    }
130
131    static final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
132    static final JavaFileManager fm = tool.getStandardFileManager(null, null, null);
133
134    public static void main(String... args) throws Exception {
135        try {
136            for (ClassType ctA : ClassType.values()) {
137                for (ParameterType ptA : ParameterType.values()) {
138                    for (ClassType ctB : ClassType.values()) {
139                        for (ParameterType ptB : ParameterType.values()) {
140                            compileAndCheck(ptA, ctA, ptB, ctB);
141                        }
142                    }
143                }
144            }
145        } finally {
146            fm.close();
147        }
148    }
149
150    static void compileAndCheck(ParameterType ptA, ClassType ctA, ParameterType ptB, ClassType ctB) throws Exception {
151        JavaSource source = new JavaSource(ptA.instantiate(ctA), ptB.instantiate(ctB));
152        JavacTask ct = (JavacTask)tool.getTask(null, fm, null,
153                null, null, Arrays.asList(source));
154        ct.setProcessors(Arrays.asList(new ContainTypesTester(ParameterType.contains(ptA, ctA, ptB, ctB), source)));
155        System.err.println("A = " + ptA +" / " + ptA.instantiate(ctA));
156        System.err.println("B = " + ptB +" / " + ptB.instantiate(ctB));
157        System.err.println("Source = " + source.source);
158        ct.analyze();
159    }
160
161    @SupportedSourceVersion(SourceVersion.RELEASE_7)
162    static class ContainTypesTester extends AbstractProcessor {
163
164        boolean expected;
165        JavaSource source;
166
167        ContainTypesTester(boolean expected, JavaSource source) {
168            this.expected = expected;
169            this.source = source;
170        }
171
172        @Override
173        public Set<String> getSupportedAnnotationTypes() {
174            Set<String> supportedAnnos = new HashSet();
175            supportedAnnos.add("*");
176            return supportedAnnos;
177        }
178
179        private void error(String msg) {
180            System.err.println(source.source);
181            throw new AssertionError(msg);
182        }
183
184        @Override
185        public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
186            if (roundEnv.getRootElements().size() == 0) {
187                return true;
188            }
189            if (annotations.isEmpty() || annotations.size() > 1) {
190                error("no anno found/wrong number of annotations found: " + annotations.size());
191            }
192            TypeElement anno = (TypeElement)annotations.toArray()[0];
193            Set<? extends Element> annoElems = roundEnv.getElementsAnnotatedWith(anno);
194            if (annoElems.isEmpty() || annoElems.size() > 1) {
195                error("no annotated element found/wrong number of annotated elements found: " + annoElems.size());
196            }
197            Element annoElement = (Element)annoElems.toArray()[0];
198            if (!(annoElement instanceof ExecutableElement)) {
199                error("annotated element must be a method");
200            }
201            ExecutableElement method = (ExecutableElement)annoElement;
202            if (method.getParameters().size() != 2) {
203                error("annotated method must have 2 arguments");
204            }
205            DeclaredType d1 = (DeclaredType)method.getParameters().get(0).asType();
206            DeclaredType d2 = (DeclaredType)method.getParameters().get(1).asType();
207            if (d1.getTypeArguments().size() != 1 ||
208                    d1.getTypeArguments().size() != 1) {
209                error("parameter type must be generic in one type-variable");
210            }
211            TypeMirror t1 = d1.getTypeArguments().get(0);
212            TypeMirror t2 = d2.getTypeArguments().get(0);
213
214            if (processingEnv.getTypeUtils().contains(t1, t2) != expected) {
215                error("bad type containment result\n" +
216                        "t1 : " + t1 +"\n" +
217                        "t2 : " + t2 +"\n" +
218                        "expected answer : " + expected +"\n");
219            }
220            return true;
221        }
222    }
223}
224