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