aboutsummaryrefslogtreecommitdiff
path: root/src/lombok/eclipse/HandlerLibrary.java
blob: f458cf4593cc46290b151f1bd80cc5a73b8bd177 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package lombok.eclipse;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;

import lombok.core.TypeLibrary;
import lombok.eclipse.EclipseAST.Node;

import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer;
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.ImportReference;
import org.eclipse.jdt.internal.compiler.ast.Literal;
import org.eclipse.jdt.internal.compiler.ast.MemberValuePair;
import org.eclipse.jdt.internal.compiler.ast.NameReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;

public class HandlerLibrary {
	private TypeLibrary typeLibrary = new TypeLibrary();
	
	private static class AnnotationHandlerContainer<T extends Annotation> {
		private EclipseAnnotationHandler<T> handler;
		private Class<T> annotationClass;
		
		AnnotationHandlerContainer(EclipseAnnotationHandler<T> handler, Class<T> annotationClass) {
			this.handler = handler;
			this.annotationClass = annotationClass;
		}
		
		@SuppressWarnings("unchecked")
		public void handle(Object annInstance,
				org.eclipse.jdt.internal.compiler.ast.Annotation annotation,
				Node annotationNode) {
			handler.handle((T) annInstance, annotation, annotationNode);
		}
	}
	
	private Map<String, AnnotationHandlerContainer<?>> annotationHandlers =
		new HashMap<String, AnnotationHandlerContainer<?>>();
	
	private Collection<EclipseASTVisitor> visitorHandlers = new ArrayList<EclipseASTVisitor>();
	
	@SuppressWarnings("unchecked")
	public <A extends Annotation> A createAnnotation(Class<A> target,
			CompilationUnitDeclaration ast,
			org.eclipse.jdt.internal.compiler.ast.Annotation node) throws EnumDecodeFail {
		final Map<String, Object> values = new HashMap<String, Object>();
		
		final MemberValuePair[] pairs = node.memberValuePairs();
		
		for ( Method m : target.getMethods() ) {
			String name = m.getName();
			Object value = m.getDefaultValue();
			for ( MemberValuePair pair : pairs ) {
				if ( name.equals(new String(pair.name)) ) {
					value = calculateValue(pair, ast, m.getReturnType(), pair.value);
					break;
				}
			}
			values.put(name, value);
		}
		
		InvocationHandler invocations = new InvocationHandler() {
			@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				return values.get(method.getName());
			}
		};
		
