aboutsummaryrefslogtreecommitdiff
path: root/src_eclipseagent/lombok/agent/eclipse/EclipseParserPatcher.java
blob: 81309b344a7288bf0425dea03605ab7c203d4b3f (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
package lombok.agent.eclipse;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.security.ProtectionDomain;

public class EclipseParserPatcher {
	private static class Patcher implements ClassFileTransformer {
		@Override public byte[] transform(ClassLoader loader, String className,
				Class<?> classBeingRedefined,
				ProtectionDomain protectionDomain, byte[] classfileBuffer)
				throws IllegalClassFormatException {
			
			if ( ECLIPSE_PARSER_CLASS_NAME.equals(className) ) {
				EclipseParserTransformer transformer = new EclipseParserTransformer(classfileBuffer);
				return transformer.transform();
			}
			
			if ( ECLIPSE_CUD_CLASS_NAME.equals(className) ) {
				EclipseCUDTransformer transformer = new EclipseCUDTransformer(classfileBuffer);
				return transformer.transform();
			}
			
			return null;
		}
	}
	
	static final String ECLIPSE_CUD_CLASS_NAME = "org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration";
	static final String ECLIPSE_PARSER_CLASS_NAME = "org/eclipse/jdt/internal/compiler/parser/Parser";
	
	public static void agentmain(String agentArgs, Instrumentation instrumentation) {
		registerPatcher(instrumentation, true);
	}
	
	public static void premain(String agentArgs, Instrumentation instrumentation) {
		registerPatcher(instrumentation, false);
	}
	
	private static void registerPatcher(Instrumentation instrumentation, boolean transformExisting) {
		instrumentation.addTransformer(new Patcher(), true);
		
		if ( transformExisting ) for ( Class<?> c : instrumentation.getAllLoadedClasses() ) {
			if ( c.getName().equals(ECLIPSE_PARSER_CLASS_NAME) ) {
				try {
					instrumentation.retransformClasses(c);
				} catch ( UnmodifiableClassException ex ) {
					throw new UnsupportedOperationException(
							"The eclipse parser class is already loaded and cannot be modified. " +
							"You'll have to restart eclipse in order to use Lombok in eclipse.");
				}
			}
		}
	}
}