BridgeMethodTestCase.java 15.3 KB
Newer Older
E
emc 已提交
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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
/*
 * Copyright (c) 2013, 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.
 *
 */
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import tools.javac.combo.*;

import static org.testng.Assert.fail;

/**
 * BridgeMethodTestCase -- used for asserting linkage to bridges under separate compilation.
 *
 * Example test case:
 *     public void test1() throws IOException, ReflectiveOperationException {
 *         compileSpec("C(Bc1(A))");
 *         assertLinkage("C", LINKAGE_ERROR, "B1");
 *         recompileSpec("C(Bc1(Ac0))", "A");
 *          assertLinkage("C", "A0", "B1");
 *     }
 *
 * This compiles A, B, and C, asserts that C.m()Object does not exist, asserts
 * that C.m()Number eventually invokes B.m()Number, recompiles B, and then asserts
 * that the result of calling C.m()Object now arrives at A.
 *
 * @author Brian Goetz
 */

@Test
public abstract class BridgeMethodTestCase extends JavacTemplateTestBase {

    private static final String TYPE_LETTERS = "ABCDIJK";

    private static final String BASE_INDEX_CLASS = "class C0 {\n" +
                                                   "    int val;\n" +
                                                   "    C0(int val) { this.val = val; }\n" +
                                                   "    public int getVal() { return val; }\n" +
                                                   "}\n";
    private static final String INDEX_CLASS_TEMPLATE = "class C#ID extends C#PREV {\n" +
                                                       "    C#ID(int val) { super(val); }\n" +
                                                       "}\n";



    protected static String LINKAGE_ERROR = "-1";

    private List<File> compileDirs = new ArrayList<>();

    /**
     * Compile all the classes in a class spec, and put them on the classpath.
     *
     * The spec is the specification for a nest of classes, using the following notation
     * A, B represent abstract classes
     * C represents a concrete class
     * I, J, K represent interfaces
     * Lowercase 'c' following a class means that the method m() is concrete
     * Lowercase 'a' following a class or interface means that the method m() is abstract
     * Lowercase 'd' following an interface means that the method m() is default
     * A number 0, 1, or 2 following the lowercase letter indicates the return type of that method
     * 0 = Object, 1 = Number, 2 = Integer (these form an inheritance chain so bridges are generated)
     * A classes supertypes follow its method spec, in parentheses
     * Examples:
     *   C(Ia0, Jd0) -- C extends I and J, I has abstract m()Object, J has default m()Object
     *   Cc1(Ia0) -- C has concrete m()Number, extends I with abstract m()Object
     * If a type must appear multiple times, its full spec must be in the first occurrence
     * Example:
     *   C(I(Kd0), J(K))
     */
   protected void compileSpec(String spec) throws IOException {
        compileSpec(spec, false);
    }

    /**
     * Compile all the classes in a class spec, and assert that there were compilation errors.
     */
    protected void compileSpec(String spec, String... errorKeys) throws IOException {
        compileSpec(spec, false, errorKeys);
    }

    protected void compileSpec(String spec, boolean debug, String... errorKeys) throws IOException {
        ClassModel cm = new Parser(spec).parseClassModel();
        for (int i = 0; i <= cm.maxIndex() ; i++) {
            if (debug) System.out.println(indexClass(i));
            addSourceFile(String.format("C%d.java", i), new StringTemplate(indexClass(i)));
        }
        for (Map.Entry<String, ClassModel> e : classes(cm).entrySet()) {
            if (debug) System.out.println(e.getValue().toSource());
            addSourceFile(e.getKey() + ".java", new StringTemplate(e.getValue().toSource()));
        }
        compileDirs.add(compile(true));
        resetSourceFiles();
        if (errorKeys.length == 0)
            assertCompileSucceeded();
        else
            assertCompileErrors(errorKeys);
    }