		return (A) Proxy.newProxyInstance(target.getClassLoader(), new Class[] { target }, invocations);
	}
	
	private Object calculateValue(MemberValuePair pair,
			CompilationUnitDeclaration ast, Class<?> type, Expression e) throws EnumDecodeFail {
		if ( e instanceof Literal ) {
			((Literal)e).computeConstant();
			return convertConstant(pair, type, e.constant);
		} else if ( e instanceof ArrayInitializer ) {
			if ( !type.isArray() ) throw new EnumDecodeFail(pair, "Did not expect an array here.");
			
			Class<?> component = type.getComponentType();
			Expression[] expressions = ((ArrayInitializer)e).expressions;
			int length = expressions == null ? 0 : expressions.length;
			Object[] values = new Object[length];
			for (int i = 0; i < length; i++) {
				values[i] = calculateValue(pair, ast, component, expressions[i]);
			}
			return values;
		} else if ( e instanceof ClassLiteralAccess ) {
			if ( type == Class.class ) return toClass(pair, ast, str(((ClassLiteralAccess)e).type.getTypeName()));
			else throw new EnumDecodeFail(pair, "Expected a " + type + " literal.");
		} else if ( e instanceof NameReference ) {
			String s = null;
			if ( e instanceof SingleNameReference ) s = new String(((SingleNameReference)e).token);
			else if ( e instanceof QualifiedNameReference ) s = str(((QualifiedNameReference)e).tokens);
			if ( Enum.class.isAssignableFrom(type) ) return toEnum(pair, type, s);
			throw new EnumDecodeFail(pair, "Lombok annotations must contain literals only.");
		} else {
			throw new EnumDecodeFail(pair, "Lombok could not decode this annotation parameter.");
		}
	}
	
	private Enum<?> toEnum(MemberValuePair pair, Class<?> enumType, String ref) throws EnumDecodeFail {
		int idx = ref.indexOf('.');
		if ( idx > -1 ) ref = ref.substring(idx +1);
		Object[] enumConstants = enumType.getEnumConstants();
		for ( Object constant : enumConstants ) {
			String target = ((Enum<?>)constant).name();
			if ( target.equals(ref) ) return (Enum<?>) constant;
		}
		throw new EnumDecodeFail(pair, "I can't figure out which enum constant you mean.");
	}
	
	private Class<?> toClass(MemberValuePair pair, CompilationUnitDeclaration ast, String typeName) throws EnumDecodeFail {
		Class<?> c;
		boolean fqn = typeName.indexOf('.') > -1;
		
		if ( fqn ) {
			c = tryClass(typeName);
			if ( c != null ) return c;
		}
		
		for ( ImportReference ref : ast.imports ) {
			String im = str(ref.tokens);
			int idx = im.lastIndexOf('.');
			String simple = im;
			if ( idx > -1 ) simple = im.substring(idx+1);
			if ( simple.equals(typeName) ) {
				c = tryClass(im);
				if ( c != null ) return c;
			}
		}
		
		if ( ast.currentPackage != null && ast.currentPackage.tokens != null ) {
			String pkg = str(ast.currentPackage.tokens);
			c = tryClass(pkg + "." + typeName);
			if ( c != null ) return c;
		}
		
		c = tryClass("java.lang." + typeName);
		if ( c != null ) return c;
		
		if ( !fqn ) {
			c = tryClass(typeName);
			if ( c != null ) return c;
		}
		
		//Try star imports
		for ( ImportReference ref : ast.imports ) {
			String im = str(ref.tokens);
			if ( im.endsWith(".*") ) {
				c = tryClass(im.substring(0, im.length() -1) + typeName);
				if ( c != null ) return c;
			}
		}
		
		throw new EnumDecodeFail(pair, "I can't find this class. Try using the fully qualified name.");
	}
	
	private Class<?> tryClass(String name) {
		try {
			return Class.forName(name);
		} catch ( ClassNotFoundException e ) {
			return null;
		}
	}
	
	private Object convertConstant(MemberValuePair pair, Class<?> type, Constant constant) throws EnumDecodeFail {
		int targetTypeID;
		boolean array = type.isArray();
		if ( array ) type = type.getComponentType();
		
		if ( type == int.class ) targetTypeID = TypeIds.T_int;
		else if ( type == long.class ) targetTypeID = TypeIds.T_long;
		else if ( type == short.class ) targetTypeID = TypeIds.T_short;
		else if ( type == byte.class ) targetTypeID = TypeIds.T_byte;
		else if ( type == double.class ) targetTypeID = TypeIds.T_double;
		else if ( type == float.class ) targetTypeID = TypeIds.T_float;
		else if ( type == String.class ) targetTypeID = TypeIds.T_JavaLangString;
		else if ( type == char.class ) targetTypeID = TypeIds.T_char;
		else if ( type == boolean.class ) targetTypeID = TypeIds.T_boolean;
		else {
			//Enum or Class, so a constant isn't going to be very useful.
			throw new EnumDecodeFail(pair, "Expected a constant of some sort here (a number or a string)");
		}
		if ( !Expression.isConstantValueRepresentable(constant, constant.typeID(), targetTypeID) ) {
			throw new EnumDecodeFail(pair, "I can't turn this literal into a " + type);
		}
		
		Object o = null;
		
		if ( type == int.class ) o = constant.intValue();
		else if ( type == long.class ) o = constant.longValue();
		else if ( type == short.class ) o = constant.shortValue();
		else if ( type == byte.class ) o = constant.byteValue();
		else if ( type == double.class ) o = constant.doubleValue();
		else if ( type == float.class ) o = constant.floatValue();
		else if ( type == String.class ) o = constant.stringValue();
		else if ( type == char.class ) o = constant.charValue();
		else if ( type == boolean.class ) o = constant.booleanValue();
		
		if ( array ) {
			Object a = Array.newInstance(type, 1);
			Array.set(a, 0, o);
			return a;
		}
		
		return o;
	}
	
	private static class EnumDecodeFail extends Exception {
		private static final long serialVersionUID = 1L;
		
		MemberValuePair pair;
		
		EnumDecodeFail(MemberValuePair pair, String msg) {
			super(msg);
			this.pair = pair;
		}
	}
	
	private static String str(char[][] c) {
		boolean first = true;
		StringBuilder sb = new StringBuilder();
		for ( char[] part : c ) {
			sb.append(first ? "" : ".").append(part);
			first = false;
		}
		return sb.toString();
	}
	
	public static HandlerLibrary load() {
		HandlerLibrary lib = new HandlerLibrary();
		
		loadAnnotationHandlers(lib);
		loadVisitorHandlers(lib);
		
		return lib;
	}
	
	@SuppressWarnings("unchecked") private static void loadAnnotationHandlers(HandlerLibrary lib) {
		Iterator<EclipseAnnotationHandler> it = ServiceLoader.load(EclipseAnnotationHandler.class).iterator();
		while ( it.hasNext() ) {
			try {
				EclipseAnnotationHandler<?> handler = it.next();
				Class<? extends Annotation> annotationClass = lib.findAnnotationClass(handler.getClass());
				AnnotationHandlerContainer<?> container = new AnnotationHandlerContainer(handler, annotationClass);
				if ( lib.annotationHandlers.put(container.annotationClass.getName(), container) != null ) {
					Eclipse.error("Duplicate handlers for annotation type: " + container.annotationClass.getName());
				}
				lib.typeLibrary.addType(container.annotationClass.getName());
			} catch ( ServiceConfigurationError e ) {
				Eclipse.error("Can't load Lombok annotation handler for eclipse: ", e);
			}
		}
	}
	
	private static void loadVisitorHandlers(HandlerLibrary lib) {
		Iterator<EclipseASTVisitor> it = ServiceLoader.load(EclipseASTVisitor.class).iterator();
		while ( it.hasNext() ) {
			try {
				lib.visitorHandlers.add(it.next());
			} catch ( ServiceConfigurationError e ) {
				Eclipse.error("Can't load Lombok visitor handler for eclipse: ", e);
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	private Class<? extends Annotation> findAnnotationClass(Class<?> c) {
		if ( c == Object.class || c == null ) return null;
		for ( Type iface : c.getGenericInterfaces() ) {
			if ( iface instanceof ParameterizedType ) {
				ParameterizedType p = (ParameterizedType)iface;
				if ( !EclipseAnnotationHandler.class.equals(p.getRawType()) ) continue;
				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);
			}
		}
		
		Class<? extends Annotation> potential = findAnnotationClass(c.getSuperclass());
		if ( potential != null ) return potential;
		for ( Class<?> iface : c.getInterfaces() ) {
			potential = findAnnotationClass(iface);
			if ( potential != null ) return potential;
		}
		
		return null;
	}
	
	public void handle(CompilationUnitDeclaration ast, EclipseAST.Node annotationNode,
			org.eclipse.jdt.internal.compiler.ast.Annotation annotation) {
		TypeResolver resolver = new TypeResolver(typeLibrary, annotationNode.top());
		TypeReference rawType = annotation.type;
		if ( rawType == null ) return;
		for ( String fqn : resolver.findTypeMatches(annotationNode, annotation.type) ) {
			AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn);
			if ( container == null ) continue;
			Object annInstance;
			try {
				annInstance = createAnnotation(container.annotationClass, ast, annotation);
			} catch ( EnumDecodeFail e ) {
				annotationNode.addError(e.getMessage(), e.pair.sourceStart, e.pair.sourceEnd);
				return;
			}
			
			try {
				container.handle(annInstance, annotation, annotationNode);
			} catch ( Throwable t ) {
				Eclipse.error(String.format("Lombok annotation handler %s failed", container.handler.getClass()), t);
			}
		}
	}
	
	public void callASTVisitors(EclipseAST ast) {
		for ( EclipseASTVisitor visitor : visitorHandlers ) try {
			ast.traverse(visitor);
		} catch ( Throwable t ) {
			Eclipse.error(String.format("Lombok visitor handler %s failed", visitor.getClass()), t);
		}
	}
}