aboutsummaryrefslogtreecommitdiff
path: root/test/core/src/lombok/RunTestsViaEclipse.java
blob: 03f205baab78df441ba18670e46be26198292f68 (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
/*
 * 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;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.eclipse.jdt.core.compiler.CategorizedProblem;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
import org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.eclipse.jdt.internal.compiler.ISourceElementRequestor;
import org.eclipse.jdt.internal.compiler.SourceElementParser;
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.batch.CompilationUnit;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;

/**
 * Simulates more or less what happens in eclipse
 */
public class RunTestsViaEclipse extends AbstractRunTests {
	protected static CompilerOptions ecjCompilerOptions() {
		CompilerOptions options = new CompilerOptions();
		options.complianceLevel = ClassFileConstants.JDK1_6;
		options.sourceLevel = ClassFileConstants.JDK1_6;
		options.targetJDK = ClassFileConstants.JDK1_6;
		options.parseLiteralExpressionsAsConstants = true;
		return options;
	}
	
	@Override public void transformCode(final StringBuilder messages, StringWriter result, File file) throws Throwable {
		String source = readFile(file);
		CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(), "UTF-8");
		IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
		IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);
		INameEnvironment nameEnvironment = new LombokTestNameEnvironment();
		ICompilerRequestor compilerRequestor = new LombokTestCompilerRequestor();
		CompilerOptions options = ecjCompilerOptions();
		
		
		ISourceElementRequestor sourceElementRequestor = new LombokTestSourceElementRequestor();
		SourceElementParser parser = new SourceElementParser(sourceElementRequestor, problemFactory, options, true, true);
		final CompilationUnitDeclaration cud = parser.parseCompilationUnit(sourceUnit, true, null);
		
		final LombokTestCompiler jdtCompiler = new LombokTestCompiler(nameEnvironment, policy, options, compilerRequestor, problemFactory);
		jdtCompiler.lookupEnvironment.buildTypeBindings(cud, null);
		jdtCompiler.lookupEnvironment.completeTypeBindings(cud, true);
		
		CategorizedProblem[] problems = cud.compilationResult.getAllProblems();
		
		if (problems != null) for (CategorizedProblem p : problems) {
			messages.append(String.format("%d %s %s\n", p.getSourceLineNumber(), p.isError() ? "error" : p.isWarning() ? "warning" : "unknown", p.getMessage()));
		}
		
		result.append(cud.toString());
	}
	
	private static class LombokTestCompiler extends Compiler {
		public LombokTestCompiler(INameEnvironment nameEnvironment, IErrorHandlingPolicy policy, CompilerOptions ecjCompilerOptions, ICompilerRequestor requestor, IProblemFactory problemFactory) {
			super(nameEnvironment, policy, ecjCompilerOptions, requestor, problemFactory);
		}
		
		@Override protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud, CompilationResult result) {
			throw new RuntimeException(e);
		}
		
		@Override public void beginToCompile(ICompilationUnit[] sourceUnits) {
			super.beginToCompile(sourceUnits);
		}
	};
	
	private static class LombokTestCompilerRequestor implements ICompilerRequestor {
		public void acceptResult(CompilationResult result) {
		}
	}
	
	private static class LombokTestSourceElementRequestor implements ISourceElementRequestor {

		@Override public void acceptAnnotationTypeReference(char[][] annotation, int sourceStart, int sourceEnd) {
			// do nothing
		}

		@Override public void acceptAnnotationTypeReference(char[] annotation, int sourcePosition) {
			// do nothing
		}

		@Override public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) {
			// do nothing
		}

		@Override public void acceptFieldReference(char[] fieldName, int sourcePosition) {
			// do nothing
		}

		@Override public void acceptImport(int declarationStart, int declarationEnd, char[][] tokens, boolean onDemand, int modifiers) {
			// do nothing
		}

		@Override public void acceptLineSeparatorPositions(int[] positions) {
			// do nothing
		}

		@Override public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) {
			// do nothing
		}

		@Override public void acceptPackage(ImportReference importReference) {
			// do nothing
		}

		@Override public void acceptProblem(CategorizedProblem problem) {
			// do nothing
		}

		@Override public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) {
			// do nothing
		}

		@Override public void acceptTypeReference(char[] typeName, int sourcePosition) {
			// do nothing
		}

		@Override public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) {
			// do nothing
		}

		@Override public void acceptUnknownReference(char[] name, int sourcePosition) {
			// do nothing
		}

		@Override public void enterCompilationUnit() {
			// do nothing
		}

		@Override public void enterConstructor(MethodInfo methodInfo) {
			// do nothing
		}

		@Override public void enterField(FieldInfo fieldInfo) {
			// do nothing
		}

		@Override public void enterInitializer(int declarationStart, int modifiers) {
			// do nothing
		}

		@Override public void enterMethod(MethodInfo methodInfo) {
			// do nothing
		}

		@Override public void enterType(TypeInfo typeInfo) {
			// do nothing
		}

		@Override public void exitCompilationUnit(int declarationEnd) {
			// do nothing
		}

		@Override public void exitConstructor(int declarationEnd) {
			// do nothing
		}

		@Override public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) {
			// do nothing
		}

		@Override public void exitInitializer(int declarationEnd) {
			// do nothing
		}

		@Override public void exitMethod(int declarationEnd, Expression defaultValue) {
			// do nothing
		}

		@Override public void exitType(int declarationEnd) {
			// do nothing
		}
	}
	
	private static class LombokTestNameEnvironment implements INameEnvironment {
		Map<String, Boolean> packagesCache = new HashMap<String, Boolean>();
		
		public NameEnvironmentAnswer findType(final char[][] compoundTypeName) {
			final StringBuffer result = new StringBuffer();
			for (int i = 0; i < compoundTypeName.length; i++) {
				if (i != 0) {
					result.append('.');
				}
				result.append(compoundTypeName[i]);
			}
			return findType(result.toString());
		}
		
		public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) {
			final StringBuffer result = new StringBuffer();
			for (int i = 0; i < packageName.length; i++) {
				result.append(packageName[i]);
				result.append('.');
			}
			result.append(typeName);
			return findType(result.toString());
		}
		
		protected byte[] getClassDefinition(String name) {
			name = name.replace(".", "/") + ".class";
			InputStream is = this.getClass().getClassLoader().getResourceAsStream(name);
			if (is == null) {
				return null;
			}
			try {
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				byte[] buffer = new byte[8192];
				int count;
				while ((count = is.read(buffer, 0, buffer.length)) > 0) {
					os.write(buffer, 0, count);
				}
				return os.toByteArray();
			} catch (Exception e) {
				throw new RuntimeException(e);
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
		
		private NameEnvironmentAnswer findType(final String name) {
			try {
				byte[] bytes = getClassDefinition(name);
				if (bytes != null) {
					ClassFileReader classFileReader;
					classFileReader = new ClassFileReader(bytes, name.toCharArray(), true);
					return new NameEnvironmentAnswer(classFileReader, null);
				}
				return null;
			} catch (ClassFormatException e) {
				throw new RuntimeException(e);
			}
		}
		
		public boolean isPackage(char[][] parentPackageName, char[] packageName) {
			final StringBuilder sb = new StringBuilder();
			if (parentPackageName != null) {
				for (char[] p : parentPackageName) {
					sb.append(p).append("/");
				}
			}
			sb.append(packageName);
			String name = sb.toString();
			if (packagesCache.containsKey(name)) {
				return packagesCache.get(name).booleanValue();
			}
			byte[] bytes = getClassDefinition(name);
			if (bytes != null) {
				packagesCache.put(name, false);
				return false;
			}
			packagesCache.put(name, true);
			return true;
		}
		
		public void cleanup() {
		}
	}
}