diff options
author | Reinier Zwitserloot <reinier@tipit.to> | 2009-10-07 23:54:12 +0200 |
---|---|---|
committer | Reinier Zwitserloot <reinier@tipit.to> | 2009-10-07 23:54:12 +0200 |
commit | bb09fa4f050a7f3cb172af69487de21d6d630bbd (patch) | |
tree | 77719ba6e3e092ab47ac1edff3d78e70af2de94a /src_eclipseagent/lombok | |
parent | c2f1858781a4a1a5ae6f47a961172ee0b4cb6d53 (diff) | |
parent | 23da5b1e80bd03ee3fc02b7d7ee03130f158e7c4 (diff) | |
download | lombok-bb09fa4f050a7f3cb172af69487de21d6d630bbd.tar.gz lombok-bb09fa4f050a7f3cb172af69487de21d6d630bbd.tar.bz2 lombok-bb09fa4f050a7f3cb172af69487de21d6d630bbd.zip |
Merge branch 'lombokpatcher'
Diffstat (limited to 'src_eclipseagent/lombok')
8 files changed, 173 insertions, 673 deletions
diff --git a/src_eclipseagent/lombok/eclipse/agent/EclipseASTConverterTransformer.java b/src_eclipseagent/lombok/eclipse/agent/EclipseASTConverterTransformer.java deleted file mode 100644 index 4245e246..00000000 --- a/src_eclipseagent/lombok/eclipse/agent/EclipseASTConverterTransformer.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.eclipse.agent; - -import org.mangosdk.spi.ProviderFor; -import org.objectweb.asm.ClassAdapter; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodAdapter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -/** - * Transforms Eclipse's <code>org.eclipse.jdt.core.dom.ASTConverter</code> class, which sometimes rescans bits and pieces - * of source files because Eclipse's own AST doesn't actually have enough information for eclipse (why they don't just fix - * the AST tree generator is beyond me). At any rate, for catch blocks generated by lombok, eclipse tries to rescan the - * source file to find the source position of the catch statement, which will of course fail as there's nothing there. - * We will fix the code to return the original starting position, which is a pretty good simile, instead of '-1', which - * screws up all sorts of things. - * - * Transformations applied:<ul> - * <li>The <code>retrieveStartingCatchPosition(int, int)</code> method is instrumented to return its first parameter - * instead of the constant -1.</li></ul> - */ -@ProviderFor(EclipseTransformer.class) -public class EclipseASTConverterTransformer implements EclipseTransformer { - public byte[] transform(byte[] classfileBuffer) { - ClassReader reader = new ClassReader(classfileBuffer); - ClassWriter writer = new ClassWriter(reader, 0); - - ClassAdapter adapter = new ASTConverterPatcherAdapter(writer); - reader.accept(adapter, 0); - return writer.toByteArray(); - } - - private static class ASTConverterPatcherAdapter extends ClassAdapter { - public ASTConverterPatcherAdapter(ClassVisitor cv) { - super(cv); - } - - @Override public MethodVisitor visitMethod(int access, String name, String desc, - String signature, String[] exceptions) { - MethodVisitor writerVisitor = super.visitMethod(access, name, desc, signature, exceptions); - if ( !name.equals("retrieveStartingCatchPosition") ) return writerVisitor; - - return new RetrieveStartingCatchPositionPatcher(writerVisitor); - } - } - - static class RetrieveStartingCatchPositionPatcher extends MethodAdapter { - RetrieveStartingCatchPositionPatcher(MethodVisitor mv) { - super(mv); - } - - int count = 0; - @Override public void visitInsn(int opcode) { - if ( opcode == Opcodes.IRETURN ) { - if ( count++ == 0 ) { - super.visitInsn(opcode); - return; - } - //replaces: "return -1" with "return [firstParam]"; - super.visitInsn(Opcodes.POP); - super.visitVarInsn(Opcodes.ILOAD, 1); - super.visitInsn(Opcodes.IRETURN); - } else { - super.visitInsn(opcode); - } - } - } - - @Override public String getTargetClassName() { - return "org/eclipse/jdt/core/dom/ASTConverter"; - } -} diff --git a/src_eclipseagent/lombok/eclipse/agent/EclipseASTNodeTransformer.java b/src_eclipseagent/lombok/eclipse/agent/EclipseASTNodeTransformer.java deleted file mode 100644 index e27aa08c..00000000 --- a/src_eclipseagent/lombok/eclipse/agent/EclipseASTNodeTransformer.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.eclipse.agent; - -import org.mangosdk.spi.ProviderFor; -import org.objectweb.asm.ClassAdapter; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.Opcodes; - -/** - * Transforms Eclipse's {@code org.eclipse.jdt.internal.compiler.ast.ASTNode} class, - * which is the super-class of all AST Node class for Eclipse. - * - * Transformations applied:<ul> - * <li>A field is added: 'public transient ASTNode $generatedBy = null;'. It is set to something other than {@code null} if - * this node is generated; the reference then points at the node that is responsible for its generation (example: a {@code @Data} annotation).</li></ul> - */ -@ProviderFor(EclipseTransformer.class) -public class EclipseASTNodeTransformer implements EclipseTransformer { - private static final String ASTNODE = "org/eclipse/jdt/internal/compiler/ast/ASTNode"; - - public byte[] transform(byte[] classfileBuffer) { - ClassReader reader = new ClassReader(classfileBuffer); - ClassWriter writer = new ClassWriter(reader, 0); - - ClassAdapter adapter = new ASTNodePatcherAdapter(writer); - reader.accept(adapter, 0); - return writer.toByteArray(); - } - - private static class ASTNodePatcherAdapter extends ClassAdapter { - ASTNodePatcherAdapter(ClassVisitor cv) { - super(cv); - } - - @Override public void visitEnd() { - FieldVisitor fv = cv.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_TRANSIENT, "$generatedBy", "L" + ASTNODE + ";", null, null); - fv.visitEnd(); - cv.visitEnd(); - } - } - - @Override public String getTargetClassName() { - return ASTNODE; - } -} diff --git a/src_eclipseagent/lombok/eclipse/agent/EclipseCUDTransformer.java b/src_eclipseagent/lombok/eclipse/agent/EclipseCUDTransformer.java deleted file mode 100644 index b18a1ff1..00000000 --- a/src_eclipseagent/lombok/eclipse/agent/EclipseCUDTransformer.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.eclipse.agent; - -import org.mangosdk.spi.ProviderFor; -import org.objectweb.asm.ClassAdapter; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.Opcodes; - -/** - * Transforms Eclipse's <code>org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration</code> class, - * which is the top-level AST Node class for Eclipse. - * - * Transformations applied:<ul> - * <li>A field is added: 'public transient Object $lombokAST = null;'. We use it to cache our own AST object, - * usually of type <code>lombok.eclipse.EclipseAST.</code></li></ul> - */ -@ProviderFor(EclipseTransformer.class) -public class EclipseCUDTransformer implements EclipseTransformer { - public byte[] transform(byte[] classfileBuffer) { - ClassReader reader = new ClassReader(classfileBuffer); - ClassWriter writer = new ClassWriter(reader, 0); - - ClassAdapter adapter = new CUDPatcherAdapter(writer); - reader.accept(adapter, 0); - return writer.toByteArray(); - } - - private static class CUDPatcherAdapter extends ClassAdapter { - CUDPatcherAdapter(ClassVisitor cv) { - super(cv); - } - - @Override public void visitEnd() { - FieldVisitor fv = cv.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_TRANSIENT, "$lombokAST", "Ljava/lang/Object;", null, null); - fv.visitEnd(); - cv.visitEnd(); - } - } - - @Override public String getTargetClassName() { - return "org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration"; - } -} diff --git a/src_eclipseagent/lombok/eclipse/agent/EclipseLinkedNodeFinderTransformer.java b/src_eclipseagent/lombok/eclipse/agent/EclipseLinkedNodeFinderTransformer.java deleted file mode 100644 index 9a1ebbb2..00000000 --- a/src_eclipseagent/lombok/eclipse/agent/EclipseLinkedNodeFinderTransformer.java +++ /dev/null @@ -1,169 +0,0 @@ -package lombok.eclipse.agent; - -import org.mangosdk.spi.ProviderFor; -import org.objectweb.asm.ClassAdapter; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import static org.objectweb.asm.Opcodes.*; - -@ProviderFor(EclipseTransformer.class) -public class EclipseLinkedNodeFinderTransformer implements EclipseTransformer { - private static final String LINKED_NODE_FINDER = "org/eclipse/jdt/core/internal/corext/dom/LinkedNodeFinder"; - - @Override public String getTargetClassName() { - return LINKED_NODE_FINDER; - } - - @Override public byte[] transform(byte[] in) { - ClassReader reader = new ClassReader(in); - ClassWriter writer = new ClassWriter(reader, 0); - - ClassAdapter adapter = new LinkedNodeFinderPatcherAdapter(writer); - reader.accept(adapter, 0); - return writer.toByteArray(); - } - - private static class LinkedNodeFinderPatcherAdapter extends ClassAdapter { - private int originalAccess; - private String originalDesc; - private String originalSignature; - private String[] originalExceptions; - - LinkedNodeFinderPatcherAdapter(ClassVisitor cv) { - super(cv); - } - - @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - if ( !name.equals("findByNode") ) return super.visitMethod(access, name, desc, signature, exceptions); - - originalAccess = access; - originalDesc = desc; - originalSignature = signature; - originalExceptions = exceptions; - - return super.visitMethod(0, "findByNode0", desc, signature, exceptions); - } - - private static final String SIMPLENAME = "org/eclipse/jdt/core/dom/SimpleName"; - private static final String SIMPLENAME_ARRAY = "[L" + SIMPLENAME + ";"; - private static final String ASTNODE = "Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;"; - - /* - * code generated by running ASMifier on: - * - public SimpleName[] findByNode(ASTNode a, SimpleName b) { - SimpleName[] ps = this.findByNode0(a, b); - int count = 0; - for (int i = 0; i < ps.length; i++) { - if ( ps[i] == null || ps[i].$generatedBy == null ) count++; - } - if (count == ps.length) return ps; - SimpleName[] newPs = new SimpleName[count]; - count = 0; - for (int i = 0; i < ps.length; i++) { - if ( ps[i] == null || ps[i].p == null ) newPs[count++] = ps[i]; - } - return newPs; - } - */ - @Override public void visitEnd() { - MethodVisitor mv = super.visitMethod(originalAccess, "findByNode", originalDesc, originalSignature, originalExceptions); - mv.visitCode(); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitVarInsn(ALOAD, 1); - mv.visitVarInsn(ALOAD, 2); - mv.visitMethodInsn(INVOKESPECIAL, LINKED_NODE_FINDER, "findByNode0", originalDesc); - mv.visitVarInsn(ASTORE, 3); - mv.visitInsn(ICONST_0); - mv.visitVarInsn(ISTORE, 4); - mv.visitInsn(ICONST_0); - mv.visitVarInsn(ISTORE, 5); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitFrame(F_APPEND,3, new Object[] {SIMPLENAME_ARRAY, INTEGER, INTEGER}, 0, null); - mv.visitVarInsn(ILOAD, 5); - mv.visitVarInsn(ALOAD, 3); - mv.visitInsn(ARRAYLENGTH); - Label l1 = new Label(); - mv.visitJumpInsn(IF_ICMPGE, l1); - mv.visitVarInsn(ALOAD, 3); - mv.visitVarInsn(ILOAD, 5); - mv.visitInsn(AALOAD); - Label l2 = new Label(); - mv.visitJumpInsn(IFNULL, l2); - mv.visitVarInsn(ALOAD, 3); - mv.visitVarInsn(ILOAD, 5); - mv.visitInsn(AALOAD); - mv.visitFieldInsn(GETFIELD, SIMPLENAME, "$generatedBy", ASTNODE); - Label l3 = new Label(); - mv.visitJumpInsn(IFNONNULL, l3); - mv.visitLabel(l2); - mv.visitFrame(F_SAME, 0, null, 0, null); - mv.visitIincInsn(4, 1); - mv.visitLabel(l3); - mv.visitFrame(F_SAME, 0, null, 0, null); - mv.visitIincInsn(5, 1); - mv.visitJumpInsn(GOTO, l0); - mv.visitLabel(l1); - mv.visitFrame(F_CHOP,1, null, 0, null); - mv.visitVarInsn(ILOAD, 4); - mv.visitVarInsn(ALOAD, 3); - mv.visitInsn(ARRAYLENGTH); - Label l4 = new Label(); - mv.visitJumpInsn(IF_ICMPNE, l4); - mv.visitVarInsn(ALOAD, 3); - mv.visitInsn(ARETURN); - mv.visitLabel(l4); - mv.visitFrame(F_SAME, 0, null, 0, null); - mv.visitVarInsn(ILOAD, 4); - mv.visitTypeInsn(ANEWARRAY, SIMPLENAME); - mv.visitVarInsn(ASTORE, 5); - mv.visitInsn(ICONST_0); - mv.visitVarInsn(ISTORE, 4); - mv.visitInsn(ICONST_0); - mv.visitVarInsn(ISTORE, 6); - Label l5 = new Label(); - mv.visitLabel(l5); - mv.visitFrame(F_APPEND,2, new Object[] {SIMPLENAME_ARRAY, INTEGER}, 0, null); - mv.visitVarInsn(ILOAD, 6); - mv.visitVarInsn(ALOAD, 3); - mv.visitInsn(ARRAYLENGTH); - Label l6 = new Label(); - mv.visitJumpInsn(IF_ICMPGE, l6); - mv.visitVarInsn(ALOAD, 3); - mv.visitVarInsn(ILOAD, 6); - mv.visitInsn(AALOAD); - Label l7 = new Label(); - mv.visitJumpInsn(IFNULL, l7); - mv.visitVarInsn(ALOAD, 3); - mv.visitVarInsn(ILOAD, 6); - mv.visitInsn(AALOAD); - mv.visitFieldInsn(GETFIELD, SIMPLENAME, "$generatedBy", ASTNODE); - Label l8 = new Label(); - mv.visitJumpInsn(IFNONNULL, l8); - mv.visitLabel(l7); - mv.visitFrame(F_SAME, 0, null, 0, null); - mv.visitVarInsn(ALOAD, 5); - mv.visitVarInsn(ILOAD, 4); - mv.visitIincInsn(4, 1); - mv.visitVarInsn(ALOAD, 3); - mv.visitVarInsn(ILOAD, 6); - mv.visitInsn(AALOAD); - mv.visitInsn(AASTORE); - mv.visitLabel(l8); - mv.visitFrame(F_SAME, 0, null, 0, null); - mv.visitIincInsn(6, 1); - mv.visitJumpInsn(GOTO, l5); - mv.visitLabel(l6); - mv.visitFrame(F_CHOP,1, null, 0, null); - mv.visitVarInsn(ALOAD, 5); - mv.visitInsn(ARETURN); - mv.visitMaxs(4, 7); - super.visitEnd(); - } - } -} diff --git a/src_eclipseagent/lombok/eclipse/agent/EclipseParserTransformer.java b/src_eclipseagent/lombok/eclipse/agent/EclipseParserTransformer.java deleted file mode 100644 index 38917332..00000000 --- a/src_eclipseagent/lombok/eclipse/agent/EclipseParserTransformer.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package lombok.eclipse.agent; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import lombok.Lombok; - -import org.mangosdk.spi.ProviderFor; -import org.objectweb.asm.ClassAdapter; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodAdapter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -/** - * Transforms Eclipse's <code>org.eclipse.jdt.internal.compiler.parser.Parser</code> class, - * which handles all the actual java source to AST tree conversion in eclipse. - * - * Transformations applied:<ul> - * <li>The <code>CompilationUnitDeclaration endParse(int)</code> method is instrumented to call - * the lombok framework via ClassLoaderWorkaround to TransformEclipseAST with the CompilationUnitDeclaration - * right before it returns the CompilationUnitDeclaration.</li> - * <li>The <code>getMethodBodies(CompilationUnitDeclaration)</code> is similarly instrumented; eclipse uses a - * 2-step parsing system, where the bodies of methods aren't filled in until its actually neccessary. Lombok - * gets a chance to change the AST immediately after either step.</li> - * <li>The <code>parse(MethodDeclaration, CUD)</code>, <code>parse(ConstructorDeclaration, CUD)</code> and - * <code>parse(Initializer, TypeDeclaration, CUD)</code> methods are all instrumented to not attempt to - * complete parsing a method generated by lombok, as the source positions are obviously all wrong - * (the method content isn't in the source file!) - lombok has already filled in the complete AST. - * - * Bit24 on the flags field on all ASTNode objects is used as a marker.</li></ul> - */ -@ProviderFor(EclipseTransformer.class) -public class EclipseParserTransformer implements EclipseTransformer { - private static final String COMPILER_PKG = - "Lorg/eclipse/jdt/internal/compiler/ast/"; - private static final String TARGET_STATIC_CLASS = "java/lombok/eclipse/ClassLoaderWorkaround"; - private static final String TARGET_STATIC_METHOD_NAME = "transformCompilationUnitDeclaration"; - private static final String TARGET_STATIC_METHOD_DESC = "(Ljava/lang/Object;Ljava/lang/Object;)V"; - - private static final Map<String, Class<? extends MethodVisitor>> rewriters; - - static { - Map<String, Class<? extends MethodVisitor>> map = new HashMap<String, Class<? extends MethodVisitor>>(); - map.put(String.format("endParse(I)%sCompilationUnitDeclaration;", COMPILER_PKG), EndParsePatcher.class); - map.put(String.format("getMethodBodies(%sCompilationUnitDeclaration;)V", COMPILER_PKG), GetMethodBodiesPatcher.class); - map.put(String.format("parse(%1$sMethodDeclaration;%1$sCompilationUnitDeclaration;)V", COMPILER_PKG), ParseBlockContainerPatcher.class); - map.put(String.format("parse(%1$sConstructorDeclaration;%1$sCompilationUnitDeclaration;Z)V", COMPILER_PKG), ParseBlockContainerPatcher.class); - map.put(String.format("parse(%1$sInitializer;%1$sTypeDeclaration;%1$sCompilationUnitDeclaration;)V", COMPILER_PKG), ParseBlockContainerPatcher.class); - rewriters = Collections.unmodifiableMap(map); - } - - public byte[] transform(byte[] classfileBuffer) { - ClassReader reader = new ClassReader(classfileBuffer); - ClassWriter writer = new ClassWriter(reader, 0); - - ClassAdapter adapter = new ParserPatcherAdapter(writer); - reader.accept(adapter, 0); - return writer.toByteArray(); - } - - private static class ParserPatcherAdapter extends ClassAdapter { - public ParserPatcherAdapter(ClassVisitor cv) { - super(cv); - } - - @Override public MethodVisitor visitMethod(int access, String name, String desc, - String signature, String[] exceptions) { - MethodVisitor writerVisitor = super.visitMethod(access, name, desc, signature, exceptions); - Class<? extends MethodVisitor> targetVisitorClass = rewriters.get(name+desc); - if ( targetVisitorClass == null ) return writerVisitor; - - try { - Constructor<? extends MethodVisitor> c = targetVisitorClass.getDeclaredConstructor(MethodVisitor.class); - c.setAccessible(true); - return c.newInstance(writerVisitor); - } catch ( InvocationTargetException e ) { - throw Lombok.sneakyThrow(e.getCause()); - } catch ( Exception e ) { - //NoSuchMethodException: We know they exist. - //IllegalAccessException: We called setAccessible. - //InstantiationException: None of these classes are abstract. - throw Lombok.sneakyThrow(e); - } - } - } - - private static final int BIT24 = 0x800000; - - static class GetMethodBodiesPatcher extends MethodAdapter { - GetMethodBodiesPatcher(MethodVisitor mv) { - super(mv); - } - - @Override public void visitInsn(int opcode) { - if ( opcode == Opcodes.RETURN ) { - //injects: ClassLoaderWorkaround.transformCUD(parser, compilationUnitDeclaration); - super.visitVarInsn(Opcodes.ALOAD, 0); - super.visitVarInsn(Opcodes.ALOAD, 1); - super.visitMethodInsn(Opcodes.INVOKESTATIC, TARGET_STATIC_CLASS, - TARGET_STATIC_METHOD_NAME, TARGET_STATIC_METHOD_DESC); - } - super.visitInsn(opcode); - } - } - - static class ParseBlockContainerPatcher extends MethodAdapter { - ParseBlockContainerPatcher(MethodVisitor mv) { - super(mv); - } - - @Override public void visitCode() { - //injects: if ( constructorDeclaration.bits & BIT24 > 0 ) return; - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitFieldInsn(Opcodes.GETFIELD, "org/eclipse/jdt/internal/compiler/ast/ASTNode", "bits", "I"); - mv.visitLdcInsn(Integer.valueOf(BIT24)); - mv.visitInsn(Opcodes.IAND); - Label l0 = new Label(); - mv.visitJumpInsn(Opcodes.IFLE, l0); - mv.visitInsn(Opcodes.RETURN); - mv.visitLabel(l0); - mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); - super.visitCode(); - } - } - - static class EndParsePatcher extends MethodAdapter { - private static final String TARGET_STATIC_METHOD_NAME = "transformCompilationUnitDeclaration"; - - EndParsePatcher(MethodVisitor mv) { - super(mv); - } - - @Override public void visitInsn(int opcode) { - if ( opcode == Opcodes.ARETURN ) { - //injects: ClassLoaderWorkaround.transformCUD(parser, compilationUnitDeclaration); - super.visitInsn(Opcodes.DUP); - super.visitVarInsn(Opcodes.ALOAD, 0); - super.visitInsn(Opcodes.SWAP); - super.visitMethodInsn(Opcodes.INVOKESTATIC, TARGET_STATIC_CLASS, - TARGET_STATIC_METHOD_NAME, TARGET_STATIC_METHOD_DESC); - } - - super.visitInsn(opcode); - } - } - - @Override public String getTargetClassName() { - return "org/eclipse/jdt/internal/compiler/parser/Parser"; - } -} diff --git a/src_eclipseagent/lombok/eclipse/agent/EclipsePatcher.java b/src_eclipseagent/lombok/eclipse/agent/EclipsePatcher.java index 7659302c..c39a7d4e 100644 --- a/src_eclipseagent/lombok/eclipse/agent/EclipsePatcher.java +++ b/src_eclipseagent/lombok/eclipse/agent/EclipsePatcher.java @@ -21,24 +21,18 @@ */ package lombok.eclipse.agent; -import java.io.File; -import java.io.IOException; -import java.lang.instrument.ClassFileTransformer; -import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URLDecoder; -import java.nio.charset.Charset; -import java.security.ProtectionDomain; -import java.util.HashMap; -import java.util.Map; -import java.util.jar.JarFile; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.util.Collection; +import java.util.Collections; +import java.util.List; -import lombok.Lombok; -import lombok.core.SpiLoadUtil; +import lombok.patcher.Hook; +import lombok.patcher.MethodTarget; +import lombok.patcher.ScriptManager; +import lombok.patcher.StackRequest; +import lombok.patcher.TargetMatcher; +import lombok.patcher.equinox.EquinoxClassLoader; +import lombok.patcher.scripts.ScriptBuilder; /** * This is a java-agent that patches some of eclipse's classes so AST Nodes are handed off to Lombok @@ -50,85 +44,127 @@ import lombok.core.SpiLoadUtil; public class EclipsePatcher { private EclipsePatcher() {} - private static Map<String, EclipseTransformer> transformers = new HashMap<String, EclipseTransformer>(); - static { - try { - for ( EclipseTransformer transformer : SpiLoadUtil.findServices(EclipseTransformer.class) ) { - String targetClassName = transformer.getTargetClassName(); - transformers.put(targetClassName, transformer); - } - } catch ( Throwable t ) { - throw Lombok.sneakyThrow(t); - } - } - - private static class Patcher implements ClassFileTransformer { - public byte[] transform(ClassLoader loader, String className, - Class<?> classBeingRedefined, - ProtectionDomain protectionDomain, byte[] classfileBuffer) - throws IllegalClassFormatException { - -// ClassLoader classLoader = Patcher.class.getClassLoader(); -// if ( classLoader == null ) classLoader = ClassLoader.getSystemClassLoader(); - - EclipseTransformer transformer = transformers.get(className); - if ( transformer != null ) return transformer.transform(classfileBuffer); - - return null; - } - } - public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception { - registerPatcher(instrumentation, true); - addLombokToSearchPaths(instrumentation); - } - - private static void addLombokToSearchPaths(Instrumentation instrumentation) throws Exception { - String path = findPathOfOurClassloader(); - //On java 1.5, you don't have these methods, so you'll be forced to manually -Xbootclasspath/a them in. - tryCallMethod(instrumentation, "appendToSystemClassLoaderSearch", path + "/lombok.jar"); - tryCallMethod(instrumentation, "appendToBootstrapClassLoaderSearch", path + "/lombok.eclipse.agent.jar"); - } - - private static void tryCallMethod(Object o, String methodName, String path) { - try { - Instrumentation.class.getMethod(methodName, JarFile.class).invoke(o, new JarFile(path)); - } catch ( Throwable ignore ) {} - } - - private static String findPathOfOurClassloader() throws Exception { - URI uri = EclipsePatcher.class.getResource("/" + EclipsePatcher.class.getName().replace('.', '/') + ".class").toURI(); - Pattern p = Pattern.compile("^jar:file:([^\\!]+)\\!.*\\.class$"); - Matcher m = p.matcher(uri.toString()); - if ( !m.matches() ) return "."; - String rawUri = m.group(1); - return new File(URLDecoder.decode(rawUri, Charset.defaultCharset().name())).getParent(); + registerPatchScripts(instrumentation, true); } public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception { - registerPatcher(instrumentation, false); - addLombokToSearchPaths(instrumentation); + registerPatchScripts(instrumentation, false); } - private static void registerPatcher(Instrumentation instrumentation, boolean transformExisting) throws IOException { - instrumentation.addTransformer(new Patcher()/*, true*/); + private static void registerPatchScripts(Instrumentation instrumentation, boolean reloadExistingClasses) { + ScriptManager sm = new ScriptManager(); + sm.registerTransformer(instrumentation); + EquinoxClassLoader.getInstance().addPrefix("lombok."); + EquinoxClassLoader.getInstance().registerScripts(sm); + + sm.addScript(ScriptBuilder.wrapReturnValue() + .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveStartingCatchPosition")) + .wrapMethod(new Hook("lombok/eclipse/agent/PatchFixes", "fixRetrieveStartingCatchPosition", "(I)I")) + .transplant().request(StackRequest.PARAM1).build()); + + sm.addScript(ScriptBuilder.addField() + .targetClass("org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration") + .fieldName("$lombokAST").fieldType("Ljava/lang/Object;") + .setPublic().setTransient().build()); + + final String PARSER_SIG1 = "org.eclipse.jdt.internal.compiler.parser.Parser"; + final String PARSER_SIG2 = "Lorg/eclipse/jdt/internal/compiler/parser/Parser;"; + final String CUD_SIG1 = "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration"; + final String CUD_SIG2 = "Lorg/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration;"; + + sm.addScript(ScriptBuilder.wrapReturnValue() + .target(new MethodTarget(PARSER_SIG1, "getMethodBodies", "void", CUD_SIG1)) + .wrapMethod(new Hook("lombok/eclipse/TransformEclipseAST", "transform", + "(" + PARSER_SIG2 + CUD_SIG2 + ")V")) + .request(StackRequest.THIS, StackRequest.PARAM1).build()); + + sm.addScript(ScriptBuilder.wrapReturnValue() + .target(new MethodTarget(PARSER_SIG1, "endParse", CUD_SIG1, "int")) + .wrapMethod(new Hook("lombok/eclipse/TransformEclipseAST", "transform_swapped", + "(" + CUD_SIG2 + PARSER_SIG2 + ")V")) + .request(StackRequest.THIS, StackRequest.RETURN_VALUE).build()); + + sm.addScript(ScriptBuilder.exitEarly() + .target(new MethodTarget(PARSER_SIG1, "parse", "void", + "org.eclipse.jdt.internal.compiler.ast.MethodDeclaration", + "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) + .decisionMethod(new Hook("lombok/eclipse/agent/PatchFixes", "checkBit24", "(Ljava/lang/Object;)Z")) + .transplant().request(StackRequest.PARAM1).build()); + + sm.addScript(ScriptBuilder.exitEarly() + .target(new MethodTarget(PARSER_SIG1, "parse", "void", + "org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration", + "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration", "boolean")) + .decisionMethod(new Hook("lombok/eclipse/agent/PatchFixes", "checkBit24", "(Ljava/lang/Object;)Z")) + .transplant().request(StackRequest.PARAM1).build()); + + sm.addScript(ScriptBuilder.exitEarly() + .target(new MethodTarget(PARSER_SIG1, "parse", "void", + "org.eclipse.jdt.internal.compiler.ast.Initializer", + "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", + "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) + .decisionMethod(new Hook("lombok/eclipse/agent/PatchFixes", "checkBit24", "(Ljava/lang/Object;)Z")) + .transplant().request(StackRequest.PARAM1).build()); + + sm.addScript(ScriptBuilder.addField() + .targetClass("org.eclipse.jdt.internal.compiler.ast.ASTNode") + .fieldName("$generatedBy") + .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") + .setPublic().setTransient().build()); + + sm.addScript(ScriptBuilder.addField() + .targetClass("org.eclipse.jdt.core.dom.ASTNode") + .fieldName("$isGenerated").fieldType("Z") + .setPublic().setTransient().build()); + + sm.addScript(ScriptBuilder.wrapReturnValue() + .target(new TargetMatcher() { + @Override public boolean matches(String classSpec, String methodName, String descriptor) { + if (!"convert".equals(methodName)) return false; + + List<String> fullDesc = MethodTarget.decomposeFullDesc(descriptor); + if ("V".equals(fullDesc.get(0))) return false; + if (fullDesc.size() < 2) return false; + if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; + return true; + } + + @Override public Collection<String> getAffectedClasses() { + return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); + } + }).request(StackRequest.PARAM1, StackRequest.RETURN_VALUE) + .wrapMethod(new Hook("lombok/eclipse/agent/PatchFixes", "setIsGeneratedFlag", + "(Lorg/eclipse/jdt/core/dom/ASTNode;Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;)V")) + .transplant().build()); + + sm.addScript(ScriptBuilder.wrapMethodCall() + .target(new TargetMatcher() { + @Override public boolean matches(String classSpec, String methodName, String descriptor) { + if (!methodName.startsWith("convert")) return false; + + List<String> fullDesc = MethodTarget.decomposeFullDesc(descriptor); + if (fullDesc.size() < 2) return false; + if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; + + return true; + } + + @Override public Collection<String> getAffectedClasses() { + return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); + } + }).methodToWrap(new Hook("org/eclipse/jdt/core/dom/SimpleName", "<init>", "(Lorg/eclipse/jdt/core/dom/AST;)V")) + .requestExtra(StackRequest.PARAM1) + .replacementMethod(new Hook("lombok/eclipse/agent/PatchFixes", "setIsGeneratedFlagForSimpleName", + "(Lorg/eclipse/jdt/core/dom/SimpleName;Ljava/lang/Object;)V")) + .transplant().build()); + + sm.addScript(ScriptBuilder.wrapReturnValue() + .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByNode")) + .wrapMethod(new Hook("lombok/eclipse/agent/PatchFixes", "removeGeneratedSimpleNames", + "([Lorg/eclipse/jdt/core/dom/SimpleName;)[Lorg/eclipse/jdt/core/dom/SimpleName;")) + .request(StackRequest.RETURN_VALUE).build()); - if ( transformExisting ) for ( Class<?> c : instrumentation.getAllLoadedClasses() ) { - if ( transformers.containsKey(c.getName()) ) { - try { - //instrumentation.retransformClasses(c); - //not in java 1.5. - Instrumentation.class.getMethod("retransformClasses", Class[].class).invoke(instrumentation, - new Object[] { new Class[] {c }}); - } catch ( InvocationTargetException e ) { - 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."); - } catch ( Throwable t ) { - throw new UnsupportedOperationException( - "This appears to be a java 1.5 instance, which cannot reload already loaded classes. " + - "You'll have to restart eclipse in order to use Lombok in eclipse."); - } - } - } + if (reloadExistingClasses) sm.reloadClasses(instrumentation); } } diff --git a/src_eclipseagent/lombok/eclipse/agent/EclipseTransformer.java b/src_eclipseagent/lombok/eclipse/agent/EclipseTransformer.java deleted file mode 100644 index 31f8413f..00000000 --- a/src_eclipseagent/lombok/eclipse/agent/EclipseTransformer.java +++ /dev/null @@ -1,8 +0,0 @@ -package lombok.eclipse.agent; - -public interface EclipseTransformer { - /** slash and not dot separated */ - String getTargetClassName(); - - byte[] transform(byte[] in); -} diff --git a/src_eclipseagent/lombok/eclipse/agent/PatchFixes.java b/src_eclipseagent/lombok/eclipse/agent/PatchFixes.java new file mode 100644 index 00000000..1914bba7 --- /dev/null +++ b/src_eclipseagent/lombok/eclipse/agent/PatchFixes.java @@ -0,0 +1,48 @@ +package lombok.eclipse.agent; + +import java.lang.reflect.Field; + +import org.eclipse.jdt.core.dom.SimpleName; + +public class PatchFixes { + public static int fixRetrieveStartingCatchPosition(int in) { + return in; + } + + private static final int BIT24 = 0x800000; + + public static boolean checkBit24(Object node) throws Exception { + int bits = (Integer)(node.getClass().getField("bits").get(node)); + return (bits & BIT24) != 0; + } + + public static void setIsGeneratedFlag(org.eclipse.jdt.core.dom.ASTNode domNode, + org.eclipse.jdt.internal.compiler.ast.ASTNode internalNode) throws Exception { + boolean isGenerated = internalNode.getClass().getField("$generatedBy").get(internalNode) != null; + if (isGenerated) domNode.getClass().getField("$isGenerated").set(domNode, true); + } + + public static void setIsGeneratedFlagForSimpleName(SimpleName name, Object internalNode) throws Exception { + if (internalNode instanceof org.eclipse.jdt.internal.compiler.ast.ASTNode) { + if (internalNode.getClass().getField("$generatedBy").get(internalNode) != null) { + name.getClass().getField("$isGenerated").set(name, true); + } + } + } + + public static SimpleName[] removeGeneratedSimpleNames(SimpleName[] in) throws Exception { + Field f = SimpleName.class.getField("$isGenerated"); + + int count = 0; + for (int i = 0; i < in.length; i++) { + if ( in[i] == null || !((Boolean)f.get(in[i])).booleanValue() ) count++; + } + if (count == in.length) return in; + SimpleName[] newSimpleNames = new SimpleName[count]; + count = 0; + for (int i = 0; i < in.length; i++) { + if ( in[i] == null || !((Boolean)f.get(in[i])).booleanValue() ) newSimpleNames[count++] = in[i]; + } + return newSimpleNames; + } +} |