    /**
     * Recompile only a subset of classes in the class spec, as named by names,
     * and put them on the classpath such that they shadow earlier versions of that class.
     */
    protected void recompileSpec(String spec, String... names) throws IOException {
        List<String> nameList = Arrays.asList(names);
        ClassModel cm = new Parser(spec).parseClassModel();
        for (int i = 0; i <= cm.maxIndex() ; i++) {
            addSourceFile(String.format("C%d.java", i), new StringTemplate(indexClass(i)));
        }
        for (Map.Entry<String, ClassModel> e : classes(cm).entrySet())
            if (nameList.contains(e.getKey()))
                addSourceFile(e.getKey() + ".java", new StringTemplate(e.getValue().toSource()));
        compileDirs.add(compile(Arrays.asList(classPaths()), true));
        resetSourceFiles();
        assertCompileSucceeded();
    }

    protected void assertLinkage(String name, String... expected) throws ReflectiveOperationException {
        for (int i=0; i<expected.length; i++) {
            String e = expected[i];
            if (e.equals(LINKAGE_ERROR)) {
                try {
                    int actual = invoke(name, i);
                    fail("Expected linkage error, got" + fromNum(actual));
                }
                catch (LinkageError x) {
                    // success
                }
            }
            else {
                if (e.length() == 1)
                    e += "0";
                int expectedInt = toNum(e);
                int actual = invoke(name, i);
                if (expectedInt != actual)
                    fail(String.format("Expected %s but found %s for %s.m()%d", fromNum(expectedInt), fromNum(actual), name, i));
            }
        }
    }

    private Map<String, ClassModel> classes(ClassModel cm) {
        HashMap<String, ClassModel> m = new HashMap<>();
        classesHelper(cm, m);
        return m;
    }

    private String indexClass(int index) {
        if (index == 0) {
            return BASE_INDEX_CLASS;
        } else {
            return INDEX_CLASS_TEMPLATE
                    .replace("#ID", String.valueOf(index))
                    .replace("#PREV", String.valueOf(index - 1));
        }
    }

    private static String overrideName(int index) {
        return "C" + index;
    }

    private void classesHelper(ClassModel cm, Map<String, ClassModel> m) {
        if (!m.containsKey(cm.name))
            m.put(cm.name, cm);
        for (ClassModel s : cm.supertypes)
            classesHelper(s, m);
    }

    private static String fromNum(int num) {
        return String.format("%c%d", TYPE_LETTERS.charAt(num / 10), num % 10);
    }

    private static int toNum(String name, int index) {
        return 10*(TYPE_LETTERS.indexOf(name.charAt(0))) + index;
    }

    private static int toNum(String string) {
        return 10*(TYPE_LETTERS.indexOf(string.charAt(0))) + Integer.parseInt(string.substring(1, 2));
    }

    private int invoke(String name, int index) throws ReflectiveOperationException {
        File[] files = classPaths();
        Class clazz = loadClass(name, files);
        Method[] ms = clazz.getMethods();
        for (Method m : ms) {
            if (m.getName().equals("m") && m.getReturnType().getName().equals(overrideName(index))) {
                m.setAccessible(true);
                Object instance = clazz.newInstance();
                Object c0 = m.invoke(instance);
                Method getVal = c0.getClass().getMethod("getVal");
                getVal.setAccessible(true);
                return (int)getVal.invoke(c0);
            }
        }
        throw new NoSuchMethodError("cannot find method m()" + index + " in class " + name);
    }

    private File[] classPaths() {
        File[] files = new File[compileDirs.size()];
        for (int i=0; i<files.length; i++)
            files[files.length - i - 1] = compileDirs.get(i);
        return files;
    }

    @BeforeMethod
    @Override
    public void reset() {
        compileDirs.clear();
        super.reset();
    }

    private static class ClassModel {

        enum MethodType {
            ABSTRACT('a'), CONCRETE('c'), DEFAULT('d');

            public final char designator;

            MethodType(char designator) {
                this.designator = designator;
            }

            public static MethodType find(char c) {
                for (MethodType m : values())
                    if (m.designator == c)
                        return m;
                throw new IllegalArgumentException();
            }
        }

        private final String name;
        private final boolean isInterface;
        private final List<ClassModel> supertypes;
        private final MethodType methodType;
        private final int methodIndex;

