diff options
Diffstat (limited to 'src/core')
39 files changed, 1207 insertions, 2556 deletions
diff --git a/src/core/lombok/bytecode/ClassFileMetaData.java b/src/core/lombok/bytecode/ClassFileMetaData.java deleted file mode 100644 index b1e0eff3..00000000 --- a/src/core/lombok/bytecode/ClassFileMetaData.java +++ /dev/null @@ -1,453 +0,0 @@ -/* - * Copyright © 2010 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.bytecode; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Utility to read the constant pool, header, and inheritance information of any class file. - */ -public class ClassFileMetaData { - private static final byte UTF8 = 1; - private static final byte INTEGER = 3; - private static final byte FLOAT = 4; - private static final byte LONG = 5; - private static final byte DOUBLE = 6; - private static final byte CLASS = 7; - private static final byte STRING = 8; - private static final byte FIELD = 9; - private static final byte METHOD = 10; - private static final byte INTERFACE_METHOD = 11; - private static final byte NAME_TYPE = 12; - // New in java7: support for methodhandles and invokedynamic - private static final byte METHOD_HANDLE = 15; - private static final byte METHOD_TYPE = 16; - private static final byte INVOKE_DYNAMIC = 18; - - private static final int NOT_FOUND = -1; - private static final int START_OF_CONSTANT_POOL = 8; - - private final byte[] byteCode; - - private final int maxPoolSize; - private final int[] offsets; - private final byte[] types; - private final String[] utf8s; - private final int endOfPool; - - public ClassFileMetaData(byte[] byteCode) { - this.byteCode = byteCode; - - maxPoolSize = readValue(START_OF_CONSTANT_POOL); - offsets = new int[maxPoolSize]; - types = new byte[maxPoolSize]; - utf8s = new String[maxPoolSize]; - int position = 10; - for (int i = 1; i < maxPoolSize; i++) { - byte type = byteCode[position]; - types[i] = type; - position++; - offsets[i] = position; - switch (type) { - case UTF8: - int length = readValue(position); - position += 2; - utf8s[i] = decodeString(position, length); - position += length; - break; - case CLASS: - case STRING: - case METHOD_TYPE: - position += 2; - break; - case METHOD_HANDLE: - position += 3; - break; - case INTEGER: - case FLOAT: - case FIELD: - case METHOD: - case INTERFACE_METHOD: - case NAME_TYPE: - case INVOKE_DYNAMIC: - position += 4; - break; - case LONG: - case DOUBLE: - position += 8; - i++; - break; - case 0: - break; - default: - throw new AssertionError("Unknown constant pool type " + type); - } - } - endOfPool = position; - } - - private String decodeString(int pos, int size) { - int end = pos + size; - - // the resulting string might be smaller - StringBuilder result = new StringBuilder(size); - while (pos < end) { - int first = (byteCode[pos++] & 0xFF); - if (first < 0x80) { - result.append((char)first); - } else if ((first & 0xE0) == 0xC0) { - int x = (first & 0x1F) << 6; - int y = (byteCode[pos++] & 0x3F); - result.append((char)(x | y)); - } else { - int x = (first & 0x0F) << 12; - int y = (byteCode[pos++] & 0x3F) << 6; - int z = (byteCode[pos++] & 0x3F); - result.append((char)(x | y | z)); - } - } - return result.toString(); - } - - /** - * Checks if the constant pool contains the provided 'raw' string. These are used as source material for further JVM types, such as string constants, type references, etcetera. - */ - public boolean containsUtf8(String value) { - return findUtf8(value) != NOT_FOUND; - } - - /** - * Checks if the constant pool contains a reference to the provided class. - * - * NB: Most uses of a type do <em>NOT</em> show up as a class in the constant pool. - * For example, the parameter types and return type of any method you invoke or declare, are stored as signatures and not as type references, - * but the type to which any method you invoke belongs, is. Read the JVM Specification for more information. - * - * @param className must be provided JVM-style, such as {@code java/lang/String} - */ - public boolean usesClass(String className) { - return findClass(className) != NOT_FOUND; - } - - /** - * Checks if the constant pool contains a reference to a given field, either for writing or reading. - * - * @param className must be provided JVM-style, such as {@code java/lang/String} - */ - public boolean usesField(String className, String fieldName) { - int classIndex = findClass(className); - if (classIndex == NOT_FOUND) return false; - int fieldNameIndex = findUtf8(fieldName); - if (fieldNameIndex == NOT_FOUND) return false; - - for (int i = 1; i < maxPoolSize; i++) { - if (types[i] == FIELD && readValue(offsets[i]) == classIndex) { - int nameAndTypeIndex = readValue(offsets[i] + 2); - if (readValue(offsets[nameAndTypeIndex]) == fieldNameIndex) return true; - } - } - return false; - } - - /** - * Checks if the constant pool contains a reference to a given method, with any signature (return type and parameter types). - * - * @param className must be provided JVM-style, such as {@code java/lang/String} - */ - public boolean usesMethod(String className, String methodName) { - int classIndex = findClass(className); - if (classIndex == NOT_FOUND) return false; - int methodNameIndex = findUtf8(methodName); - if (methodNameIndex == NOT_FOUND) return false; - - for (int i = 1; i < maxPoolSize; i++) { - if (isMethod(i) && readValue(offsets[i]) == classIndex) { - int nameAndTypeIndex = readValue(offsets[i] + 2); - if (readValue(offsets[nameAndTypeIndex]) == methodNameIndex) return true; - } - } - return false; - } - - /** - * Checks if the constant pool contains a reference to a given method. - * - * @param className must be provided JVM-style, such as {@code java/lang/String} - * @param descriptor must be provided JVM-style, such as {@code (IZ)Ljava/lang/String;} - */ - public boolean usesMethod(String className, String methodName, String descriptor) { - int classIndex = findClass(className); - if (classIndex == NOT_FOUND) return false; - int nameAndTypeIndex = findNameAndType(methodName, descriptor); - if (nameAndTypeIndex == NOT_FOUND) return false; - - for (int i = 1; i < maxPoolSize; i++) { - if (isMethod(i) && - readValue(offsets[i]) == classIndex && - readValue(offsets[i] + 2) == nameAndTypeIndex) return true; - } - return false; - } - - /** - * Checks if the constant pool contains the provided string constant, which implies the constant is used somewhere in the code. - * - * NB: String literals get concatenated by the compiler. - */ - public boolean containsStringConstant(String value) { - int index = findUtf8(value); - if (index == NOT_FOUND) return false; - for (int i = 1; i < maxPoolSize; i++) { - if (types[i] == STRING && readValue(offsets[i]) == index) return true; - } - return false; - } - - /** - * Checks if the constant pool contains the provided long constant, which implies the constant is used somewhere in the code. - * - * NB: compile-time constant expressions are evaluated at compile time. - */ - public boolean containsLong(long value) { - for (int i = 1; i < maxPoolSize; i++) { - if (types[i] == LONG && readLong(i) == value) return true; - } - return false; - } - - /** - * Checks if the constant pool contains the provided double constant, which implies the constant is used somewhere in the code. - * - * NB: compile-time constant expressions are evaluated at compile time. - */ - public boolean containsDouble(double value) { - boolean isNan = Double.isNaN(value); - for (int i = 1; i < maxPoolSize; i++) { - if (types[i] == DOUBLE) { - double d = readDouble(i); - if (d == value || (isNan && Double.isNaN(d))) return true; - } - } - return false; - } - - /** - * Checks if the constant pool contains the provided int constant, which implies the constant is used somewhere in the code. - * - * NB: compile-time constant expressions are evaluated at compile time. - */ - public boolean containsInteger(int value) { - for (int i = 1; i < maxPoolSize; i++) { - if (types[i] == INTEGER && readInteger(i) == value) return true; - } - return false; - } - - /** - * Checks if the constant pool contains the provided float constant, which implies the constant is used somewhere in the code. - * - * NB: compile-time constant expressions are evaluated at compile time. - */ - public boolean containsFloat(float value) { - boolean isNan = Float.isNaN(value); - for (int i = 1; i < maxPoolSize; i++) { - if (types[i] == FLOAT) { - float f = readFloat(i); - if (f == value || (isNan && Float.isNaN(f))) return true; - } - } - return false; - } - - private long readLong(int index) { - int pos = offsets[index]; - return ((long)read32(pos)) << 32 | read32(pos + 4); - } - - private double readDouble(int index) { - int pos = offsets[index]; - long bits = ((long)read32(pos)) << 32 | (read32(pos + 4) & 0x00000000FFFFFFFF); - return Double.longBitsToDouble(bits); - } - - private long readInteger(int index) { - return read32(offsets[index]); - } - - private float readFloat(int index) { - return Float.intBitsToFloat(read32(offsets[index])); - } - - private int read32(int pos) { - return (byteCode[pos] & 0xFF) << 24 | (byteCode[pos + 1] & 0xFF) << 16 | (byteCode[pos + 2] & 0xFF) << 8 | (byteCode[pos + 3] &0xFF); - } - - /** - * Returns the name of the class in JVM format, such as {@code java/lang/String} - */ - public String getClassName() { - return getClassName(readValue(endOfPool + 2)); - } - - /** - * Returns the name of the superclass in JVM format, such as {@code java/lang/Object} - * - * NB: If you try this on Object itself, you'll get {@code null}.<br /> - * NB2: For interfaces and annotation interfaces, you'll always get {@code java/lang/Object} - */ - public String getSuperClassName() { - return getClassName(readValue(endOfPool + 4)); - } - - /** - * Returns the name of all implemented interfaces. - */ - public List<String> getInterfaces() { - int size = readValue(endOfPool + 6); - if (size == 0) return Collections.emptyList(); - - List<String> result = new ArrayList<String>(); - for (int i = 0; i < size; i++) { - result.add(getClassName(readValue(endOfPool + 8 + (i * 2)))); - } - return result; - } - - /** - * A {@code toString()} like utility to dump all contents of the constant pool into a string. - * - * NB: No guarantees are made about the exact layout of this string. It is for informational purposes only, don't try to parse it.<br /> - * NB2: After a double or long, there's a JVM spec-mandated gap, which is listed as {@code (cont.)} in the returned string. - */ - public String poolContent() { - StringBuilder result = new StringBuilder(); - for (int i = 1; i < maxPoolSize; i++) { - result.append(String.format("#%02x: ", i)); - int pos = offsets[i]; - switch(types[i]) { - case UTF8: - result.append("Utf8 ").append(utf8s[i]); - break; - case CLASS: - result.append("Class ").append(getClassName(i)); - break; - case STRING: - result.append("String \"").append(utf8s[readValue(pos)]).append("\""); - break; - case INTEGER: - result.append("int ").append(readInteger(i)); - break; - case FLOAT: - result.append("float ").append(readFloat(i)); - break; - case FIELD: - appendAccess(result.append("Field "), i); - break; - case METHOD: - case INTERFACE_METHOD: - appendAccess(result.append("Method "), i); - break; - case NAME_TYPE: - appendNameAndType(result.append("Name&Type "), i); - break; - case LONG: - result.append("long ").append(readLong(i)); - break; - case DOUBLE: - result.append("double ").append(readDouble(i)); - break; - case METHOD_HANDLE: - result.append("MethodHandle..."); - break; - case METHOD_TYPE: - result.append("MethodType..."); - break; - case INVOKE_DYNAMIC: - result.append("InvokeDynamic..."); - break; - case 0: - result.append("(cont.)"); - break; - } - result.append("\n"); - } - return result.toString(); - } - - private void appendAccess(StringBuilder result, int index) { - int pos = offsets[index]; - result.append(getClassName(readValue(pos))).append("."); - appendNameAndType(result, readValue(pos + 2)); - } - - private void appendNameAndType(StringBuilder result, int index) { - int pos = offsets[index]; - result.append(utf8s[readValue(pos)]).append(":").append(utf8s[readValue(pos + 2)]); - } - - private String getClassName(int classIndex) { - if (classIndex < 1) return null; - return utf8s[readValue(offsets[classIndex])]; - } - - private boolean isMethod(int i) { - byte type = types[i]; - return type == METHOD || type == INTERFACE_METHOD; - } - - private int findNameAndType(String name, String descriptor) { - int nameIndex = findUtf8(name); - if (nameIndex == NOT_FOUND) return NOT_FOUND; - int descriptorIndex = findUtf8(descriptor); - if (descriptorIndex == NOT_FOUND) return NOT_FOUND; - for (int i = 1; i < maxPoolSize; i++) { - if (types[i] == NAME_TYPE && - readValue(offsets[i]) == nameIndex && - readValue(offsets[i] + 2) == descriptorIndex) return i; - } - return NOT_FOUND; - } - - private int findUtf8(String value) { - for (int i = 1; i < maxPoolSize; i++) { - if (value.equals(utf8s[i])) { - return i; - } - } - return NOT_FOUND; - } - - private int findClass(String className) { - int index = findUtf8(className); - if (index == -1) return NOT_FOUND; - for (int i = 1; i < maxPoolSize; i++) { - if (types[i] == CLASS && readValue(offsets[i]) == index) return i; - } - return NOT_FOUND; - } - - private int readValue(int position) { - return ((byteCode[position] & 0xFF) << 8) | (byteCode[position + 1] & 0xFF); - } -} diff --git a/src/core/lombok/bytecode/FixedClassWriter.java b/src/core/lombok/bytecode/FixedClassWriter.java deleted file mode 100644 index 52de2317..00000000 --- a/src/core/lombok/bytecode/FixedClassWriter.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright © 2010 Reinier Zwitserloot, Roel Spilker and Robbert Jan Grootjans. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.bytecode; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; - -class FixedClassWriter extends ClassWriter { - FixedClassWriter(ClassReader classReader, int flags) { - super(classReader, flags); - } - - @Override protected String getCommonSuperClass(String type1, String type2) { - //By default, ASM will attempt to live-load the class types, which will fail if meddling with classes in an - //environment with custom classloaders, such as Equinox. It's just an optimization; returning Object is always legal. - try { - return super.getCommonSuperClass(type1, type2); - } catch (Exception e) { - return "java/lang/Object"; - } - } -}
\ No newline at end of file diff --git a/src/core/lombok/bytecode/PostCompilationUtil.java b/src/core/lombok/bytecode/PostCompilationUtil.java deleted file mode 100644 index 1c1bb0c1..00000000 --- a/src/core/lombok/bytecode/PostCompilationUtil.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright © 2010 Reinier Zwitserloot, Roel Spilker and Robbert Jan Grootjans. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.bytecode; - -import org.objectweb.asm.ClassAdapter; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.commons.JSRInlinerAdapter; - -class PostCompilationUtil { - - private PostCompilationUtil() { - throw new UnsupportedOperationException(); - } - - static byte[] fixJSRInlining(byte[] byteCode) { - ClassReader reader = new ClassReader(byteCode); - ClassWriter writer = new FixedClassWriter(reader, 0); - - ClassVisitor visitor = new ClassAdapter(writer) { - @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - return new JSRInlinerAdapter(super.visitMethod(access, name, desc, signature, exceptions), access, name, desc, signature, exceptions); - } - }; - - reader.accept(visitor, 0); - return writer.toByteArray(); - } -} diff --git a/src/core/lombok/bytecode/PreventNullAnalysisRemover.java b/src/core/lombok/bytecode/PreventNullAnalysisRemover.java index 4dc08bb4..b7b29f9f 100644 --- a/src/core/lombok/bytecode/PreventNullAnalysisRemover.java +++ b/src/core/lombok/bytecode/PreventNullAnalysisRemover.java @@ -21,7 +21,7 @@ */ package lombok.bytecode; -import static lombok.bytecode.PostCompilationUtil.fixJSRInlining; +import static lombok.bytecode.AsmUtil.fixJSRInlining; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/src/core/lombok/bytecode/SneakyThrowsRemover.java b/src/core/lombok/bytecode/SneakyThrowsRemover.java index 54b00052..7c9a08a6 100644 --- a/src/core/lombok/bytecode/SneakyThrowsRemover.java +++ b/src/core/lombok/bytecode/SneakyThrowsRemover.java @@ -21,7 +21,7 @@ */ package lombok.bytecode; -import static lombok.bytecode.PostCompilationUtil.*; +import static lombok.bytecode.AsmUtil.*; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/src/core/lombok/core/SpiLoadUtil.java b/src/core/lombok/core/SpiLoadUtil.java deleted file mode 100644 index 09a59709..00000000 --- a/src/core/lombok/core/SpiLoadUtil.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright © 2009-2011 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.core; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.annotation.Annotation; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import lombok.Lombok; - -/** - * The java core libraries have a SPI discovery system, but it works only in Java 1.6 and up. For at least Eclipse, - * lombok actually works in java 1.5, so we've rolled our own SPI discovery system. - * - * It is not API compatible with {@code ServiceLoader}. - * - * @see java.util.ServiceLoader - */ -public class SpiLoadUtil { - private SpiLoadUtil() { - //Prevent instantiation - } - - /** - * Method that conveniently turn the {@code Iterable}s returned by the other methods in this class to a - * {@code List}. - * - * @see #findServices(Class) - * @see #findServices(Class, ClassLoader) - */ - public static <T> List<T> readAllFromIterator(Iterable<T> findServices) { - List<T> list = new ArrayList<T>(); - for (T t : findServices) list.add(t); - return list; - } - - /** - * Returns an iterator of instances that, at least according to the spi discovery file, are implementations - * of the stated class. - * - * Like ServiceLoader, each listed class is turned into an instance by calling the public no-args constructor. - * - * Convenience method that calls the more elaborate {@link #findServices(Class, ClassLoader)} method with - * this {@link java.lang.Thread}'s context class loader as {@code ClassLoader}. - * - * @param target class to find implementations for. - */ - public static <C> Iterable<C> findServices(Class<C> target) throws IOException { - return findServices(target, Thread.currentThread().getContextClassLoader()); - } - - /** - * Returns an iterator of class objects that, at least according to the spi discovery file, are implementations - * of the stated class. - * - * Like ServiceLoader, each listed class is turned into an instance by calling the public no-args constructor. - * - * @param target class to find implementations for. - * @param loader The classloader object to use to both the spi discovery files, as well as the loader to use - * to make the returned instances. - */ - public static <C> Iterable<C> findServices(final Class<C> target, ClassLoader loader) throws IOException { - if (loader == null) loader = ClassLoader.getSystemClassLoader(); - Enumeration<URL> resources = loader.getResources("META-INF/services/" + target.getName()); - final Set<String> entries = new LinkedHashSet<String>(); - while (resources.hasMoreElements()) { - URL url = resources.nextElement(); - readServicesFromUrl(entries, url); - } - - final Iterator<String> names = entries.iterator(); - final ClassLoader fLoader = loader; - return new Iterable<C> () { - @Override public Iterator<C> iterator() { - return new Iterator<C>() { - @Override public boolean hasNext() { - return names.hasNext(); - } - - @Override public C next() { - try { - return target.cast(Class.forName(names.next(), true, fLoader).newInstance()); - } catch (Throwable t) { - throw Lombok.sneakyThrow(t); - } - } - - @Override public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - }; - } - - private static void readServicesFromUrl(Collection<String> list, URL url) throws IOException { - InputStream in = url.openStream(); - try { - if (in == null) return; - BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8")); - while (true) { - String line = r.readLine(); - if (line == null) break; - int idx = line.indexOf('#'); - if (idx != -1) line = line.substring(0, idx); - line = line.trim(); - if (line.length() == 0) continue; - list.add(line); - } - } finally { - try { - if (in != null) in.close(); - } catch (Throwable ignore) {} - } - } - - /** - * This method will find the @{code T} in {@code public class Foo extends BaseType<T>}. - * - * It returns an annotation type because it is used exclusively to figure out which annotations are - * being handled by {@link lombok.eclipse.EclipseAnnotationHandler} and {@link lombok.javac.JavacAnnotationHandler}. - */ - public static Class<? extends Annotation> findAnnotationClass(Class<?> c, Class<?> base) { - if (c == Object.class || c == null) return null; - Class<? extends Annotation> answer = null; - - answer = findAnnotationHelper(base, c.getGenericSuperclass()); - if (answer != null) return answer; - - for (Type iface : c.getGenericInterfaces()) { - answer = findAnnotationHelper(base, iface); - if (answer != null) return answer; - } - - Class<? extends Annotation> potential = findAnnotationClass(c.getSuperclass(), base); - if (potential != null) return potential; - for (Class<?> iface : c.getInterfaces()) { - potential = findAnnotationClass(iface, base); - if (potential != null) return potential; - } - - return null; - } - - @SuppressWarnings("unchecked") - private static Class<? extends Annotation> findAnnotationHelper(Class<?> base, Type iface) { - if (iface instanceof ParameterizedType) { - ParameterizedType p = (ParameterizedType)iface; - if (!base.equals(p.getRawType())) return null; - Type target = p.getActualTypeArguments()[0]; - if (target instanceof Class<?>) { - if (Annotation.class.isAssignableFrom((Class<?>) target)) { - return (Class<? extends Annotation>) target; - } - } - - throw new ClassCastException("Not an annotation type: " + target); - } - return null; - } -} diff --git a/src/core/lombok/core/handlers/TransformationsUtil.java b/src/core/lombok/core/handlers/TransformationsUtil.java deleted file mode 100644 index 3c1fc421..00000000 --- a/src/core/lombok/core/handlers/TransformationsUtil.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.core.handlers; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * Container for static utility methods useful for some of the standard lombok transformations, regardless of - * target platform (e.g. useful for both javac and Eclipse lombok implementations). - */ -public class TransformationsUtil { - private TransformationsUtil() { - //Prevent instantiation - } - - /** - * Generates a getter name from a given field name. - * - * Strategy: - * - * First, pick a prefix. 'get' normally, but 'is' if {@code isBoolean} is true. - * - * Then, check if the first character of the field is lowercase. If so, check if the second character - * exists and is title or upper case. If so, uppercase the first character. If not, titlecase the first character. - * - * return the prefix plus the possibly title/uppercased first character, and the rest of the field name. - * - * Note that for boolean fields, if the field starts with 'is', and the character after that is - * <b>not</b> a lowercase character, the field name is returned without changing any character's case and without - * any prefix. - * - * @param fieldName the name of the field. - * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. - */ - public static String toGetterName(CharSequence fieldName, boolean isBoolean) { - final String prefix = isBoolean ? "is" : "get"; - - if (fieldName.length() == 0) return prefix; - - if (isBoolean && fieldName.toString().startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { - // The field is for example named 'isRunning'. - return fieldName.toString(); - } - - return buildName(prefix, fieldName.toString()); - } - - public static final Pattern PRIMITIVE_TYPE_NAME_PATTERN = Pattern.compile( - "^(boolean|byte|short|int|long|float|double|char)$"); - - public static final Pattern NON_NULL_PATTERN = Pattern.compile("^(?:notnull|nonnull)$", Pattern.CASE_INSENSITIVE); - public static final Pattern NULLABLE_PATTERN = Pattern.compile("^(?:nullable|checkfornull)$", Pattern.CASE_INSENSITIVE); - - /** - * Generates a setter name from a given field name. - * - * Strategy: - * - * Check if the first character of the field is lowercase. If so, check if the second character - * exists and is title or upper case. If so, uppercase the first character. If not, titlecase the first character. - * - * return "set" plus the possibly title/uppercased first character, and the rest of the field name. - * - * Note that if the field is boolean and starts with 'is' followed by a non-lowercase letter, the 'is' is stripped and replaced with 'set'. - * - * @param fieldName the name of the field. - * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. - */ - public static String toSetterName(CharSequence fieldName, boolean isBoolean) { - if (fieldName.length() == 0) return "set"; - - if (isBoolean && fieldName.toString().startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { - // The field is for example named 'isRunning'. - return "set" + fieldName.toString().substring(2); - } - - return buildName("set", fieldName.toString()); - } - - private static String buildName(String prefix, String suffix) { - if (suffix.length() == 0) return prefix; - - char first = suffix.charAt(0); - if (Character.isLowerCase(first)) { - boolean useUpperCase = suffix.length() > 2 && - (Character.isTitleCase(suffix.charAt(1)) || Character.isUpperCase(suffix.charAt(1))); - suffix = String.format("%s%s", - useUpperCase ? Character.toUpperCase(first) : Character.toTitleCase(first), - suffix.subSequence(1, suffix.length())); - } - return String.format("%s%s", prefix, suffix); - } - - /** - * Returns all names of methods that would represent the getter for a field with the provided name. - * - * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:<br /> - * {@code [isRunning, getRunning, isIsRunning, getIsRunning]} - * - * @param fieldName the name of the field. - * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. - */ - public static List<String> toAllGetterNames(CharSequence fieldName, boolean isBoolean) { - if (!isBoolean) return Collections.singletonList(toGetterName(fieldName, false)); - - List<String> baseNames = new ArrayList<String>(); - baseNames.add(fieldName.toString()); - - // isPrefix = field is called something like 'isRunning', so 'running' could also be the fieldname. - if (fieldName.toString().startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { - baseNames.add(fieldName.toString().substring(2)); - } - - Set<String> names = new HashSet<String>(); - for (String baseName : baseNames) { - if (baseName.length() > 0 && Character.isLowerCase(baseName.charAt(0))) { - baseName = Character.toTitleCase(baseName.charAt(0)) + baseName.substring(1); - } - - names.add("is" + baseName); - names.add("get" + baseName); - } - - return new ArrayList<String>(names); - } - - /** - * Returns all names of methods that would represent the setter for a field with the provided name. - * - * For example if {@code isBoolean} is true, then a field named {@code isRunning} would produce:<br /> - * {@code [setRunning, setIsRunning]} - * - * @param fieldName the name of the field. - * @param isBoolean if the field is of type 'boolean'. For fields of type 'java.lang.Boolean', you should provide {@code false}. - */ - public static List<String> toAllSetterNames(CharSequence fieldName, boolean isBoolean) { - if (!isBoolean) return Collections.singletonList(toSetterName(fieldName, false)); - - List<String> baseNames = new ArrayList<String>(); - baseNames.add(fieldName.toString()); - - // isPrefix = field is called something like 'isRunning', so 'running' could also be the fieldname. - if (fieldName.toString().startsWith("is") && fieldName.length() > 2 && !Character.isLowerCase(fieldName.charAt(2))) { - baseNames.add(fieldName.toString().substring(2)); - } - - Set<String> names = new HashSet<String>(); - for (String baseName : baseNames) { - if (baseName.length() > 0 && Character.isLowerCase(baseName.charAt(0))) { - baseName = Character.toTitleCase(baseName.charAt(0)) + baseName.substring(1); - } - - names.add("set" + baseName); - } - - return new ArrayList<String>(names); - } -} diff --git a/src/core/lombok/eclipse/Eclipse.java b/src/core/lombok/eclipse/Eclipse.java deleted file mode 100644 index 858c2fe9..00000000 --- a/src/core/lombok/eclipse/Eclipse.java +++ /dev/null @@ -1,743 +0,0 @@ -/* - * Copyright © 2009-2011 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.eclipse; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; - -import lombok.core.AnnotationValues; -import lombok.core.TypeLibrary; -import lombok.core.TypeResolver; -import lombok.core.AST.Kind; -import lombok.core.AnnotationValues.AnnotationValue; - -import org.eclipse.core.runtime.ILog; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.jdt.internal.compiler.ast.ASTNode; -import org.eclipse.jdt.internal.compiler.ast.Annotation; -import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; -import org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference; -import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; -import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; -import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; -import org.eclipse.jdt.internal.compiler.ast.Expression; -import org.eclipse.jdt.internal.compiler.ast.Literal; -import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; -import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; -import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; -import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; -import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; -import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; -import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; -import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; -import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; -import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; -import org.eclipse.jdt.internal.compiler.ast.TypeParameter; -import org.eclipse.jdt.internal.compiler.ast.TypeReference; -import org.eclipse.jdt.internal.compiler.ast.Wildcard; -import org.eclipse.jdt.internal.compiler.lookup.CaptureBinding; -import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; -import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; -import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; -import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; -import org.eclipse.jdt.internal.compiler.lookup.TypeIds; -import org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; -import org.osgi.framework.Bundle; - -public class Eclipse { - /** - * Eclipse's Parser class is instrumented to not attempt to fill in the body of any method or initializer - * or field initialization if this flag is set. Set it on the flag field of - * any method, field, or initializer you create! - */ - public static final int ECLIPSE_DO_NOT_TOUCH_FLAG = ASTNode.Bit24; - - private Eclipse() { - //Prevent instantiation - } - - private static final String DEFAULT_BUNDLE = "org.eclipse.jdt.core"; - - /** - * Generates an error in the Eclipse error log. Note that most people never look at it! - * - * @param cud The {@code CompilationUnitDeclaration} where the error occurred. - * An error will be generated on line 0 linking to the error log entry. Can be {@code null}. - * @param message Human readable description of the problem. - * @param error The associated exception. Can be {@code null}. - */ - public static void error(CompilationUnitDeclaration cud, String message, Throwable error) { - error(cud, message, null, error); - } - - /** - * Generates an error in the Eclipse error log. Note that most people never look at it! - * - * @param cud The {@code CompilationUnitDeclaration} where the error occurred. - * An error will be generated on line 0 linking to the error log entry. Can be {@code null}. - * @param message Human readable description of the problem. - * @param bundleName Can be {@code null} to default to {@code org.eclipse.jdt.core} which is usually right. - * @param error The associated exception. Can be {@code null}. - */ - public static void error(CompilationUnitDeclaration cud, String message, String bundleName, Throwable error) { - if (bundleName == null) bundleName = DEFAULT_BUNDLE; - try { - new EclipseWorkspaceLogger().error(message, bundleName, error); - } catch (NoClassDefFoundError e) { //standalone ecj does not jave Platform, ILog, IStatus, and friends. - new TerminalLogger().error(message, bundleName, error); - } - if (cud != null) EclipseAST.addProblemToCompilationResult(cud, false, message + " - See error log.", 0, 0); - } - - /** - * Generates a warning in the Eclipse error log. Note that most people never look at it! - * - * @param message Human readable description of the problem. - * @param error The associated exception. Can be {@code null}. - */ - public static void warning(String message, Throwable error) { - warning(message, null, error); - } - - /** - * Generates a warning in the Eclipse error log. Note that most people never look at it! - * - * @param message Human readable description of the problem. - * @param bundleName Can be {@code null} to default to {@code org.eclipse.jdt.core} which is usually right. - * @param error The associated exception. Can be {@code null}. - */ - public static void warning(String message, String bundleName, Throwable error) { - if (bundleName == null) bundleName = DEFAULT_BUNDLE; - try { - new EclipseWorkspaceLogger().warning(message, bundleName, error); - } catch (NoClassDefFoundError e) { //standalone ecj does not jave Platform, ILog, IStatus, and friends. - new TerminalLogger().warning(message, bundleName, error); - } - } - - private static class TerminalLogger { - void error(String message, String bundleName, Throwable error) { - System.err.println(message); - if (error != null) error.printStackTrace(); - } - - void warning(String message, String bundleName, Throwable error) { - System.err.println(message); - if (error != null) error.printStackTrace(); - } - } - - private static class EclipseWorkspaceLogger { - void error(String message, String bundleName, Throwable error) { - msg(IStatus.ERROR, message, bundleName, error); - } - - void warning(String message, String bundleName, Throwable error) { - msg(IStatus.WARNING, message, bundleName, error); - } - - private void msg(int msgType, String message, String bundleName, Throwable error) { - Bundle bundle = Platform.getBundle(bundleName); - if (bundle == null) { - System.err.printf("Can't find bundle %s while trying to report error:\n%s\n", bundleName, message); - return; - } - - ILog log = Platform.getLog(bundle); - - log.log(new Status(msgType, bundleName, message, error)); - } - } - - /** - * For 'speed' reasons, Eclipse works a lot with char arrays. I have my doubts this was a fruitful exercise, - * but we need to deal with it. This turns [[java][lang][String]] into "java.lang.String". - */ - public static String toQualifiedName(char[][] typeName) { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for (char[] c : typeName) { - sb.append(first ? "" : ".").append(c); - first = false; - } - return sb.toString(); - } - - public static char[][] fromQualifiedName(String typeName) { - String[] split = typeName.split("\\."); - char[][] result = new char[split.length][]; - for (int i = 0; i < split.length; i++) { - result[i] = split[i].toCharArray(); - } - return result; - } - - /** - * You can't share TypeParameter objects or bad things happen; for example, one 'T' resolves differently - * from another 'T', even for the same T in a single class file. Unfortunately the TypeParameter type hierarchy - * is complicated and there's no clone method on TypeParameter itself. This method can clone them. - */ - public static TypeParameter[] copyTypeParams(TypeParameter[] params, ASTNode source) { - if (params == null) return null; - TypeParameter[] out = new TypeParameter[params.length]; - int idx = 0; - for (TypeParameter param : params) { - TypeParameter o = new TypeParameter(); - setGeneratedBy(o, source); - o.annotations = param.annotations; - o.bits = param.bits; - o.modifiers = param.modifiers; - o.name = param.name; - o.type = copyType(param.type, source); - o.sourceStart = param.sourceStart; - o.sourceEnd = param.sourceEnd; - o.declarationEnd = param.declarationEnd; - o.declarationSourceStart = param.declarationSourceStart; - o.declarationSourceEnd = param.declarationSourceEnd; - if (param.bounds != null) { - TypeReference[] b = new TypeReference[param.bounds.length]; - int idx2 = 0; - for (TypeReference ref : param.bounds) b[idx2++] = copyType(ref, source); - o.bounds = b; - } - out[idx++] = o; - } - return out; - } - - /** - * Convenience method that creates a new array and copies each TypeReference in the source array via - * {@link #copyType(TypeReference, ASTNode)}. - */ - public static TypeReference[] copyTypes(TypeReference[] refs, ASTNode source) { - if (refs == null) return null; - TypeReference[] outs = new TypeReference[refs.length]; - int idx = 0; - for (TypeReference ref : refs) { - outs[idx++] = copyType(ref, source); - } - return outs; - } - - /** - * You can't share TypeReference objects or subtle errors start happening. - * Unfortunately the TypeReference type hierarchy is complicated and there's no clone - * method on TypeReference itself. This method can clone them. - */ - public static TypeReference copyType(TypeReference ref, ASTNode source) { - if (ref instanceof ParameterizedQualifiedTypeReference) { - ParameterizedQualifiedTypeReference iRef = (ParameterizedQualifiedTypeReference) ref; - TypeReference[][] args = null; - if (iRef.typeArguments != null) { - args = new TypeReference[iRef.typeArguments.length][]; - int idx = 0; - for (TypeReference[] inRefArray : iRef.typeArguments) { - if (inRefArray == null) args[idx++] = null; - else { - TypeReference[] outRefArray = new TypeReference[inRefArray.length]; - int idx2 = 0; - for (TypeReference inRef : inRefArray) { - outRefArray[idx2++] = copyType(inRef, source); - } - args[idx++] = outRefArray; - } - } - } - TypeReference typeRef = new ParameterizedQualifiedTypeReference(iRef.tokens, args, iRef.dimensions(), iRef.sourcePositions); - setGeneratedBy(typeRef, source); - return typeRef; - } - - if (ref instanceof ArrayQualifiedTypeReference) { - ArrayQualifiedTypeReference iRef = (ArrayQualifiedTypeReference) ref; - TypeReference typeRef = new ArrayQualifiedTypeReference(iRef.tokens, iRef.dimensions(), iRef.sourcePositions); - setGeneratedBy(typeRef, source); - return typeRef; - } - - if (ref instanceof QualifiedTypeReference) { - QualifiedTypeReference iRef = (QualifiedTypeReference) ref; - TypeReference typeRef = new QualifiedTypeReference(iRef.tokens, iRef.sourcePositions); - setGeneratedBy(typeRef, source); - return typeRef; - } - - if (ref instanceof ParameterizedSingleTypeReference) { - ParameterizedSingleTypeReference iRef = (ParameterizedSingleTypeReference) ref; - TypeReference[] args = null; - if (iRef.typeArguments != null) { - args = new TypeReference[iRef.typeArguments.length]; - int idx = 0; - for (TypeReference inRef : iRef.typeArguments) { - if (inRef == null) args[idx++] = null; - else args[idx++] = copyType(inRef, source); - } - } - - TypeReference typeRef = new ParameterizedSingleTypeReference(iRef.token, args, iRef.dimensions(), (long)iRef.sourceStart << 32 | iRef.sourceEnd); - setGeneratedBy(typeRef, source); - return typeRef; - } - - if (ref instanceof ArrayTypeReference) { - ArrayTypeReference iRef = (ArrayTypeReference) ref; - TypeReference typeRef = new ArrayTypeReference(iRef.token, iRef.dimensions(), (long)iRef.sourceStart << 32 | iRef.sourceEnd); - setGeneratedBy(typeRef, source); - return typeRef; - } - - if (ref instanceof Wildcard) { - Wildcard original = (Wildcard)ref; - - Wildcard wildcard = new Wildcard(original.kind); - wildcard.sourceStart = original.sourceStart; - wildcard.sourceEnd = original.sourceEnd; - if (original.bound != null) wildcard.bound = copyType(original.bound, source); - setGeneratedBy(wildcard, source); - return wildcard; - } - - if (ref instanceof SingleTypeReference) { - SingleTypeReference iRef = (SingleTypeReference) ref; - TypeReference typeRef = new SingleTypeReference(iRef.token, (long)iRef.sourceStart << 32 | iRef.sourceEnd); - setGeneratedBy(typeRef, source); - return typeRef; - } - - return ref; - } - - public static long pos(ASTNode node) { - return ((long) node.sourceStart << 32) | (node.sourceEnd & 0xFFFFFFFFL); - } - - public static long[] poss(ASTNode node, int repeat) { - long p = ((long) node.sourceStart << 32) | (node.sourceEnd & 0xFFFFFFFFL); - long[] out = new long[repeat]; - Arrays.fill(out, p); - return out; - } - - public static TypeReference makeType(TypeBinding binding, ASTNode pos, boolean allowCompound) { - int dims = binding.dimensions(); - binding = binding.leafComponentType(); - - // Primitives - - char[] base = null; - - switch (binding.id) { - case TypeIds.T_int: - base = TypeConstants.INT; - break; - case TypeIds.T_long: - base = TypeConstants.LONG; - break; - case TypeIds.T_short: - base = TypeConstants.SHORT; - break; - case TypeIds.T_byte: - base = TypeConstants.BYTE; - break; - case TypeIds.T_double: - base = TypeConstants.DOUBLE; - break; - case TypeIds.T_float: - base = TypeConstants.FLOAT; - break; - case TypeIds.T_boolean: - base = TypeConstants.BOOLEAN; - break; - case TypeIds.T_char: - base = TypeConstants.CHAR; - break; - case TypeIds.T_void: - base = TypeConstants.VOID; - break; - case TypeIds.T_null: - return null; - } - - if (base != null) { - if (dims > 0) { - TypeReference result = new ArrayTypeReference(base, dims, pos(pos)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - TypeReference result = new SingleTypeReference(base, pos(pos)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - - if (binding.isAnonymousType()) { - ReferenceBinding ref = (ReferenceBinding)binding; - ReferenceBinding[] supers = ref.superInterfaces(); - if (supers == null || supers.length == 0) supers = new ReferenceBinding[] {ref.superclass()}; - if (supers[0] == null) { - TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - return makeType(supers[0], pos, false); - } - - if (binding instanceof CaptureBinding) { - return makeType(((CaptureBinding)binding).wildcard, pos, allowCompound); - } - - if (binding.isUnboundWildcard()) { - if (!allowCompound) { - TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); - Eclipse.setGeneratedBy(result, pos); - return result; - } else { - Wildcard out = new Wildcard(Wildcard.UNBOUND); - Eclipse.setGeneratedBy(out, pos); - out.sourceStart = pos.sourceStart; - out.sourceEnd = pos.sourceEnd; - return out; - } - } - - if (binding.isWildcard()) { - WildcardBinding wildcard = (WildcardBinding) binding; - if (wildcard.boundKind == Wildcard.EXTENDS) { - if (!allowCompound) { - return makeType(wildcard.bound, pos, false); - } else { - Wildcard out = new Wildcard(Wildcard.EXTENDS); - Eclipse.setGeneratedBy(out, pos); - out.bound = makeType(wildcard.bound, pos, false); - out.sourceStart = pos.sourceStart; - out.sourceEnd = pos.sourceEnd; - return out; - } - } else if (allowCompound && wildcard.boundKind == Wildcard.SUPER) { - Wildcard out = new Wildcard(Wildcard.SUPER); - Eclipse.setGeneratedBy(out, pos); - out.bound = makeType(wildcard.bound, pos, false); - out.sourceStart = pos.sourceStart; - out.sourceEnd = pos.sourceEnd; - return out; - } else { - TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - } - - char[][] parts; - - if (binding.isLocalType() || binding.isTypeVariable()) { - parts = new char[][] { binding.shortReadableName() }; - } else { - String[] pkg = new String(binding.qualifiedPackageName()).split("\\."); - String[] name = new String(binding.qualifiedSourceName()).split("\\."); - if (pkg.length == 1 && pkg[0].isEmpty()) pkg = new String[0]; - parts = new char[pkg.length + name.length][]; - int ptr; - for (ptr = 0; ptr < pkg.length; ptr++) parts[ptr] = pkg[ptr].toCharArray(); - for (; ptr < pkg.length + name.length; ptr++) parts[ptr] = name[ptr - pkg.length].toCharArray(); - } - - TypeReference[] params = new TypeReference[0]; - - if (binding instanceof ParameterizedTypeBinding) { - ParameterizedTypeBinding paramized = (ParameterizedTypeBinding) binding; - if (paramized.arguments != null) { - params = new TypeReference[paramized.arguments.length]; - for (int i = 0; i < params.length; i++) { - params[i] = makeType(paramized.arguments[i], pos, true); - } - } - } - - if (params.length > 0) { - if (parts.length > 1) { - TypeReference[][] typeArguments = new TypeReference[parts.length][]; - typeArguments[typeArguments.length - 1] = params; - TypeReference result = new ParameterizedQualifiedTypeReference(parts, typeArguments, dims, poss(pos, parts.length)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - TypeReference result = new ParameterizedSingleTypeReference(parts[0], params, dims, pos(pos)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - - if (dims > 0) { - if (parts.length > 1) { - TypeReference result = new ArrayQualifiedTypeReference(parts, dims, poss(pos, parts.length)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - TypeReference result = new ArrayTypeReference(parts[0], dims, pos(pos)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - - if (parts.length > 1) { - TypeReference result = new QualifiedTypeReference(parts, poss(pos, parts.length)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - TypeReference result = new SingleTypeReference(parts[0], pos(pos)); - Eclipse.setGeneratedBy(result, pos); - return result; - } - - private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0]; - - public static Annotation[] copyAnnotations(ASTNode source, Annotation[]... allAnnotations) { - boolean allNull = true; - - List<Annotation> result = new ArrayList<Annotation>(); - for (Annotation[] annotations : allAnnotations) { - if (annotations != null) { - allNull = false; - for (Annotation annotation : annotations) { - result.add(copyAnnotation(annotation, source)); - } - } - } - if (allNull) return null; - return result.toArray(EMPTY_ANNOTATION_ARRAY); - } - - public static Annotation copyAnnotation(Annotation annotation, ASTNode source) { - int pS = source.sourceStart, pE = source.sourceEnd; - - if (annotation instanceof MarkerAnnotation) { - MarkerAnnotation ann = new MarkerAnnotation(copyType(annotation.type, source), pS); - setGeneratedBy(ann, source); - ann.declarationSourceEnd = ann.sourceEnd = ann.statementEnd = pE; - return ann; - } - - if (annotation instanceof SingleMemberAnnotation) { - SingleMemberAnnotation ann = new SingleMemberAnnotation(copyType(annotation.type, source), pS); - setGeneratedBy(ann, source); - ann.declarationSourceEnd = ann.sourceEnd = ann.statementEnd = pE; - //TODO memberValue(s) need to be copied as well (same for copying a NormalAnnotation as below). - ann.memberValue = ((SingleMemberAnnotation)annotation).memberValue; - return ann; - } - - if (annotation instanceof NormalAnnotation) { - NormalAnnotation ann = new NormalAnnotation(copyType(annotation.type, source), pS); - setGeneratedBy(ann, source); - ann.declarationSourceEnd = ann.statementEnd = ann.sourceEnd = pE; - ann.memberValuePairs = ((NormalAnnotation)annotation).memberValuePairs; - return ann; - } - - return annotation; - } - - /** - * Checks if the provided annotation type is likely to be the intended type for the given annotation node. - * - * This is a guess, but a decent one. - */ - public static boolean annotationTypeMatches(Class<? extends java.lang.annotation.Annotation> type, EclipseNode node) { - if (node.getKind() != Kind.ANNOTATION) return false; - return typeMatches(type, node, ((Annotation)node.get()).type); - } - - /** - * Checks if the given TypeReference node is likely to be a reference to the provided class. - * - * @param type An actual type. This method checks if {@code typeNode} is likely to be a reference to this type. - * @param node A Lombok AST node. Any node in the appropriate compilation unit will do (used to get access to import statements). - * @param typeRef A type reference to check. - */ - public static boolean typeMatches(Class<?> type, EclipseNode node, TypeReference typeRef) { - if (typeRef == null || typeRef.getTypeName() == null || typeRef.getTypeName().length == 0) return false; - String lastPartA = new String(typeRef.getTypeName()[typeRef.getTypeName().length -1]); - String lastPartB = type.getSimpleName(); - if (!lastPartA.equals(lastPartB)) return false; - String typeName = toQualifiedName(typeRef.getTypeName()); - - TypeLibrary library = new TypeLibrary(); - library.addType(type.getName()); - TypeResolver resolver = new TypeResolver(library, node.getPackageDeclaration(), node.getImportStatements()); - Collection<String> typeMatches = resolver.findTypeMatches(node, typeName); - - for (String match : typeMatches) { - if (match.equals(type.getName())) return true; - } - - return false; - } - - /** - * Provides AnnotationValues with the data it needs to do its thing. - */ - public static <A extends java.lang.annotation.Annotation> AnnotationValues<A> - createAnnotation(Class<A> type, final EclipseNode annotationNode) { - final Annotation annotation = (Annotation) annotationNode.get(); - Map<String, AnnotationValue> values = new HashMap<String, AnnotationValue>(); - - final MemberValuePair[] pairs = annotation.memberValuePairs(); - for (Method m : type.getDeclaredMethods()) { - if (!Modifier.isPublic(m.getModifiers())) continue; - String name = m.getName(); - List<String> raws = new ArrayList<String>(); - List<Object> expressionValues = new ArrayList<Object>(); - List<Object> guesses = new ArrayList<Object>(); - Expression fullExpression = null; - Expression[] expressions = null; - - if (pairs != null) for (MemberValuePair pair : pairs) { - char[] n = pair.name; - String mName = n == null ? "value" : new String(pair.name); - if (mName.equals(name)) fullExpression = pair.value; - } - - boolean isExplicit = fullExpression != null; - - if (isExplicit) { - if (fullExpression instanceof ArrayInitializer) { - expressions = ((ArrayInitializer)fullExpression).expressions; - } else expressions = new Expression[] { fullExpression }; - if (expressions != null) for (Expression ex : expressions) { - StringBuffer sb = new StringBuffer(); - ex.print(0, sb); - raws.add(sb.toString()); - expressionValues.add(ex); - guesses.add(calculateValue(ex)); - } - } - - final Expression fullExpr = fullExpression; - final Expression[] exprs = expressions; - - values.put(name, new AnnotationValue(annotationNode, raws, expressionValues, guesses, isExplicit) { - @Override public void setError(String message, int valueIdx) { - Expression ex; - if (valueIdx == -1) ex = fullExpr; - else ex = exprs != null ? exprs[valueIdx] : null; - - if (ex == null) ex = annotation; - - int sourceStart = ex.sourceStart; - int sourceEnd = ex.sourceEnd; - - annotationNode.addError(message, sourceStart, sourceEnd); - } - - @Override public void setWarning(String message, int valueIdx) { - Expression ex; - if (valueIdx == -1) ex = fullExpr; - else ex = exprs != null ? exprs[valueIdx] : null; - - if (ex == null) ex = annotation; - - int sourceStart = ex.sourceStart; - int sourceEnd = ex.sourceEnd; - - annotationNode.addWarning(message, sourceStart, sourceEnd); - } - }); - } - - return new AnnotationValues<A>(type, values, annotationNode); - } - - private static Object calculateValue(Expression e) { - if (e instanceof Literal) { - ((Literal)e).computeConstant(); - switch (e.constant.typeID()) { - case TypeIds.T_int: return e.constant.intValue(); - case TypeIds.T_byte: return e.constant.byteValue(); - case TypeIds.T_short: return e.constant.shortValue(); - case TypeIds.T_char: return e.constant.charValue(); - case TypeIds.T_float: return e.constant.floatValue(); - case TypeIds.T_double: return e.constant.doubleValue(); - case TypeIds.T_boolean: return e.constant.booleanValue(); - case TypeIds.T_long: return e.constant.longValue(); - case TypeIds.T_JavaLangString: return e.constant.stringValue(); - default: return null; - } - } else if (e instanceof ClassLiteralAccess) { - return Eclipse.toQualifiedName(((ClassLiteralAccess)e).type.getTypeName()); - } else if (e instanceof SingleNameReference) { - return new String(((SingleNameReference)e).token); - } else if (e instanceof QualifiedNameReference) { - String qName = Eclipse.toQualifiedName(((QualifiedNameReference)e).tokens); - int idx = qName.lastIndexOf('.'); - return idx == -1 ? qName : qName.substring(idx+1); - } - - return null; - } - - private static Field generatedByField; - - static { - try { - generatedByField = ASTNode.class.getDeclaredField("$generatedBy"); - } catch (Throwable t) { - //ignore - no $generatedBy exists when running in ecj. - } - } - - private static Map<ASTNode, ASTNode> generatedNodes = new WeakHashMap<ASTNode, ASTNode>(); - - public static ASTNode getGeneratedBy(ASTNode node) { - if (generatedByField != null) { - try { - return (ASTNode) generatedByField.get(node); - } catch (Exception e) {} - } - synchronized (generatedNodes) { - return generatedNodes.get(node); - } - } - - public static boolean isGenerated(ASTNode node) { - return getGeneratedBy(node) != null; - } - - public static ASTNode setGeneratedBy(ASTNode node, ASTNode source) { - if (generatedByField != null) { - try { - generatedByField.set(node, source); - return node; - } catch (Exception e) {} - } - synchronized (generatedNodes) { - generatedNodes.put(node, source); - } - return node; - } -} diff --git a/src/core/lombok/eclipse/EclipseAST.java b/src/core/lombok/eclipse/EclipseAST.java index 91db0baa..816f50af 100644 --- a/src/core/lombok/eclipse/EclipseAST.java +++ b/src/core/lombok/eclipse/EclipseAST.java @@ -144,7 +144,7 @@ public class EclipseAST extends AST<EclipseAST, EclipseNode, ASTNode> { * Adds a problem to the provided CompilationResult object so that it will show up * in the Problems/Warnings view. */ - static void addProblemToCompilationResult(CompilationUnitDeclaration ast, + public static void addProblemToCompilationResult(CompilationUnitDeclaration ast, boolean isWarning, String message, int sourceStart, int sourceEnd) { if (ast.compilationResult == null) return; char[] fileNameArray = ast.getFileName(); diff --git a/src/core/lombok/eclipse/EclipseASTVisitor.java b/src/core/lombok/eclipse/EclipseASTVisitor.java index 7f9faf43..513e7114 100644 --- a/src/core/lombok/eclipse/EclipseASTVisitor.java +++ b/src/core/lombok/eclipse/EclipseASTVisitor.java @@ -21,6 +21,8 @@ */ package lombok.eclipse; +import static lombok.eclipse.handlers.EclipseHandlerUtil.isGenerated; + import java.io.PrintStream; import java.lang.reflect.Modifier; @@ -193,7 +195,7 @@ public interface EclipseASTVisitor { out.println("---------------------------------------------------------"); out.println(node.isCompleteParse() ? "COMPLETE" : "incomplete"); - print("<CUD %s%s>", node.getFileName(), Eclipse.isGenerated(unit) ? " (GENERATED)" : ""); + print("<CUD %s%s>", node.getFileName(), isGenerated(unit) ? " (GENERATED)" : ""); indent++; } @@ -203,7 +205,7 @@ public interface EclipseASTVisitor { } public void visitType(EclipseNode node, TypeDeclaration type) { - print("<TYPE %s%s>", str(type.name), Eclipse.isGenerated(type) ? " (GENERATED)" : ""); + print("<TYPE %s%s>", str(type.name), isGenerated(type) ? " (GENERATED)" : ""); indent++; if (printContent) { print("%s", type); @@ -212,7 +214,7 @@ public interface EclipseASTVisitor { } public void visitAnnotationOnType(TypeDeclaration type, EclipseNode node, Annotation annotation) { - forcePrint("<ANNOTATION%s: %s />", Eclipse.isGenerated(annotation) ? " (GENERATED)" : "", annotation); + forcePrint("<ANNOTATION%s: %s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation); } public void endVisitType(EclipseNode node, TypeDeclaration type) { @@ -227,7 +229,7 @@ public interface EclipseASTVisitor { print("<%s INITIALIZER: %s%s>", (initializer.modifiers & Modifier.STATIC) != 0 ? "static" : "instance", s ? "filled" : "blank", - Eclipse.isGenerated(initializer) ? " (GENERATED)" : ""); + isGenerated(initializer) ? " (GENERATED)" : ""); indent++; if (printContent) { if (initializer.block != null) print("%s", initializer.block); @@ -242,7 +244,7 @@ public interface EclipseASTVisitor { } public void visitField(EclipseNode node, FieldDeclaration field) { - print("<FIELD%s %s %s = %s>", Eclipse.isGenerated(field) ? " (GENERATED)" : "", + print("<FIELD%s %s %s = %s>", isGenerated(field) ? " (GENERATED)" : "", str(field.type), str(field.name), field.initialization); indent++; if (printContent) { @@ -252,7 +254,7 @@ public interface EclipseASTVisitor { } public void visitAnnotationOnField(FieldDeclaration field, EclipseNode node, Annotation annotation) { - forcePrint("<ANNOTATION%s: %s />", Eclipse.isGenerated(annotation) ? " (GENERATED)" : "", annotation); + forcePrint("<ANNOTATION%s: %s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation); } public void endVisitField(EclipseNode node, FieldDeclaration field) { @@ -264,7 +266,7 @@ public interface EclipseASTVisitor { public void visitMethod(EclipseNode node, AbstractMethodDeclaration method) { String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD"; print("<%s %s: %s%s>", type, str(method.selector), method.statements != null ? "filled" : "blank", - Eclipse.isGenerated(method) ? " (GENERATED)" : ""); + isGenerated(method) ? " (GENERATED)" : ""); indent++; if (printContent) { if (method.statements != null) print("%s", method); @@ -273,7 +275,7 @@ public interface EclipseASTVisitor { } public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode node, Annotation annotation) { - forcePrint("<ANNOTATION%s: %s />", Eclipse.isGenerated(method) ? " (GENERATED)" : "", annotation); + forcePrint("<ANNOTATION%s: %s />", isGenerated(method) ? " (GENERATED)" : "", annotation); } public void endVisitMethod(EclipseNode node, AbstractMethodDeclaration method) { @@ -284,12 +286,12 @@ public interface EclipseASTVisitor { } public void visitMethodArgument(EclipseNode node, Argument arg, AbstractMethodDeclaration method) { - print("<METHODARG%s %s %s = %s>", Eclipse.isGenerated(arg) ? " (GENERATED)" : "", str(arg.type), str(arg.name), arg.initialization); + print("<METHODARG%s %s %s = %s>", isGenerated(arg) ? " (GENERATED)" : "", str(arg.type), str(arg.name), arg.initialization); indent++; } public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode node, Annotation annotation) { - print("<ANNOTATION%s: %s />", Eclipse.isGenerated(annotation) ? " (GENERATED)" : "", annotation); + print("<ANNOTATION%s: %s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation); } public void endVisitMethodArgument(EclipseNode node, Argument arg, AbstractMethodDeclaration method) { @@ -298,12 +300,12 @@ public interface EclipseASTVisitor { } public void visitLocal(EclipseNode node, LocalDeclaration local) { - print("<LOCAL%s %s %s = %s>", Eclipse.isGenerated(local) ? " (GENERATED)" : "", str(local.type), str(local.name), local.initialization); + print("<LOCAL%s %s %s = %s>", isGenerated(local) ? " (GENERATED)" : "", str(local.type), str(local.name), local.initialization); indent++; } public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode node, Annotation annotation) { - print("<ANNOTATION%s: %s />", Eclipse.isGenerated(annotation) ? " (GENERATED)" : "", annotation); + print("<ANNOTATION%s: %s />", isGenerated(annotation) ? " (GENERATED)" : "", annotation); } public void endVisitLocal(EclipseNode node, LocalDeclaration local) { @@ -312,7 +314,7 @@ public interface EclipseASTVisitor { } public void visitStatement(EclipseNode node, Statement statement) { - print("<%s%s>", statement.getClass(), Eclipse.isGenerated(statement) ? " (GENERATED)" : ""); + print("<%s%s>", statement.getClass(), isGenerated(statement) ? " (GENERATED)" : ""); indent++; print("%s", statement); } diff --git a/src/core/lombok/eclipse/HandlerLibrary.java b/src/core/lombok/eclipse/HandlerLibrary.java index b6684c2f..24b84779 100644 --- a/src/core/lombok/eclipse/HandlerLibrary.java +++ b/src/core/lombok/eclipse/HandlerLibrary.java @@ -22,6 +22,7 @@ package lombok.eclipse; import static lombok.eclipse.Eclipse.toQualifiedName; +import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.io.IOException; import java.lang.annotation.Annotation; @@ -69,13 +70,13 @@ public class HandlerLibrary { public void handle(org.eclipse.jdt.internal.compiler.ast.Annotation annotation, final EclipseNode annotationNode) { - AnnotationValues<T> annValues = Eclipse.createAnnotation(annotationClass, annotationNode); + AnnotationValues<T> annValues = createAnnotation(annotationClass, annotationNode); handler.handle(annValues, annotation, annotationNode); } public void preHandle(org.eclipse.jdt.internal.compiler.ast.Annotation annotation, final EclipseNode annotationNode) { - AnnotationValues<T> annValues = Eclipse.createAnnotation(annotationClass, annotationNode); + AnnotationValues<T> annValues = createAnnotation(annotationClass, annotationNode); handler.preHandle(annValues, annotation, annotationNode); } @@ -113,11 +114,11 @@ public class HandlerLibrary { SpiLoadUtil.findAnnotationClass(handler.getClass(), EclipseAnnotationHandler.class); AnnotationHandlerContainer<?> container = new AnnotationHandlerContainer(handler, annotationClass); if (lib.annotationHandlers.put(container.annotationClass.getName(), container) != null) { - Eclipse.error(null, "Duplicate handlers for annotation type: " + container.annotationClass.getName(), null); + error(null, "Duplicate handlers for annotation type: " + container.annotationClass.getName(), null); } lib.typeLibrary.addType(container.annotationClass.getName()); } catch (Throwable t) { - Eclipse.error(null, "Can't load Lombok annotation handler for Eclipse: ", t); + error(null, "Can't load Lombok annotation handler for Eclipse: ", t); } } } catch (IOException e) { @@ -192,7 +193,7 @@ public class HandlerLibrary { } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); } catch (Throwable t) { - Eclipse.error(ast, String.format("Lombok annotation handler %s failed", container.handler.getClass()), t); + error(ast, String.format("Lombok annotation handler %s failed", container.handler.getClass()), t); } } } @@ -204,7 +205,7 @@ public class HandlerLibrary { for (EclipseASTVisitor visitor : visitorHandlers) try { ast.traverse(visitor); } catch (Throwable t) { - Eclipse.error((CompilationUnitDeclaration) ast.top().get(), + error((CompilationUnitDeclaration) ast.top().get(), String.format("Lombok visitor handler %s failed", visitor.getClass()), t); } } diff --git a/src/core/lombok/eclipse/TransformEclipseAST.java b/src/core/lombok/eclipse/TransformEclipseAST.java index c91299bb..b6a8b914 100644 --- a/src/core/lombok/eclipse/TransformEclipseAST.java +++ b/src/core/lombok/eclipse/TransformEclipseAST.java @@ -21,6 +21,8 @@ */ package lombok.eclipse; +import static lombok.eclipse.handlers.EclipseHandlerUtil.error; + import java.lang.reflect.Field; import lombok.core.debug.DebugSnapshotStore; @@ -64,7 +66,7 @@ public class TransformEclipseAST { h = HandlerLibrary.load(); } catch (Throwable t) { try { - Eclipse.error(null, "Problem initializing lombok", t); + error(null, "Problem initializing lombok", t); } catch (Throwable t2) { System.err.println("Problem initializing lombok"); t.printStackTrace(); @@ -140,7 +142,7 @@ public class TransformEclipseAST { t.printStackTrace(); } catch (Throwable t2) { try { - Eclipse.error(ast, "Can't create an error in the problems dialog while adding: " + t.toString(), t2); + error(ast, "Can't create an error in the problems dialog while adding: " + t.toString(), t2); } catch (Throwable t3) { //This seems risky to just silently turn off lombok, but if we get this far, something pretty //drastic went wrong. For example, the eclipse help system's JSP compiler will trigger a lombok call, diff --git a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java index c1204c84..fef55904 100644 --- a/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java +++ b/src/core/lombok/eclipse/handlers/EclipseHandlerUtil.java @@ -24,13 +24,17 @@ package lombok.eclipse.handlers; import static lombok.eclipse.Eclipse.*; import java.lang.reflect.Constructor; +import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; import java.util.List; -import java.util.regex.Pattern; +import java.util.Map; +import java.util.WeakHashMap; import lombok.AccessLevel; import lombok.Data; @@ -38,18 +42,28 @@ import lombok.Getter; import lombok.Lombok; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; -import lombok.core.handlers.TransformationsUtil; -import lombok.eclipse.Eclipse; +import lombok.core.AnnotationValues.AnnotationValue; +import lombok.eclipse.EclipseAST; import lombok.eclipse.EclipseNode; +import lombok.core.TransformationsUtil; +import lombok.core.TypeLibrary; +import lombok.core.TypeResolver; +import org.eclipse.core.runtime.ILog; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; +import org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference; +import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.Clinit; +import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; @@ -65,6 +79,8 @@ import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; +import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; +import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; @@ -75,10 +91,19 @@ import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; +import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; +import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.lookup.Binding; +import org.eclipse.jdt.internal.compiler.lookup.CaptureBinding; +import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; +import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; +import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants; +import org.eclipse.jdt.internal.compiler.lookup.TypeIds; +import org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; +import org.osgi.framework.Bundle; /** * Container for static utility methods useful to handlers written for eclipse. @@ -88,12 +113,596 @@ public class EclipseHandlerUtil { //Prevent instantiation } + private static final String DEFAULT_BUNDLE = "org.eclipse.jdt.core"; + + /** + * Generates an error in the Eclipse error log. Note that most people never look at it! + * + * @param cud The {@code CompilationUnitDeclaration} where the error occurred. + * An error will be generated on line 0 linking to the error log entry. Can be {@code null}. + * @param message Human readable description of the problem. + * @param error The associated exception. Can be {@code null}. + */ + public static void error(CompilationUnitDeclaration cud, String message, Throwable error) { + error(cud, message, null, error); + } + + /** + * Generates an error in the Eclipse error log. Note that most people never look at it! + * + * @param cud The {@code CompilationUnitDeclaration} where the error occurred. + * An error will be generated on line 0 linking to the error log entry. Can be {@code null}. + * @param message Human readable description of the problem. + * @param bundleName Can be {@code null} to default to {@code org.eclipse.jdt.core} which is usually right. + * @param error The associated exception. Can be {@code null}. + */ + public static void error(CompilationUnitDeclaration cud, String message, String bundleName, Throwable error) { + if (bundleName == null) bundleName = DEFAULT_BUNDLE; + try { + new EclipseWorkspaceLogger().error(message, bundleName, error); + } catch (NoClassDefFoundError e) { //standalone ecj does not jave Platform, ILog, IStatus, and friends. + new TerminalLogger().error(message, bundleName, error); + } + if (cud != null) EclipseAST.addProblemToCompilationResult(cud, false, message + " - See error log.", 0, 0); + } + + /** + * Generates a warning in the Eclipse error log. Note that most people never look at it! + * + * @param message Human readable description of the problem. + * @param error The associated exception. Can be {@code null}. + */ + public static void warning(String message, Throwable error) { + warning(message, null, error); + } + + /** + * Generates a warning in the Eclipse error log. Note that most people never look at it! + * + * @param message Human readable description of the problem. + * @param bundleName Can be {@code null} to default to {@code org.eclipse.jdt.core} which is usually right. + * @param error The associated exception. Can be {@code null}. + */ + public static void warning(String message, String bundleName, Throwable error) { + if (bundleName == null) bundleName = DEFAULT_BUNDLE; + try { + new EclipseWorkspaceLogger().warning(message, bundleName, error); + } catch (NoClassDefFoundError e) { //standalone ecj does not jave Platform, ILog, IStatus, and friends. + new TerminalLogger().warning(message, bundleName, error); + } + } + + private static class TerminalLogger { + void error(String message, String bundleName, Throwable error) { + System.err.println(message); + if (error != null) error.printStackTrace(); + } + + void warning(String message, String bundleName, Throwable error) { + System.err.println(message); + if (error != null) error.printStackTrace(); + } + } + + private static class EclipseWorkspaceLogger { + void error(String message, String bundleName, Throwable error) { + msg(IStatus.ERROR, message, bundleName, error); + } + + void warning(String message, String bundleName, Throwable error) { + msg(IStatus.WARNING, message, bundleName, error); + } + + private void msg(int msgType, String message, String bundleName, Throwable error) { + Bundle bundle = Platform.getBundle(bundleName); + if (bundle == null) { + System.err.printf("Can't find bundle %s while trying to report error:\n%s\n", bundleName, message); + return; + } + + ILog log = Platform.getLog(bundle); + + log.log(new Status(msgType, bundleName, message, error)); + } + } + + private static Field generatedByField; + + static { + try { + generatedByField = ASTNode.class.getDeclaredField("$generatedBy"); + } catch (Throwable t) { + //ignore - no $generatedBy exists when running in ecj. + } + } + + private static Map<ASTNode, ASTNode> generatedNodes = new WeakHashMap<ASTNode, ASTNode>(); + + public static ASTNode getGeneratedBy(ASTNode node) { + if (generatedByField != null) { + try { + return (ASTNode) generatedByField.get(node); + } catch (Exception e) {} + } + synchronized (generatedNodes) { + return generatedNodes.get(node); + } + } + + public static boolean isGenerated(ASTNode node) { + return getGeneratedBy(node) != null; + } + + public static ASTNode setGeneratedBy(ASTNode node, ASTNode source) { + if (generatedByField != null) { + try { + generatedByField.set(node, source); + return node; + } catch (Exception e) {} + } + synchronized (generatedNodes) { + generatedNodes.put(node, source); + } + return node; + } + + /** + * Checks if the given TypeReference node is likely to be a reference to the provided class. + * + * @param type An actual type. This method checks if {@code typeNode} is likely to be a reference to this type. + * @param node A Lombok AST node. Any node in the appropriate compilation unit will do (used to get access to import statements). + * @param typeRef A type reference to check. + */ + public static boolean typeMatches(Class<?> type, EclipseNode node, TypeReference typeRef) { + if (typeRef == null || typeRef.getTypeName() == null || typeRef.getTypeName().length == 0) return false; + String lastPartA = new String(typeRef.getTypeName()[typeRef.getTypeName().length -1]); + String lastPartB = type.getSimpleName(); + if (!lastPartA.equals(lastPartB)) return false; + String typeName = toQualifiedName(typeRef.getTypeName()); + + TypeLibrary library = new TypeLibrary(); + library.addType(type.getName()); + TypeResolver resolver = new TypeResolver(library, node.getPackageDeclaration(), node.getImportStatements()); + Collection<String> typeMatches = resolver.findTypeMatches(node, typeName); + + for (String match : typeMatches) { + if (match.equals(type.getName())) return true; + } + + return false; + } + + public static Annotation copyAnnotation(Annotation annotation, ASTNode source) { + int pS = source.sourceStart, pE = source.sourceEnd; + + if (annotation instanceof MarkerAnnotation) { + MarkerAnnotation ann = new MarkerAnnotation(copyType(annotation.type, source), pS); + setGeneratedBy(ann, source); + ann.declarationSourceEnd = ann.sourceEnd = ann.statementEnd = pE; + return ann; + } + + if (annotation instanceof SingleMemberAnnotation) { + SingleMemberAnnotation ann = new SingleMemberAnnotation(copyType(annotation.type, source), pS); + setGeneratedBy(ann, source); + ann.declarationSourceEnd = ann.sourceEnd = ann.statementEnd = pE; + //TODO memberValue(s) need to be copied as well (same for copying a NormalAnnotation as below). + ann.memberValue = ((SingleMemberAnnotation)annotation).memberValue; + return ann; + } + + if (annotation instanceof NormalAnnotation) { + NormalAnnotation ann = new NormalAnnotation(copyType(annotation.type, source), pS); + setGeneratedBy(ann, source); + ann.declarationSourceEnd = ann.statementEnd = ann.sourceEnd = pE; + ann.memberValuePairs = ((NormalAnnotation)annotation).memberValuePairs; + return ann; + } + + return annotation; + } + + /** + * You can't share TypeParameter objects or bad things happen; for example, one 'T' resolves differently + * from another 'T', even for the same T in a single class file. Unfortunately the TypeParameter type hierarchy + * is complicated and there's no clone method on TypeParameter itself. This method can clone them. + */ + public static TypeParameter[] copyTypeParams(TypeParameter[] params, ASTNode source) { + if (params == null) return null; + TypeParameter[] out = new TypeParameter[params.length]; + int idx = 0; + for (TypeParameter param : params) { + TypeParameter o = new TypeParameter(); + setGeneratedBy(o, source); + o.annotations = param.annotations; + o.bits = param.bits; + o.modifiers = param.modifiers; + o.name = param.name; + o.type = copyType(param.type, source); + o.sourceStart = param.sourceStart; + o.sourceEnd = param.sourceEnd; + o.declarationEnd = param.declarationEnd; + o.declarationSourceStart = param.declarationSourceStart; + o.declarationSourceEnd = param.declarationSourceEnd; + if (param.bounds != null) { + TypeReference[] b = new TypeReference[param.bounds.length]; + int idx2 = 0; + for (TypeReference ref : param.bounds) b[idx2++] = copyType(ref, source); + o.bounds = b; + } + out[idx++] = o; + } + return out; + } + + /** + * Convenience method that creates a new array and copies each TypeReference in the source array via + * {@link #copyType(TypeReference, ASTNode)}. + */ + public static TypeReference[] copyTypes(TypeReference[] refs, ASTNode source) { + if (refs == null) return null; + TypeReference[] outs = new TypeReference[refs.length]; + int idx = 0; + for (TypeReference ref : refs) { + outs[idx++] = copyType(ref, source); + } + return outs; + } + + /** + * You can't share TypeReference objects or subtle errors start happening. + * Unfortunately the TypeReference type hierarchy is complicated and there's no clone + * method on TypeReference itself. This method can clone them. + */ + public static TypeReference copyType(TypeReference ref, ASTNode source) { + if (ref instanceof ParameterizedQualifiedTypeReference) { + ParameterizedQualifiedTypeReference iRef = (ParameterizedQualifiedTypeReference) ref; + TypeReference[][] args = null; + if (iRef.typeArguments != null) { + args = new TypeReference[iRef.typeArguments.length][]; + int idx = 0; + for (TypeReference[] inRefArray : iRef.typeArguments) { + if (inRefArray == null) args[idx++] = null; + else { + TypeReference[] outRefArray = new TypeReference[inRefArray.length]; + int idx2 = 0; + for (TypeReference inRef : inRefArray) { + outRefArray[idx2++] = copyType(inRef, source); + } + args[idx++] = outRefArray; + } + } + } + TypeReference typeRef = new ParameterizedQualifiedTypeReference(iRef.tokens, args, iRef.dimensions(), iRef.sourcePositions); + setGeneratedBy(typeRef, source); + return typeRef; + } + + if (ref instanceof ArrayQualifiedTypeReference) { + ArrayQualifiedTypeReference iRef = (ArrayQualifiedTypeReference) ref; + TypeReference typeRef = new ArrayQualifiedTypeReference(iRef.tokens, iRef.dimensions(), iRef.sourcePositions); + setGeneratedBy(typeRef, source); + return typeRef; + } + + if (ref instanceof QualifiedTypeReference) { + QualifiedTypeReference iRef = (QualifiedTypeReference) ref; + TypeReference typeRef = new QualifiedTypeReference(iRef.tokens, iRef.sourcePositions); + setGeneratedBy(typeRef, source); + return typeRef; + } + + if (ref instanceof ParameterizedSingleTypeReference) { + ParameterizedSingleTypeReference iRef = (ParameterizedSingleTypeReference) ref; + TypeReference[] args = null; + if (iRef.typeArguments != null) { + args = new TypeReference[iRef.typeArguments.length]; + int idx = 0; + for (TypeReference inRef : iRef.typeArguments) { + if (inRef == null) args[idx++] = null; + else args[idx++] = copyType(inRef, source); + } + } + + TypeReference typeRef = new ParameterizedSingleTypeReference(iRef.token, args, iRef.dimensions(), (long)iRef.sourceStart << 32 | iRef.sourceEnd); + setGeneratedBy(typeRef, source); + return typeRef; + } + + if (ref instanceof ArrayTypeReference) { + ArrayTypeReference iRef = (ArrayTypeReference) ref; + TypeReference typeRef = new ArrayTypeReference(iRef.token, iRef.dimensions(), (long)iRef.sourceStart << 32 | iRef.sourceEnd); + setGeneratedBy(typeRef, source); + return typeRef; + } + + if (ref instanceof Wildcard) { + Wildcard original = (Wildcard)ref; + + Wildcard wildcard = new Wildcard(original.kind); + wildcard.sourceStart = original.sourceStart; + wildcard.sourceEnd = original.sourceEnd; + if (original.bound != null) wildcard.bound = copyType(original.bound, source); + setGeneratedBy(wildcard, source); + return wildcard; + } + + if (ref instanceof SingleTypeReference) { + SingleTypeReference iRef = (SingleTypeReference) ref; + TypeReference typeRef = new SingleTypeReference(iRef.token, (long)iRef.sourceStart << 32 | iRef.sourceEnd); + setGeneratedBy(typeRef, source); + return typeRef; + } + + return ref; + } + + public static Annotation[] copyAnnotations(ASTNode source, Annotation[]... allAnnotations) { + boolean allNull = true; + + List<Annotation> result = new ArrayList<Annotation>(); + for (Annotation[] annotations : allAnnotations) { + if (annotations != null) { + allNull = false; + for (Annotation annotation : annotations) { + result.add(copyAnnotation(annotation, source)); + } + } + } + if (allNull) return null; + return result.toArray(EMPTY_ANNOTATION_ARRAY); + } + + /** + * Checks if the provided annotation type is likely to be the intended type for the given annotation node. + * + * This is a guess, but a decent one. + */ + public static boolean annotationTypeMatches(Class<? extends java.lang.annotation.Annotation> type, EclipseNode node) { + if (node.getKind() != Kind.ANNOTATION) return false; + return typeMatches(type, node, ((Annotation)node.get()).type); + } + + public static TypeReference makeType(TypeBinding binding, ASTNode pos, boolean allowCompound) { + int dims = binding.dimensions(); + binding = binding.leafComponentType(); + + // Primitives + + char[] base = null; + + switch (binding.id) { + case TypeIds.T_int: + base = TypeConstants.INT; + break; + case TypeIds.T_long: + base = TypeConstants.LONG; + break; + case TypeIds.T_short: + base = TypeConstants.SHORT; + break; + case TypeIds.T_byte: + base = TypeConstants.BYTE; + break; + case TypeIds.T_double: + base = TypeConstants.DOUBLE; + break; + case TypeIds.T_float: + base = TypeConstants.FLOAT; + break; + case TypeIds.T_boolean: + base = TypeConstants.BOOLEAN; + break; + case TypeIds.T_char: + base = TypeConstants.CHAR; + break; + case TypeIds.T_void: + base = TypeConstants.VOID; + break; + case TypeIds.T_null: + return null; + } + + if (base != null) { + if (dims > 0) { + TypeReference result = new ArrayTypeReference(base, dims, pos(pos)); + setGeneratedBy(result, pos); + return result; + } + TypeReference result = new SingleTypeReference(base, pos(pos)); + setGeneratedBy(result, pos); + return result; + } + + if (binding.isAnonymousType()) { + ReferenceBinding ref = (ReferenceBinding)binding; + ReferenceBinding[] supers = ref.superInterfaces(); + if (supers == null || supers.length == 0) supers = new ReferenceBinding[] {ref.superclass()}; + if (supers[0] == null) { + TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); + setGeneratedBy(result, pos); + return result; + } + return makeType(supers[0], pos, false); + } + + if (binding instanceof CaptureBinding) { + return makeType(((CaptureBinding)binding).wildcard, pos, allowCompound); + } + + if (binding.isUnboundWildcard()) { + if (!allowCompound) { + TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); + setGeneratedBy(result, pos); + return result; + } else { + Wildcard out = new Wildcard(Wildcard.UNBOUND); + setGeneratedBy(out, pos); + out.sourceStart = pos.sourceStart; + out.sourceEnd = pos.sourceEnd; + return out; + } + } + + if (binding.isWildcard()) { + WildcardBinding wildcard = (WildcardBinding) binding; + if (wildcard.boundKind == Wildcard.EXTENDS) { + if (!allowCompound) { + return makeType(wildcard.bound, pos, false); + } else { + Wildcard out = new Wildcard(Wildcard.EXTENDS); + setGeneratedBy(out, pos); + out.bound = makeType(wildcard.bound, pos, false); + out.sourceStart = pos.sourceStart; + out.sourceEnd = pos.sourceEnd; + return out; + } + } else if (allowCompound && wildcard.boundKind == Wildcard.SUPER) { + Wildcard out = new Wildcard(Wildcard.SUPER); + setGeneratedBy(out, pos); + out.bound = makeType(wildcard.bound, pos, false); + out.sourceStart = pos.sourceStart; + out.sourceEnd = pos.sourceEnd; + return out; + } else { + TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3)); + setGeneratedBy(result, pos); + return result; + } + } + + char[][] parts; + + if (binding.isLocalType() || binding.isTypeVariable()) { + parts = new char[][] { binding.shortReadableName() }; + } else { + String[] pkg = new String(binding.qualifiedPackageName()).split("\\."); + String[] name = new String(binding.qualifiedSourceName()).split("\\."); + if (pkg.length == 1 && pkg[0].isEmpty()) pkg = new String[0]; + parts = new char[pkg.length + name.length][]; + int ptr; + for (ptr = 0; ptr < pkg.length; ptr++) parts[ptr] = pkg[ptr].toCharArray(); + for (; ptr < pkg.length + name.length; ptr++) parts[ptr] = name[ptr - pkg.length].toCharArray(); + } + + TypeReference[] params = new TypeReference[0]; + + if (binding instanceof ParameterizedTypeBinding) { + ParameterizedTypeBinding paramized = (ParameterizedTypeBinding) binding; + if (paramized.arguments != null) { + params = new TypeReference[paramized.arguments.length]; + for (int i = 0; i < params.length; i++) { + params[i] = makeType(paramized.arguments[i], pos, true); + } + } + } + + if (params.length > 0) { + if (parts.length > 1) { + TypeReference[][] typeArguments = new TypeReference[parts.length][]; + typeArguments[typeArguments.length - 1] = params; + TypeReference result = new ParameterizedQualifiedTypeReference(parts, typeArguments, dims, poss(pos, parts.length)); + setGeneratedBy(result, pos); + return result; + } + TypeReference result = new ParameterizedSingleTypeReference(parts[0], params, dims, pos(pos)); + setGeneratedBy(result, pos); + return result; + } + + if (dims > 0) { + if (parts.length > 1) { + TypeReference result = new ArrayQualifiedTypeReference(parts, dims, poss(pos, parts.length)); + setGeneratedBy(result, pos); + return result; + } + TypeReference result = new ArrayTypeReference(parts[0], dims, pos(pos)); + setGeneratedBy(result, pos); + return result; + } + + if (parts.length > 1) { + TypeReference result = new QualifiedTypeReference(parts, poss(pos, parts.length)); + setGeneratedBy(result, pos); + return result; + } + TypeReference result = new SingleTypeReference(parts[0], pos(pos)); + setGeneratedBy(result, pos); + return result; + } + /** - * Checks if the given type reference represents a primitive type. + * Provides AnnotationValues with the data it needs to do its thing. */ - public static boolean isPrimitive(TypeReference ref) { - if (ref.dimensions() > 0) return false; - return TransformationsUtil.PRIMITIVE_TYPE_NAME_PATTERN.matcher(Eclipse.toQualifiedName(ref.getTypeName())).matches(); + public static <A extends java.lang.annotation.Annotation> AnnotationValues<A> + createAnnotation(Class<A> type, final EclipseNode annotationNode) { + final Annotation annotation = (Annotation) annotationNode.get(); + Map<String, AnnotationValue> values = new HashMap<String, AnnotationValue>(); + + final MemberValuePair[] pairs = annotation.memberValuePairs(); + for (Method m : type.getDeclaredMethods()) { + if (!Modifier.isPublic(m.getModifiers())) continue; + String name = m.getName(); + List<String> raws = new ArrayList<String>(); + List<Object> expressionValues = new ArrayList<Object>(); + List<Object> guesses = new ArrayList<Object>(); + Expression fullExpression = null; + Expression[] expressions = null; + + if (pairs != null) for (MemberValuePair pair : pairs) { + char[] n = pair.name; + String mName = n == null ? "value" : new String(pair.name); + if (mName.equals(name)) fullExpression = pair.value; + } + + boolean isExplicit = fullExpression != null; + + if (isExplicit) { + if (fullExpression instanceof ArrayInitializer) { + expressions = ((ArrayInitializer)fullExpression).expressions; + } else expressions = new Expression[] { fullExpression }; + if (expressions != null) for (Expression ex : expressions) { + StringBuffer sb = new StringBuffer(); + ex.print(0, sb); + raws.add(sb.toString()); + expressionValues.add(ex); + guesses.add(calculateValue(ex)); + } + } + + final Expression fullExpr = fullExpression; + final Expression[] exprs = expressions; + + values.put(name, new AnnotationValue(annotationNode, raws, expressionValues, guesses, isExplicit) { + @Override public void setError(String message, int valueIdx) { + Expression ex; + if (valueIdx == -1) ex = fullExpr; + else ex = exprs != null ? exprs[valueIdx] : null; + + if (ex == null) ex = annotation; + + int sourceStart = ex.sourceStart; + int sourceEnd = ex.sourceEnd; + + annotationNode.addError(message, sourceStart, sourceEnd); + } + + @Override public void setWarning(String message, int valueIdx) { + Expression ex; + if (valueIdx == -1) ex = fullExpr; + else ex = exprs != null ? exprs[valueIdx] : null; + + if (ex == null) ex = annotation; + + int sourceStart = ex.sourceStart; + int sourceEnd = ex.sourceEnd; + + annotationNode.addWarning(message, sourceStart, sourceEnd); + } + }); + } + + return new AnnotationValues<A>(type, values, annotationNode); } /** @@ -149,7 +758,7 @@ public class EclipseHandlerUtil { for (EclipseNode child : field.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { - AnnotationValues<Getter> ann = Eclipse.createAnnotation(Getter.class, child); + AnnotationValues<Getter> ann = createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } @@ -164,7 +773,7 @@ public class EclipseHandlerUtil { if (containingType != null) for (EclipseNode child : containingType.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Data.class, child)) hasGetterAnnotation = true; if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { - AnnotationValues<Getter> ann = Eclipse.createAnnotation(Getter.class, child); + AnnotationValues<Getter> ann = createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } @@ -190,8 +799,8 @@ public class EclipseHandlerUtil { // If @Getter(lazy = true) is used, then using it is mandatory. for (EclipseNode child : field.down()) { if (child.getKind() != Kind.ANNOTATION) continue; - if (Eclipse.annotationTypeMatches(Getter.class, child)) { - AnnotationValues<Getter> ann = Eclipse.createAnnotation(Getter.class, child); + if (annotationTypeMatches(Getter.class, child)) { + AnnotationValues<Getter> ann = createAnnotation(Getter.class, child); if (ann.getInstance().lazy()) return true; } } @@ -226,22 +835,22 @@ public class EclipseHandlerUtil { ref.receiver = new SingleNameReference(((TypeDeclaration)containerNode.get()).name, p); } else { Expression smallRef = new FieldReference(field.getName().toCharArray(), p); - Eclipse.setGeneratedBy(smallRef, source); + setGeneratedBy(smallRef, source); return smallRef; } } else { ref.receiver = new ThisReference(pS, pE); } - Eclipse.setGeneratedBy(ref, source); - Eclipse.setGeneratedBy(ref.receiver, source); + setGeneratedBy(ref, source); + setGeneratedBy(ref.receiver, source); return ref; } MessageSend call = new MessageSend(); - Eclipse.setGeneratedBy(call, source); + setGeneratedBy(call, source); call.sourceStart = pS; call.sourceEnd = pE; call.receiver = new ThisReference(pS, pE); - Eclipse.setGeneratedBy(call.receiver, source); + setGeneratedBy(call.receiver, source); call.selector = getter.name; return call; } @@ -263,35 +872,19 @@ public class EclipseHandlerUtil { long[] poss = {p, p}; ref = new QualifiedNameReference(tokens, poss, pS, pE); - Eclipse.setGeneratedBy(ref, source); + setGeneratedBy(ref, source); return ref; } MessageSend call = new MessageSend(); - Eclipse.setGeneratedBy(call, source); + setGeneratedBy(call, source); call.sourceStart = pS; call.sourceEnd = pE; call.receiver = new SingleNameReference(receiver, p); - Eclipse.setGeneratedBy(call.receiver, source); + setGeneratedBy(call.receiver, source); call.selector = getter.name; return call; } - /** - * Checks if an eclipse-style array-of-array-of-characters to represent a fully qualified name ('foo.bar.baz'), matches a plain - * string containing the same fully qualified name with dots in the string. - */ - public static boolean nameEquals(char[][] typeName, String string) { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for (char[] elem : typeName) { - if (first) first = false; - else sb.append('.'); - sb.append(elem); - } - - return string.contentEquals(sb); - } - /** Serves as return value for the methods that check for the existence of fields and methods. */ public enum MemberExistsResult { NOT_EXISTS, EXISTS_BY_LOMBOK, EXISTS_BY_USER; @@ -334,7 +927,7 @@ public class EclipseHandlerUtil { char[] fName = def.name; if (fName == null) continue; if (fieldName.equals(new String(fName))) { - return Eclipse.getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } @@ -369,7 +962,7 @@ public class EclipseHandlerUtil { char[] mName = def.selector; if (mName == null) continue; boolean nameEquals = caseSensitive ? methodName.equals(new String(mName)) : methodName.equalsIgnoreCase(new String(mName)); - if (nameEquals) return Eclipse.getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + if (nameEquals) return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } @@ -393,7 +986,7 @@ public class EclipseHandlerUtil { if (typeDecl.methods != null) for (AbstractMethodDeclaration def : typeDecl.methods) { if (def instanceof ConstructorDeclaration) { if ((def.bits & ASTNode.IsDefaultConstructor) != 0) continue; - return Eclipse.getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } @@ -435,15 +1028,6 @@ public class EclipseHandlerUtil { type.add(field, Kind.FIELD); } - private static boolean hasClinit(TypeDeclaration parent) { - if (parent.methods == null) return false; - - for (AbstractMethodDeclaration method : parent.methods) { - if (method instanceof Clinit) return true; - } - return false; - } - /** * Inserts a method into an existing type. The type must represent a {@code TypeDeclaration}. */ @@ -480,7 +1064,7 @@ public class EclipseHandlerUtil { if (current instanceof ConstructorDeclaration) continue; break; } - if (Eclipse.isGenerated(current)) continue; + if (isGenerated(current)) continue; break; } AbstractMethodDeclaration[] newArray = new AbstractMethodDeclaration[parent.methods.length + 1]; @@ -504,12 +1088,12 @@ public class EclipseHandlerUtil { long[] poss = new long[3]; Arrays.fill(poss, p); QualifiedTypeReference suppressWarningsType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_SUPPRESSWARNINGS, poss); - Eclipse.setGeneratedBy(suppressWarningsType, source); + setGeneratedBy(suppressWarningsType, source); SingleMemberAnnotation ann = new SingleMemberAnnotation(suppressWarningsType, pS); ann.declarationSourceEnd = pE; ann.memberValue = new StringLiteral(ALL, pS, pE, 0); - Eclipse.setGeneratedBy(ann, source); - Eclipse.setGeneratedBy(ann.memberValue, source); + setGeneratedBy(ann, source); + setGeneratedBy(ann.memberValue, source); if (originalAnnotationArray == null) return new Annotation[] { ann }; Annotation[] newAnnotationArray = Arrays.copyOf(originalAnnotationArray, originalAnnotationArray.length + 1); newAnnotationArray[originalAnnotationArray.length] = ann; @@ -517,27 +1101,6 @@ public class EclipseHandlerUtil { } /** - * Searches the given field node for annotations and returns each one that matches the provided regular expression pattern. - * - * Only the simple name is checked - the package and any containing class are ignored. - */ - public static Annotation[] findAnnotations(FieldDeclaration field, Pattern namePattern) { - List<Annotation> result = new ArrayList<Annotation>(); - if (field.annotations == null) return new Annotation[0]; - for (Annotation annotation : field.annotations) { - TypeReference typeRef = annotation.type; - if (typeRef != null && typeRef.getTypeName()!= null) { - char[][] typeName = typeRef.getTypeName(); - String suspect = new String(typeName[typeName.length - 1]); - if (namePattern.matcher(suspect).matches()) { - result.add(annotation); - } - } - } - return result.toArray(new Annotation[0]); - } - - /** * Generates a new statement that checks if the given variable is null, and if so, throws a {@code NullPointerException} with the * variable name as message. */ @@ -547,23 +1110,23 @@ public class EclipseHandlerUtil { if (isPrimitive(variable.type)) return null; AllocationExpression exception = new AllocationExpression(); - Eclipse.setGeneratedBy(exception, source); + setGeneratedBy(exception, source); exception.type = new QualifiedTypeReference(fromQualifiedName("java.lang.NullPointerException"), new long[]{p, p, p}); - Eclipse.setGeneratedBy(exception.type, source); + setGeneratedBy(exception.type, source); exception.arguments = new Expression[] { new StringLiteral(variable.name, pS, pE, 0)}; - Eclipse.setGeneratedBy(exception.arguments[0], source); + setGeneratedBy(exception.arguments[0], source); ThrowStatement throwStatement = new ThrowStatement(exception, pS, pE); - Eclipse.setGeneratedBy(throwStatement, source); + setGeneratedBy(throwStatement, source); SingleNameReference varName = new SingleNameReference(variable.name, p); - Eclipse.setGeneratedBy(varName, source); + setGeneratedBy(varName, source); NullLiteral nullLiteral = new NullLiteral(pS, pE); - Eclipse.setGeneratedBy(nullLiteral, source); + setGeneratedBy(nullLiteral, source); EqualExpression equalExpression = new EqualExpression(varName, nullLiteral, OperatorIds.EQUAL_EQUAL); equalExpression.sourceStart = pS; equalExpression.sourceEnd = pE; - Eclipse.setGeneratedBy(equalExpression, source); + setGeneratedBy(equalExpression, source); IfStatement ifStatement = new IfStatement(equalExpression, throwStatement, 0, 0); - Eclipse.setGeneratedBy(ifStatement, source); + setGeneratedBy(ifStatement, source); return ifStatement; } @@ -573,10 +1136,10 @@ public class EclipseHandlerUtil { public static MarkerAnnotation makeMarkerAnnotation(char[][] name, ASTNode source) { long pos = (long)source.sourceStart << 32 | source.sourceEnd; TypeReference typeRef = new QualifiedTypeReference(name, new long[] {pos, pos, pos}); - Eclipse.setGeneratedBy(typeRef, source); + setGeneratedBy(typeRef, source); MarkerAnnotation ann = new MarkerAnnotation(typeRef, (int)(pos >> 32)); ann.declarationSourceEnd = ann.sourceEnd = ann.statementEnd = (int)pos; - Eclipse.setGeneratedBy(ann, source); + setGeneratedBy(ann, source); return ann; } @@ -622,21 +1185,20 @@ public class EclipseHandlerUtil { } else { Expression castToConverted = castTo; - if (castTo.getClass() == SingleTypeReference.class && !PRIMITIVE_NAMES.contains( - " " + new String(((SingleTypeReference)castTo).token) + " ")) { + if (castTo.getClass() == SingleTypeReference.class && !isPrimitive(castTo)) { SingleTypeReference str = (SingleTypeReference) castTo; //Why a SingleNameReference instead of a SingleTypeReference you ask? I don't know. It seems dumb. Ask the ecj guys. castToConverted = new SingleNameReference(str.token, 0); castToConverted.bits = (castToConverted.bits & ~Binding.VARIABLE) | Binding.TYPE; castToConverted.sourceStart = str.sourceStart; castToConverted.sourceEnd = str.sourceEnd; - Eclipse.setGeneratedBy(castToConverted, source); + setGeneratedBy(castToConverted, source); } else if (castTo.getClass() == QualifiedTypeReference.class) { QualifiedTypeReference qtr = (QualifiedTypeReference) castTo; //Same here, but for the more complex types, they stay types. castToConverted = new QualifiedNameReference(qtr.tokens, qtr.sourcePositions, qtr.sourceStart, qtr.sourceEnd); castToConverted.bits = (castToConverted.bits & ~Binding.VARIABLE) | Binding.TYPE; - Eclipse.setGeneratedBy(castToConverted, source); + setGeneratedBy(castToConverted, source); } result = castExpressionConstructor.newInstance(ref, castToConverted); @@ -649,11 +1211,10 @@ public class EclipseHandlerUtil { throw Lombok.sneakyThrow(e); } - Eclipse.setGeneratedBy(result, source); + setGeneratedBy(result, source); return result; } - private static final String PRIMITIVE_NAMES = " int long float double char short byte boolean "; private static final Constructor<CastExpression> castExpressionConstructor; private static final boolean castExpressionConstructorIsTypeRefBased; @@ -693,7 +1254,7 @@ public class EclipseHandlerUtil { } catch (InstantiationException e) { throw Lombok.sneakyThrow(e); } - Eclipse.setGeneratedBy(result, source); + setGeneratedBy(result, source); return result; } @@ -764,8 +1325,8 @@ public class EclipseHandlerUtil { QualifiedNameReference nameReference = new QualifiedNameReference(nameTokens, pos, pS, pE); nameReference.statementEnd = pE; - - Eclipse.setGeneratedBy(nameReference, source); + + setGeneratedBy(nameReference, source); return nameReference; } } diff --git a/src/core/lombok/eclipse/handlers/HandleCleanup.java b/src/core/lombok/eclipse/handlers/HandleCleanup.java index e17d3d3e..500e744e 100644 --- a/src/core/lombok/eclipse/handlers/HandleCleanup.java +++ b/src/core/lombok/eclipse/handlers/HandleCleanup.java @@ -21,15 +21,13 @@ */ package lombok.eclipse.handlers; -import static lombok.eclipse.handlers.EclipseHandlerUtil.createNameReference; -import static lombok.eclipse.handlers.EclipseHandlerUtil.makeIntLiteral; +import static lombok.eclipse.handlers.EclipseHandlerUtil.*; import java.util.Arrays; import lombok.Cleanup; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; -import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; @@ -143,10 +141,10 @@ public class HandleCleanup extends EclipseAnnotationHandler<Cleanup> { doAssignmentCheck(annotationNode, tryBlock, decl.name); TryStatement tryStatement = new TryStatement(); - Eclipse.setGeneratedBy(tryStatement, ast); + setGeneratedBy(tryStatement, ast); tryStatement.tryBlock = new Block(0); tryStatement.tryBlock.statements = tryBlock; - Eclipse.setGeneratedBy(tryStatement.tryBlock, ast); + setGeneratedBy(tryStatement.tryBlock, ast); // Positions for in-method generated nodes are special int ss = decl.declarationSourceEnd + 1; @@ -164,11 +162,11 @@ public class HandleCleanup extends EclipseAnnotationHandler<Cleanup> { Statement[] finallyBlock = new Statement[1]; MessageSend unsafeClose = new MessageSend(); - Eclipse.setGeneratedBy(unsafeClose, ast); + setGeneratedBy(unsafeClose, ast); unsafeClose.sourceStart = ast.sourceStart; unsafeClose.sourceEnd = ast.sourceEnd; SingleNameReference receiver = new SingleNameReference(decl.name, 0); - Eclipse.setGeneratedBy(receiver, ast); + setGeneratedBy(receiver, ast); unsafeClose.receiver = receiver; long nameSourcePosition = (long)ast.sourceStart << 32 | ast.sourceEnd; if (ast.memberValuePairs() != null) for (MemberValuePair pair : ast.memberValuePairs()) { @@ -185,22 +183,22 @@ public class HandleCleanup extends EclipseAnnotationHandler<Cleanup> { long p = (long)pS << 32 | pE; SingleNameReference varName = new SingleNameReference(decl.name, p); - Eclipse.setGeneratedBy(varName, ast); + setGeneratedBy(varName, ast); NullLiteral nullLiteral = new NullLiteral(pS, pE); - Eclipse.setGeneratedBy(nullLiteral, ast); + setGeneratedBy(nullLiteral, ast); MessageSend preventNullAnalysis = preventNullAnalysis(ast, varName); EqualExpression equalExpression = new EqualExpression(preventNullAnalysis, nullLiteral, OperatorIds.NOT_EQUAL); equalExpression.sourceStart = pS; equalExpression.sourceEnd = pE; - Eclipse.setGeneratedBy(equalExpression, ast); + setGeneratedBy(equalExpression, ast); Block closeBlock = new Block(0); closeBlock.statements = new Statement[1]; closeBlock.statements[0] = unsafeClose; - Eclipse.setGeneratedBy(closeBlock, ast); + setGeneratedBy(closeBlock, ast); IfStatement ifStatement = new IfStatement(equalExpression, closeBlock, 0, 0); - Eclipse.setGeneratedBy(ifStatement, ast); + setGeneratedBy(ifStatement, ast); finallyBlock[0] = ifStatement; tryStatement.finallyBlock = new Block(0); @@ -210,7 +208,7 @@ public class HandleCleanup extends EclipseAnnotationHandler<Cleanup> { tryStatement.finallyBlock.sourceStart = blockNode.sourceEnd; tryStatement.finallyBlock.sourceEnd = blockNode.sourceEnd; } - Eclipse.setGeneratedBy(tryStatement.finallyBlock, ast); + setGeneratedBy(tryStatement.finallyBlock, ast); tryStatement.finallyBlock.statements = finallyBlock; tryStatement.catchArguments = null; @@ -229,7 +227,7 @@ public class HandleCleanup extends EclipseAnnotationHandler<Cleanup> { private MessageSend preventNullAnalysis(Annotation ast, Expression expr) { MessageSend singletonList = new MessageSend(); - Eclipse.setGeneratedBy(singletonList, ast); + setGeneratedBy(singletonList, ast); int pS = ast.sourceStart, pE = ast.sourceEnd; long p = (long)pS << 32 | pE; @@ -243,7 +241,7 @@ public class HandleCleanup extends EclipseAnnotationHandler<Cleanup> { singletonList.sourceEnd = singletonList.statementEnd = pE; MessageSend preventNullAnalysis = new MessageSend(); - Eclipse.setGeneratedBy(preventNullAnalysis, ast); + setGeneratedBy(preventNullAnalysis, ast); preventNullAnalysis.receiver = singletonList; preventNullAnalysis.selector = "get".toCharArray(); diff --git a/src/core/lombok/eclipse/handlers/HandleConstructor.java b/src/core/lombok/eclipse/handlers/HandleConstructor.java index 6aca4ccc..45815465 100644 --- a/src/core/lombok/eclipse/handlers/HandleConstructor.java +++ b/src/core/lombok/eclipse/handlers/HandleConstructor.java @@ -36,11 +36,9 @@ import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; -import lombok.core.handlers.TransformationsUtil; -import lombok.eclipse.Eclipse; +import lombok.core.TransformationsUtil; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; -import lombok.eclipse.handlers.EclipseHandlerUtil.MemberExistsResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; @@ -105,7 +103,7 @@ public class HandleConstructor { for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); - if (!EclipseHandlerUtil.filterField(fieldDecl)) continue; + if (!filterField(fieldDecl)) continue; boolean isFinal = (fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0; boolean isNonNull = findAnnotations(fieldDecl, TransformationsUtil.NON_NULL_PATTERN).length != 0; if ((isFinal || isNonNull) && fieldDecl.initialization == null) fields.add(child); @@ -128,7 +126,7 @@ public class HandleConstructor { for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); - if (!EclipseHandlerUtil.filterField(fieldDecl)) continue; + if (!filterField(fieldDecl)) continue; // Skip initialized final fields. if (((fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0) && fieldDecl.initialization != null) continue; @@ -162,9 +160,9 @@ public class HandleConstructor { if (skipIfConstructorExists) { for (EclipseNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Eclipse.annotationTypeMatches(NoArgsConstructor.class, child) || - Eclipse.annotationTypeMatches(AllArgsConstructor.class, child) || - Eclipse.annotationTypeMatches(RequiredArgsConstructor.class, child)) + if (annotationTypeMatches(NoArgsConstructor.class, child) || + annotationTypeMatches(AllArgsConstructor.class, child) || + annotationTypeMatches(RequiredArgsConstructor.class, child)) return; } } @@ -189,7 +187,7 @@ public class HandleConstructor { long[] poss = new long[3]; Arrays.fill(poss, p); QualifiedTypeReference constructorPropertiesType = new QualifiedTypeReference(JAVA_BEANS_CONSTRUCTORPROPERTIES, poss); - Eclipse.setGeneratedBy(constructorPropertiesType, source); + setGeneratedBy(constructorPropertiesType, source); SingleMemberAnnotation ann = new SingleMemberAnnotation(constructorPropertiesType, pS); ann.declarationSourceEnd = pE; @@ -201,13 +199,13 @@ public class HandleConstructor { int ctr = 0; for (EclipseNode field : fields) { fieldNames.expressions[ctr] = new StringLiteral(field.getName().toCharArray(), pS, pE, 0); - Eclipse.setGeneratedBy(fieldNames.expressions[ctr], source); + setGeneratedBy(fieldNames.expressions[ctr], source); ctr++; } ann.memberValue = fieldNames; - Eclipse.setGeneratedBy(ann, source); - Eclipse.setGeneratedBy(ann.memberValue, source); + setGeneratedBy(ann, source); + setGeneratedBy(ann.memberValue, source); if (originalAnnotationArray == null) return new Annotation[] { ann }; Annotation[] newAnnotationArray = Arrays.copyOf(originalAnnotationArray, originalAnnotationArray.length + 1); newAnnotationArray[originalAnnotationArray.length] = ann; @@ -224,15 +222,15 @@ public class HandleConstructor { ConstructorDeclaration constructor = new ConstructorDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); - Eclipse.setGeneratedBy(constructor, source); + setGeneratedBy(constructor, source); - constructor.modifiers = EclipseHandlerUtil.toEclipseModifier(level); + constructor.modifiers = toEclipseModifier(level); constructor.selector = ((TypeDeclaration)type.get()).name; constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); - Eclipse.setGeneratedBy(constructor.constructorCall, source); + setGeneratedBy(constructor.constructorCall, source); constructor.thrownExceptions = null; constructor.typeParameters = null; - constructor.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; + constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart; constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd; constructor.arguments = null; @@ -244,18 +242,18 @@ public class HandleConstructor { for (EclipseNode fieldNode : fields) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); FieldReference thisX = new FieldReference(field.name, p); - Eclipse.setGeneratedBy(thisX, source); + setGeneratedBy(thisX, source); thisX.receiver = new ThisReference((int)(p >> 32), (int)p); - Eclipse.setGeneratedBy(thisX.receiver, source); + setGeneratedBy(thisX.receiver, source); SingleNameReference assignmentNameRef = new SingleNameReference(field.name, p); - Eclipse.setGeneratedBy(assignmentNameRef, source); + setGeneratedBy(assignmentNameRef, source); Assignment assignment = new Assignment(thisX, assignmentNameRef, (int)p); - Eclipse.setGeneratedBy(assignment, source); + setGeneratedBy(assignment, source); assigns.add(assignment); long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd; Argument parameter = new Argument(field.name, fieldPos, copyType(field.type, source), Modifier.FINAL); - Eclipse.setGeneratedBy(parameter, source); + setGeneratedBy(parameter, source); Annotation[] nonNulls = findAnnotations(field, TransformationsUtil.NON_NULL_PATTERN); Annotation[] nullables = findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN); if (nonNulls.length != 0) { @@ -291,26 +289,26 @@ public class HandleConstructor { MethodDeclaration constructor = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); - Eclipse.setGeneratedBy(constructor, source); + setGeneratedBy(constructor, source); - constructor.modifiers = EclipseHandlerUtil.toEclipseModifier(level) | Modifier.STATIC; + constructor.modifiers = toEclipseModifier(level) | Modifier.STATIC; TypeDeclaration typeDecl = (TypeDeclaration) type.get(); if (typeDecl.typeParameters != null && typeDecl.typeParameters.length > 0) { TypeReference[] refs = new TypeReference[typeDecl.typeParameters.length]; int idx = 0; for (TypeParameter param : typeDecl.typeParameters) { TypeReference typeRef = new SingleTypeReference(param.name, (long)param.sourceStart << 32 | param.sourceEnd); - Eclipse.setGeneratedBy(typeRef, source); + setGeneratedBy(typeRef, source); refs[idx++] = typeRef; } constructor.returnType = new ParameterizedSingleTypeReference(typeDecl.name, refs, 0, p); } else constructor.returnType = new SingleTypeReference(((TypeDeclaration)type.get()).name, p); - Eclipse.setGeneratedBy(constructor.returnType, source); + setGeneratedBy(constructor.returnType, source); constructor.annotations = null; constructor.selector = name.toCharArray(); constructor.thrownExceptions = null; constructor.typeParameters = copyTypeParams(((TypeDeclaration)type.get()).typeParameters, source); - constructor.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; + constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart; constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd; @@ -318,18 +316,18 @@ public class HandleConstructor { List<Expression> assigns = new ArrayList<Expression>(); AllocationExpression statement = new AllocationExpression(); statement.sourceStart = pS; statement.sourceEnd = pE; - Eclipse.setGeneratedBy(statement, source); + setGeneratedBy(statement, source); statement.type = copyType(constructor.returnType, source); for (EclipseNode fieldNode : fields) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd; SingleNameReference nameRef = new SingleNameReference(field.name, fieldPos); - Eclipse.setGeneratedBy(nameRef, source); + setGeneratedBy(nameRef, source); assigns.add(nameRef); Argument parameter = new Argument(field.name, fieldPos, copyType(field.type, source), Modifier.FINAL); - Eclipse.setGeneratedBy(parameter, source); + setGeneratedBy(parameter, source); Annotation[] copiedAnnotations = copyAnnotations(source, findAnnotations(field, TransformationsUtil.NON_NULL_PATTERN), findAnnotations(field, TransformationsUtil.NULLABLE_PATTERN)); if (copiedAnnotations.length != 0) parameter.annotations = copiedAnnotations; @@ -339,7 +337,7 @@ public class HandleConstructor { statement.arguments = assigns.isEmpty() ? null : assigns.toArray(new Expression[assigns.size()]); constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]); constructor.statements = new Statement[] { new ReturnStatement(statement, (int)(p >> 32), (int)p) }; - Eclipse.setGeneratedBy(constructor.statements[0], source); + setGeneratedBy(constructor.statements[0], source); return constructor; } } diff --git a/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java b/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java index bbb1d56b..a4989b4c 100644 --- a/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java +++ b/src/core/lombok/eclipse/handlers/HandleEqualsAndHashCode.java @@ -23,8 +23,6 @@ package lombok.eclipse.handlers; import static lombok.eclipse.handlers.EclipseHandlerUtil.*; -import static lombok.eclipse.Eclipse.copyTypes; - import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; @@ -106,7 +104,7 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH public void generateEqualsAndHashCodeForType(EclipseNode typeNode, EclipseNode errorNode) { for (EclipseNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Eclipse.annotationTypeMatches(EqualsAndHashCode.class, child)) { + if (annotationTypeMatches(EqualsAndHashCode.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -193,7 +191,7 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); - if (!EclipseHandlerUtil.filterField(fieldDecl)) continue; + if (!filterField(fieldDecl)) continue; //Skip transient fields. if ((fieldDecl.modifiers & ClassFileConstants.AccTransient) != 0) continue; @@ -241,11 +239,11 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH MethodDeclaration method = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); - Eclipse.setGeneratedBy(method, source); + setGeneratedBy(method, source); - method.modifiers = EclipseHandlerUtil.toEclipseModifier(AccessLevel.PUBLIC); + method.modifiers = toEclipseModifier(AccessLevel.PUBLIC); method.returnType = TypeReference.baseTypeReference(TypeIds.T_int, 0); - Eclipse.setGeneratedBy(method.returnType, source); + setGeneratedBy(method.returnType, source); method.annotations = new Annotation[] {makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source)}; method.selector = "hashCode".toCharArray(); method.thrownExceptions = null; @@ -266,11 +264,11 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH /* Without fields, PRIME isn't used, and that would trigger a 'local variable not used' warning. */ if (!isEmpty || callSuper) { LocalDeclaration primeDecl = new LocalDeclaration(PRIME, pS, pE); - Eclipse.setGeneratedBy(primeDecl, source); + setGeneratedBy(primeDecl, source); primeDecl.modifiers |= Modifier.FINAL; primeDecl.type = TypeReference.baseTypeReference(TypeIds.T_int, 0); primeDecl.type.sourceStart = pS; primeDecl.type.sourceEnd = pE; - Eclipse.setGeneratedBy(primeDecl.type, source); + setGeneratedBy(primeDecl.type, source); primeDecl.initialization = makeIntLiteral("31".toCharArray(), source); statements.add(primeDecl); } @@ -278,20 +276,20 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH /* int result = 1; */ { LocalDeclaration resultDecl = new LocalDeclaration(RESULT, pS, pE); - Eclipse.setGeneratedBy(resultDecl, source); + setGeneratedBy(resultDecl, source); resultDecl.initialization = makeIntLiteral("1".toCharArray(), source); resultDecl.type = TypeReference.baseTypeReference(TypeIds.T_int, 0); resultDecl.type.sourceStart = pS; resultDecl.type.sourceEnd = pE; - Eclipse.setGeneratedBy(resultDecl.type, source); + setGeneratedBy(resultDecl.type, source); statements.add(resultDecl); } if (callSuper) { MessageSend callToSuper = new MessageSend(); - Eclipse.setGeneratedBy(callToSuper, source); + setGeneratedBy(callToSuper, source); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; callToSuper.receiver = new SuperReference(pS, pE); - Eclipse.setGeneratedBy(callToSuper.receiver, source); + setGeneratedBy(callToSuper.receiver, source); callToSuper.selector = "hashCode".toCharArray(); intoResult.add(callToSuper); } @@ -306,7 +304,7 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH /* Float.floatToIntBits(fieldName) */ MessageSend floatToIntBits = new MessageSend(); floatToIntBits.sourceStart = pS; floatToIntBits.sourceEnd = pE; - Eclipse.setGeneratedBy(floatToIntBits, source); + setGeneratedBy(floatToIntBits, source); floatToIntBits.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA_LANG_FLOAT); floatToIntBits.selector = "floatToIntBits".toCharArray(); floatToIntBits.arguments = new Expression[] { fieldAccessor }; @@ -315,30 +313,30 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH /* longToIntForHashCode(Double.doubleToLongBits(fieldName)) */ MessageSend doubleToLongBits = new MessageSend(); doubleToLongBits.sourceStart = pS; doubleToLongBits.sourceEnd = pE; - Eclipse.setGeneratedBy(doubleToLongBits, source); + setGeneratedBy(doubleToLongBits, source); doubleToLongBits.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA_LANG_DOUBLE); doubleToLongBits.selector = "doubleToLongBits".toCharArray(); doubleToLongBits.arguments = new Expression[] { fieldAccessor }; final char[] tempName = ("temp" + ++tempCounter).toCharArray(); LocalDeclaration tempVar = new LocalDeclaration(tempName, pS, pE); - Eclipse.setGeneratedBy(tempVar, source); + setGeneratedBy(tempVar, source); tempVar.initialization = doubleToLongBits; tempVar.type = TypeReference.baseTypeReference(TypeIds.T_long, 0); tempVar.type.sourceStart = pS; tempVar.type.sourceEnd = pE; - Eclipse.setGeneratedBy(tempVar.type, source); + setGeneratedBy(tempVar.type, source); tempVar.modifiers = Modifier.FINAL; statements.add(tempVar); SingleNameReference copy1 = new SingleNameReference(tempName, p); - Eclipse.setGeneratedBy(copy1, source); + setGeneratedBy(copy1, source); SingleNameReference copy2 = new SingleNameReference(tempName, p); - Eclipse.setGeneratedBy(copy2, source); + setGeneratedBy(copy2, source); intoResult.add(longToIntForHashCode(copy1, copy2, source)); } else if (Arrays.equals(TypeConstants.BOOLEAN, token)) { /* booleanField ? 1231 : 1237 */ IntLiteral int1231 = makeIntLiteral("1231".toCharArray(), source); IntLiteral int1237 = makeIntLiteral("1237".toCharArray(), source); ConditionalExpression int1231or1237 = new ConditionalExpression(fieldAccessor, int1231, int1237); - Eclipse.setGeneratedBy(int1231or1237, source); + setGeneratedBy(int1231or1237, source); intoResult.add(int1231or1237); } else if (Arrays.equals(TypeConstants.LONG, token)) { intoResult.add(longToIntForHashCode(fieldAccessor, createFieldAccessor(field, fieldAccess, source), source)); @@ -348,24 +346,24 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH /* this.fieldName == null ? 0 : this.fieldName.hashCode() */ MessageSend hashCodeCall = new MessageSend(); hashCodeCall.sourceStart = pS; hashCodeCall.sourceEnd = pE; - Eclipse.setGeneratedBy(hashCodeCall, source); + setGeneratedBy(hashCodeCall, source); hashCodeCall.receiver = createFieldAccessor(field, fieldAccess, source); hashCodeCall.selector = "hashCode".toCharArray(); NullLiteral nullLiteral = new NullLiteral(pS, pE); - Eclipse.setGeneratedBy(nullLiteral, source); + setGeneratedBy(nullLiteral, source); EqualExpression objIsNull = new EqualExpression(fieldAccessor, nullLiteral, OperatorIds.EQUAL_EQUAL); - Eclipse.setGeneratedBy(objIsNull, source); + setGeneratedBy(objIsNull, source); IntLiteral int0 = makeIntLiteral("0".toCharArray(), source); ConditionalExpression nullOrHashCode = new ConditionalExpression(objIsNull, int0, hashCodeCall); nullOrHashCode.sourceStart = pS; nullOrHashCode.sourceEnd = pE; - Eclipse.setGeneratedBy(nullOrHashCode, source); + setGeneratedBy(nullOrHashCode, source); intoResult.add(nullOrHashCode); } } else if (fType.dimensions() > 0 && token != null) { /* Arrays.deepHashCode(array) //just hashCode for simple arrays */ MessageSend arraysHashCodeCall = new MessageSend(); arraysHashCodeCall.sourceStart = pS; arraysHashCodeCall.sourceEnd = pE; - Eclipse.setGeneratedBy(arraysHashCodeCall, source); + setGeneratedBy(arraysHashCodeCall, source); arraysHashCodeCall.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); if (fType.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token))) { arraysHashCodeCall.selector = "deepHashCode".toCharArray(); @@ -381,29 +379,29 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH result = result * PRIME + (item); */ { for (Expression ex : intoResult) { SingleNameReference resultRef = new SingleNameReference(RESULT, p); - Eclipse.setGeneratedBy(resultRef, source); + setGeneratedBy(resultRef, source); SingleNameReference primeRef = new SingleNameReference(PRIME, p); - Eclipse.setGeneratedBy(primeRef, source); + setGeneratedBy(primeRef, source); BinaryExpression multiplyByPrime = new BinaryExpression(resultRef, primeRef, OperatorIds.MULTIPLY); multiplyByPrime.sourceStart = pS; multiplyByPrime.sourceEnd = pE; - Eclipse.setGeneratedBy(multiplyByPrime, source); + setGeneratedBy(multiplyByPrime, source); BinaryExpression addItem = new BinaryExpression(multiplyByPrime, ex, OperatorIds.PLUS); addItem.sourceStart = pS; addItem.sourceEnd = pE; - Eclipse.setGeneratedBy(addItem, source); + setGeneratedBy(addItem, source); resultRef = new SingleNameReference(RESULT, p); - Eclipse.setGeneratedBy(resultRef, source); + setGeneratedBy(resultRef, source); Assignment assignment = new Assignment(resultRef, addItem, pE); assignment.sourceStart = pS; assignment.sourceEnd = pE; - Eclipse.setGeneratedBy(assignment, source); + setGeneratedBy(assignment, source); statements.add(assignment); } } /* return result; */ { SingleNameReference resultRef = new SingleNameReference(RESULT, p); - Eclipse.setGeneratedBy(resultRef, source); + setGeneratedBy(resultRef, source); ReturnStatement returnStatement = new ReturnStatement(resultRef, pS, pE); - Eclipse.setGeneratedBy(returnStatement, source); + setGeneratedBy(returnStatement, source); statements.add(returnStatement); } method.statements = statements.toArray(new Statement[statements.size()]); @@ -417,11 +415,11 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH MethodDeclaration method = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); - Eclipse.setGeneratedBy(method, source); - method.modifiers = EclipseHandlerUtil.toEclipseModifier(AccessLevel.PUBLIC); + setGeneratedBy(method, source); + method.modifiers = toEclipseModifier(AccessLevel.PUBLIC); method.returnType = TypeReference.baseTypeReference(TypeIds.T_boolean, 0); method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; - Eclipse.setGeneratedBy(method.returnType, source); + setGeneratedBy(method.returnType, source); method.annotations = new Annotation[] {makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source)}; method.selector = "equals".toCharArray(); method.thrownExceptions = null; @@ -430,52 +428,52 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; TypeReference objectRef = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { p, p, p }); - Eclipse.setGeneratedBy(objectRef, source); + setGeneratedBy(objectRef, source); method.arguments = new Argument[] {new Argument(new char[] { 'o' }, 0, objectRef, Modifier.FINAL)}; method.arguments[0].sourceStart = pS; method.arguments[0].sourceEnd = pE; - Eclipse.setGeneratedBy(method.arguments[0], source); + setGeneratedBy(method.arguments[0], source); List<Statement> statements = new ArrayList<Statement>(); /* if (o == this) return true; */ { SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p); - Eclipse.setGeneratedBy(oRef, source); + setGeneratedBy(oRef, source); ThisReference thisRef = new ThisReference(pS, pE); - Eclipse.setGeneratedBy(thisRef, source); + setGeneratedBy(thisRef, source); EqualExpression otherEqualsThis = new EqualExpression(oRef, thisRef, OperatorIds.EQUAL_EQUAL); - Eclipse.setGeneratedBy(otherEqualsThis, source); + setGeneratedBy(otherEqualsThis, source); TrueLiteral trueLiteral = new TrueLiteral(pS, pE); - Eclipse.setGeneratedBy(trueLiteral, source); + setGeneratedBy(trueLiteral, source); ReturnStatement returnTrue = new ReturnStatement(trueLiteral, pS, pE); - Eclipse.setGeneratedBy(returnTrue, source); + setGeneratedBy(returnTrue, source); IfStatement ifOtherEqualsThis = new IfStatement(otherEqualsThis, returnTrue, pS, pE); - Eclipse.setGeneratedBy(ifOtherEqualsThis, source); + setGeneratedBy(ifOtherEqualsThis, source); statements.add(ifOtherEqualsThis); } /* if (!(o instanceof MyType) return false; */ { SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p); - Eclipse.setGeneratedBy(oRef, source); + setGeneratedBy(oRef, source); SingleTypeReference typeReference = new SingleTypeReference(typeDecl.name, p); - Eclipse.setGeneratedBy(typeReference, source); + setGeneratedBy(typeReference, source); InstanceOfExpression instanceOf = new InstanceOfExpression(oRef, typeReference); instanceOf.sourceStart = pS; instanceOf.sourceEnd = pE; - Eclipse.setGeneratedBy(instanceOf, source); + setGeneratedBy(instanceOf, source); Expression notInstanceOf = new UnaryExpression(instanceOf, OperatorIds.NOT); - Eclipse.setGeneratedBy(notInstanceOf, source); + setGeneratedBy(notInstanceOf, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); - Eclipse.setGeneratedBy(falseLiteral, source); + setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); - Eclipse.setGeneratedBy(returnFalse, source); + setGeneratedBy(returnFalse, source); IfStatement ifNotInstanceOf = new IfStatement(notInstanceOf, returnFalse, pS, pE); - Eclipse.setGeneratedBy(ifNotInstanceOf, source); + setGeneratedBy(ifNotInstanceOf, source); statements.add(ifNotInstanceOf); } @@ -485,29 +483,29 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH if (!fields.isEmpty() || needsCanEqual) { LocalDeclaration other = new LocalDeclaration(otherName, pS, pE); other.modifiers |= ClassFileConstants.AccFinal; - Eclipse.setGeneratedBy(other, source); + setGeneratedBy(other, source); char[] typeName = typeDecl.name; TypeReference targetType; if (typeDecl.typeParameters == null || typeDecl.typeParameters.length == 0) { targetType = new SingleTypeReference(typeName, p); - Eclipse.setGeneratedBy(targetType, source); + setGeneratedBy(targetType, source); other.type = new SingleTypeReference(typeName, p); - Eclipse.setGeneratedBy(other.type, source); + setGeneratedBy(other.type, source); } else { TypeReference[] typeArgs = new TypeReference[typeDecl.typeParameters.length]; for (int i = 0; i < typeArgs.length; i++) { typeArgs[i] = new Wildcard(Wildcard.UNBOUND); typeArgs[i].sourceStart = pS; typeArgs[i].sourceEnd = pE; - Eclipse.setGeneratedBy(typeArgs[i], source); + setGeneratedBy(typeArgs[i], source); } targetType = new ParameterizedSingleTypeReference(typeName, typeArgs, 0, p); - Eclipse.setGeneratedBy(targetType, source); + setGeneratedBy(targetType, source); other.type = new ParameterizedSingleTypeReference(typeName, copyTypes(typeArgs, source), 0, p); - Eclipse.setGeneratedBy(other.type, source); + setGeneratedBy(other.type, source); } NameReference oRef = new SingleNameReference(new char[] { 'o' }, p); - Eclipse.setGeneratedBy(oRef, source); - other.initialization = EclipseHandlerUtil.makeCastExpression(oRef, targetType, source); + setGeneratedBy(oRef, source); + other.initialization = makeCastExpression(oRef, targetType, source); statements.add(other); } } @@ -516,29 +514,29 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH if (needsCanEqual) { MessageSend otherCanEqual = new MessageSend(); otherCanEqual.sourceStart = pS; otherCanEqual.sourceEnd = pE; - Eclipse.setGeneratedBy(otherCanEqual, source); + setGeneratedBy(otherCanEqual, source); otherCanEqual.receiver = new SingleNameReference(otherName, p); - Eclipse.setGeneratedBy(otherCanEqual.receiver, source); + setGeneratedBy(otherCanEqual.receiver, source); otherCanEqual.selector = "canEqual".toCharArray(); ThisReference thisReference = new ThisReference(pS, pE); - Eclipse.setGeneratedBy(thisReference, source); - CastExpression castThisRef = EclipseHandlerUtil.makeCastExpression(thisReference, generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), source); + setGeneratedBy(thisReference, source); + CastExpression castThisRef = makeCastExpression(thisReference, generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), source); castThisRef.sourceStart = pS; castThisRef.sourceEnd = pE; otherCanEqual.arguments = new Expression[] {castThisRef}; Expression notOtherCanEqual = new UnaryExpression(otherCanEqual, OperatorIds.NOT); - Eclipse.setGeneratedBy(notOtherCanEqual, source); + setGeneratedBy(notOtherCanEqual, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); - Eclipse.setGeneratedBy(falseLiteral, source); + setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); - Eclipse.setGeneratedBy(returnFalse, source); + setGeneratedBy(returnFalse, source); IfStatement ifNotCanEqual = new IfStatement(notOtherCanEqual, returnFalse, pS, pE); - Eclipse.setGeneratedBy(ifNotCanEqual, source); + setGeneratedBy(ifNotCanEqual, source); statements.add(ifNotCanEqual); } @@ -548,21 +546,21 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH if (callSuper) { MessageSend callToSuper = new MessageSend(); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; - Eclipse.setGeneratedBy(callToSuper, source); + setGeneratedBy(callToSuper, source); callToSuper.receiver = new SuperReference(pS, pE); - Eclipse.setGeneratedBy(callToSuper.receiver, source); + setGeneratedBy(callToSuper.receiver, source); callToSuper.selector = "equals".toCharArray(); SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p); - Eclipse.setGeneratedBy(oRef, source); + setGeneratedBy(oRef, source); callToSuper.arguments = new Expression[] {oRef}; Expression superNotEqual = new UnaryExpression(callToSuper, OperatorIds.NOT); - Eclipse.setGeneratedBy(superNotEqual, source); + setGeneratedBy(superNotEqual, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); - Eclipse.setGeneratedBy(falseLiteral, source); + setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); - Eclipse.setGeneratedBy(returnFalse, source); + setGeneratedBy(returnFalse, source); IfStatement ifSuperEquals = new IfStatement(superNotEqual, returnFalse, pS, pE); - Eclipse.setGeneratedBy(ifSuperEquals, source); + setGeneratedBy(ifSuperEquals, source); statements.add(ifSuperEquals); } @@ -579,48 +577,48 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH statements.add(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor, "Double".toCharArray(), source)); } else if (BUILT_IN_TYPES.contains(new String(token))) { EqualExpression fieldsNotEqual = new EqualExpression(thisFieldAccessor, otherFieldAccessor, OperatorIds.NOT_EQUAL); - Eclipse.setGeneratedBy(fieldsNotEqual, source); + setGeneratedBy(fieldsNotEqual, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); - Eclipse.setGeneratedBy(falseLiteral, source); + setGeneratedBy(falseLiteral, source); ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE); - Eclipse.setGeneratedBy(returnStatement, source); + setGeneratedBy(returnStatement, source); IfStatement ifStatement = new IfStatement(fieldsNotEqual, returnStatement, pS, pE); - Eclipse.setGeneratedBy(ifStatement, source); + setGeneratedBy(ifStatement, source); statements.add(ifStatement); } else /* objects */ { NullLiteral nullLiteral = new NullLiteral(pS, pE); - Eclipse.setGeneratedBy(nullLiteral, source); + setGeneratedBy(nullLiteral, source); EqualExpression fieldIsNull = new EqualExpression(thisFieldAccessor, nullLiteral, OperatorIds.EQUAL_EQUAL); nullLiteral = new NullLiteral(pS, pE); - Eclipse.setGeneratedBy(nullLiteral, source); + setGeneratedBy(nullLiteral, source); EqualExpression otherFieldIsntNull = new EqualExpression(otherFieldAccessor, nullLiteral, OperatorIds.NOT_EQUAL); MessageSend equalsCall = new MessageSend(); equalsCall.sourceStart = pS; equalsCall.sourceEnd = pE; - Eclipse.setGeneratedBy(equalsCall, source); + setGeneratedBy(equalsCall, source); equalsCall.receiver = createFieldAccessor(field, fieldAccess, source); equalsCall.selector = "equals".toCharArray(); Expression equalsArg = createFieldAccessor(field, fieldAccess, source, otherName); - CastExpression castEqualsArg = EclipseHandlerUtil.makeCastExpression(equalsArg, generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), source); + CastExpression castEqualsArg = makeCastExpression(equalsArg, generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), source); castEqualsArg.sourceStart = pS; castEqualsArg.sourceEnd = pE; equalsCall.arguments = new Expression[] { castEqualsArg }; UnaryExpression fieldsNotEqual = new UnaryExpression(equalsCall, OperatorIds.NOT); fieldsNotEqual.sourceStart = pS; fieldsNotEqual.sourceEnd = pE; - Eclipse.setGeneratedBy(fieldsNotEqual, source); + setGeneratedBy(fieldsNotEqual, source); ConditionalExpression fullEquals = new ConditionalExpression(fieldIsNull, otherFieldIsntNull, fieldsNotEqual); fullEquals.sourceStart = pS; fullEquals.sourceEnd = pE; - Eclipse.setGeneratedBy(fullEquals, source); + setGeneratedBy(fullEquals, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); - Eclipse.setGeneratedBy(falseLiteral, source); + setGeneratedBy(falseLiteral, source); ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE); - Eclipse.setGeneratedBy(returnStatement, source); + setGeneratedBy(returnStatement, source); IfStatement ifStatement = new IfStatement(fullEquals, returnStatement, pS, pE); - Eclipse.setGeneratedBy(ifStatement, source); + setGeneratedBy(ifStatement, source); statements.add(ifStatement); } } else if (fType.dimensions() > 0 && token != null) { MessageSend arraysEqualCall = new MessageSend(); arraysEqualCall.sourceStart = pS; arraysEqualCall.sourceEnd = pE; - Eclipse.setGeneratedBy(arraysEqualCall, source); + setGeneratedBy(arraysEqualCall, source); arraysEqualCall.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); if (fType.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token))) { arraysEqualCall.selector = "deepEquals".toCharArray(); @@ -630,22 +628,22 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH arraysEqualCall.arguments = new Expression[] { thisFieldAccessor, otherFieldAccessor }; UnaryExpression arraysNotEqual = new UnaryExpression(arraysEqualCall, OperatorIds.NOT); arraysNotEqual.sourceStart = pS; arraysNotEqual.sourceEnd = pE; - Eclipse.setGeneratedBy(arraysNotEqual, source); + setGeneratedBy(arraysNotEqual, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); - Eclipse.setGeneratedBy(falseLiteral, source); + setGeneratedBy(falseLiteral, source); ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE); - Eclipse.setGeneratedBy(returnStatement, source); + setGeneratedBy(returnStatement, source); IfStatement ifStatement = new IfStatement(arraysNotEqual, returnStatement, pS, pE); - Eclipse.setGeneratedBy(ifStatement, source); + setGeneratedBy(ifStatement, source); statements.add(ifStatement); } } /* return true; */ { TrueLiteral trueLiteral = new TrueLiteral(pS, pE); - Eclipse.setGeneratedBy(trueLiteral, source); + setGeneratedBy(trueLiteral, source); ReturnStatement returnStatement = new ReturnStatement(trueLiteral, pS, pE); - Eclipse.setGeneratedBy(returnStatement, source); + setGeneratedBy(returnStatement, source); statements.add(returnStatement); } method.statements = statements.toArray(new Statement[statements.size()]); @@ -665,11 +663,11 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH MethodDeclaration method = new MethodDeclaration( ((CompilationUnitDeclaration) type.top().get()).compilationResult); - Eclipse.setGeneratedBy(method, source); - method.modifiers = EclipseHandlerUtil.toEclipseModifier(AccessLevel.PUBLIC); + setGeneratedBy(method, source); + method.modifiers = toEclipseModifier(AccessLevel.PUBLIC); method.returnType = TypeReference.baseTypeReference(TypeIds.T_boolean, 0); method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; - Eclipse.setGeneratedBy(method.returnType, source); + setGeneratedBy(method.returnType, source); method.selector = "canEqual".toCharArray(); method.thrownExceptions = null; method.typeParameters = null; @@ -677,23 +675,23 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; TypeReference objectRef = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { p, p, p }); - Eclipse.setGeneratedBy(objectRef, source); + setGeneratedBy(objectRef, source); method.arguments = new Argument[] {new Argument(otherName, 0, objectRef, Modifier.FINAL)}; method.arguments[0].sourceStart = pS; method.arguments[0].sourceEnd = pE; - Eclipse.setGeneratedBy(method.arguments[0], source); + setGeneratedBy(method.arguments[0], source); SingleNameReference otherRef = new SingleNameReference(otherName, p); - Eclipse.setGeneratedBy(otherRef, source); + setGeneratedBy(otherRef, source); SingleTypeReference typeReference = new SingleTypeReference(((TypeDeclaration)type.get()).name, p); - Eclipse.setGeneratedBy(typeReference, source); + setGeneratedBy(typeReference, source); InstanceOfExpression instanceOf = new InstanceOfExpression(otherRef, typeReference); instanceOf.sourceStart = pS; instanceOf.sourceEnd = pE; - Eclipse.setGeneratedBy(instanceOf, source); + setGeneratedBy(instanceOf, source); ReturnStatement returnStatement = new ReturnStatement(instanceOf, pS, pE); - Eclipse.setGeneratedBy(returnStatement, source); + setGeneratedBy(returnStatement, source); method.statements = new Statement[] {returnStatement}; return method; @@ -705,20 +703,20 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH /* if (Float.compare(fieldName, other.fieldName) != 0) return false */ MessageSend floatCompare = new MessageSend(); floatCompare.sourceStart = pS; floatCompare.sourceEnd = pE; - Eclipse.setGeneratedBy(floatCompare, source); + setGeneratedBy(floatCompare, source); floatCompare.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.LANG, floatOrDouble); floatCompare.selector = "compare".toCharArray(); floatCompare.arguments = new Expression[] {thisRef, otherRef}; IntLiteral int0 = makeIntLiteral("0".toCharArray(), source); EqualExpression ifFloatCompareIsNot0 = new EqualExpression(floatCompare, int0, OperatorIds.NOT_EQUAL); ifFloatCompareIsNot0.sourceStart = pS; ifFloatCompareIsNot0.sourceEnd = pE; - Eclipse.setGeneratedBy(ifFloatCompareIsNot0, source); + setGeneratedBy(ifFloatCompareIsNot0, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); - Eclipse.setGeneratedBy(falseLiteral, source); + setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); - Eclipse.setGeneratedBy(returnFalse, source); + setGeneratedBy(returnFalse, source); IfStatement ifStatement = new IfStatement(ifFloatCompareIsNot0, returnFalse, pS, pE); - Eclipse.setGeneratedBy(ifStatement, source); + setGeneratedBy(ifStatement, source); return ifStatement; } @@ -728,13 +726,13 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH /* (int)(ref >>> 32 ^ ref) */ IntLiteral int32 = makeIntLiteral("32".toCharArray(), source); BinaryExpression higherBits = new BinaryExpression(ref1, int32, OperatorIds.UNSIGNED_RIGHT_SHIFT); - Eclipse.setGeneratedBy(higherBits, source); + setGeneratedBy(higherBits, source); BinaryExpression xorParts = new BinaryExpression(ref2, higherBits, OperatorIds.XOR); - Eclipse.setGeneratedBy(xorParts, source); + setGeneratedBy(xorParts, source); TypeReference intRef = TypeReference.baseTypeReference(TypeIds.T_int, 0); intRef.sourceStart = pS; intRef.sourceEnd = pE; - Eclipse.setGeneratedBy(intRef, source); - CastExpression expr = EclipseHandlerUtil.makeCastExpression(xorParts, intRef, source); + setGeneratedBy(intRef, source); + CastExpression expr = makeCastExpression(xorParts, intRef, source); expr.sourceStart = pS; expr.sourceEnd = pE; return expr; } @@ -747,7 +745,7 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH if (varNames.length > 1) ref = new QualifiedNameReference(varNames, new long[varNames.length], pS, pE); else ref = new SingleNameReference(varNames[0], p); - Eclipse.setGeneratedBy(ref, source); + setGeneratedBy(ref, source); return ref; } @@ -760,7 +758,7 @@ public class HandleEqualsAndHashCode extends EclipseAnnotationHandler<EqualsAndH long[] poss = Eclipse.poss(source, varNames.length); if (varNames.length > 1) ref = new QualifiedTypeReference(varNames, poss); else ref = new SingleTypeReference(varNames[0], p); - Eclipse.setGeneratedBy(ref, source); + setGeneratedBy(ref, source); return ref; } } diff --git a/src/core/lombok/eclipse/handlers/HandleGetter.java b/src/core/lombok/eclipse/handlers/HandleGetter.java index 7dec8550..ff2c84e7 100644 --- a/src/core/lombok/eclipse/handlers/HandleGetter.java +++ b/src/core/lombok/eclipse/handlers/HandleGetter.java @@ -32,12 +32,10 @@ import java.util.Map; import lombok.AccessLevel; import lombok.Getter; import lombok.core.AnnotationValues; +import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; -import lombok.core.handlers.TransformationsUtil; -import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; -import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; @@ -103,7 +101,7 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { public boolean fieldQualifiesForGetterGeneration(EclipseNode field) { if (field.getKind() != Kind.FIELD) return false; FieldDeclaration fieldDecl = (FieldDeclaration) field.get(); - return EclipseHandlerUtil.filterField(fieldDecl); + return filterField(fieldDecl); } /** @@ -228,7 +226,7 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { } MethodDeclaration method = new MethodDeclaration(parent.compilationResult); - Eclipse.setGeneratedBy(method, source); + setGeneratedBy(method, source); method.modifiers = modifier; method.returnType = returnType; method.annotations = null; @@ -248,7 +246,7 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Statement returnStatement = new ReturnStatement(fieldRef, field.sourceStart, field.sourceEnd); - Eclipse.setGeneratedBy(returnStatement, source); + setGeneratedBy(returnStatement, source); return new Statement[] {returnStatement}; } @@ -295,7 +293,7 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { char[][] newType = TYPE_MAP.get(new String(((SingleTypeReference)field.type).token)); if (newType != null) { componentType = new QualifiedTypeReference(newType, poss(source, 3)); - Eclipse.setGeneratedBy(componentType, source); + setGeneratedBy(componentType, source); } } @@ -303,21 +301,21 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { /* java.util.concurrent.atomic.AtomicReference<ValueType> value = this.fieldName.get(); */ { LocalDeclaration valueDecl = new LocalDeclaration(valueName, pS, pE); - Eclipse.setGeneratedBy(valueDecl, source); + setGeneratedBy(valueDecl, source); TypeReference[][] typeParams = AR_PARAMS.clone(); typeParams[4] = new TypeReference[] {copyType(componentType, source)}; valueDecl.type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5)); valueDecl.type.sourceStart = pS; valueDecl.type.sourceEnd = pE; - Eclipse.setGeneratedBy(valueDecl.type, source); + setGeneratedBy(valueDecl.type, source); MessageSend getter = new MessageSend(); - Eclipse.setGeneratedBy(getter, source); + setGeneratedBy(getter, source); getter.sourceStart = pS; getter.sourceEnd = pE; getter.selector = new char[] {'g', 'e', 't'}; - getter.receiver = EclipseHandlerUtil.createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); + getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); valueDecl.initialization = getter; - Eclipse.setGeneratedBy(valueDecl.initialization, source); + setGeneratedBy(valueDecl.initialization, source); statements[0] = valueDecl; } @@ -335,88 +333,88 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { EqualExpression cond = new EqualExpression( new SingleNameReference(valueName, p), new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL); - Eclipse.setGeneratedBy(cond.left, source); - Eclipse.setGeneratedBy(cond.right, source); - Eclipse.setGeneratedBy(cond, source); + setGeneratedBy(cond.left, source); + setGeneratedBy(cond.right, source); + setGeneratedBy(cond, source); Block then = new Block(0); - Eclipse.setGeneratedBy(then, source); - Expression lock = EclipseHandlerUtil.createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); + setGeneratedBy(then, source); + Expression lock = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Block inner = new Block(0); - Eclipse.setGeneratedBy(inner, source); + setGeneratedBy(inner, source); inner.statements = new Statement[2]; /* value = this.fieldName.get(); */ { MessageSend getter = new MessageSend(); - Eclipse.setGeneratedBy(getter, source); + setGeneratedBy(getter, source); getter.sourceStart = pS; getter.sourceEnd = pE; getter.selector = new char[] {'g', 'e', 't'}; - getter.receiver = EclipseHandlerUtil.createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); + getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); Assignment assign = new Assignment(new SingleNameReference(valueName, p), getter, pE); - Eclipse.setGeneratedBy(assign, source); - Eclipse.setGeneratedBy(assign.lhs, source); + setGeneratedBy(assign, source); + setGeneratedBy(assign.lhs, source); inner.statements[0] = assign; } /* if (value == null) */ { EqualExpression innerCond = new EqualExpression( new SingleNameReference(valueName, p), new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL); - Eclipse.setGeneratedBy(innerCond.left, source); - Eclipse.setGeneratedBy(innerCond.right, source); - Eclipse.setGeneratedBy(innerCond, source); + setGeneratedBy(innerCond.left, source); + setGeneratedBy(innerCond.right, source); + setGeneratedBy(innerCond, source); Block innerThen = new Block(0); - Eclipse.setGeneratedBy(innerThen, source); + setGeneratedBy(innerThen, source); innerThen.statements = new Statement[2]; /*value = new java.util.concurrent.atomic.AtomicReference<ValueType>(new ValueType()); */ { AllocationExpression create = new AllocationExpression(); - Eclipse.setGeneratedBy(create, source); + setGeneratedBy(create, source); create.sourceStart = pS; create.sourceEnd = pE; TypeReference[][] typeParams = AR_PARAMS.clone(); typeParams[4] = new TypeReference[] {copyType(componentType, source)}; create.type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5)); create.type.sourceStart = pS; create.type.sourceEnd = pE; - Eclipse.setGeneratedBy(create.type, source); + setGeneratedBy(create.type, source); create.arguments = new Expression[] {field.initialization}; Assignment innerAssign = new Assignment(new SingleNameReference(valueName, p), create, pE); - Eclipse.setGeneratedBy(innerAssign, source); - Eclipse.setGeneratedBy(innerAssign.lhs, source); + setGeneratedBy(innerAssign, source); + setGeneratedBy(innerAssign.lhs, source); innerThen.statements[0] = innerAssign; } /*this.fieldName.set(value);*/ { MessageSend setter = new MessageSend(); - Eclipse.setGeneratedBy(setter, source); + setGeneratedBy(setter, source); setter.sourceStart = pS; setter.sourceEnd = pE; - setter.receiver = EclipseHandlerUtil.createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); + setter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); setter.selector = new char[] { 's', 'e', 't' }; setter.arguments = new Expression[] { new SingleNameReference(valueName, p)}; - Eclipse.setGeneratedBy(setter.arguments[0], source); + setGeneratedBy(setter.arguments[0], source); innerThen.statements[1] = setter; } IfStatement innerIf = new IfStatement(innerCond, innerThen, pS, pE); - Eclipse.setGeneratedBy(innerIf, source); + setGeneratedBy(innerIf, source); inner.statements[1] = innerIf; } SynchronizedStatement sync = new SynchronizedStatement(lock, inner, pS, pE); - Eclipse.setGeneratedBy(sync, source); + setGeneratedBy(sync, source); then.statements = new Statement[] {sync}; IfStatement ifStatement = new IfStatement(cond, then, pS, pE); - Eclipse.setGeneratedBy(ifStatement, source); + setGeneratedBy(ifStatement, source); statements[1] = ifStatement; } /* return value.get(); */ { MessageSend getter = new MessageSend(); - Eclipse.setGeneratedBy(getter, source); + setGeneratedBy(getter, source); getter.sourceStart = pS; getter.sourceEnd = pE; getter.selector = new char[] {'g', 'e', 't'}; getter.receiver = new SingleNameReference(valueName, p); - Eclipse.setGeneratedBy(getter.receiver, source); + setGeneratedBy(getter.receiver, source); statements[2] = new ReturnStatement(getter, pS, pE); - Eclipse.setGeneratedBy(statements[2], source); + setGeneratedBy(statements[2], source); } @@ -432,7 +430,7 @@ public class HandleGetter extends EclipseAnnotationHandler<Getter> { TypeReference type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5)); // Some magic here type.sourceStart = -1; type.sourceEnd = -2; - Eclipse.setGeneratedBy(type, source); + setGeneratedBy(type, source); field.type = type; AllocationExpression init = new AllocationExpression(); diff --git a/src/core/lombok/eclipse/handlers/HandleLog.java b/src/core/lombok/eclipse/handlers/HandleLog.java index f6d0745b..a16de8c2 100644 --- a/src/core/lombok/eclipse/handlers/HandleLog.java +++ b/src/core/lombok/eclipse/handlers/HandleLog.java @@ -28,10 +28,8 @@ import java.lang.reflect.Modifier; import java.util.Arrays; import lombok.core.AnnotationValues; -import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; -import lombok.eclipse.handlers.EclipseHandlerUtil.MemberExistsResult; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; @@ -88,10 +86,10 @@ public class HandleLog { TypeDeclaration typeDeclaration = (TypeDeclaration)type.get(); TypeReference typeReference = new SingleTypeReference(typeDeclaration.name, p); - Eclipse.setGeneratedBy(typeReference, source); + setGeneratedBy(typeReference, source); ClassLiteralAccess result = new ClassLiteralAccess(source.sourceEnd, typeReference); - Eclipse.setGeneratedBy(result, source); + setGeneratedBy(result, source); return result; } @@ -103,14 +101,14 @@ public class HandleLog { // private static final <loggerType> log = <factoryMethod>(<parameter>); FieldDeclaration fieldDecl = new FieldDeclaration("log".toCharArray(), 0, -1); - Eclipse.setGeneratedBy(fieldDecl, source); + setGeneratedBy(fieldDecl, source); fieldDecl.declarationSourceEnd = -1; fieldDecl.modifiers = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL; fieldDecl.type = createTypeReference(framework.getLoggerTypeName(), source); MessageSend factoryMethodCall = new MessageSend(); - Eclipse.setGeneratedBy(factoryMethodCall, source); + setGeneratedBy(factoryMethodCall, source); factoryMethodCall.receiver = createNameReference(framework.getLoggerFactoryTypeName(), source); factoryMethodCall.selector = framework.getLoggerFactoryMethodName().toCharArray(); @@ -144,7 +142,7 @@ public class HandleLog { typeReference = null; } - Eclipse.setGeneratedBy(typeReference, source); + setGeneratedBy(typeReference, source); return typeReference; } @@ -199,7 +197,7 @@ public class HandleLog { long p = (long)pS << 32 | pE; MessageSend factoryParameterCall = new MessageSend(); - Eclipse.setGeneratedBy(factoryParameterCall, source); + setGeneratedBy(factoryParameterCall, source); factoryParameterCall.receiver = super.createFactoryParameter(type, source); factoryParameterCall.selector = "getName".toCharArray(); @@ -243,9 +241,9 @@ public class HandleLog { } Expression createFactoryParameter(ClassLiteralAccess loggingType, Annotation source){ - TypeReference copy = Eclipse.copyType(loggingType.type, source); + TypeReference copy = copyType(loggingType.type, source); ClassLiteralAccess result = new ClassLiteralAccess(source.sourceEnd, copy); - Eclipse.setGeneratedBy(result, source); + setGeneratedBy(result, source); return result; }; } diff --git a/src/core/lombok/eclipse/handlers/HandleSetter.java b/src/core/lombok/eclipse/handlers/HandleSetter.java index 5f684410..e3bfe935 100644 --- a/src/core/lombok/eclipse/handlers/HandleSetter.java +++ b/src/core/lombok/eclipse/handlers/HandleSetter.java @@ -30,12 +30,10 @@ import java.util.Collection; import lombok.AccessLevel; import lombok.Setter; import lombok.core.AnnotationValues; +import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; -import lombok.core.handlers.TransformationsUtil; -import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; -import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; @@ -84,7 +82,7 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { for (EclipseNode field : typeNode.down()) { if (field.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) field.get(); - if (!EclipseHandlerUtil.filterField(fieldDecl)) continue; + if (!filterField(fieldDecl)) continue; //Skip final fields. if ((fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0) continue; @@ -181,15 +179,15 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; MethodDeclaration method = new MethodDeclaration(parent.compilationResult); - Eclipse.setGeneratedBy(method, source); + setGeneratedBy(method, source); method.modifiers = modifier; method.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0); method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE; - Eclipse.setGeneratedBy(method.returnType, source); + setGeneratedBy(method.returnType, source); method.annotations = null; Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL); param.sourceStart = pS; param.sourceEnd = pE; - Eclipse.setGeneratedBy(param, source); + setGeneratedBy(param, source); method.arguments = new Argument[] { param }; method.selector = name.toCharArray(); method.binding = null; @@ -198,10 +196,10 @@ public class HandleSetter extends EclipseAnnotationHandler<Setter> { method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source); NameReference fieldNameRef = new SingleNameReference(field.name, p); - Eclipse.setGeneratedBy(fieldNameRef, source); + setGeneratedBy(fieldNameRef, source); Assignment assignment = new Assignment(fieldRef, fieldNameRef, (int)p); assignment.sourceStart = pS; assignment.sourceEnd = pE; - Eclipse.setGeneratedBy(assignment, source); + setGeneratedBy(assignment, source); method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart; method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd; diff --git a/src/core/lombok/eclipse/handlers/HandleSneakyThrows.java b/src/core/lombok/eclipse/handlers/HandleSneakyThrows.java index 95c11c2d..16105b72 100644 --- a/src/core/lombok/eclipse/handlers/HandleSneakyThrows.java +++ b/src/core/lombok/eclipse/handlers/HandleSneakyThrows.java @@ -21,6 +21,8 @@ */ package lombok.eclipse.handlers; +import static lombok.eclipse.handlers.EclipseHandlerUtil.*; + import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; @@ -28,7 +30,6 @@ import java.util.List; import lombok.SneakyThrows; import lombok.core.AnnotationValues; -import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; @@ -166,13 +167,13 @@ public class HandleSneakyThrows extends EclipseAnnotationHandler<SneakyThrows> { long methodPosEnd = methodEnd << 32 | (methodEnd & 0xFFFFFFFFL); TryStatement tryStatement = new TryStatement(); - Eclipse.setGeneratedBy(tryStatement, source); + setGeneratedBy(tryStatement, source); tryStatement.tryBlock = new Block(0); // Positions for in-method generated nodes are special tryStatement.tryBlock.sourceStart = methodStart; tryStatement.tryBlock.sourceEnd = methodEnd; - Eclipse.setGeneratedBy(tryStatement.tryBlock, source); + setGeneratedBy(tryStatement.tryBlock, source); tryStatement.tryBlock.statements = contents; TypeReference typeReference; if (exception.exceptionName.indexOf('.') == -1) { @@ -188,23 +189,23 @@ public class HandleSneakyThrows extends EclipseAnnotationHandler<SneakyThrows> { } typeReference = new QualifiedTypeReference(elems, poss); } - Eclipse.setGeneratedBy(typeReference, source); + setGeneratedBy(typeReference, source); Argument catchArg = new Argument("$ex".toCharArray(), methodPosEnd, typeReference, Modifier.FINAL); - Eclipse.setGeneratedBy(catchArg, source); + setGeneratedBy(catchArg, source); catchArg.declarationSourceEnd = catchArg.declarationEnd = catchArg.sourceEnd = methodEnd; catchArg.declarationSourceStart = catchArg.modifiersSourceStart = catchArg.sourceStart = methodEnd; tryStatement.catchArguments = new Argument[] { catchArg }; MessageSend sneakyThrowStatement = new MessageSend(); - Eclipse.setGeneratedBy(sneakyThrowStatement, source); + setGeneratedBy(sneakyThrowStatement, source); sneakyThrowStatement.receiver = new QualifiedNameReference(new char[][] { "lombok".toCharArray(), "Lombok".toCharArray() }, new long[2], methodEnd, methodEnd); - Eclipse.setGeneratedBy(sneakyThrowStatement.receiver, source); + setGeneratedBy(sneakyThrowStatement.receiver, source); sneakyThrowStatement.receiver.statementEnd = methodEnd; sneakyThrowStatement.selector = "sneakyThrow".toCharArray(); SingleNameReference exRef = new SingleNameReference("$ex".toCharArray(), methodPosEnd); - Eclipse.setGeneratedBy(exRef, source); + setGeneratedBy(exRef, source); exRef.statementEnd = methodEnd; sneakyThrowStatement.arguments = new Expression[] { exRef }; @@ -217,12 +218,12 @@ public class HandleSneakyThrows extends EclipseAnnotationHandler<SneakyThrows> { sneakyThrowStatement.sourceEnd = sneakyThrowStatement.statementEnd = methodEnd; Statement rethrowStatement = new ThrowStatement(sneakyThrowStatement, methodEnd, methodEnd); - Eclipse.setGeneratedBy(rethrowStatement, source); + setGeneratedBy(rethrowStatement, source); Block block = new Block(0); block.sourceStart = methodEnd; block.sourceEnd = methodEnd; - Eclipse.setGeneratedBy(block, source); + setGeneratedBy(block, source); block.statements = new Statement[] { rethrowStatement }; tryStatement.catchBlocks = new Block[] { block }; diff --git a/src/core/lombok/eclipse/handlers/HandleSynchronized.java b/src/core/lombok/eclipse/handlers/HandleSynchronized.java index ce1ac315..aa7885aa 100644 --- a/src/core/lombok/eclipse/handlers/HandleSynchronized.java +++ b/src/core/lombok/eclipse/handlers/HandleSynchronized.java @@ -28,10 +28,8 @@ import java.lang.reflect.Modifier; import lombok.Synchronized; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; -import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; -import lombok.eclipse.handlers.EclipseHandlerUtil.MemberExistsResult; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression; @@ -84,19 +82,19 @@ public class HandleSynchronized extends EclipseAnnotationHandler<Synchronized> { return null; } FieldDeclaration fieldDecl = new FieldDeclaration(lockName, 0, -1); - Eclipse.setGeneratedBy(fieldDecl, source); + setGeneratedBy(fieldDecl, source); fieldDecl.declarationSourceEnd = -1; fieldDecl.modifiers = (isStatic ? Modifier.STATIC : 0) | Modifier.FINAL | Modifier.PRIVATE; //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable! ArrayAllocationExpression arrayAlloc = new ArrayAllocationExpression(); - Eclipse.setGeneratedBy(arrayAlloc, source); + setGeneratedBy(arrayAlloc, source); arrayAlloc.dimensions = new Expression[] { makeIntLiteral("0".toCharArray(), source) }; arrayAlloc.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { 0, 0, 0 }); - Eclipse.setGeneratedBy(arrayAlloc.type, source); + setGeneratedBy(arrayAlloc.type, source); fieldDecl.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { 0, 0, 0 }); - Eclipse.setGeneratedBy(fieldDecl.type, source); + setGeneratedBy(fieldDecl.type, source); fieldDecl.initialization = arrayAlloc; // TODO temporary workaround for issue 217. http://code.google.com/p/projectlombok/issues/detail?id=217 // injectFieldSuppressWarnings(annotationNode.up().up(), fieldDecl); @@ -127,7 +125,7 @@ public class HandleSynchronized extends EclipseAnnotationHandler<Synchronized> { if (method.statements == null) return; Block block = new Block(0); - Eclipse.setGeneratedBy(block, source); + setGeneratedBy(block, source); block.statements = method.statements; // Positions for in-method generated nodes are special @@ -140,10 +138,10 @@ public class HandleSynchronized extends EclipseAnnotationHandler<Synchronized> { else { lockVariable = new FieldReference(lockName, pos); ThisReference thisReference = new ThisReference(p1, p2); - Eclipse.setGeneratedBy(thisReference, source); + setGeneratedBy(thisReference, source); ((FieldReference)lockVariable).receiver = thisReference; } - Eclipse.setGeneratedBy(lockVariable, source); + setGeneratedBy(lockVariable, source); method.statements = new Statement[] { new SynchronizedStatement(lockVariable, block, 0, 0) @@ -153,7 +151,7 @@ public class HandleSynchronized extends EclipseAnnotationHandler<Synchronized> { method.statements[0].sourceEnd = method.bodyEnd; method.statements[0].sourceStart = method.bodyStart; - Eclipse.setGeneratedBy(method.statements[0], source); + setGeneratedBy(method.statements[0], source); methodNode.rebuild(); } diff --git a/src/core/lombok/eclipse/handlers/HandleToString.java b/src/core/lombok/eclipse/handlers/HandleToString.java index f1679161..9fa7c6de 100644 --- a/src/core/lombok/eclipse/handlers/HandleToString.java +++ b/src/core/lombok/eclipse/handlers/HandleToString.java @@ -38,7 +38,6 @@ import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; import lombok.eclipse.EclipseNode; -import lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; @@ -84,7 +83,7 @@ public class HandleToString extends EclipseAnnotationHandler<ToString> { public void generateToStringForType(EclipseNode typeNode, EclipseNode errorNode) { for (EclipseNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Eclipse.annotationTypeMatches(ToString.class, child)) { + if (annotationTypeMatches(ToString.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -151,7 +150,7 @@ public class HandleToString extends EclipseAnnotationHandler<ToString> { for (EclipseNode child : typeNode.down()) { if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); - if (!EclipseHandlerUtil.filterField(fieldDecl)) continue; + if (!filterField(fieldDecl)) continue; //Skip excluded fields. if (excludes != null && excludes.contains(new String(fieldDecl.name))) continue; @@ -199,17 +198,17 @@ public class HandleToString extends EclipseAnnotationHandler<ToString> { boolean first = true; Expression current = new StringLiteral(prefix, pS, pE, 0); - Eclipse.setGeneratedBy(current, source); + setGeneratedBy(current, source); if (callSuper) { MessageSend callToSuper = new MessageSend(); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; - Eclipse.setGeneratedBy(callToSuper, source); + setGeneratedBy(callToSuper, source); callToSuper.receiver = new SuperReference(pS, pE); - Eclipse.setGeneratedBy(callToSuper, source); + setGeneratedBy(callToSuper, source); callToSuper.selector = "toString".toCharArray(); current = new BinaryExpression(current, callToSuper, PLUS); - Eclipse.setGeneratedBy(current, source); + setGeneratedBy(current, source); first = false; } @@ -223,7 +222,7 @@ public class HandleToString extends EclipseAnnotationHandler<ToString> { arrayToString.sourceStart = pS; arrayToString.sourceEnd = pE; arrayToString.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); arrayToString.arguments = new Expression[] { fieldAccessor }; - Eclipse.setGeneratedBy(arrayToString.arguments[0], source); + setGeneratedBy(arrayToString.arguments[0], source); if (fType.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(fType.getLastToken()))) { arrayToString.selector = "deepToString".toCharArray(); } else { @@ -233,12 +232,12 @@ public class HandleToString extends EclipseAnnotationHandler<ToString> { } else { ex = fieldAccessor; } - Eclipse.setGeneratedBy(ex, source); + setGeneratedBy(ex, source); if (first) { current = new BinaryExpression(current, ex, PLUS); current.sourceStart = pS; current.sourceEnd = pE; - Eclipse.setGeneratedBy(current, source); + setGeneratedBy(current, source); first = false; continue; } @@ -250,27 +249,27 @@ public class HandleToString extends EclipseAnnotationHandler<ToString> { } else { fieldNameLiteral = new StringLiteral(infix, pS, pE, 0); } - Eclipse.setGeneratedBy(fieldNameLiteral, source); + setGeneratedBy(fieldNameLiteral, source); current = new BinaryExpression(current, fieldNameLiteral, PLUS); - Eclipse.setGeneratedBy(current, source); + setGeneratedBy(current, source); current = new BinaryExpression(current, ex, PLUS); - Eclipse.setGeneratedBy(current, source); + setGeneratedBy(current, source); } if (!first) { StringLiteral suffixLiteral = new StringLiteral(suffix, pS, pE, 0); - Eclipse.setGeneratedBy(suffixLiteral, source); + setGeneratedBy(suffixLiteral, source); current = new BinaryExpression(current, suffixLiteral, PLUS); - Eclipse.setGeneratedBy(current, source); + setGeneratedBy(current, source); } ReturnStatement returnStatement = new ReturnStatement(current, pS, pE); - Eclipse.setGeneratedBy(returnStatement, source); + setGeneratedBy(returnStatement, source); MethodDeclaration method = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult); - Eclipse.setGeneratedBy(method, source); + setGeneratedBy(method, source); method.modifiers = toEclipseModifier(AccessLevel.PUBLIC); method.returnType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING, new long[] {p, p, p}); - Eclipse.setGeneratedBy(method.returnType, source); + setGeneratedBy(method.returnType, source); method.annotations = new Annotation[] {makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source)}; method.arguments = null; method.selector = "toString".toCharArray(); @@ -308,7 +307,7 @@ public class HandleToString extends EclipseAnnotationHandler<ToString> { NameReference ref; if (varNames.length > 1) ref = new QualifiedNameReference(varNames, new long[varNames.length], pS, pE); else ref = new SingleNameReference(varNames[0], p); - Eclipse.setGeneratedBy(ref, source); + setGeneratedBy(ref, source); return ref; } } diff --git a/src/core/lombok/eclipse/handlers/HandleVal.java b/src/core/lombok/eclipse/handlers/HandleVal.java index cca5d690..babf8c81 100644 --- a/src/core/lombok/eclipse/handlers/HandleVal.java +++ b/src/core/lombok/eclipse/handlers/HandleVal.java @@ -22,7 +22,6 @@ package lombok.eclipse.handlers; import lombok.val; -import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseASTAdapter; import lombok.eclipse.EclipseASTVisitor; import lombok.eclipse.EclipseNode; @@ -42,7 +41,7 @@ public class HandleVal extends EclipseASTAdapter { } @Override public void visitLocal(EclipseNode localNode, LocalDeclaration local) { - if (!Eclipse.typeMatches(val.class, localNode, local.type)) return; + if (!EclipseHandlerUtil.typeMatches(val.class, localNode, local.type)) return; boolean variableOfForEach = false; if (localNode.directUp().get() instanceof ForeachStatement) { diff --git a/src/core/lombok/javac/HandlerLibrary.java b/src/core/lombok/javac/HandlerLibrary.java index f0bd3442..d0cadab1 100644 --- a/src/core/lombok/javac/HandlerLibrary.java +++ b/src/core/lombok/javac/HandlerLibrary.java @@ -37,6 +37,7 @@ import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.core.TypeResolver; import lombok.core.AnnotationValues.AnnotationValueDecodeFail; +import lombok.javac.handlers.JavacHandlerUtil; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; @@ -77,7 +78,7 @@ public class HandlerLibrary { } public void handle(final JavacNode node) { - handler.handle(Javac.createAnnotation(annotationClass, node), (JCAnnotation)node.get(), node); + handler.handle(JavacHandlerUtil.createAnnotation(annotationClass, node), (JCAnnotation)node.get(), node); } } diff --git a/src/core/lombok/javac/Javac.java b/src/core/lombok/javac/Javac.java deleted file mode 100644 index 594539cd..00000000 --- a/src/core/lombok/javac/Javac.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright © 2009-2011 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.javac; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; - -import lombok.Lombok; -import lombok.core.AST.Kind; -import lombok.core.AnnotationValues; -import lombok.core.AnnotationValues.AnnotationValue; -import lombok.core.TypeLibrary; -import lombok.core.TypeResolver; - -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.JCAnnotation; -import com.sun.tools.javac.tree.JCTree.JCAssign; -import com.sun.tools.javac.tree.JCTree.JCExpression; -import com.sun.tools.javac.tree.JCTree.JCFieldAccess; -import com.sun.tools.javac.tree.JCTree.JCIdent; -import com.sun.tools.javac.tree.JCTree.JCLiteral; -import com.sun.tools.javac.tree.JCTree.JCNewArray; -import com.sun.tools.javac.tree.TreeScanner; -import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; - -/** - * Container for static utility methods relevant to lombok's operation on javac. - */ -public class Javac { - private Javac() { - //prevent instantiation - } - - /** - * Checks if the Annotation AST Node provided is likely to be an instance of the provided annotation type. - * - * @param type An actual annotation type, such as {@code lombok.Getter.class}. - * @param node A Lombok AST node representing an annotation in source code. - */ - public static boolean annotationTypeMatches(Class<? extends Annotation> type, JavacNode node) { - if (node.getKind() != Kind.ANNOTATION) return false; - return typeMatches(type, node, ((JCAnnotation)node.get()).annotationType); - } - - /** - * Checks if the given TypeReference node is likely to be a reference to the provided class. - * - * @param type An actual type. This method checks if {@code typeNode} is likely to be a reference to this type. - * @param node A Lombok AST node. Any node in the appropriate compilation unit will do (used to get access to import statements). - * @param typeNode A type reference to check. - */ - public static boolean typeMatches(Class<?> type, JavacNode node, JCTree typeNode) { - String typeName = typeNode.toString(); - - TypeLibrary library = new TypeLibrary(); - library.addType(type.getName()); - TypeResolver resolver = new TypeResolver(library, node.getPackageDeclaration(), node.getImportStatements()); - Collection<String> typeMatches = resolver.findTypeMatches(node, typeName); - - for (String match : typeMatches) { - if (match.equals(type.getName())) return true; - } - - return false; - } - - /** - * Creates an instance of {@code AnnotationValues} for the provided AST Node. - * - * @param type An annotation class type, such as {@code lombok.Getter.class}. - * @param node A Lombok AST node representing an annotation in source code. - */ - public static <A extends Annotation> AnnotationValues<A> createAnnotation(Class<A> type, final JavacNode node) { - Map<String, AnnotationValue> values = new HashMap<String, AnnotationValue>(); - JCAnnotation anno = (JCAnnotation) node.get(); - List<JCExpression> arguments = anno.getArguments(); - for (Method m : type.getDeclaredMethods()) { - if (!Modifier.isPublic(m.getModifiers())) continue; - String name = m.getName(); - List<String> raws = new ArrayList<String>(); - List<Object> guesses = new ArrayList<Object>(); - List<Object> expressions = new ArrayList<Object>(); - final List<DiagnosticPosition> positions = new ArrayList<DiagnosticPosition>(); - boolean isExplicit = false; - - for (JCExpression arg : arguments) { - String mName; - JCExpression rhs; - - if (arg instanceof JCAssign) { - JCAssign assign = (JCAssign) arg; - mName = assign.lhs.toString(); - rhs = assign.rhs; - } else { - rhs = arg; - mName = "value"; - } - - if (!mName.equals(name)) continue; - isExplicit = true; - if (rhs instanceof JCNewArray) { - List<JCExpression> elems = ((JCNewArray)rhs).elems; - for (JCExpression inner : elems) { - raws.add(inner.toString()); - expressions.add(inner); - guesses.add(calculateGuess(inner)); - positions.add(inner.pos()); - } - } else { - raws.add(rhs.toString()); - expressions.add(rhs); - guesses.add(calculateGuess(rhs)); - positions.add(rhs.pos()); - } - } - - values.put(name, new AnnotationValue(node, raws, expressions, guesses, isExplicit) { - @Override public void setError(String message, int valueIdx) { - if (valueIdx < 0) node.addError(message); - else node.addError(message, positions.get(valueIdx)); - } - @Override public void setWarning(String message, int valueIdx) { - if (valueIdx < 0) node.addWarning(message); - else node.addWarning(message, positions.get(valueIdx)); - } - }); - } - - return new AnnotationValues<A>(type, values, node); - } - - /** - * Turns an expression into a guessed intended literal. Only works for literals, as you can imagine. - * - * Will for example turn a TrueLiteral into 'Boolean.valueOf(true)'. - */ - private static Object calculateGuess(JCExpression expr) { - if (expr instanceof JCLiteral) { - JCLiteral lit = (JCLiteral)expr; - if (lit.getKind() == com.sun.source.tree.Tree.Kind.BOOLEAN_LITERAL) { - return ((Number)lit.value).intValue() == 0 ? false : true; - } - return lit.value; - } else if (expr instanceof JCIdent || expr instanceof JCFieldAccess) { - String x = expr.toString(); - if (x.endsWith(".class")) x = x.substring(0, x.length() - 6); - else { - int idx = x.lastIndexOf('.'); - if (idx > -1) x = x.substring(idx + 1); - } - return x; - } else return null; - } - - /** - * Retrieves a compile time constant of type int from the specified class location. - * - * Solves the problem of compile time constant inlining, resulting in lombok having the wrong value - * (javac compiler changes private api constants from time to time) - * - * @param ctcLocation location of the compile time constant - * @param identifier the name of the field of the compile time constant. - */ - public static int getCtcInt(Class<?> ctcLocation, String identifier) { - try { - return (Integer)ctcLocation.getField(identifier).get(null); - } catch (NoSuchFieldException e) { - throw Lombok.sneakyThrow(e); - } catch (IllegalAccessException e) { - throw Lombok.sneakyThrow(e); - } - } - - private static class MarkingScanner extends TreeScanner { - private final JCTree source; - - MarkingScanner(JCTree source) { - this.source = source; - } - - @Override public void scan(JCTree tree) { - setGeneratedBy(tree, source); - super.scan(tree); - } - } - - private static Map<JCTree, JCTree> generatedNodes = new WeakHashMap<JCTree, JCTree>(); - - public static JCTree getGeneratedBy(JCTree node) { - synchronized (generatedNodes) { - return generatedNodes.get(node); - } - } - - public static boolean isGenerated(JCTree node) { - return getGeneratedBy(node) != null; - } - - public static <T extends JCTree> T recursiveSetGeneratedBy(T node, JCTree source) { - setGeneratedBy(node, source); - node.accept(new MarkingScanner(source)); - - return node; - } - - public static <T extends JCTree> T setGeneratedBy(T node, JCTree source) { - synchronized (generatedNodes) { - if (source == null) generatedNodes.remove(node); - else generatedNodes.put(node, source); - } - return node; - } -} diff --git a/src/core/lombok/javac/JavacResolution.java b/src/core/lombok/javac/JavacResolution.java index a116b503..e0d56b85 100644 --- a/src/core/lombok/javac/JavacResolution.java +++ b/src/core/lombok/javac/JavacResolution.java @@ -48,6 +48,7 @@ public class JavacResolution { attr = Attr.instance(context); logDisabler = new LogDisabler(context); } + /** * During resolution, the resolver will emit resolution errors, but without appropriate file names and line numbers. If these resolution errors stick around * then they will be generated AGAIN, this time with proper names and line numbers, at the end. Therefore, we want to suppress the logger. @@ -297,7 +298,7 @@ public class JavacResolution { EnvFinder finder = new EnvFinder(node.getContext()); while (!stack.isEmpty()) stack.pop().accept(finder); - TreeMirrorMaker mirrorMaker = new TreeMirrorMaker(node); + TreeMirrorMaker mirrorMaker = new TreeMirrorMaker(node.getTreeMaker()); JCTree copy = mirrorMaker.copy(finder.copyAt()); attrib(copy, finder.get()); diff --git a/src/core/lombok/javac/TreeMirrorMaker.java b/src/core/lombok/javac/TreeMirrorMaker.java deleted file mode 100644 index 2036e414..00000000 --- a/src/core/lombok/javac/TreeMirrorMaker.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright © 2010-2011 Reinier Zwitserloot, Roel Spilker and Robbert Jan Grootjans. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.javac; - -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.Map; - -import com.sun.source.tree.VariableTree; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.JCVariableDecl; -import com.sun.tools.javac.tree.TreeCopier; -import com.sun.tools.javac.util.List; - -public class TreeMirrorMaker extends TreeCopier<Void> { - private final IdentityHashMap<JCTree, JCTree> originalToCopy = new IdentityHashMap<JCTree, JCTree>(); - - public TreeMirrorMaker(JavacNode node) { - super(node.getTreeMaker()); - } - - @Override public <T extends JCTree> T copy(T original) { - T copy = super.copy(original); - originalToCopy.put(original, copy); - return copy; - } - - @Override public <T extends JCTree> T copy(T original, Void p) { - T copy = super.copy(original, p); - originalToCopy.put(original, copy); - return copy; - } - - @Override public <T extends JCTree> List<T> copy(List<T> originals) { - List<T> copies = super.copy(originals); - if (originals != null) { - Iterator<T> it1 = originals.iterator(); - Iterator<T> it2 = copies.iterator(); - while (it1.hasNext()) originalToCopy.put(it1.next(), it2.next()); - } - return copies; - } - - @Override public <T extends JCTree> List<T> copy(List<T> originals, Void p) { - List<T> copies = super.copy(originals, p); - if (originals != null) { - Iterator<T> it1 = originals.iterator(); - Iterator<T> it2 = copies.iterator(); - while (it1.hasNext()) originalToCopy.put(it1.next(), it2.next()); - } - return copies; - } - - public Map<JCTree, JCTree> getOriginalToCopyMap() { - return Collections.unmodifiableMap(originalToCopy); - } - - // Fix for NPE in HandleVal. See http://code.google.com/p/projectlombok/issues/detail?id=205 - // Maybe this should be done elsewhere... - @Override public JCTree visitVariable(VariableTree node, Void p) { - JCVariableDecl copy = (JCVariableDecl) super.visitVariable(node, p); - copy.sym = ((JCVariableDecl) node).sym; - return copy; - } -} diff --git a/src/core/lombok/javac/handlers/HandleCleanup.java b/src/core/lombok/javac/handlers/HandleCleanup.java index 43dacda2..5b77554c 100644 --- a/src/core/lombok/javac/handlers/HandleCleanup.java +++ b/src/core/lombok/javac/handlers/HandleCleanup.java @@ -21,7 +21,7 @@ */ package lombok.javac.handlers; -import static lombok.javac.handlers.JavacHandlerUtil.deleteAnnotationIfNeccessary; +import static lombok.javac.handlers.JavacHandlerUtil.*; import lombok.Cleanup; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; @@ -122,9 +122,9 @@ public class HandleCleanup extends JavacAnnotationHandler<Cleanup> { JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null); - JCBlock finalizer = Javac.recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), ast); + JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), ast); - newStatements.append(Javac.setGeneratedBy(maker.Try(Javac.setGeneratedBy(maker.Block(0, tryBlock.toList()), ast), List.<JCCatch>nil(), finalizer), ast)); + newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), ast), List.<JCCatch>nil(), finalizer), ast)); if (blockNode instanceof JCBlock) { ((JCBlock)blockNode).stats = newStatements.toList(); @@ -138,7 +138,7 @@ public class HandleCleanup extends JavacAnnotationHandler<Cleanup> { } private JCMethodInvocation preventNullAnalysis(TreeMaker maker, JavacNode node, JCExpression expression) { - JCMethodInvocation singletonList = maker.Apply(List.<JCExpression>nil(), JavacHandlerUtil.chainDotsString(maker, node, "java.util.Collections.singletonList"), List.of(expression)); + JCMethodInvocation singletonList = maker.Apply(List.<JCExpression>nil(), chainDotsString(node, "java.util.Collections.singletonList"), List.of(expression)); JCMethodInvocation cleanedExpr = maker.Apply(List.<JCExpression>nil(), maker.Select(singletonList, node.toName("get")) , List.<JCExpression>of(maker.Literal(TypeTags.INT, 0))); return cleanedExpr; } diff --git a/src/core/lombok/javac/handlers/HandleConstructor.java b/src/core/lombok/javac/handlers/HandleConstructor.java index 212daf16..88ff523f 100644 --- a/src/core/lombok/javac/handlers/HandleConstructor.java +++ b/src/core/lombok/javac/handlers/HandleConstructor.java @@ -27,12 +27,10 @@ import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.core.AnnotationValues; +import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; -import lombok.core.handlers.TransformationsUtil; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; -import lombok.javac.handlers.JavacHandlerUtil.MemberExistsResult; import org.mangosdk.spi.ProviderFor; @@ -160,9 +158,9 @@ public class HandleConstructor { if (skipIfConstructorExists) { for (JavacNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Javac.annotationTypeMatches(NoArgsConstructor.class, child) || - Javac.annotationTypeMatches(AllArgsConstructor.class, child) || - Javac.annotationTypeMatches(RequiredArgsConstructor.class, child)) + if (annotationTypeMatches(NoArgsConstructor.class, child) || + annotationTypeMatches(AllArgsConstructor.class, child) || + annotationTypeMatches(RequiredArgsConstructor.class, child)) return; } } @@ -181,7 +179,7 @@ public class HandleConstructor { private static void addConstructorProperties(JCModifiers mods, JavacNode node, List<JavacNode> fields) { if (fields.isEmpty()) return; TreeMaker maker = node.getTreeMaker(); - JCExpression constructorPropertiesType = chainDots(maker, node, "java", "beans", "ConstructorProperties"); + JCExpression constructorPropertiesType = chainDots(node, "java", "beans", "ConstructorProperties"); ListBuffer<JCExpression> fieldNames = ListBuffer.lb(); for (JavacNode field : fields) { fieldNames.append(maker.Literal(field.getName())); @@ -221,7 +219,7 @@ public class HandleConstructor { if (!suppressConstructorProperties && level != AccessLevel.PRIVATE && !isLocalType(typeNode)) { addConstructorProperties(mods, typeNode, fields); } - return Javac.recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("<init>"), + return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("<init>"), null, List.<JCTypeParameter>nil(), params.toList(), List.<JCExpression>nil(), maker.Block(0L, nullChecks.appendList(assigns).toList()), null), source); } @@ -280,6 +278,6 @@ public class HandleConstructor { JCReturn returnStatement = maker.Return(maker.NewClass(null, List.<JCExpression>nil(), constructorType, args.toList(), null)); JCBlock body = maker.Block(0, List.<JCStatement>of(returnStatement)); - return Javac.recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName(name), returnType, typeParams.toList(), params.toList(), List.<JCExpression>nil(), body, null), source); + return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName(name), returnType, typeParams.toList(), params.toList(), List.<JCExpression>nil(), body, null), source); } } diff --git a/src/core/lombok/javac/handlers/HandleDelegate.java b/src/core/lombok/javac/handlers/HandleDelegate.java index 0294171f..9f8e5e91 100644 --- a/src/core/lombok/javac/handlers/HandleDelegate.java +++ b/src/core/lombok/javac/handlers/HandleDelegate.java @@ -21,7 +21,7 @@ */ package lombok.javac.handlers; -import static lombok.javac.handlers.JavacHandlerUtil.deleteAnnotationIfNeccessary; +import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.ArrayList; import java.util.Arrays; @@ -43,7 +43,6 @@ import lombok.Delegate; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.javac.FindTypeVarScanner; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacResolution; @@ -186,7 +185,7 @@ public class HandleDelegate extends JavacAnnotationHandler<Delegate> { } for (JCMethodDecl method : toAdd) { - JavacHandlerUtil.injectMethod(annotation.up().up(), method); + injectMethod(annotation.up().up(), method); } } @@ -254,7 +253,7 @@ public class HandleDelegate extends JavacAnnotationHandler<Delegate> { com.sun.tools.javac.util.List<JCAnnotation> annotations; if (sig.isDeprecated) { annotations = com.sun.tools.javac.util.List.of(maker.Annotation( - JavacHandlerUtil.chainDots(maker, annotation, "java", "lang", "Deprecated"), + chainDots(annotation, "java", "lang", "Deprecated"), com.sun.tools.javac.util.List.<JCExpression>nil())); } else { annotations = com.sun.tools.javac.util.List.nil(); @@ -295,7 +294,7 @@ public class HandleDelegate extends JavacAnnotationHandler<Delegate> { JCStatement body = useReturn ? maker.Return(delegateCall) : maker.Exec(delegateCall); JCBlock bodyBlock = maker.Block(0, com.sun.tools.javac.util.List.of(body)); - return Javac.recursiveSetGeneratedBy(maker.MethodDef(mods, sig.name, returnType, toList(typeParams), toList(params), toList(thrown), bodyBlock, null), annotation.get()); + return recursiveSetGeneratedBy(maker.MethodDef(mods, sig.name, returnType, toList(typeParams), toList(params), toList(thrown), bodyBlock, null), annotation.get()); } private static <T> com.sun.tools.javac.util.List<T> toList(ListBuffer<T> collection) { diff --git a/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java b/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java index afd299ef..50bcdd3e 100644 --- a/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java +++ b/src/core/lombok/javac/handlers/HandleEqualsAndHashCode.java @@ -22,6 +22,7 @@ package lombok.javac.handlers; import static lombok.javac.handlers.JavacHandlerUtil.*; +import static lombok.javac.Javac.getCtcInt; import java.util.ArrayList; import java.util.Collections; @@ -29,7 +30,6 @@ import java.util.Collections; import lombok.EqualsAndHashCode; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; @@ -103,7 +103,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas public void generateEqualsAndHashCodeForType(JavacNode typeNode, JavacNode source) { for (JavacNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Javac.annotationTypeMatches(EqualsAndHashCode.class, child)) { + if (annotationTypeMatches(EqualsAndHashCode.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -209,9 +209,9 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas private JCMethodDecl createHashCode(JavacNode typeNode, List<JavacNode> fields, boolean callSuper, FieldAccess fieldAccess, JCTree source) { TreeMaker maker = typeNode.getTreeMaker(); - JCAnnotation overrideAnnotation = maker.Annotation(chainDots(maker, typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); + JCAnnotation overrideAnnotation = maker.Annotation(chainDots(typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); - JCExpression returnType = maker.TypeIdent(Javac.getCtcInt(TypeTags.class, "INT")); + JCExpression returnType = maker.TypeIdent(getCtcInt(TypeTags.class, "INT")); ListBuffer<JCStatement> statements = ListBuffer.lb(); Name primeName = typeNode.toName("PRIME"); @@ -219,12 +219,12 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas /* final int PRIME = 31; */ { if (!fields.isEmpty() || callSuper) { statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), - primeName, maker.TypeIdent(Javac.getCtcInt(TypeTags.class, "INT")), maker.Literal(31))); + primeName, maker.TypeIdent(getCtcInt(TypeTags.class, "INT")), maker.Literal(31))); } } /* int result = 1; */ { - statements.append(maker.VarDef(maker.Modifiers(0), resultName, maker.TypeIdent(Javac.getCtcInt(TypeTags.class, "INT")), maker.Literal(1))); + statements.append(maker.VarDef(maker.Modifiers(0), resultName, maker.TypeIdent(getCtcInt(TypeTags.class, "INT")), maker.Literal(1))); } ListBuffer<JCExpression> intoResult = ListBuffer.lb(); @@ -253,7 +253,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas /* Float.floatToIntBits(this.fieldName) */ intoResult.append(maker.Apply( List.<JCExpression>nil(), - chainDots(maker, typeNode, "java", "lang", "Float", "floatToIntBits"), + chainDots(typeNode, "java", "lang", "Float", "floatToIntBits"), List.of(fieldAccessor))); break; case DOUBLE: @@ -261,7 +261,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas Name tempVar = typeNode.toName("temp" + (++tempCounter)); JCExpression init = maker.Apply( List.<JCExpression>nil(), - chainDots(maker, typeNode, "java", "lang", "Double", "doubleToLongBits"), + chainDots(typeNode, "java", "lang", "Double", "doubleToLongBits"), List.of(fieldAccessor)); statements.append( maker.VarDef(maker.Modifiers(Flags.FINAL), tempVar, maker.TypeIdent(TypeTags.LONG), init)); @@ -282,14 +282,14 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas boolean primitiveArray = ((JCArrayTypeTree)fType).elemtype instanceof JCPrimitiveTypeTree; boolean useDeepHC = multiDim || !primitiveArray; - JCExpression hcMethod = chainDots(maker, typeNode, "java", "util", "Arrays", useDeepHC ? "deepHashCode" : "hashCode"); + JCExpression hcMethod = chainDots(typeNode, "java", "util", "Arrays", useDeepHC ? "deepHashCode" : "hashCode"); intoResult.append( maker.Apply(List.<JCExpression>nil(), hcMethod, List.of(fieldAccessor))); } else /* objects */ { /* this.fieldName == null ? 0 : this.fieldName.hashCode() */ JCExpression hcCall = maker.Apply(List.<JCExpression>nil(), maker.Select(createFieldAccessor(maker, fieldNode, fieldAccess), typeNode.toName("hashCode")), List.<JCExpression>nil()); - JCExpression thisEqualsNull = maker.Binary(Javac.getCtcInt(JCTree.class, "EQ"), fieldAccessor, maker.Literal(Javac.getCtcInt(TypeTags.class, "BOT"), null)); + JCExpression thisEqualsNull = maker.Binary(getCtcInt(JCTree.class, "EQ"), fieldAccessor, maker.Literal(getCtcInt(TypeTags.class, "BOT"), null)); intoResult.append( maker.Conditional(thisEqualsNull, maker.Literal(0), hcCall)); } @@ -298,8 +298,8 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas /* fold each intoResult entry into: result = result * PRIME + (item); */ for (JCExpression expr : intoResult) { - JCExpression mult = maker.Binary(Javac.getCtcInt(JCTree.class, "MUL"), maker.Ident(resultName), maker.Ident(primeName)); - JCExpression add = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), mult, expr); + JCExpression mult = maker.Binary(getCtcInt(JCTree.class, "MUL"), maker.Ident(resultName), maker.Ident(primeName)); + JCExpression add = maker.Binary(getCtcInt(JCTree.class, "PLUS"), mult, expr); statements.append(maker.Exec(maker.Assign(maker.Ident(resultName), add))); } @@ -308,16 +308,16 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas } JCBlock body = maker.Block(0, statements.toList()); - return Javac.recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("hashCode"), returnType, + return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("hashCode"), returnType, List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null), source); } /** The 2 references must be clones of each other. */ private JCExpression longToIntForHashCode(TreeMaker maker, JCExpression ref1, JCExpression ref2) { /* (int)(ref >>> 32 ^ ref) */ - JCExpression shift = maker.Binary(Javac.getCtcInt(JCTree.class, "USR"), ref1, maker.Literal(32)); - JCExpression xorBits = maker.Binary(Javac.getCtcInt(JCTree.class, "BITXOR"), shift, ref2); - return maker.TypeCast(maker.TypeIdent(Javac.getCtcInt(TypeTags.class, "INT")), xorBits); + JCExpression shift = maker.Binary(getCtcInt(JCTree.class, "USR"), ref1, maker.Literal(32)); + JCExpression xorBits = maker.Binary(getCtcInt(JCTree.class, "BITXOR"), shift, ref2); + return maker.TypeCast(maker.TypeIdent(getCtcInt(TypeTags.class, "INT")), xorBits); } private JCMethodDecl createEquals(JavacNode typeNode, List<JavacNode> fields, boolean callSuper, FieldAccess fieldAccess, boolean needsCanEqual, JCTree source) { @@ -328,21 +328,21 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas Name otherName = typeNode.toName("other"); Name thisName = typeNode.toName("this"); - JCAnnotation overrideAnnotation = maker.Annotation(chainDots(maker, typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); + JCAnnotation overrideAnnotation = maker.Annotation(chainDots(typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); - JCExpression objectType = chainDots(maker, typeNode, "java", "lang", "Object"); - JCExpression returnType = maker.TypeIdent(Javac.getCtcInt(TypeTags.class, "BOOLEAN")); + JCExpression objectType = chainDots(typeNode, "java", "lang", "Object"); + JCExpression returnType = maker.TypeIdent(getCtcInt(TypeTags.class, "BOOLEAN")); ListBuffer<JCStatement> statements = ListBuffer.lb(); final List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(Flags.FINAL), oName, objectType, null)); /* if (o == this) return true; */ { - statements.append(maker.If(maker.Binary(Javac.getCtcInt(JCTree.class, "EQ"), maker.Ident(oName), + statements.append(maker.If(maker.Binary(getCtcInt(JCTree.class, "EQ"), maker.Ident(oName), maker.Ident(thisName)), returnBool(maker, true), null)); } /* if (!(o instanceof MyType) return false; */ { - JCUnary notInstanceOf = maker.Unary(Javac.getCtcInt(JCTree.class, "NOT"), maker.TypeTest(maker.Ident(oName), maker.Ident(type.name))); + JCUnary notInstanceOf = maker.Unary(getCtcInt(JCTree.class, "NOT"), maker.TypeTest(maker.Ident(oName), maker.Ident(type.name))); statements.append(maker.If(notInstanceOf, returnBool(maker, false), null)); } @@ -373,11 +373,11 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas if (needsCanEqual) { List<JCExpression> exprNil = List.nil(); JCExpression thisRef = maker.Ident(thisName); - JCExpression castThisRef = maker.TypeCast(chainDots(maker, typeNode, "java", "lang", "Object"), thisRef); + JCExpression castThisRef = maker.TypeCast(chainDots(typeNode, "java", "lang", "Object"), thisRef); JCExpression equalityCheck = maker.Apply(exprNil, maker.Select(maker.Ident(otherName), typeNode.toName("canEqual")), List.of(castThisRef)); - statements.append(maker.If(maker.Unary(Javac.getCtcInt(JCTree.class, "NOT"), equalityCheck), returnBool(maker, false), null)); + statements.append(maker.If(maker.Unary(getCtcInt(JCTree.class, "NOT"), equalityCheck), returnBool(maker, false), null)); } } @@ -386,7 +386,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("equals")), List.<JCExpression>of(maker.Ident(oName))); - JCUnary superNotEqual = maker.Unary(Javac.getCtcInt(JCTree.class, "NOT"), callToSuper); + JCUnary superNotEqual = maker.Unary(getCtcInt(JCTree.class, "NOT"), callToSuper); statements.append(maker.If(superNotEqual, returnBool(maker, false), null)); } @@ -407,7 +407,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas default: /* if (this.fieldName != other.fieldName) return false; */ statements.append( - maker.If(maker.Binary(Javac.getCtcInt(JCTree.class, "NE"), thisFieldAccessor, otherFieldAccessor), returnBool(maker, false), null)); + maker.If(maker.Binary(getCtcInt(JCTree.class, "NE"), thisFieldAccessor, otherFieldAccessor), returnBool(maker, false), null)); break; } } else if (fType instanceof JCArrayTypeTree) { @@ -416,20 +416,20 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas boolean primitiveArray = ((JCArrayTypeTree)fType).elemtype instanceof JCPrimitiveTypeTree; boolean useDeepEquals = multiDim || !primitiveArray; - JCExpression eqMethod = chainDots(maker, typeNode, "java", "util", "Arrays", useDeepEquals ? "deepEquals" : "equals"); + JCExpression eqMethod = chainDots(typeNode, "java", "util", "Arrays", useDeepEquals ? "deepEquals" : "equals"); List<JCExpression> args = List.of(thisFieldAccessor, otherFieldAccessor); - statements.append(maker.If(maker.Unary(Javac.getCtcInt(JCTree.class, "NOT"), + statements.append(maker.If(maker.Unary(getCtcInt(JCTree.class, "NOT"), maker.Apply(List.<JCExpression>nil(), eqMethod, args)), returnBool(maker, false), null)); } else /* objects */ { /* if (this.fieldName == null ? other.fieldName != null : !this.fieldName.equals(other.fieldName)) return false; */ - JCExpression thisEqualsNull = maker.Binary(Javac.getCtcInt(JCTree.class, "EQ"), thisFieldAccessor, maker.Literal(Javac.getCtcInt(TypeTags.class, "BOT"), null)); - JCExpression otherNotEqualsNull = maker.Binary(Javac.getCtcInt(JCTree.class, "NE"), otherFieldAccessor, maker.Literal(Javac.getCtcInt(TypeTags.class, "BOT"), null)); + JCExpression thisEqualsNull = maker.Binary(getCtcInt(JCTree.class, "EQ"), thisFieldAccessor, maker.Literal(getCtcInt(TypeTags.class, "BOT"), null)); + JCExpression otherNotEqualsNull = maker.Binary(getCtcInt(JCTree.class, "NE"), otherFieldAccessor, maker.Literal(getCtcInt(TypeTags.class, "BOT"), null)); JCExpression equalsArg = createFieldAccessor(maker, fieldNode, fieldAccess, maker.Ident(otherName)); - JCExpression castEqualsArg = maker.TypeCast(chainDots(maker, typeNode, "java", "lang", "Object"), equalsArg); + JCExpression castEqualsArg = maker.TypeCast(chainDots(typeNode, "java", "lang", "Object"), equalsArg); JCExpression thisEqualsThat = maker.Apply(List.<JCExpression>nil(), maker.Select(createFieldAccessor(maker, fieldNode, fieldAccess), typeNode.toName("equals")), List.of(castEqualsArg)); - JCExpression fieldsAreNotEqual = maker.Conditional(thisEqualsNull, otherNotEqualsNull, maker.Unary(Javac.getCtcInt(JCTree.class, "NOT"), thisEqualsThat)); + JCExpression fieldsAreNotEqual = maker.Conditional(thisEqualsNull, otherNotEqualsNull, maker.Unary(getCtcInt(JCTree.class, "NOT"), thisEqualsThat)); statements.append(maker.If(fieldsAreNotEqual, returnBool(maker, false), null)); } } @@ -439,7 +439,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas } JCBlock body = maker.Block(0, statements.toList()); - return Javac.recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("equals"), returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source); + return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("equals"), returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source); } private JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source) { @@ -451,29 +451,29 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas JCClassDecl type = (JCClassDecl) typeNode.get(); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.<JCAnnotation>nil()); - JCExpression returnType = maker.TypeIdent(Javac.getCtcInt(TypeTags.class, "BOOLEAN")); + JCExpression returnType = maker.TypeIdent(getCtcInt(TypeTags.class, "BOOLEAN")); Name canEqualName = typeNode.toName("canEqual"); - JCExpression objectType = chainDots(maker, typeNode, "java", "lang", "Object"); + JCExpression objectType = chainDots(typeNode, "java", "lang", "Object"); Name otherName = typeNode.toName("other"); List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(Flags.FINAL), otherName, objectType, null)); JCBlock body = maker.Block(0, List.<JCStatement>of( maker.Return(maker.TypeTest(maker.Ident(otherName), maker.Ident(type.name))))); - return Javac.recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source); + return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source); } private JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField, TreeMaker maker, JavacNode node, boolean isDouble) { /* if (Float.compare(fieldName, other.fieldName) != 0) return false; */ - JCExpression clazz = chainDots(maker, node, "java", "lang", isDouble ? "Double" : "Float"); + JCExpression clazz = chainDots(node, "java", "lang", isDouble ? "Double" : "Float"); List<JCExpression> args = List.of(thisDotField, otherDotField); - JCBinary compareCallEquals0 = maker.Binary(Javac.getCtcInt(JCTree.class, "NE"), maker.Apply( + JCBinary compareCallEquals0 = maker.Binary(getCtcInt(JCTree.class, "NE"), maker.Apply( List.<JCExpression>nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0)); return maker.If(compareCallEquals0, returnBool(maker, false), null); } private JCStatement returnBool(TreeMaker maker, boolean bool) { - return maker.Return(maker.Literal(Javac.getCtcInt(TypeTags.class, "BOOLEAN"), bool ? 1 : 0)); + return maker.Return(maker.Literal(getCtcInt(TypeTags.class, "BOOLEAN"), bool ? 1 : 0)); } } diff --git a/src/core/lombok/javac/handlers/HandleGetter.java b/src/core/lombok/javac/handlers/HandleGetter.java index a7e357ad..77a63839 100644 --- a/src/core/lombok/javac/handlers/HandleGetter.java +++ b/src/core/lombok/javac/handlers/HandleGetter.java @@ -22,6 +22,7 @@ package lombok.javac.handlers; import static lombok.javac.handlers.JavacHandlerUtil.*; +import static lombok.javac.Javac.*; import java.util.Collection; import java.util.Collections; @@ -31,9 +32,8 @@ import java.util.Map; import lombok.AccessLevel; import lombok.Getter; import lombok.core.AnnotationValues; +import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; -import lombok.core.handlers.TransformationsUtil; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; @@ -74,7 +74,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { if (checkForTypeLevelGetter) { if (typeNode != null) for (JavacNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Javac.annotationTypeMatches(Getter.class, child)) { + if (annotationTypeMatches(Getter.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -125,7 +125,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { public void generateGetterForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level, boolean lazy) { for (JavacNode child : fieldNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Javac.annotationTypeMatches(Getter.class, child)) { + if (annotationTypeMatches(Getter.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -242,10 +242,10 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { List<JCAnnotation> annsOnMethod = nonNulls.appendList(nullables); - JCMethodDecl decl = Javac.recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType, + JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType, methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source); - if (toClearOfMarkers != null) Javac.recursiveSetGeneratedBy(toClearOfMarkers, null); + if (toClearOfMarkers != null) recursiveSetGeneratedBy(toClearOfMarkers, null); return decl; } @@ -260,14 +260,14 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { private static final java.util.Map<Integer, String> TYPE_MAP; static { Map<Integer, String> m = new HashMap<Integer, String>(); - m.put(Javac.getCtcInt(TypeTags.class, "INT"), "java.lang.Integer"); - m.put(Javac.getCtcInt(TypeTags.class, "DOUBLE"), "java.lang.Double"); - m.put(Javac.getCtcInt(TypeTags.class, "FLOAT"), "java.lang.Float"); - m.put(Javac.getCtcInt(TypeTags.class, "SHORT"), "java.lang.Short"); - m.put(Javac.getCtcInt(TypeTags.class, "BYTE"), "java.lang.Byte"); - m.put(Javac.getCtcInt(TypeTags.class, "LONG"), "java.lang.Long"); - m.put(Javac.getCtcInt(TypeTags.class, "BOOLEAN"), "java.lang.Boolean"); - m.put(Javac.getCtcInt(TypeTags.class, "CHAR"), "java.lang.Character"); + m.put(getCtcInt(TypeTags.class, "INT"), "java.lang.Integer"); + m.put(getCtcInt(TypeTags.class, "DOUBLE"), "java.lang.Double"); + m.put(getCtcInt(TypeTags.class, "FLOAT"), "java.lang.Float"); + m.put(getCtcInt(TypeTags.class, "SHORT"), "java.lang.Short"); + m.put(getCtcInt(TypeTags.class, "BYTE"), "java.lang.Byte"); + m.put(getCtcInt(TypeTags.class, "LONG"), "java.lang.Long"); + m.put(getCtcInt(TypeTags.class, "BOOLEAN"), "java.lang.Boolean"); + m.put(getCtcInt(TypeTags.class, "CHAR"), "java.lang.Character"); TYPE_MAP = Collections.unmodifiableMap(m); } @@ -293,14 +293,14 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { if (field.vartype instanceof JCPrimitiveTypeTree) { String boxed = TYPE_MAP.get(((JCPrimitiveTypeTree)field.vartype).typetag); if (boxed != null) { - field.vartype = chainDotsString(maker, fieldNode, boxed); + field.vartype = chainDotsString(fieldNode, boxed); } } Name valueName = fieldNode.toName("value"); /* java.util.concurrent.atomic.AtomicReference<ValueType> value = this.fieldName.get();*/ { - JCTypeApply valueVarType = maker.TypeApply(chainDotsString(maker, fieldNode, AR), List.of(copyType(maker, field))); + JCTypeApply valueVarType = maker.TypeApply(chainDotsString(fieldNode, AR), List.of(copyType(maker, field))); statements.append(maker.VarDef(maker.Modifiers(0), valueName, valueVarType, callGet(fieldNode, createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD)))); } @@ -316,7 +316,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { /* if (value == null) { */ { ListBuffer<JCStatement> innerIfStatements = ListBuffer.lb(); /* value = new java.util.concurrent.atomic.AtomicReference<ValueType>(new ValueType());*/ { - JCTypeApply valueVarType = maker.TypeApply(chainDotsString(maker, fieldNode, AR), List.of(copyType(maker, field))); + JCTypeApply valueVarType = maker.TypeApply(chainDotsString(fieldNode, AR), List.of(copyType(maker, field))); JCNewClass newInstance = maker.NewClass(null, NIL_EXPRESSION, valueVarType, List.<JCExpression>of(field.init), null); JCStatement statement = maker.Exec(maker.Assign(maker.Ident(valueName), newInstance)); @@ -327,7 +327,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { innerIfStatements.append(statement); } - JCBinary isNull = maker.Binary(Javac.getCtcInt(JCTree.class, "EQ"), maker.Ident(valueName), maker.Literal(Javac.getCtcInt(TypeTags.class, "BOT"), null)); + JCBinary isNull = maker.Binary(getCtcInt(JCTree.class, "EQ"), maker.Ident(valueName), maker.Literal(getCtcInt(TypeTags.class, "BOT"), null)); JCIf ifStatement = maker.If(isNull, maker.Block(0, innerIfStatements.toList()), null); synchronizedStatements.append(ifStatement); } @@ -335,7 +335,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { synchronizedStatement = maker.Synchronized(createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD), maker.Block(0, synchronizedStatements.toList())); } - JCBinary isNull = maker.Binary(Javac.getCtcInt(JCTree.class, "EQ"), maker.Ident(valueName), maker.Literal(Javac.getCtcInt(TypeTags.class, "BOT"), null)); + JCBinary isNull = maker.Binary(getCtcInt(JCTree.class, "EQ"), maker.Ident(valueName), maker.Literal(getCtcInt(TypeTags.class, "BOT"), null)); JCIf ifStatement = maker.If(isNull, maker.Block(0, List.<JCStatement>of(synchronizedStatement)), null); statements.append(ifStatement); } @@ -345,10 +345,10 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> { // update the field type and init last /* private final java.util.concurrent.atomic.AtomicReference<java.util.concurrent.atomic.AtomicReference<ValueType> fieldName = new java.util.concurrent.atomic.AtomicReference<java.util.concurrent.atomic.AtomicReference<ValueType>>(); */ { - field.vartype = Javac.recursiveSetGeneratedBy( - maker.TypeApply(chainDotsString(maker, fieldNode, AR), List.<JCExpression>of(maker.TypeApply(chainDotsString(maker, fieldNode, AR), List.of(copyType(maker, field))))), + field.vartype = recursiveSetGeneratedBy( + maker.TypeApply(chainDotsString(fieldNode, AR), List.<JCExpression>of(maker.TypeApply(chainDotsString(fieldNode, AR), List.of(copyType(maker, field))))), source); - field.init = Javac.recursiveSetGeneratedBy(maker.NewClass(null, NIL_EXPRESSION, copyType(maker, field), NIL_EXPRESSION, null), source); + field.init = recursiveSetGeneratedBy(maker.NewClass(null, NIL_EXPRESSION, copyType(maker, field), NIL_EXPRESSION, null), source); } return statements.toList(); diff --git a/src/core/lombok/javac/handlers/HandleLog.java b/src/core/lombok/javac/handlers/HandleLog.java index 885bd538..d084e5b6 100644 --- a/src/core/lombok/javac/handlers/HandleLog.java +++ b/src/core/lombok/javac/handlers/HandleLog.java @@ -26,10 +26,8 @@ import static lombok.javac.handlers.JavacHandlerUtil.*; import java.lang.annotation.Annotation; import lombok.core.AnnotationValues; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; -import lombok.javac.handlers.JavacHandlerUtil.MemberExistsResult; import org.mangosdk.spi.ProviderFor; @@ -86,13 +84,13 @@ public class HandleLog { TreeMaker maker = typeNode.getTreeMaker(); // private static final <loggerType> log = <factoryMethod>(<parameter>); - JCExpression loggerType = chainDotsString(maker, typeNode, framework.getLoggerTypeName()); - JCExpression factoryMethod = chainDotsString(maker, typeNode, framework.getLoggerFactoryMethodName()); + JCExpression loggerType = chainDotsString(typeNode, framework.getLoggerTypeName()); + JCExpression factoryMethod = chainDotsString(typeNode, framework.getLoggerFactoryMethodName()); JCExpression loggerName = framework.createFactoryParameter(typeNode, loggingType); JCMethodInvocation factoryMethodCall = maker.Apply(List.<JCExpression>nil(), factoryMethod, List.<JCExpression>of(loggerName)); - JCVariableDecl fieldDecl = Javac.recursiveSetGeneratedBy(maker.VarDef( + JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef( maker.Modifiers(Flags.PRIVATE | Flags.FINAL | Flags.STATIC), typeNode.toName("log"), loggerType, factoryMethodCall), source); diff --git a/src/core/lombok/javac/handlers/HandleSetter.java b/src/core/lombok/javac/handlers/HandleSetter.java index d899336f..e7a97214 100644 --- a/src/core/lombok/javac/handlers/HandleSetter.java +++ b/src/core/lombok/javac/handlers/HandleSetter.java @@ -22,6 +22,7 @@ package lombok.javac.handlers; import static lombok.javac.handlers.JavacHandlerUtil.*; +import static lombok.javac.Javac.*; import java.util.Collection; @@ -33,11 +34,9 @@ import lombok.AccessLevel; import lombok.Setter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; -import lombok.core.handlers.TransformationsUtil; -import lombok.javac.Javac; +import lombok.core.TransformationsUtil; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; -import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import org.mangosdk.spi.ProviderFor; @@ -68,7 +67,7 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { if (checkForTypeLevelSetter) { if (typeNode != null) for (JavacNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Javac.annotationTypeMatches(Setter.class, child)) { + if (annotationTypeMatches(Setter.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -118,7 +117,7 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { public void generateSetterForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level) { for (JavacNode child : fieldNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Javac.annotationTypeMatches(Setter.class, child)) { + if (annotationTypeMatches(Setter.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -211,14 +210,14 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { List<JCAnnotation> annsOnParam = nonNulls.appendList(nullables); JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(Flags.FINAL, annsOnParam), fieldDecl.name, fieldDecl.vartype, null); //WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6. - JCExpression methodType = treeMaker.Type(new JCNoType(Javac.getCtcInt(TypeTags.class, "VOID"))); + JCExpression methodType = treeMaker.Type(new JCNoType(getCtcInt(TypeTags.class, "VOID"))); List<JCTypeParameter> methodGenericParams = List.nil(); List<JCVariableDecl> parameters = List.of(param); List<JCExpression> throwsClauses = List.nil(); JCExpression annotationMethodDefaultValue = null; - return Javac.recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, List.<JCAnnotation>nil()), methodName, methodType, + return recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, List.<JCAnnotation>nil()), methodName, methodType, methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source); } @@ -229,8 +228,8 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> { @Override public TypeKind getKind() { - if (tag == Javac.getCtcInt(TypeTags.class, "VOID")) return TypeKind.VOID; - if (tag == Javac.getCtcInt(TypeTags.class, "NONE")) return TypeKind.NONE; + if (tag == getCtcInt(TypeTags.class, "VOID")) return TypeKind.VOID; + if (tag == getCtcInt(TypeTags.class, "NONE")) return TypeKind.NONE; throw new AssertionError("Unexpected tag: " + tag); } diff --git a/src/core/lombok/javac/handlers/HandleSneakyThrows.java b/src/core/lombok/javac/handlers/HandleSneakyThrows.java index 5b20d79e..8f6e12d6 100644 --- a/src/core/lombok/javac/handlers/HandleSneakyThrows.java +++ b/src/core/lombok/javac/handlers/HandleSneakyThrows.java @@ -21,8 +21,7 @@ */ package lombok.javac.handlers; -import static lombok.javac.handlers.JavacHandlerUtil.chainDots; -import static lombok.javac.handlers.JavacHandlerUtil.deleteAnnotationIfNeccessary; +import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.ArrayList; import java.util.Collection; @@ -30,7 +29,6 @@ import java.util.Collections; import lombok.SneakyThrows; import lombok.core.AnnotationValues; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; @@ -99,16 +97,16 @@ public class HandleSneakyThrows extends JavacAnnotationHandler<SneakyThrows> { private JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception, JCTree source) { TreeMaker maker = node.getTreeMaker(); - JCBlock tryBlock = Javac.setGeneratedBy(maker.Block(0, contents), source); + JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source); - JCExpression varType = chainDots(maker, node, exception.split("\\.")); + JCExpression varType = chainDots(node, exception.split("\\.")); JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL), node.toName("$ex"), varType, null); - JCExpression lombokLombokSneakyThrowNameRef = chainDots(maker, node, "lombok", "Lombok", "sneakyThrow"); + JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow"); JCBlock catchBody = maker.Block(0, List.<JCStatement>of(maker.Throw(maker.Apply( List.<JCExpression>nil(), lombokLombokSneakyThrowNameRef, List.<JCExpression>of(maker.Ident(node.toName("$ex"))))))); - return Javac.setGeneratedBy(maker.Try(tryBlock, List.of(Javac.recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source)), null), source); + return setGeneratedBy(maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source)), null), source); } } diff --git a/src/core/lombok/javac/handlers/HandleSynchronized.java b/src/core/lombok/javac/handlers/HandleSynchronized.java index fa4a0474..8cdfff68 100644 --- a/src/core/lombok/javac/handlers/HandleSynchronized.java +++ b/src/core/lombok/javac/handlers/HandleSynchronized.java @@ -83,11 +83,11 @@ public class HandleSynchronized extends JavacAnnotationHandler<Synchronized> { annotationNode.addError("The field " + lockName + " does not exist."); return; } - JCExpression objectType = chainDots(maker, methodNode, "java", "lang", "Object"); + JCExpression objectType = chainDots(methodNode, "java", "lang", "Object"); //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable! - JCNewArray newObjectArray = maker.NewArray(chainDots(maker, methodNode, "java", "lang", "Object"), + JCNewArray newObjectArray = maker.NewArray(chainDots(methodNode, "java", "lang", "Object"), List.<JCExpression>of(maker.Literal(Javac.getCtcInt(TypeTags.class, "INT"), 0)), null); - JCVariableDecl fieldDecl = Javac.recursiveSetGeneratedBy(maker.VarDef( + JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef( maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (isStatic ? Flags.STATIC : 0)), methodNode.toName(lockName), objectType, newObjectArray), ast); injectFieldSuppressWarnings(methodNode.up(), fieldDecl); @@ -97,13 +97,13 @@ public class HandleSynchronized extends JavacAnnotationHandler<Synchronized> { JCExpression lockNode; if (isStatic) { - lockNode = chainDots(maker, methodNode, methodNode.up().getName(), lockName); + lockNode = chainDots(methodNode, methodNode.up().getName(), lockName); } else { lockNode = maker.Select(maker.Ident(methodNode.toName("this")), methodNode.toName(lockName)); } - Javac.recursiveSetGeneratedBy(lockNode, ast); - method.body = Javac.setGeneratedBy(maker.Block(0, List.<JCStatement>of(Javac.setGeneratedBy(maker.Synchronized(lockNode, method.body), ast))), ast); + recursiveSetGeneratedBy(lockNode, ast); + method.body = setGeneratedBy(maker.Block(0, List.<JCStatement>of(setGeneratedBy(maker.Synchronized(lockNode, method.body), ast))), ast); methodNode.rebuild(); } diff --git a/src/core/lombok/javac/handlers/HandleToString.java b/src/core/lombok/javac/handlers/HandleToString.java index 06e70e7a..80f77dc7 100644 --- a/src/core/lombok/javac/handlers/HandleToString.java +++ b/src/core/lombok/javac/handlers/HandleToString.java @@ -22,14 +22,13 @@ package lombok.javac.handlers; import static lombok.javac.handlers.JavacHandlerUtil.*; +import static lombok.javac.Javac.getCtcInt; import lombok.ToString; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; -import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import org.mangosdk.spi.ProviderFor; @@ -98,7 +97,7 @@ public class HandleToString extends JavacAnnotationHandler<ToString> { public void generateToStringForType(JavacNode typeNode, JavacNode errorNode) { for (JavacNode child : typeNode.down()) { if (child.getKind() == Kind.ANNOTATION) { - if (Javac.annotationTypeMatches(ToString.class, child)) { + if (annotationTypeMatches(ToString.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -171,9 +170,9 @@ public class HandleToString extends JavacAnnotationHandler<ToString> { private JCMethodDecl createToString(JavacNode typeNode, List<JavacNode> fields, boolean includeFieldNames, boolean callSuper, FieldAccess fieldAccess, JCTree source) { TreeMaker maker = typeNode.getTreeMaker(); - JCAnnotation overrideAnnotation = maker.Annotation(chainDots(maker, typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); + JCAnnotation overrideAnnotation = maker.Annotation(chainDots(typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation)); - JCExpression returnType = chainDots(maker, typeNode, "java", "lang", "String"); + JCExpression returnType = chainDots(typeNode, "java", "lang", "String"); boolean first = true; @@ -197,7 +196,7 @@ public class HandleToString extends JavacAnnotationHandler<ToString> { JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")), List.<JCExpression>nil()); - current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, callToSuper); + current = maker.Binary(getCtcInt(JCTree.class, "PLUS"), current, callToSuper); first = false; } @@ -212,32 +211,32 @@ public class HandleToString extends JavacAnnotationHandler<ToString> { boolean primitiveArray = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCPrimitiveTypeTree; boolean useDeepTS = multiDim || !primitiveArray; - JCExpression hcMethod = chainDots(maker, typeNode, "java", "util", "Arrays", useDeepTS ? "deepToString" : "toString"); + JCExpression hcMethod = chainDots(typeNode, "java", "util", "Arrays", useDeepTS ? "deepToString" : "toString"); expr = maker.Apply(List.<JCExpression>nil(), hcMethod, List.<JCExpression>of(fieldAccessor)); } else expr = fieldAccessor; if (first) { - current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, expr); + current = maker.Binary(getCtcInt(JCTree.class, "PLUS"), current, expr); first = false; continue; } if (includeFieldNames) { - current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(infix + fieldNode.getName() + "=")); + current = maker.Binary(getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(infix + fieldNode.getName() + "=")); } else { - current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(infix)); + current = maker.Binary(getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(infix)); } - current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, expr); + current = maker.Binary(getCtcInt(JCTree.class, "PLUS"), current, expr); } - if (!first) current = maker.Binary(Javac.getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(suffix)); + if (!first) current = maker.Binary(getCtcInt(JCTree.class, "PLUS"), current, maker.Literal(suffix)); JCStatement returnStatement = maker.Return(current); JCBlock body = maker.Block(0, List.of(returnStatement)); - return Javac.recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("toString"), returnType, + return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("toString"), returnType, List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null), source); } diff --git a/src/core/lombok/javac/handlers/HandleVal.java b/src/core/lombok/javac/handlers/HandleVal.java index bc70899d..b8de8996 100644 --- a/src/core/lombok/javac/handlers/HandleVal.java +++ b/src/core/lombok/javac/handlers/HandleVal.java @@ -21,8 +21,9 @@ */ package lombok.javac.handlers; +import static lombok.javac.handlers.JavacHandlerUtil.*; + import lombok.val; -import lombok.javac.Javac; import lombok.javac.JavacASTAdapter; import lombok.javac.JavacASTVisitor; import lombok.javac.JavacNode; @@ -51,7 +52,7 @@ public class HandleVal extends JavacASTAdapter { JCTree source = local.vartype; - if (!Javac.typeMatches(val.class, localNode, local.vartype)) return; + if (!typeMatches(val.class, localNode, local.vartype)) return; JCExpression rhsOfEnhancedForLoop = null; if (local.init == null) { @@ -77,7 +78,7 @@ public class HandleVal extends JavacASTAdapter { local.mods.flags |= Flags.FINAL; if (!localNode.shouldDeleteLombokAnnotations()) { - JCAnnotation valAnnotation = Javac.recursiveSetGeneratedBy(localNode.getTreeMaker().Annotation(local.vartype, List.<JCExpression>nil()), source); + JCAnnotation valAnnotation = recursiveSetGeneratedBy(localNode.getTreeMaker().Annotation(local.vartype, List.<JCExpression>nil()), source); local.mods.annotations = local.mods.annotations == null ? List.of(valAnnotation) : local.mods.annotations.append(valAnnotation); } @@ -126,7 +127,7 @@ public class HandleVal extends JavacASTAdapter { local.vartype = JavacResolution.createJavaLangObject(localNode.getTreeMaker(), localNode.getAst()); throw e; } finally { - Javac.recursiveSetGeneratedBy(local.vartype, source); + recursiveSetGeneratedBy(local.vartype, source); } } } diff --git a/src/core/lombok/javac/handlers/JavacHandlerUtil.java b/src/core/lombok/javac/handlers/JavacHandlerUtil.java index c733304b..fedd9d47 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -21,23 +21,33 @@ */ package lombok.javac.handlers; -import static lombok.javac.Javac.annotationTypeMatches; +import static lombok.javac.Javac.*; import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.WeakHashMap; import java.util.regex.Pattern; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import lombok.core.AnnotationValues; +import lombok.core.TypeLibrary; +import lombok.core.TypeResolver; import lombok.core.AST.Kind; -import lombok.core.handlers.TransformationsUtil; +import lombok.core.AnnotationValues.AnnotationValue; import lombok.javac.Javac; import lombok.javac.JavacNode; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.TreeMaker; @@ -56,6 +66,7 @@ import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; +import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; /** * Container for static utility methods useful to handlers written for javac. @@ -65,12 +76,142 @@ public class JavacHandlerUtil { //Prevent instantiation } + private static class MarkingScanner extends TreeScanner { + private final JCTree source; + + MarkingScanner(JCTree source) { + this.source = source; + } + + @Override public void scan(JCTree tree) { + setGeneratedBy(tree, source); + super.scan(tree); + } + } + + private static Map<JCTree, JCTree> generatedNodes = new WeakHashMap<JCTree, JCTree>(); + + public static JCTree getGeneratedBy(JCTree node) { + synchronized (generatedNodes) { + return generatedNodes.get(node); + } + } + + public static boolean isGenerated(JCTree node) { + return getGeneratedBy(node) != null; + } + + public static <T extends JCTree> T recursiveSetGeneratedBy(T node, JCTree source) { + setGeneratedBy(node, source); + node.accept(new MarkingScanner(source)); + + return node; + } + + public static <T extends JCTree> T setGeneratedBy(T node, JCTree source) { + synchronized (generatedNodes) { + if (source == null) generatedNodes.remove(node); + else generatedNodes.put(node, source); + } + return node; + } + /** - * Checks if the given expression (that really ought to refer to a type expression) represents a primitive type. + * Checks if the Annotation AST Node provided is likely to be an instance of the provided annotation type. + * + * @param type An actual annotation type, such as {@code lombok.Getter.class}. + * @param node A Lombok AST node representing an annotation in source code. + */ + public static boolean annotationTypeMatches(Class<? extends Annotation> type, JavacNode node) { + if (node.getKind() != Kind.ANNOTATION) return false; + return typeMatches(type, node, ((JCAnnotation)node.get()).annotationType); + } + + /** + * Checks if the given TypeReference node is likely to be a reference to the provided class. + * + * @param type An actual type. This method checks if {@code typeNode} is likely to be a reference to this type. + * @param node A Lombok AST node. Any node in the appropriate compilation unit will do (used to get access to import statements). + * @param typeNode A type reference to check. + */ + public static boolean typeMatches(Class<?> type, JavacNode node, JCTree typeNode) { + String typeName = typeNode.toString(); + + TypeLibrary library = new TypeLibrary(); + library.addType(type.getName()); + TypeResolver resolver = new TypeResolver(library, node.getPackageDeclaration(), node.getImportStatements()); + Collection<String> typeMatches = resolver.findTypeMatches(node, typeName); + + for (String match : typeMatches) { + if (match.equals(type.getName())) return true; + } + + return false; + } + + /** + * Creates an instance of {@code AnnotationValues} for the provided AST Node. + * + * @param type An annotation class type, such as {@code lombok.Getter.class}. + * @param node A Lombok AST node representing an annotation in source code. */ - public static boolean isPrimitive(JCExpression ref) { - String typeName = ref.toString(); - return TransformationsUtil.PRIMITIVE_TYPE_NAME_PATTERN.matcher(typeName).matches(); + public static <A extends Annotation> AnnotationValues<A> createAnnotation(Class<A> type, final JavacNode node) { + Map<String, AnnotationValue> values = new HashMap<String, AnnotationValue>(); + JCAnnotation anno = (JCAnnotation) node.get(); + List<JCExpression> arguments = anno.getArguments(); + for (Method m : type.getDeclaredMethods()) { + if (!Modifier.isPublic(m.getModifiers())) continue; + String name = m.getName(); + java.util.List<String> raws = new ArrayList<String>(); + java.util.List<Object> guesses = new ArrayList<Object>(); + java.util.List<Object> expressions = new ArrayList<Object>(); + final java.util.List<DiagnosticPosition> positions = new ArrayList<DiagnosticPosition>(); + boolean isExplicit = false; + + for (JCExpression arg : arguments) { + String mName; + JCExpression rhs; + + if (arg instanceof JCAssign) { + JCAssign assign = (JCAssign) arg; + mName = assign.lhs.toString(); + rhs = assign.rhs; + } else { + rhs = arg; + mName = "value"; + } + + if (!mName.equals(name)) continue; + isExplicit = true; + if (rhs instanceof JCNewArray) { + List<JCExpression> elems = ((JCNewArray)rhs).elems; + for (JCExpression inner : elems) { + raws.add(inner.toString()); + expressions.add(inner); + guesses.add(calculateGuess(inner)); + positions.add(inner.pos()); + } + } else { + raws.add(rhs.toString()); + expressions.add(rhs); + guesses.add(calculateGuess(rhs)); + positions.add(rhs.pos()); + } + } + + values.put(name, new AnnotationValue(node, raws, expressions, guesses, isExplicit) { + @Override public void setError(String message, int valueIdx) { + if (valueIdx < 0) node.addError(message); + else node.addError(message, positions.get(valueIdx)); + } + @Override public void setWarning(String message, int valueIdx) { + if (valueIdx < 0) node.addWarning(message); + else node.addWarning(message, positions.get(valueIdx)); + } + }); + } + + return new AnnotationValues<A>(type, values, node); } /** @@ -133,56 +274,6 @@ public class JavacHandlerUtil { return newAnnotations.toList(); } - /** - * Translates the given field into all possible getter names. - * Convenient wrapper around {@link TransformationsUtil#toAllGetterNames(CharSequence, boolean)}. - */ - public static java.util.List<String> toAllGetterNames(JCVariableDecl field) { - CharSequence fieldName = field.name; - - boolean isBoolean = field.vartype.toString().equals("boolean"); - - return TransformationsUtil.toAllGetterNames(fieldName, isBoolean); - } - - /** - * @return the likely getter name for the stated field. (e.g. private boolean foo; to isFoo). - * - * Convenient wrapper around {@link TransformationsUtil#toGetterName(CharSequence, boolean)}. - */ - public static String toGetterName(JCVariableDecl field) { - CharSequence fieldName = field.name; - - boolean isBoolean = field.vartype.toString().equals("boolean"); - - return TransformationsUtil.toGetterName(fieldName, isBoolean); - } - - /** - * Translates the given field into all possible setter names. - * Convenient wrapper around {@link TransformationsUtil#toAllSetterNames(CharSequence, boolean)}. - */ - public static java.util.List<String> toAllSetterNames(JCVariableDecl field) { - CharSequence fieldName = field.name; - - boolean isBoolean = field.vartype.toString().equals("boolean"); - - return TransformationsUtil.toAllSetterNames(fieldName, isBoolean); - } - - /** - * @return the likely setter name for the stated field. (e.g. private boolean foo; to setFoo). - * - * Convenient wrapper around {@link TransformationsUtil#toSetterName(CharSequence, boolean)}. - */ - public static String toSetterName(JCVariableDecl field) { - CharSequence fieldName = field.name; - - boolean isBoolean = field.vartype.toString().equals("boolean"); - - return TransformationsUtil.toSetterName(fieldName, isBoolean); - } - /** Serves as return value for the methods that check for the existence of fields and methods. */ public enum MemberExistsResult { NOT_EXISTS, EXISTS_BY_LOMBOK, EXISTS_BY_USER; @@ -203,7 +294,7 @@ public class JavacHandlerUtil { for (JCTree def : ((JCClassDecl)node.get()).defs) { if (def instanceof JCVariableDecl) { if (((JCVariableDecl)def).name.contentEquals(fieldName)) { - return Javac.getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } @@ -234,7 +325,7 @@ public class JavacHandlerUtil { if (def instanceof JCMethodDecl) { String name = ((JCMethodDecl)def).name.toString(); boolean matches = caseSensitive ? name.equals(methodName) : name.equalsIgnoreCase(methodName); - if (matches) return Javac.getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + if (matches) return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } @@ -258,7 +349,7 @@ public class JavacHandlerUtil { if (def instanceof JCMethodDecl) { if (((JCMethodDecl)def).name.contentEquals("<init>")) { if ((((JCMethodDecl)def).mods.flags & Flags.GENERATEDCONSTR) != 0) continue; - return Javac.getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; + return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK; } } } @@ -318,7 +409,7 @@ public class JavacHandlerUtil { for (JavacNode child : field.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { - AnnotationValues<Getter> ann = Javac.createAnnotation(Getter.class, child); + AnnotationValues<Getter> ann = createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } @@ -333,7 +424,7 @@ public class JavacHandlerUtil { if (containingType != null) for (JavacNode child : containingType.down()) { if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Data.class, child)) hasGetterAnnotation = true; if (child.getKind() == Kind.ANNOTATION && annotationTypeMatches(Getter.class, child)) { - AnnotationValues<Getter> ann = Javac.createAnnotation(Getter.class, child); + AnnotationValues<Getter> ann = createAnnotation(Getter.class, child); if (ann.getInstance().value() == AccessLevel.NONE) return null; //Definitely WONT have a getter. hasGetterAnnotation = true; } @@ -359,8 +450,8 @@ public class JavacHandlerUtil { // If @Getter(lazy = true) is used, then using it is mandatory. for (JavacNode child : field.down()) { if (child.getKind() != Kind.ANNOTATION) continue; - if (Javac.annotationTypeMatches(Getter.class, child)) { - AnnotationValues<Getter> ann = Javac.createAnnotation(Getter.class, child); + if (annotationTypeMatches(Getter.class, child)) { + AnnotationValues<Getter> ann = createAnnotation(Getter.class, child); if (ann.getInstance().lazy()) return true; } } @@ -440,7 +531,7 @@ public class JavacHandlerUtil { private static void injectField(JavacNode typeNode, JCVariableDecl field, boolean addSuppressWarnings) { JCClassDecl type = (JCClassDecl) typeNode.get(); - if (addSuppressWarnings) addSuppressWarningsAll(field.mods, typeNode, field.pos, Javac.getGeneratedBy(field)); + if (addSuppressWarnings) addSuppressWarningsAll(field.mods, typeNode, field.pos, getGeneratedBy(field)); type.defs = type.defs.append(field); typeNode.add(field, Kind.FIELD); @@ -471,7 +562,7 @@ public class JavacHandlerUtil { } } - addSuppressWarningsAll(method.mods, typeNode, method.pos, Javac.getGeneratedBy(method)); + addSuppressWarningsAll(method.mods, typeNode, method.pos, getGeneratedBy(method)); type.defs = type.defs.append(method); typeNode.add(method, Kind.METHOD); @@ -479,11 +570,11 @@ public class JavacHandlerUtil { private static void addSuppressWarningsAll(JCModifiers mods, JavacNode node, int pos, JCTree source) { TreeMaker maker = node.getTreeMaker(); - JCExpression suppressWarningsType = chainDots(maker, node, "java", "lang", "SuppressWarnings"); + JCExpression suppressWarningsType = chainDots(node, "java", "lang", "SuppressWarnings"); JCLiteral allLiteral = maker.Literal("all"); suppressWarningsType.pos = pos; allLiteral.pos = pos; - JCAnnotation annotation = Javac.recursiveSetGeneratedBy(maker.Annotation(suppressWarningsType, List.<JCExpression>of(allLiteral)), source); + JCAnnotation annotation = recursiveSetGeneratedBy(maker.Annotation(suppressWarningsType, List.<JCExpression>of(allLiteral)), source); annotation.pos = pos; mods.annotations = mods.annotations.append(annotation); } @@ -507,13 +598,13 @@ public class JavacHandlerUtil { * @see com.sun.tools.javac.tree.JCTree.JCIdent * @see com.sun.tools.javac.tree.JCTree.JCFieldAccess */ - public static JCExpression chainDots(TreeMaker maker, JavacNode node, String... elems) { + public static JCExpression chainDots(JavacNode node, String... elems) { assert elems != null; assert elems.length > 0; - JCExpression e = maker.Ident(node.toName(elems[0])); + JCExpression e = node.getTreeMaker().Ident(node.toName(elems[0])); for (int i = 1 ; i < elems.length ; i++) { - e = maker.Select(e, node.toName(elems[i])); + e = node.getTreeMaker().Select(e, node.toName(elems[i])); } return e; @@ -530,8 +621,8 @@ public class JavacHandlerUtil { * @see com.sun.tools.javac.tree.JCTree.JCIdent * @see com.sun.tools.javac.tree.JCTree.JCFieldAccess */ - public static JCExpression chainDotsString(TreeMaker maker, JavacNode node, String elems) { - return chainDots(maker, node, elems.split("\\.")); + public static JCExpression chainDotsString(JavacNode node, String elems) { + return chainDots(node, elems.split("\\.")); } /** @@ -563,7 +654,7 @@ public class JavacHandlerUtil { JCVariableDecl varDecl = (JCVariableDecl) variable.get(); if (isPrimitive(varDecl.vartype)) return null; Name fieldName = varDecl.name; - JCExpression npe = chainDots(treeMaker, variable, "java", "lang", "NullPointerException"); + JCExpression npe = chainDots(variable, "java", "lang", "NullPointerException"); JCTree exception = treeMaker.NewClass(null, List.<JCExpression>nil(), npe, List.<JCExpression>of(treeMaker.Literal(fieldName.toString())), null); JCStatement throwStatement = treeMaker.Throw(exception); return treeMaker.If(treeMaker.Binary(Javac.getCtcInt(JCTree.class, "EQ"), treeMaker.Ident(fieldName), treeMaker.Literal(Javac.getCtcInt(TypeTags.class, "BOT"), null)), throwStatement, null); |