diff options
author | Reinier Zwitserloot <reinier@zwitserloot.com> | 2011-10-24 21:48:43 +0200 |
---|---|---|
committer | Reinier Zwitserloot <reinier@zwitserloot.com> | 2011-10-24 22:02:14 +0200 |
commit | c402dd86379e532895f73ee209c432f84bb5f421 (patch) | |
tree | f5d59432ec551caf2b02c88279a9d8890ef5e26b /src/utils | |
parent | 335d6e64c66f85110cc8cafbe1155917e821db68 (diff) | |
download | lombok-c402dd86379e532895f73ee209c432f84bb5f421.tar.gz lombok-c402dd86379e532895f73ee209c432f84bb5f421.tar.bz2 lombok-c402dd86379e532895f73ee209c432f84bb5f421.zip |
pretty big refactor; introduced a new source package which should be (and is) separately compilable, i.e. has no deps on any of the others.
This is preparation work for being able to access some of these from lombok.ast without creating a cyclic dependency nightmare.
Diffstat (limited to 'src/utils')
-rw-r--r-- | src/utils/lombok/bytecode/AsmUtil.java | 50 | ||||
-rw-r--r-- | src/utils/lombok/bytecode/ClassFileMetaData.java | 453 | ||||
-rw-r--r-- | src/utils/lombok/bytecode/FixedClassWriter.java | 41 | ||||
-rw-r--r-- | src/utils/lombok/core/SpiLoadUtil.java | 191 | ||||
-rw-r--r-- | src/utils/lombok/core/TransformationsUtil.java | 182 | ||||
-rw-r--r-- | src/utils/lombok/eclipse/Eclipse.java | 175 | ||||
-rw-r--r-- | src/utils/lombok/javac/Comment.java | 58 | ||||
-rw-r--r-- | src/utils/lombok/javac/Comments.java | 52 | ||||
-rw-r--r-- | src/utils/lombok/javac/Javac.java | 139 | ||||
-rw-r--r-- | src/utils/lombok/javac/TreeMirrorMaker.java | 86 | ||||
-rw-r--r-- | src/utils/lombok/javac/java6/CommentCollectingScanner.java | 95 | ||||
-rw-r--r-- | src/utils/lombok/javac/java6/CommentCollectingScannerFactory.java | 67 | ||||
-rw-r--r-- | src/utils/lombok/javac/java7/CommentCollectingScanner.java | 95 | ||||
-rw-r--r-- | src/utils/lombok/javac/java7/CommentCollectingScannerFactory.java | 68 |
14 files changed, 1752 insertions, 0 deletions
diff --git a/src/utils/lombok/bytecode/AsmUtil.java b/src/utils/lombok/bytecode/AsmUtil.java new file mode 100644 index 00000000..fa8b9544 --- /dev/null +++ b/src/utils/lombok/bytecode/AsmUtil.java @@ -0,0 +1,50 @@ +/* + * 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 AsmUtil { + + private AsmUtil() { + 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/utils/lombok/bytecode/ClassFileMetaData.java b/src/utils/lombok/bytecode/ClassFileMetaData.java new file mode 100644 index 00000000..b1e0eff3 --- /dev/null +++ b/src/utils/lombok/bytecode/ClassFileMetaData.java @@ -0,0 +1,453 @@ +/* + * 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/utils/lombok/bytecode/FixedClassWriter.java b/src/utils/lombok/bytecode/FixedClassWriter.java new file mode 100644 index 00000000..52de2317 --- /dev/null +++ b/src/utils/lombok/bytecode/FixedClassWriter.java @@ -0,0 +1,41 @@ +/* + * 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/utils/lombok/core/SpiLoadUtil.java b/src/utils/lombok/core/SpiLoadUtil.java new file mode 100644 index 00000000..914cccf8 --- /dev/null +++ b/src/utils/lombok/core/SpiLoadUtil.java @@ -0,0 +1,191 @@ +/* + * 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; + +/** + * 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 (Exception e) { + if (e instanceof RuntimeException) throw (RuntimeException)e; + throw new RuntimeException(e); + } + } + + @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/utils/lombok/core/TransformationsUtil.java b/src/utils/lombok/core/TransformationsUtil.java new file mode 100644 index 00000000..3fbfef58 --- /dev/null +++ b/src/utils/lombok/core/TransformationsUtil.java @@ -0,0 +1,182 @@ +/* + * 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; + +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/utils/lombok/eclipse/Eclipse.java b/src/utils/lombok/eclipse/Eclipse.java new file mode 100644 index 00000000..369a589a --- /dev/null +++ b/src/utils/lombok/eclipse/Eclipse.java @@ -0,0 +1,175 @@ +/* + * 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.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +import lombok.core.TransformationsUtil; + +import org.eclipse.jdt.internal.compiler.ast.ASTNode; +import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; +import org.eclipse.jdt.internal.compiler.ast.Annotation; +import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; +import org.eclipse.jdt.internal.compiler.ast.Clinit; +import org.eclipse.jdt.internal.compiler.ast.Expression; +import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; +import org.eclipse.jdt.internal.compiler.ast.Literal; +import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; +import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; +import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; +import org.eclipse.jdt.internal.compiler.ast.TypeReference; +import org.eclipse.jdt.internal.compiler.lookup.TypeIds; + +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 + } + + /** + * 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; + } + + 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; + } + + /** + * 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); + } + + public static boolean hasClinit(TypeDeclaration parent) { + if (parent.methods == null) return false; + + for (AbstractMethodDeclaration method : parent.methods) { + if (method instanceof Clinit) return true; + } + return false; + } + + /** + * 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]); + } + + /** + * Checks if the given type reference represents a primitive type. + */ + public static boolean isPrimitive(TypeReference ref) { + if (ref.dimensions() > 0) return false; + return TransformationsUtil.PRIMITIVE_TYPE_NAME_PATTERN.matcher(toQualifiedName(ref.getTypeName())).matches(); + } + + /** + * Returns the actual value of the given Literal or Literal-like node. + */ + public 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; + } +} diff --git a/src/utils/lombok/javac/Comment.java b/src/utils/lombok/javac/Comment.java new file mode 100644 index 00000000..f66e1f50 --- /dev/null +++ b/src/utils/lombok/javac/Comment.java @@ -0,0 +1,58 @@ +/* + * 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.javac; + +public final class Comment { + public enum StartConnection { + START_OF_LINE, + ON_NEXT_LINE, + DIRECT_AFTER_PREVIOUS, + AFTER_PREVIOUS + } + + public enum EndConnection { + DIRECT_AFTER_COMMENT, + AFTER_COMMENT, + ON_NEXT_LINE + } + + public final int pos; + public final int prevEndPos; + public final String content; + public final int endPos; + public final StartConnection start; + public final EndConnection end; + + public Comment(int prevEndPos, int pos, int endPos, String content, StartConnection start, EndConnection end) { + this.pos = pos; + this.prevEndPos = prevEndPos; + this.endPos = endPos; + this.content = content; + this.start = start; + this.end = end; + } + + @Override + public String toString() { + return String.format("%d: %s (%s,%s)", pos, content, start, end); + } +} diff --git a/src/utils/lombok/javac/Comments.java b/src/utils/lombok/javac/Comments.java new file mode 100644 index 00000000..2e8ceb26 --- /dev/null +++ b/src/utils/lombok/javac/Comments.java @@ -0,0 +1,52 @@ +/* + * Copyright © 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 com.sun.tools.javac.main.JavaCompiler; +import com.sun.tools.javac.util.Context; + +public class Comments { + public void register(Context context) { + try { + if (JavaCompiler.version().startsWith("1.6")) { + Class.forName("lombok.javac.java6.CommentCollectingScannerFactory").getMethod("preRegister", Context.class).invoke(null, context); + } else { + Class.forName("lombok.javac.java7.CommentCollectingScannerFactory").getMethod("preRegister", Context.class).invoke(null, context); + } + } catch (Exception e) { + if (e instanceof RuntimeException) throw (RuntimeException)e; + throw new RuntimeException(e); + } + context.put(Comments.class, (Comments) null); + context.put(Comments.class, this); + } + + private com.sun.tools.javac.util.ListBuffer<Comment> comments = com.sun.tools.javac.util.ListBuffer.lb(); + + public com.sun.tools.javac.util.ListBuffer<Comment> getComments() { + return comments; + } + + public void add(Comment comment) { + comments.append(comment); + } +} diff --git a/src/utils/lombok/javac/Javac.java b/src/utils/lombok/javac/Javac.java new file mode 100644 index 00000000..cd24b061 --- /dev/null +++ b/src/utils/lombok/javac/Javac.java @@ -0,0 +1,139 @@ +/* + * 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 lombok.core.TransformationsUtil; + +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.JCVariableDecl; + +/** + * Container for static utility methods relevant to lombok's operation on javac. + */ +public class Javac { + private Javac() { + //prevent instantiation + } + + /** + * 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); + } + + /** + * Checks if the given expression (that really ought to refer to a type expression) represents a primitive type. + */ + public static boolean isPrimitive(JCExpression ref) { + String typeName = ref.toString(); + return TransformationsUtil.PRIMITIVE_TYPE_NAME_PATTERN.matcher(typeName).matches(); + } + + /** + * 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)'. + */ + public 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 new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/utils/lombok/javac/TreeMirrorMaker.java b/src/utils/lombok/javac/TreeMirrorMaker.java new file mode 100644 index 00000000..4fe59ff1 --- /dev/null +++ b/src/utils/lombok/javac/TreeMirrorMaker.java @@ -0,0 +1,86 @@ +/* + * 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.tree.TreeMaker; +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(TreeMaker maker) { + super(maker); + } + + @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/utils/lombok/javac/java6/CommentCollectingScanner.java b/src/utils/lombok/javac/java6/CommentCollectingScanner.java new file mode 100644 index 00000000..363e04ba --- /dev/null +++ b/src/utils/lombok/javac/java6/CommentCollectingScanner.java @@ -0,0 +1,95 @@ +/* + * Copyright © 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.java6; + +import java.nio.CharBuffer; + +import lombok.javac.Comment; +import lombok.javac.Comments; +import lombok.javac.Comment.EndConnection; +import lombok.javac.Comment.StartConnection; + +import com.sun.tools.javac.parser.Scanner; + +public class CommentCollectingScanner extends Scanner { + private final Comments comments; + private int endComment = 0; + + public CommentCollectingScanner(CommentCollectingScannerFactory factory, CharBuffer charBuffer, Comments comments) { + super(factory, charBuffer); + this.comments = comments; + } + + public CommentCollectingScanner(CommentCollectingScannerFactory factory, char[] input, int inputLength, Comments comments) { + super(factory, input, inputLength); + this.comments = comments; + } + + @Override + protected void processComment(CommentStyle style) { + int prevEndPos = Math.max(prevEndPos(), endComment); + int pos = pos(); + int endPos = endPos(); + endComment = endPos; + String content = new String(getRawCharacters(pos, endPos)); + StartConnection start = determineStartConnection(prevEndPos, pos); + EndConnection end = determineEndConnection(endPos); + + Comment comment = new Comment(prevEndPos, pos, endPos, content, start, end); + comments.add(comment); + } + + private EndConnection determineEndConnection(int pos) { + boolean first = true; + for (int i = pos;; i++) { + char c = getRawCharacters(i, i + 1)[0]; + if (isNewLine(c)) { + return EndConnection.ON_NEXT_LINE; + } + if (Character.isWhitespace(c)) { + first = false; + continue; + } + return first ? EndConnection.DIRECT_AFTER_COMMENT : EndConnection.AFTER_COMMENT; + } + } + + private StartConnection determineStartConnection(int from, int to) { + if (from == to) { + return StartConnection.DIRECT_AFTER_PREVIOUS; + } + char[] between = getRawCharacters(from, to); + if (isNewLine(between[between.length - 1])) { + return StartConnection.START_OF_LINE; + } + for (char c : between) { + if (isNewLine(c)) { + return StartConnection.ON_NEXT_LINE; + } + } + return StartConnection.AFTER_PREVIOUS; + } + + private boolean isNewLine(char c) { + return c == '\n' || c == '\r'; + } +} diff --git a/src/utils/lombok/javac/java6/CommentCollectingScannerFactory.java b/src/utils/lombok/javac/java6/CommentCollectingScannerFactory.java new file mode 100644 index 00000000..c259a4cf --- /dev/null +++ b/src/utils/lombok/javac/java6/CommentCollectingScannerFactory.java @@ -0,0 +1,67 @@ +/* + * Copyright © 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.java6; + +import java.nio.CharBuffer; + +import lombok.javac.Comments; + +import com.sun.tools.javac.parser.Scanner; +import com.sun.tools.javac.util.Context; + +public class CommentCollectingScannerFactory extends Scanner.Factory { + private final Context context; + + public static void preRegister(final Context context) { + if (context.get(scannerFactoryKey) == null) { + context.put(scannerFactoryKey, new Context.Factory<Scanner.Factory>() { + public CommentCollectingScanner.Factory make() { + return new CommentCollectingScannerFactory(context); + } + + public CommentCollectingScanner.Factory make(Context c) { + return new CommentCollectingScannerFactory(c); + } + }); + } + } + + /** Create a new scanner factory. */ + protected CommentCollectingScannerFactory(Context context) { + super(context); + this.context = context; + } + + @Override + public Scanner newScanner(CharSequence input) { + if (input instanceof CharBuffer) { + return new CommentCollectingScanner(this, (CharBuffer)input, context.get(Comments.class)); + } + char[] array = input.toString().toCharArray(); + return newScanner(array, array.length); + } + + @Override + public Scanner newScanner(char[] input, int inputLength) { + return new CommentCollectingScanner(this, input, inputLength, context.get(Comments.class)); + } +}
\ No newline at end of file diff --git a/src/utils/lombok/javac/java7/CommentCollectingScanner.java b/src/utils/lombok/javac/java7/CommentCollectingScanner.java new file mode 100644 index 00000000..2c588175 --- /dev/null +++ b/src/utils/lombok/javac/java7/CommentCollectingScanner.java @@ -0,0 +1,95 @@ +/* + * Copyright © 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.java7; + +import java.nio.CharBuffer; + +import lombok.javac.Comment; +import lombok.javac.Comment.EndConnection; +import lombok.javac.Comment.StartConnection; +import lombok.javac.Comments; + +import com.sun.tools.javac.parser.Scanner; + +public class CommentCollectingScanner extends Scanner { + private final Comments comments; + private int endComment = 0; + + public CommentCollectingScanner(CommentCollectingScannerFactory factory, CharBuffer charBuffer, Comments comments) { + super(factory, charBuffer); + this.comments = comments; + } + + public CommentCollectingScanner(CommentCollectingScannerFactory factory, char[] input, int inputLength, Comments comments) { + super(factory, input, inputLength); + this.comments = comments; + } + + @Override + protected void processComment(CommentStyle style) { + int prevEndPos = Math.max(prevEndPos(), endComment); + int pos = pos(); + int endPos = endPos(); + endComment = endPos; + String content = new String(getRawCharacters(pos, endPos)); + StartConnection start = determineStartConnection(prevEndPos, pos); + EndConnection end = determineEndConnection(endPos); + + Comment comment = new Comment(prevEndPos, pos, endPos, content, start, end); + comments.add(comment); + } + + private EndConnection determineEndConnection(int pos) { + boolean first = true; + for (int i = pos;; i++) { + char c = getRawCharacters(i, i + 1)[0]; + if (isNewLine(c)) { + return EndConnection.ON_NEXT_LINE; + } + if (Character.isWhitespace(c)) { + first = false; + continue; + } + return first ? EndConnection.DIRECT_AFTER_COMMENT : EndConnection.AFTER_COMMENT; + } + } + + private StartConnection determineStartConnection(int from, int to) { + if (from == to) { + return StartConnection.DIRECT_AFTER_PREVIOUS; + } + char[] between = getRawCharacters(from, to); + if (isNewLine(between[between.length - 1])) { + return StartConnection.START_OF_LINE; + } + for (char c : between) { + if (isNewLine(c)) { + return StartConnection.ON_NEXT_LINE; + } + } + return StartConnection.AFTER_PREVIOUS; + } + + private boolean isNewLine(char c) { + return c == '\n' || c == '\r'; + } +} diff --git a/src/utils/lombok/javac/java7/CommentCollectingScannerFactory.java b/src/utils/lombok/javac/java7/CommentCollectingScannerFactory.java new file mode 100644 index 00000000..c6cf4011 --- /dev/null +++ b/src/utils/lombok/javac/java7/CommentCollectingScannerFactory.java @@ -0,0 +1,68 @@ +/* + * Copyright © 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.java7; + +import java.nio.CharBuffer; + +import lombok.javac.Comments; + +import com.sun.tools.javac.parser.Scanner; +import com.sun.tools.javac.parser.ScannerFactory; +import com.sun.tools.javac.util.Context; + +public class CommentCollectingScannerFactory extends ScannerFactory { + private final Context context; + + public static void preRegister(final Context context) { + if (context.get(scannerFactoryKey) == null) { + context.put(scannerFactoryKey, new Context.Factory<ScannerFactory>() { + public ScannerFactory make() { + return new CommentCollectingScannerFactory(context); + } + + @Override public ScannerFactory make(Context c) { + return new CommentCollectingScannerFactory(c); + } + }); + } + } + + /** Create a new scanner factory. */ + protected CommentCollectingScannerFactory(Context context) { + super(context); + this.context = context; + } + + @Override + public Scanner newScanner(CharSequence input, boolean keepDocComments) { + if (input instanceof CharBuffer) { + return new CommentCollectingScanner(this, (CharBuffer)input, context.get(Comments.class)); + } + char[] array = input.toString().toCharArray(); + return newScanner(array, array.length, keepDocComments); + } + + @Override + public Scanner newScanner(char[] input, int inputLength, boolean keepDocComments) { + return new CommentCollectingScanner(this, input, inputLength, context.get(Comments.class)); + } +} |