        private ClassModel(String name,
                           boolean anInterface,
                           List<ClassModel> supertypes,
                           MethodType methodType,
                           int methodIndex) {
            this.name = name;
            isInterface = anInterface;
            this.supertypes = supertypes;
            this.methodType = methodType;
            this.methodIndex = methodIndex;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(name);
            if (methodType != null) {
                sb.append(methodType.designator);
                sb.append(methodIndex);
            }
            if (!supertypes.isEmpty()) {
                sb.append("(");
                for (int i=0; i<supertypes.size(); i++) {
                    if (i > 0)
                        sb.append(",");
                    sb.append(supertypes.get(i).toString());
                }
                sb.append(")");
            }
            return sb.toString();
        }

        int maxIndex() {
            int maxSoFar = methodIndex;
            for (ClassModel cm : supertypes) {
                maxSoFar = Math.max(cm.maxIndex(), maxSoFar);
            }
            return maxSoFar;
        }

        public String toSource() {
            String extendsClause = "";
            String implementsClause = "";
            String methodBody = "";
            boolean isAbstract = "AB".contains(name);

            for (ClassModel s : supertypes) {
                if (!s.isInterface) {
                    extendsClause = String.format("extends %s", s.name);
                    break;
                }
            }

            StringJoiner sj = new StringJoiner(", ");
            for (ClassModel s : supertypes)
                if (s.isInterface)
                    sj.add(s.name);
            if (sj.length() > 0) {
                if (isInterface)
                    implementsClause = "extends " + sj.toString();
                else
                implementsClause = "implements " + sj.toString();
            }
            if (methodType != null) {
                switch (methodType) {
                    case ABSTRACT:
                        methodBody = String.format("public abstract %s m();", overrideName(methodIndex));
                        break;
                    case CONCRETE:
                        methodBody = String.format("public %s m() { return new %s(%d); };",
                                overrideName(methodIndex), overrideName(methodIndex), toNum(name, methodIndex));
                        break;
                    case DEFAULT:
                        methodBody = String.format("public default %s m() { return new %s(%d); };",
                                overrideName(methodIndex), overrideName(methodIndex), toNum(name, methodIndex));
                        break;

                }
            }

            return String.format("public %s %s %s %s %s {  %s }", isAbstract ? "abstract" : "",
                                 isInterface ? "interface" : "class",
                                 name, extendsClause, implementsClause, methodBody);
        }
    }

    private static class Parser {
        private final String input;
        private final char[] chars;
        private int index;

        private Parser(String s) {
            input = s;
            chars = s.toCharArray();
        }

        private char peek() {
            return index < chars.length ? chars[index] : 0;
        }

        private boolean peek(String validChars) {
            return validChars.indexOf(peek()) >= 0;
        }

        private char advanceIf(String validChars) {
            if (peek(validChars))
                return chars[index++];
            else
                return 0;
        }

        private char advanceIfDigit() {
            return advanceIf("0123456789");
        }

        private int index() {
            StringBuilder buf = new StringBuilder();
            char c = advanceIfDigit();
            while (c != 0) {
                buf.append(c);
                c = advanceIfDigit();
            }
            return Integer.valueOf(buf.toString());
        }

        private char advance() {
            return chars[index++];
        }

        private char expect(String validChars) {
            char c = advanceIf(validChars);
            if (c == 0)
                throw new IllegalArgumentException(String.format("Expecting %s at position %d of %s", validChars, index, input));
            return c;
        }

        public ClassModel parseClassModel() {
            List<ClassModel> supers = new ArrayList<>();
            char name = expect(TYPE_LETTERS);
            boolean isInterface = "IJK".indexOf(name) >= 0;
            ClassModel.MethodType methodType = peek(isInterface ? "ad" : "ac") ? ClassModel.MethodType.find(advance()) : null;
            int methodIndex = 0;
            if (methodType != null) {
                methodIndex = index();
            }
            if (peek() == '(') {
                advance();
                supers.add(parseClassModel());
                while (peek() == ',') {
                    advance();
                    supers.add(parseClassModel());
                }
                expect(")");
            }
            return new ClassModel(new String(new char[]{ name }), isInterface, supers, methodType, methodIndex);
        }
    }
}